energine
[ class tree: energine ] [ index: energine ] [ all elements ]

Source for file ProductList.class.php

Documentation is available at ProductList.class.php

  1. <?php
  2. /**
  3.  * Содержит класс ProductList
  4.  *
  5.  * @package energine
  6.  * @subpackage shop
  7.  * @author dr.Pavka
  8.  * @copyright ColoCall 2006
  9.  * @version $Id$
  10.  */
  11.  
  12. /**
  13.  * Выводит список продуктов для заданного раздела
  14.  *
  15.  * @package energine
  16.  * @subpackage shop
  17.  * @author dr.Pavka
  18.  */
  19. class ProductList extends DBDataSet {
  20.     /**
  21.      * Имя поля поиска
  22.      *
  23.      */
  24.     const SEARCH_FIELD_NAME = 'product';
  25.  
  26.     /**
  27.      * Конструктор класса
  28.      *
  29.      * @param string $name 
  30.      * @param string $module 
  31.      * @param Document $document 
  32.      * @param array $params 
  33.      * @access public
  34.      */
  35.     public function __construct($name$moduleDocument $document,  array $params null{
  36.         parent::__construct($name$module$document,  $params);
  37.         $this->setTableName('shop_products');
  38.         $id $this->getParam('id');
  39.  
  40.         $descendants array_keys(Sitemap::getInstance()->getTree()->getNodeById($id)->getDescendants()->asList(false));
  41.         $id array_merge(array($id)$descendants);
  42.         $this->setFilter(array('smap_id' => $id'ps_id'=>ProductStatusEditor::getVisibleStatuses($this->document->getRights())));
  43.         $this->setParam('onlyCurrentLang'true);
  44.     }
  45.  
  46.     /**
  47.      * Добавлен параметр smapID
  48.      *
  49.      * @return array 
  50.      * @access protected
  51.      */
  52.     protected function defineParams({
  53.         return array_merge(parent::defineParams(),
  54.         array(
  55.             'id' => $this->document->getID(),
  56.             'active' => true
  57.         ));
  58.     }
  59.     /**
  60.      * Поле producer_id в списке должно выводиться как текст
  61.      *
  62.      * @return DATADescription 
  63.      * @access protected
  64.      */
  65.  
  66.     protected function createDataDescription({
  67.         $result parent::createDataDescription();
  68.         if($producerIDFD $result->getFieldDescriptionByName('producer_id')) {
  69.             $producerIDFD->setType(FieldDescription::FIELD_TYPE_TEXT);
  70.             $producerIDFD->setProperty('title'$this->translate('TXT_ANOTHER_PRODUCTS'));
  71.         }
  72.         $fd new FieldDescription('product_images');
  73.         $fd->setType(FieldDescription::FIELD_TYPE_CUSTOM);
  74.         $result->addFieldDescription($fd);
  75.         return $result;
  76.     }
  77.  
  78.     /**
  79.      * Для поля producer_id вместо ключа выводится значение а ключ пишется в аттрибут
  80.      *
  81.      * @return Data 
  82.      * @access protected
  83.      */
  84.  
  85.     protected function createData({
  86.         $result parent::createData();
  87.         if ($result{
  88.             $sitemap Sitemap::getInstance();
  89.             $this->buildProductImagesField($result);
  90.             
  91.             if ($producerIDField $result->getFieldByName('producer_id')) {
  92.                 $producerData 
  93.                     convertDBResult(
  94.                         $this->dbh->select(
  95.                            'shop_producers'
  96.                            array('producer_id','producer_name''producer_segment')
  97.                            array('producer_id'=>$producerIDField->getData())
  98.                         ),
  99.                         'producer_id',
  100.                         true
  101.                     );
  102.             }
  103.             for ($i 0$i $result->getRowCount()$i++{
  104.                 if($producerIDField && ($producerID $producerIDField->getRowData($i))){
  105.                     $producerIDField->setRowProperty($i'producerID'$producerID);
  106.                     $producerIDField->setRowProperty($i'producer_segment'$producerData[$producerID]['producer_segment']);
  107.                     $producerIDField->setRowData($i$producerData[$producerID]['producer_name']);
  108.                 }
  109.                 if ($smapID $result->getFieldByName('smap_id')) {
  110.                     $smapInfo $sitemap->getDocumentInfo($smapID->getRowData($i));
  111.                     $smapID->setRowProperty($i'smap_segment'$sitemap->getURLByID($smapID->getRowData($i)));
  112.                     $smapID->setRowData($i$smapInfo['Name']);
  113.                 }
  114.             }
  115.         }
  116.  
  117.         return $result;
  118.     }
  119.  
  120.     /**
  121.      * Добавляет значение product_price(если есть в перечне полей
  122.      *
  123.      * @return array 
  124.      * @access protected
  125.      */
  126.  
  127.     protected function loadData({
  128.         if ($this->getAction()=='search' && isset($_GET[self::SEARCH_FIELD_NAME])) {
  129.             $searchData explode(' '$_GET[self::SEARCH_FIELD_NAME]);
  130.             $searchData array_map(create_function('$str''return trim($str);')$searchData);
  131.             $searchString '';
  132.             reset($searchData);
  133.             while ($str current($searchData)) {
  134.                 $searchString .= ' (product_name like "%'.$str.'%" OR product_description_rtf LIKE "%'.$str.'%") ';
  135.                 if (next($searchData)) {
  136.                     $searchString .= 'OR';
  137.                 }
  138.             }
  139.             $searchString '('.$searchString.') AND ps_id IN ('.implode(','ProductStatusEditor::getVisibleStatuses($this->document->getRights())).') ';
  140.  
  141.             $this->setFilter($searchString);
  142.         }
  143.  
  144.         $result parent::loadData();
  145.         if (is_array($result&& $this->getDataDescription()->getFieldDescriptionByName('product_price')) {
  146.             $converter CurrencyConverter::getInstance();
  147.             $currentCurrency $converter->getCurrent();
  148.  
  149.             $res $this->dbh->selectRequest(
  150.              'SELECT product_id, product_price, curr_id '.
  151.              'FROM shop_product_external_properties e '.
  152.              'LEFT JOIN shop_products p ON p.product_code = e.product_code '.
  153.              'WHERE product_id IN('.
  154.             implode(',',
  155.             array_map(
  156.             create_function(
  157.                          '$row''return $row["product_id"];'
  158.                          ),
  159.                          $result
  160.                          )
  161.                          ).')');
  162.                              
  163.                          if(is_array($res)){
  164.                              $res convertDBResult($res'product_id'true);
  165.                              foreach ($result as $key => $row{
  166.                                  $result[$key]['product_price'$converter->format(
  167.                                  $converter->convert(
  168.                                  $res[$row['product_id']]['product_price'],
  169.                                  $currentCurrency,
  170.                                  $res[$row['product_id']]['curr_id']),
  171.                                  $currentCurrency
  172.                                  );
  173.                              }
  174.                          }
  175.         }
  176.         return $result;
  177.     }
  178.  
  179.     /**
  180.      * Выводит продук
  181.      *
  182.      * @return void 
  183.      * @access protected
  184.      */
  185.  
  186.     protected function view({
  187.         $this->setType(self::COMPONENT_TYPE_FORM);
  188.         list($segment$this->getActionParams();
  189.         $id simplifyDBResult($this->dbh->select($this->getTableName()$this->getPK()array('product_segment' => $segment))$this->getPK()true);
  190.         if (!$this->recordExists($id)) {
  191.             throw new SystemException('ERR_404'SystemException::ERR_404);
  192.         }
  193.         $this->setFilter($id);
  194.  
  195.         $this->prepare();
  196.         $this->document->componentManager->getComponentByName('breadCrumbs')->addCrumb('',$this->getData()->getFieldByName('product_name')->getRowData(0));
  197.         //Получаем параметры и их значения
  198.  
  199.         //Сначала  - набор параметров
  200.         $res $this->dbh->selectRequest(
  201.             'SELECT pp.pp_id, pp_name, pp_type, pp_value FROM `shop_product_params` pp '
  202.             'LEFT JOIN shop_product_params_translation ppt ON ppt.pp_id = pp.pp_id '
  203.             'LEFT JOIN  shop_products p On p.pt_id = pp.pt_id '.
  204.             'LEFT JOIN  shop_product_param_values pv On pv.pp_id = pp.pp_id AND pv.product_id = p.product_id '.
  205.             'WHERE p.product_id = %s  AND lang_id = %s',
  206.             $id,
  207.             $this->document->getLang()
  208.         );
  209.  
  210.         if(is_array($res)){
  211.             foreach ($res as $row{
  212.                 $paramName 'product_param_'.$row['pp_id'];
  213.                 //Для каждого параметра создаем FieldDescription
  214.                 $paramFD new FieldDescription($paramName);
  215.                 $paramFD->setType($row['pp_type']);
  216.                 $paramFD->setProperty('title'$row['pp_name']);
  217.                 $paramFD->setProperty('param'$this->translate('TXT_PRODUCT_PARAMS'));
  218.                 $this->getDataDescription()->addFieldDescription($paramFD);
  219.                 $paramF new Field('product_param_'.$row['pp_id']);
  220.                 $paramF->setData($row['pp_value']);
  221.                 $this->getData()->addField($paramF);
  222.         }
  223.         }
  224.         foreach ($this->getDataDescription(as $fieldDescription{
  225.             $fieldDescription->setMode(FieldDescription::FIELD_MODE_READ);
  226.         }
  227.  
  228.         if ($component $this->document->componentManager->getComponentByName('productDivisions')) {
  229.             $component->disable();
  230.         }
  231.  
  232.         if ($component $this->document->componentManager->getComponentByName('manufacturers')) {
  233.             $component->disable();
  234.         }
  235.         $this->document->setProperty('title'$this->getData()->getFieldByName('product_name')->getRowData(0));
  236.     }
  237.  
  238.     private function buildProductImagesField(Data $data){
  239.         $f new Field('product_images');
  240.         $data->addField($f);
  241.  
  242.         $images $this->dbh->selectRequest(
  243.                'SELECT spu.product_id, upl_path, upl_name FROM share_uploads su '.
  244.                'LEFT JOIN `shop_product_uploads` spu ON spu.upl_id = su.upl_id '.
  245.                'WHERE product_id IN ('.implode(','$data->getFieldByName('product_id')->getData()).')'
  246.                );
  247.  
  248.                if(is_array($images)){
  249.                 foreach($images as $row){
  250.                     $productID $row['product_id'];
  251.                     if(!isset($imageData[$productID]))
  252.                     $imageData[$productIDarray();
  253.                      
  254.                     array_push($imageData[$productID]$row);
  255.                 }
  256.  
  257.                 for ($i 0$i $data->getRowCount()$i++{
  258.                     if(isset($imageData[$data->getFieldByName('product_id')->getRowData($i)])){
  259.                         $builder new SimpleBuilder();
  260.                         $localData new Data();
  261.                         $localData->load($imageData[$data->getFieldByName('product_id')->getRowData($i)]);
  262.  
  263.                         $dataDescription new DataDescription();
  264.                         $fd new FieldDescription('product_id');
  265.                         $dataDescription->addFieldDescription($fd);
  266.                         $fd new FieldDescription('upl_path');
  267.                         $fd->setType(FieldDescription::FIELD_TYPE_IMAGE);
  268.                         $dataDescription->addFieldDescription($fd);
  269.                         $fd new FieldDescription('upl_name');
  270.                         $dataDescription->addFieldDescription($fd);
  271.                         $builder->setData($localData);
  272.                         $builder->setDataDescription($dataDescription);
  273.  
  274.                         $builder->build();
  275.  
  276.                         $f->setRowData($i$builder->getResult());
  277.                     }
  278.                 }
  279.  
  280.                }
  281.     }
  282.  
  283.     /**
  284.      * Выводит список продуктов определенного производителя в данной группе
  285.      *
  286.      * @return void 
  287.      * @access protected
  288.      */
  289.  
  290.     protected function showManufacturerProducts({
  291.         list($producerSegment$this->getActionParams();
  292.         list($producerInfo$this->dbh->select('shop_producers'array('producer_id''producer_name')array('producer_segment' => $producerSegment));
  293.         $this->addFilterCondition(array('producer_id' => $producerInfo['producer_id']));
  294.         $this->document->componentManager->getComponentByName('breadCrumbs')->addCrumb('0'$producerInfo['producer_name']$producerSegment);
  295.         $this->prepare();
  296.         $this->document->setProperty('title'($title $this->document->getProperty('title'))?$title.' / '.$producerInfo['producer_name']:$producerInfo['producer_name']);
  297.         if ($component $this->document->componentManager->getComponentByName('productDivisions')) {
  298.             $component->disable();
  299.         }
  300.         if ($component $this->document->componentManager->getComponentByName('manufacturers')) {
  301.             $component->disable();
  302.         }
  303.     }
  304.  
  305.     /**
  306.      * Переписан родительский метод
  307.      * Для метода showManufacturer изменяет принцип получения actionParams
  308.      *
  309.      * @return void 
  310.      * @access protected
  311.      */
  312.  
  313.     protected function createPager({
  314.         $recordsPerPage intval($this->getParam('recordsPerPage'));
  315.         if ($recordsPerPage 0{
  316.             $this->pager new Pager($recordsPerPage);
  317.             if ($this->isActive(&& $this->getType(== self::COMPONENT_TYPE_LIST{
  318.                 $actionParams $this->getActionParams();
  319.                 if ($this->getAction(== 'showManufacturerProducts'{
  320.                     $paramNum 1;
  321.                 }
  322.                 else {
  323.                     $paramNum 0;
  324.                 }
  325.  
  326.                 if (isset($actionParams[$paramNum])) {
  327.                     $page intval($actionParams[$paramNum]);
  328.                 }
  329.                 else {
  330.                     $page 1;
  331.                 }
  332.  
  333.                 $this->pager->setCurrentPage($page);
  334.             }
  335.  
  336.             $this->pager->setProperty('title'$this->translate('TXT_PAGES'));
  337.             if ($this->getAction(== 'search'{
  338.                 $this->pager->setProperty('additional_url''search-results/');
  339.             }
  340.         }
  341.     }
  342.  
  343.     /**
  344.      * Добавлена паенль поиска товаров
  345.      *
  346.      * @return DOMNode 
  347.      * @access public
  348.      */
  349.  
  350.     public function build({
  351.         $result parent::build();
  352.         if ($this->getType(== self::COMPONENT_TYPE_LIST {
  353.             $result->documentElement->insertBefore($this->buildSearchForm()$result->documentElement->childNodes->item(0));
  354.         }
  355.         return $result;
  356.     }
  357.  
  358.     /**
  359.      * Постройка формы поиска
  360.      *
  361.      * @return DOMNode 
  362.      * @access private
  363.      */
  364.  
  365.     private function buildSearchForm({
  366.         //inspect($this->getActionParams());
  367.         $result $this->doc->createElement('searchform');
  368.         $result->setAttribute('title'$this->translate('TXT_SEARCH_CATALOGUE'));
  369.         $result->setAttribute('action''search-results');
  370.         $field $this->doc->createElement('search_field'(isset($_GET[self::SEARCH_FIELD_NAME]))?$_GET[self::SEARCH_FIELD_NAME]:'');
  371.         $field->setAttribute('action_title'$this->translate('BTN_SEARCH'));
  372.         $field->setAttribute('name'self::SEARCH_FIELD_NAME);
  373.         $result->appendChild($field);
  374.         return $result;
  375.     }
  376.  
  377.     /**
  378.      * Выводит результаты поиска
  379.      *
  380.      * @return void 
  381.      * @access public
  382.      */
  383.  
  384.     public function search({
  385.         $this->document->componentManager->getComponentByName('breadCrumbs')->addCrumb();
  386.         $this->prepare();
  387.         if(!$this->getData()){
  388.             $this->addTranslation('MSG_EMPTY_SEARCH_RESULT');
  389.         }
  390.         if ($component $this->document->componentManager->getComponentByName('productDivisions')) {
  391.             $component->disable();
  392.         }
  393.         $this->document->setProperty('title'$this->translate('TXT_SEARCH_RESULT'));
  394.  
  395.     }
  396.  
  397. }
В создании документации нам помог: phpDocumentor