Guest User

Bitrix Get Discount products

a guest
Jun 30th, 2016
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.03 KB | None | 0 0
  1. <?php
  2.  
  3. use Bitrix\Catalog\DiscountTable;
  4. use Bitrix\Iblock\ElementTable;
  5. use Bitrix\Main\Data\Cache;
  6. use Bitrix\Main\Loader;
  7.  
  8. /**
  9.  * Class Discount
  10.  *
  11.  * Служит для создания списка идентификаторов товаров со скидкой
  12.  * для последующей филтрации где-либо
  13.  *
  14.  * @author pinguinjkeke
  15.  * @see http://dev.1c-bitrix.ru/community/webdev/user/265201/blog/12545/
  16.  */
  17. class DiscountFilter
  18. {
  19.     /**
  20.      * Время кэширования
  21.      *
  22.      * @var int
  23.      */
  24.     const CACHE_TIME = 3600000;
  25.  
  26.     /**
  27.      * Идентификатор инфоблока товаров
  28.      *
  29.      * @var int
  30.      */
  31.     const PRODUCT_IBLOCK_ID = 32;
  32.  
  33.     /**
  34.      * Поля товаров (если необходима фильтрация по другим полям, то их следует добавить сюда,
  35.      * а ненужные исключить)
  36.      *
  37.      * @var array
  38.      */
  39.     private $criteriaFields = [
  40.         'ID', 'IBLOCK_SECTION_ID', 'IBLOCK_ID', 'NAME'
  41.     ];
  42.  
  43.     /**
  44.      * Свойства товаров (добавить необходимые, лишние исключить)
  45.      *
  46.      * @var array
  47.      */
  48.     private $criteriaProperties = [
  49.         'ALCO', 'REGION', 'COUNTRY', 'newproduct', 'popular'
  50.     ];
  51.  
  52.     /**
  53.      * Дополнительная фильтрация
  54.      *
  55.      * @var array
  56.      */
  57.     private $additionalFilter = [
  58.         'ACTIVE' => 'Y'
  59.     ];
  60.  
  61.     /**
  62.      * ID товаров со скидками
  63.      *
  64.      * @var array
  65.      */
  66.     private $ids;
  67.  
  68.     /**
  69.      * Конструктор
  70.      */
  71.     public function __construct()
  72.     {
  73.         $cache = Cache::createInstance();
  74.  
  75.         if ($cache->startDataCache(self::CACHE_TIME, 'MESHGROUP_DISCOUNT_FILTER')) {
  76.             Loader::includeModule('catalog');
  77.             Loader::includeModule('iblock');
  78.             Loader::includeModule('sale');
  79.  
  80.             foreach ($this->criteriaProperties as $property) {
  81.                 $this->criteriaFields[] = "PROPERTY_{$property}";
  82.             }
  83.  
  84.  
  85.             $ids = $this->processDiscountConditions($this->getDiscounts(), $this->getProducts());
  86.  
  87.             if (empty($ids)) {
  88.                 $cache->abortDataCache();
  89.  
  90.                 return;
  91.             }
  92.  
  93.             $cache->endDataCache(compact('ids'));
  94.         } else {
  95.             extract($cache->getVars());
  96.         }
  97.  
  98.         $this->ids = $ids;
  99.     }
  100.  
  101.     /**
  102.      * Возвращает список идентификаторв товаров со скидкой
  103.      *
  104.      * @return array
  105.      */
  106.     public function getIds()
  107.     {
  108.         return $this->ids;
  109.     }
  110.  
  111.     /**
  112.      * Получение списка товаров по 1000
  113.      *
  114.      * @return array
  115.      */
  116.     private function getProducts()
  117.     {
  118.         $products = [];
  119.  
  120.         $filter = array_merge(['IBLOCK_ID' => self::PRODUCT_IBLOCK_ID], $this->additionalFilter);
  121.  
  122.         $elementsCount = ElementTable::getCount($filter);
  123.         $page = 1;
  124.  
  125.         while (($page * 1000) < $elementsCount) {
  126.             $get = CIBlockElement::GetList(
  127.                 ['ID' => 'asc'],
  128.                 $filter,
  129.                 false,
  130.                 ['nPageSize' => 1000, 'iNumPage' => $page],
  131.                 $this->criteriaFields
  132.             );
  133.  
  134.             while ($res = $get->Fetch()) {
  135.                 if (!isset($products[$res['ID']])) {
  136.                     if (isset($res['IBLOCK_SECTION_ID'])) {
  137.                         $res['SECTION_ID'] = [$res['IBLOCK_SECTION_ID']];
  138.  
  139.                         unset($res['IBLOCK_SECTION_ID']);
  140.                     }
  141.  
  142.                     $products[$res['ID']] = $res;
  143.                 }
  144.             }
  145.            
  146.             $page++;
  147.         }
  148.  
  149.         return $products;
  150.     }
  151.  
  152.     /**
  153.      * Получение списка скидок
  154.      *
  155.      * @return array
  156.      */
  157.     private function getDiscounts()
  158.     {
  159.         return DiscountTable::getList([
  160.             'select' => ['ID', 'CONDITIONS_LIST'],
  161.             'filter' => ['ACTIVE' => 'Y']
  162.         ])->fetchAll();
  163.     }
  164.  
  165.     /**
  166.      * Обработка условий скидок
  167.      *
  168.      * @param array $discounts Массив условий скидок
  169.      * @param array $products Массив товаров
  170.      * @return array|bool
  171.      */
  172.     private function processDiscountConditions(array $discounts, array $products)
  173.     {
  174.         $condition = new CCatalogCondTree;
  175.  
  176.         if (!$bool = $condition->Init(BT_COND_MODE_GENERATE, BT_COND_BUILD_CATALOG, [])) {
  177.             return false;
  178.         }
  179.  
  180.         $ids = [];
  181.  
  182.         foreach ($discounts as $discount) {
  183.             $filter = $condition->Generate($discount['CONDITIONS_LIST'], ['FIELD' => '$product']);
  184.  
  185.             foreach ($products as $product) {
  186.                 if (eval("return {$filter};")) {
  187.                     $ids[] = $product['ID'];
  188.                 }
  189.             }
  190.         }
  191.  
  192.         return $ids;
  193.     }
  194. }
Add Comment
Please, Sign In to add comment