app/Plugin/HsdRelatedProduct42/Controller/Block/HsdRelatedProduct42Controller.php line 60

Open in your IDE?
  1. <?php
  2. /*
  3.  * 「この商品を見た人はこんな商品も見ています」プラグイン(EC-CUBE4系)
  4.  * 2021/05/16 Ver.1.0.7 前バージョン
  5.  * 2021/05/18 Ver.1.0.8 商品固有の税率で価格を表示するようにした。
  6.  * 2021/05/26 Ver.1.0.9 「最低価格~最高価格」の表示で正しく税込み表示できるようにした。
  7.  */
  8. namespace Plugin\HsdRelatedProduct42\Controller\Block;
  9. use Eccube\Controller\AbstractController;
  10. use Plugin\HsdRelatedProduct42\Repository\ConfigRepository;
  11. use Plugin\HsdRelatedProduct42\Entity\HsdRelatedProduct42;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Component\Routing\RouterInterface;
  17. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  18. use Symfony\Component\HttpFoundation\RequestStack;
  19. use \PDO;
  20. class HsdRelatedProduct42Controller extends AbstractController
  21. {
  22.     // タイトル
  23.     private $_title 'この商品をみた人はこんな商品もみています';
  24.     private $_show_count 4;            // 表示個数(初期値4)
  25.     private $_rp         = [];           // 関連商品用データ
  26.     private $_show_price 'true';       // 価格の表示/非表示
  27.     private $_show_type  'normal';     // 表示タイプ(初期値 スライダーなし)
  28.     private $_pagination 'true';       // ページネーション(初期値 あり
  29.     private $_navbuttons 'true';       // ナビゲーション(初期値 あり
  30.     private $_showloop   'true';       // 表示の自動ループ//初期値 あり
  31.     private $_calc_rule  'round';      // 税率の計算方法// 四捨五入(デフォルト)
  32.     private $_tax        1.10;         // 税率(初期値10%)
  33.     // Anna用
  34.     private $_save_from_id 0;
  35.     private $_save_to_id 0;
  36.     private $_save_from_product_name '';
  37.     private $_save_to_product_name '';
  38.     private $_def_max_row 1000//データの最大保持数の初期値
  39.     /**
  40.      * HsdRelatedProduct42Controller constructor.
  41.      *
  42.      * @param ConfigRepository $configRepository
  43.      */
  44.     public function __construct(ConfigRepository $configRepositoryRequestStack $requestStack)
  45.     {
  46.         $this->_configRepository $configRepository;
  47.         $this->requestStack $requestStack;
  48.     }
  49.     /**
  50.      * @Route("block_hsd_related_product42", name="block_hsd_related_product42")
  51.      * @Template("@Block/hsd_related_product42.twig")
  52.      */
  53.     public function index(Request $request)
  54.     {
  55.         // データベースハンドルを取得
  56.         $dbh $this->entityManager->getConnection();
  57.         // 真ならPostgrSQL偽ならMySQLを表すフラグを用意
  58.         $isPostgreSQL $dbh->getDatabasePlatform()->getName() == 'postgresql';
  59.         /*
  60.          * 詳細画面の場合のみ動作
  61.          * /products/detail/[product_id] を想定
  62.          */
  63.         $request_stack $this->get('request_stack')->getMasterRequest();
  64.         $chkpath explode('/'$request_stack->getPathInfo());
  65.         if ( $chkpath[1] == 'products' && $chkpath[2] == 'detail' ) {
  66.             $id $chkpath[3]; //現在表示中のメインの商品ID
  67.             $max_row $this->_def_max_row// 初期値1000
  68.             // 保持する最大データ数を取得し、1回の削除数を設定(20%を設定)
  69.             $setting $this->_configRepository->get();
  70.             if( $setting != null ){
  71.                 if( !empty($setting->getMaxNum()) && is_numeric($setting->getMaxNum()) ) {
  72.                     $this->_show_count $setting->getMaxNum();
  73.                 }
  74.                 if( !empty($setting->getMaxRowNum()) && is_numeric($setting->getMaxRowNum()) ) {
  75.                     $max_row $setting->getMaxRowNum();
  76.                     $del_rows intval($max_row 0.2);
  77.                 }else{
  78.                     $del_rows 200;
  79.                 }
  80.                 if( !empty($setting->getTitle()) ) {
  81.                     $this->_title $setting->getTitle();
  82.                 }
  83.                 if( !empty($setting->getShowPrice()) ) {
  84.                     $this->_show_price $setting->getShowPrice();
  85.                 }
  86.                 if( !empty($setting->getShowType()) ) {
  87.                     $this->_show_type $setting->getShowType();
  88.                 }
  89.                 if( !empty($setting->getPagination()) ) {
  90.                     $this->_pagination $setting->getPagination();
  91.                 }
  92.                 if( !empty($setting->getNavbuttons()) ) {
  93.                     $this->_navbuttons $setting->getNavbuttons();
  94.                 }
  95.                 if( !empty($setting->getShowloop()) ) {
  96.                     $this->_showloop $setting->getShowloop();
  97.                 }
  98.             }
  99.             $em $this->entityManager;
  100.             $con_db_type $em->getConnection()->getDatabasePlatform()->getName(); // postgresql or mysql
  101.             // データ保持数に達していたら削除
  102.             //$rs = $dbh->query( 'SELECT COUNT(id) FROM plg_hsd_related_product' )->fetchColumn();
  103.             $rs_tmp $dbh->executeQuery'SELECT COUNT(id) as count FROM plg_hsd_related_product' )->fetchAllAssociative();
  104.             $rs $rs_tmp[0]['count'];
  105.             if ( $rs $max_row ) {
  106.                 $del_rows $rs $max_row;
  107.                 if( $con_db_type == 'postgresql' ){
  108.                     $stmt $dbh->executeQuery'DELETE FROM plg_hsd_related_product WHERE id IN ( SELECT id FROM plg_hsd_related_product ORDER BY updated_at ASC LIMIT '$del_rows ')' );
  109.                 }else{
  110.                     $stmt $dbh->executeQuery'DELETE FROM plg_hsd_related_product ORDER BY updated_at ASC LIMIT '$del_rows );
  111.                 }
  112.             }
  113.             /*
  114.              * もしセッションにsave_pr_idが保持されていたら処理を行う
  115.              */
  116.             if ( isset( $_SESSION['ec_save_pr_id'] ) ) {
  117.                 $_from_id $_SESSION['ec_save_pr_id'];
  118.                 // DB更新:もしfromとtoが異なる場合は保持
  119.                 if ( $_from_id != $id ) {
  120.                     $rp_obj = new HsdRelatedProduct42();
  121.                     $rp_obj->setIduniqid('rp_') )
  122.                         ->setFromId$_from_id )
  123.                         ->setToId$id )
  124.                         ->setUpdatedAt( new \DateTime() );
  125.                     $em->persist$rp_obj );
  126.                     $em->flush$rp_obj );
  127.                 }
  128.             }
  129.             // 現在の商品IDをもとに、次の商品IDを取得
  130.             $stmt $dbh->prepare("SELECT count(rp.to_id) cn, rp.to_id FROM plg_hsd_related_product rp, dtb_product as p WHERE rp.from_id=:id AND rp.to_id = p.id AND p.product_status_id = 1 GROUP BY rp.from_id, rp.to_id ORDER BY cn DESC");
  131.             $stmt->bindValue':id'$idPDO::PARAM_INT );
  132.             $stex $stmt->executeQuery();
  133.             $rs $stex->fetchAllAssociative();
  134.             // 関連商品自動表示ブロックの設定
  135.             $or_str '';
  136.             foreach ( $rs as $item ){
  137.                 $or_str .= '(ecp.id=' $item['to_id'] . ' AND ecp.id = ecpi.product_id) or ';
  138.             }
  139.             $or_str substr$or_str0strlen($or_str)-);
  140.             $rps = [];
  141.             if ( strlen$or_str ) > ) {
  142.                 //$sql = 'SELECT ecp.id, ecp.name, ecp.description_detail, (SELECT in_ecpi.file_name FROM dtb_product_image in_ecpi WHERE in_ecpi.product_id = ecp.id AND in_ecpi.sort_no < 2 ) file_name, (SELECT MIN(in_pcl.price02) FROM dtb_product_class in_pcl WHERE in_pcl.product_id = ecp.id and in_pcl.visible = :visible GROUP BY in_pcl.product_id) min_price, (SELECT MAX(in_pcl.price02) FROM dtb_product_class in_pcl WHERE in_pcl.product_id = ecp.id and in_pcl.visible = :visible GROUP BY in_pcl.product_id) max_price FROM dtb_product ecp, dtb_product_image ecpi WHERE ' . $or_str . ' GROUP BY ecp.id';
  143.                 $sql 'SELECT ecp.id, ecp.name, ecp.description_detail, (SELECT in_ecpi.file_name FROM dtb_product_image in_ecpi WHERE in_ecpi.product_id = ecp.id AND in_ecpi.sort_no < 2 ORDER BY in_ecpi.sort_no ASC LIMIT 1 ) file_name, (SELECT MIN(in_pcl.price02) FROM dtb_product_class in_pcl WHERE in_pcl.product_id = ecp.id and in_pcl.visible = :visible GROUP BY in_pcl.product_id) min_price, (SELECT MAX(in_pcl.price02) FROM dtb_product_class in_pcl WHERE in_pcl.product_id = ecp.id and in_pcl.visible = :visible GROUP BY in_pcl.product_id) max_price FROM dtb_product ecp, dtb_product_image ecpi WHERE ' $or_str ' GROUP BY ecp.id';
  144.                 $stmt $dbh->prepare$sql );
  145.                 if ( $isPostgreSQL ) {
  146.                     $stmt->bindValue':visible'truePDO::PARAM_BOOL );
  147.                 } else {
  148.                     $stmt->bindValue':visible',    1PDO::PARAM_INT );
  149.                 }
  150.                 $stex $stmt->executeQuery();
  151.                 $rps $stex->fetchAllAssociative(); //該当商品リストが求まる
  152.             }
  153.             //log_info( print_r($rps,true));
  154.             //「店舗設定」の税率をDBから取得できないときのデフォルトを設定
  155.             $default_tax_rate         $this->_tax 100 100;
  156.             $default_rounding_type_id 1;
  157.             $calc_rule                = [ => 'round',  //四捨五入 
  158.                                           => 'floor',  //切り捨て
  159.                                           => 'ceil' ]; //切り上げ
  160.             //DBに「店舗設定」の税率と、税率計算における丸めロジックを問い合わせる
  161.             $sql "SELECT tax_rate,rounding_type_id FROM dtb_tax_rule WHERE id = 1";
  162.             $rs_tmp $dbh->executeQuery$sql )->fetchAllAssociative();
  163.             $default_tax_rate $rs_tmp[0]['tax_rate'];
  164.             $default_rounding_type_id $rs_tmp[0]['rounding_type_id'];
  165.             //list ( $default_tax_rate, $default_rounding_type_id ) = $dbh->query( $sql )->fetch( PDO::FETCH_NUM );
  166.             if ( $calc_rule$default_rounding_type_id ] === "" ) {
  167.                 log_error'rounding_type_idが想定外の値です : '$default_rounding_type_id );
  168.                 exit;
  169.             }
  170.             // 商品ごとに税率と計算方法を取得して商品データ($rps)に追加する
  171.             for ( $i 0$i count$rps ); $i++ ) {
  172.                 $product_id $rps[$i]['id'];
  173.                 if ( $rps[$i]['min_price'] != $rps[$i]['max_price'] ) {
  174.                     // 商品規格が定義されている商品で「○○円~○○○円」といった表示が必要な場合
  175.                     $sql "SELECT tax_rate FROM dtb_tax_rule "
  176.                          "WHERE product_class_id IN ( "
  177.                          "SELECT id FROM dtb_product_class WHERE product_id = $product_id AND price02 = ? ) ORDER BY tax_rate ";
  178.                     // tax_rule表から該当商品中でもっとも低く設定されている税率を取得する。
  179.                     $stmt $dbh->prepare$sql ."ASC" );
  180.                     $stmt->bindValue1$rps[$i]['min_price'], PDO::PARAM_STR );
  181.                     $stex $stmt->executeQuery();
  182.                     $min_rate_tmp $stex->fetchAllAssociative(); // tax_rateは''か0~100の整数が返る。nullは無い。
  183.                     $min_rate $min_rate_tmp[0]['tax_rate'];
  184.                     // tax_rule表から該当商品中でもっとも高く設定されている税率を取得する。
  185.                     $stmt $dbh->prepare$sql ."DESC" );
  186.                     $stmt->bindValue1$rps[$i]['max_price'], PDO::PARAM_STR );
  187.                     $stex $stmt->executeQuery();
  188.                     $max_rate_tmp $stex->fetchAllAssociative(); // ''か0~100の整数が返る。nullは無い。
  189.                     $max_rate $max_rate_tmp[0]['tax_rate'];
  190.                     // dtb_tax_rule表に商品規格が登録され販売価格は設定されていても税率欄は空ということがある。そのときはデフォルトの税率を採用する。
  191.                     if ( ! is_numeric$min_rate ) ) {
  192.                         $min_rate =  $default_tax_rate;
  193.                     }
  194.                     if ( ! is_numeric$max_rate ) ) {
  195.                         $max_rate =  $default_tax_rate;
  196.                     }
  197.                     //log_info( "min_rate = '$min_rate', max_rate = '$max_rate'" );
  198.                     // 商品データに、求まった税率を追加
  199.                     $rps[$i]['tax']    = 1.0 $min_rate 100;
  200.                     $rps[$i]['tax2']   = 1.0 $max_rate 100;
  201.                 } else {
  202.                     // 「商品規格」を設定していない商品(たいていは未設定)はこっちの処理を通る
  203.                     // tax_rule表から税率が取得できないときはデフォルト値を使う
  204.                     //$rps[$i]['tax'] = 1.0 + $default_tax_rate / 100;
  205.                     $min_tax_rate 0;
  206.                     $min_tax_rate_tmp $dbh->executeQuery(
  207.                         "SELECT MIN(tax_rate) AS min_tax_rate FROM dtb_tax_rule WHERE product_id = $product_id)->fetchAllAssociative();
  208.                     $min_tax_rate $min_tax_rate_tmp[0]['min_tax_rate'];
  209.                     if ( $min_tax_rate ) {
  210.                         // 税率と計算ルールが取得できたときは商品データにセットする。
  211.                         $stmt $dbh->executeQuery"SELECT DISTINCT rounding_type_id  FROM dtb_tax_rule WHERE product_id = $product_id);
  212.                         if ( $stmt->rowCount() >= ) {
  213.                             log_error'同じproduct_idをもつ商品は皆同じrounding_type_idを持つことを期待しているのですが、'
  214.                                 $stmt->rowCount() . '種類のrounding_type_idが検出されました。');
  215.                             exit;
  216.                         }
  217.                         $st_tmp $stmt->fetchAllAssociative();
  218.                         $rounding_type_id $st_tmp[0]['rounding_type_id'];
  219.                         if ( $calc_rule$rounding_type_id ] === "" ) {
  220.                             log_error('rounding_type_idが想定外の値です : '$rounding_type_id );
  221.                             exit;
  222.                         }
  223.                         $rps[$i]['tax'] = 1.0 $min_tax_rate 100;
  224.                         $rps[$i]['calc_rule'] = $calc_rule$rounding_type_id ];
  225.                     } else {
  226.                         // 税率と計算ルールが取得できないときは商品データにデフォルト値をセットする。
  227.                         $rps[$i]['tax'] = 1.0 $default_tax_rate 100;
  228.                         $rps[$i]['calc_rule'] = $calc_rule$default_rounding_type_id ];
  229.                     }
  230.                 }
  231.                 // 丸めロジックは全商品共通
  232.                 $rps[$i]['calc_rule'] = $calc_rule$default_rounding_type_id ];
  233.             }
  234.             $this->_rp $rps;
  235.             //log_info( print_r($rps,true));
  236.             $_SESSION['ec_save_pr_id'] = $id;   // 現在の商品id をセッションに保持
  237.         }
  238.         return $this->render("Block/hsd_related_product42.twig",
  239.             [
  240.                 'title' => $this->_title,
  241.                 'max_count' => $this->_show_count,
  242.                 'rp_count' => count($this->_rp),
  243.                 'hsd_related_product' => $this->_rp,
  244.                 'show_price' => $this->_show_price,
  245.                 'show_type' => $this->_show_type,
  246.                 'pagination' => $this->_pagination,
  247.                 'navbuttons' => $this->_navbuttons,
  248.                 'showloop' => $this->_showloop,
  249.                 'from_id' => $this->_save_from_id,
  250.                 'from_product_name' => $this->_save_from_product_name,
  251.                 'to_id' => $this->_save_to_id,
  252.                 'to_product_name' => $this->_save_to_product_name,
  253.                 'calc_rule' => $this->_calc_rule
  254.                 //'tax' => $this->_tax
  255.             ] );
  256.     }
  257. }