<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
*
* http://www.ec-cube.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Customize\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Routing\Annotation\Route;
use Eccube\Controller\TopController as BaseController;
use Customize\Repository\ProductRepository;
use Eccube\Form\Type\SearchProductType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Form\FormFactoryInterface;
use Eccube\Form\Type\AddCartType;
class TopController extends BaseController
{
protected $productRepository;
protected $formFactory;
// コンストラクタで ProductRepository を注入
public function __construct(
ProductRepository $productRepository,
FormFactoryInterface $formFactory
)
{
$this->productRepository = $productRepository;
$this->formFactory = $formFactory;
}
/**
* @Route("/", name="homepage", methods={"GET"})
* @Template("index.twig")
*/
public function index(): array
{
// 新着タグ商品取得
$Products_new = $this->findProductsWithForms(1); // タグID 1 = 新着
$Products_semi = $this->findProductsWithForms(2); // タグID 2 = 準新作
$forms = array_merge($Products_new['forms'], $Products_semi['forms']);
// カテゴリ確認ログ出力
foreach ($Products_new['products'] as $Product) {
/** @var \Eccube\Entity\ProductCategory $ProductCategory */
foreach ($Product->getProductCategories() as $ProductCategory) {
$Category = $ProductCategory->getCategory();
if ($Category) {
log_info('[' . $Product->getId() . '] カテゴリ: ' . $Category->getName());
} else {
log_info('[' . $Product->getId() . '] カテゴリ情報なし');
}
}
}
return array_merge(parent::index(), [
'Products_new' => $Products_new['products'],
'Products_semi' => $Products_semi['products'],
'forms_new' => $Products_new['forms'],
'forms_semi' => $Products_semi['forms'],
]);
}
/**
* findByFixedTag() を用いて商品を取得し、カートフォームを適用
*/
private function findProductsWithForms(int $tagId)
{
// `findByFixedTag()` を使用してタグ付き商品を取得
$products = $this->productRepository->findByFixedTag($tagId);
// 商品IDリストを取得
$ids = array_map(fn($Product) => $Product->getId(), $products);
$ProductsAndClassCategories = $this->productRepository->findProductsWithSortedClassCategories($ids, 'p.id');
// カートフォーム作成
$forms = [];
foreach ($products as $Product) {
$builder = $this->formFactory->createNamedBuilder(
'',
AddCartType::class,
null,
[
'product' => $ProductsAndClassCategories[$Product->getId()],
'allow_extra_fields' => true,
]
);
$addCartForm = $builder->getForm();
$forms[$Product->getId()] = $addCartForm->createView();
}
return [
'products' => $ProductsAndClassCategories,
'forms' => $forms,
];
}
}