<?php
namespace App\Controller;
use App\Entity\Product;
use App\Entity\ProductCategory;
use App\Form\ProductType;
use App\Repository\ProductRepository;
use App\Repository\CategoryRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/product')]
class ProductController extends AbstractController
{
/**
* サービスパラメータからボタンラベルやProduct情報に関連するパラメータを取得します。
*
* @return array ボタンラベルやProduct情報に関連するテンプレート用のラベル配列
*/
private function getTemplateLabels(): array
{
// services.yaml labels配列を一括取得
return $this->getParameter('labels');
}
/**
* 指定された Product エンティティにラベルを適用した ProductType フォームを生成します。
*
* @param Product $product フォームの対象となる Product エンティティ
* @return \Symfony\Component\Form\FormInterface ラベルが適用された ProductType フォームインスタンス
*/
private function createProductForm(Product $product): \Symfony\Component\Form\FormInterface
{
// ラベルを取得
$labels = $this->getParameter('labels');
// フォームを作成してラベルを渡す
return $this->createForm(ProductType::class, $product, [
'labels' => $labels,
]);
}
/**
* 商品一覧画面を表示します。
*
* @param ProductRepository $productRepository Product エンティティリポジトリ
* @return Response 商品一覧ページのレスポンス
*/
#[Route('/', name: 'app_product_index', methods: ['GET'])]
public function index(ProductRepository $productRepository): Response
{
return $this->render(
'product/index.html.twig',
array_merge(
[
'products' => $productRepository->findAll(),
],
$this->getTemplateLabels()
)
);
}
/**
* 新規商品を追加する画面を表示し、フォーム送信時にデータを保存します。
*
* @param Request $request HTTPリクエストオブジェクト
* @param CategoryRepository $categoryRepository Category エンティティリポジトリ
* @param EntityManagerInterface $entityManager エンティティマネージャ
* @return Response 新規商品追加ページまたは商品一覧ページのレスポンス
*/
#[Route('/new', name: 'app_product_new', methods: ['GET', 'POST'])]
public function new(
Request $request,
CategoryRepository $categoryRepository,
EntityManagerInterface $entityManager
): Response {
$product = new Product();
// 共通関数でフォームを作成
$form = $this->createProductForm($product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$selectedCategoryIds = $form->get('categories')->getData();
// Productを保存
$entityManager->persist($product);
$entityManager->flush();
// カテゴリリレーションを構築
foreach ($selectedCategoryIds as $categoryId) {
$category = $categoryRepository->find($categoryId);
if ($category) {
$productCategory = new ProductCategory();
$productCategory->setProduct($product);
$productCategory->setCategory($category);
$entityManager->persist($productCategory);
}
}
$entityManager->flush();
return $this->redirectToRoute('app_product_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm(
'product/new.html.twig',
array_merge(
[
'product' => $product,
'form' => $form,
],
$this->getTemplateLabels()
)
);
}
// /**
// * 商品詳細を表示します。
// *
// * @param int $id 商品のID
// * @param ProductRepository $productRepository Product エンティティリポジトリ
// * @return Response 商品詳細ページのレスポンス
// */
// #[Route('/{id}', name: 'app_product_show', methods: ['GET'])]
// public function show(int $id, ProductRepository $productRepository): Response
// {
// // 商品を取得
// $product = $productRepository->findProductDetailsWithImages($id);
// // 商品が見つからなかった場合、カスタムエラーページを表示
// if (!$product) {
// return $this->render('error.html.twig', [
// 'product_not_found' => $this->getParameter('labels')['product_not_found']
// ]);
// }
// // 商品が見つかった場合、商品詳細ページを表示
// return $this->render(
// 'product/show.html.twig',
// array_merge(
// [
// 'product' => $product,
// ],
// $this->getTemplateLabels()
// )
// );
// }
/**
* 商品編集画面を表示し、フォーム送信時にデータを更新します。
*
* @param int $id 商品のID
* @param Request $request HTTPリクエストオブジェクト
* @param ProductRepository $productRepository Product エンティティリポジトリ
* @param CategoryRepository $categoryRepository Category エンティティリポジトリ
* @param EntityManagerInterface $entityManager エンティティマネージャ
* @return Response 商品編集ページまたは商品一覧ページのレスポンス
*/
#[Route('/{id}/edit', name: 'app_product_edit', methods: ['GET', 'POST'])]
public function edit(
int $id,
Request $request,
ProductRepository $productRepository,
CategoryRepository $categoryRepository,
EntityManagerInterface $entityManager
): Response {
// $product = $productRepository->find($id);
// 商品を取得
$product = $productRepository->findProductDetailsWithImages($id);
// 商品が見つからなかった場合、カスタムエラーページを表示
if (!$product) {
return $this->render('error.html.twig', [
'product_not_found' => $this->getParameter('labels')['product_not_found']
]);
}
$price02Values = $product->getPrice02();
$form = $this->createForm(ProductType::class, $product, [
'labels' => $this->getTemplateLabels(),
'price02_initial' => isset($price02Values[0]) ? $price02Values[0] : 0 // 初期値を設定
]);
$form->handleRequest($request);
// 商品画像のリストを取得
$productImages = $product->getProductImages();
// // $price02の値を取得
// $price02Values = $product->getPrice02();
// dump('edit関数',$price02Values);
// die;
if ($form->isSubmitted() && $form->isValid()) {
// 現在のProductCategoryリレーションを削除
// foreach ($product->getProductCategories() as $existingProductCategory) {
// $entityManager->remove($existingProductCategory);
// }
$newPrice02 = $form->get('price02')->getData();
foreach ($product->getProductClasses() as $ProductClass) {
$ProductClass->setPrice02($newPrice02);
}
$entityManager->flush();
// 新しいカテゴリリレーションを追加
$selectedCategoryIds = $form->get('categories')->getData();
foreach ($selectedCategoryIds as $categoryId) {
$category = $categoryRepository->find($categoryId);
if ($category) {
$productCategory = new ProductCategory();
$productCategory->setProduct($product);
$productCategory->setCategory($category);
$entityManager->persist($productCategory);
}
}
$entityManager->flush();
return $this->redirectToRoute('app_product_index');
}
return $this->render(
'product/edit.html.twig',
array_merge(
[
'product' => $product,
'form' => $form->createView(),
// 画像リストをテンプレートに渡す
'productImages' => $productImages,
// ★
'price02Values' => $price02Values,
],
$this->getTemplateLabels()
)
);
}
/**
* 商品を削除します。
*
* @param int $id 商品のID
* @param Request $request HTTPリクエストオブジェクト
* @param ProductRepository $productRepository Product エンティティリポジトリ
* @param EntityManagerInterface $entityManager エンティティマネージャ
* @return Response 商品一覧ページへのリダイレクトレスポンス
*/
#[Route('/{id}', name: 'app_product_delete', methods: ['POST'])]
public function delete(
int $id,
Request $request,
ProductRepository $productRepository,
EntityManagerInterface $entityManager
): Response {
$product = $productRepository->find($id);
// 商品が見つからなかった場合、カスタムエラーページを表示
if (!$product) {
// throw $this->createNotFoundException('登録商品はありません');
return $this->render('error.html.twig', [
'product_not_found' => $this->getParameter('labels')['product_not_found']
]);
}
if ($this->isCsrfTokenValid('delete' . $product->getId(), $request->request->get('_token'))) {
$entityManager->remove($product);
$entityManager->flush();
}
return $this->redirectToRoute('app_product_index', [], Response::HTTP_SEE_OTHER);
}
}