<?php
namespace Plugin\TeikiOrder42\Form\Extension;
use Eccube\Form\Type\AddCartType;
use Eccube\Entity\Product;
use Eccube\Repository\ProductRepository;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class AddCartTypeExtension extends AbstractTypeExtension
{
private $productRepository;
/**
* @var \Eccube\Entity\Product
*/
protected $Product = null;
/**
* @var SessionInterface
*/
protected $session;
public function __construct(
ProductRepository $productRepository,
ContainerInterface $container,
SessionInterface $session
){
$this->productRepository = $productRepository;
$this->container = $container;
$this->session = $session;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* @var $Product \Eccube\Entity\Product */
$Product = $options['product'];
$this->Product = $Product;
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
$TEIKI_PRODUCT_ID = $this->container->getParameter('TEIKI_PRODUCT_ID');
if ($form->get('product_id')->getData() == $TEIKI_PRODUCT_ID) {
$timestamp = time();
//$timestamp = strtotime("2024-3-10");
// 前年4月号〜今月号までをプルダウンで表示
// 今月号を取得 10日以降なら次月号
$day = date('j', $timestamp);
$start_month = '+4 month';
if ($day >= 10) {
$start_month = '+5 month';
}
//$start_book = date('Y年n月号', strtotime(+ $mon1 .' month', $timestamp));
$start_book = date('Y年n月号', strtotime($start_month, $timestamp));
// 前年4月号を取得
$month = date('n', $timestamp);
$end_month = '-1 year';
if ($month < 4) {
$end_month = '-2 year';
}
$end_date = date("Y-4-01", strtotime($end_month));
$end_timestamp = strtotime($end_date);
$end_book = date('Y年n月号', $end_timestamp);
$Product = $this->productRepository->find($TEIKI_PRODUCT_ID);
$Choices = $Product->getClassCategories1AsFlip();
arsort($Choices);
$change_choices = array_flip(array_keys($Choices));
if (array_key_exists($start_book, $change_choices) == false) {
$change_choices[$start_book] = 0;
}
if ($this->session->has('_security_admin')) {
$Choices = array_slice($Choices, $change_choices[$start_book]);
} else {
$Choices = array_slice($Choices, $change_choices[$start_book], $change_choices[$end_book] - $change_choices[$start_book] + 1);
}
$classcategory_id1 = $form['classcategory_id1'];
$options1 = $classcategory_id1->getConfig()->getOptions();
$options1['choices'] = ['common.select' => '__unselected'] + $Choices;
$form->add('classcategory_id1', ChoiceType::class, $options1);
}
});
}
/**
* {@inheritdoc}
*/
public function getExtendedType()
{
return AddCartType::class;
}
/**
* Return the class of the type being extended.
*/
public static function getExtendedTypes(): iterable
{
return [AddCartType::class];
}
}