<?php
declare(strict_types=0);
/*
* WellCommerce Foundation
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>, Adrian Potepa <adrian@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\OrderBundle\EventListener;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WellCommerce\Bundle\AppBundle\Entity\Client;
use WellCommerce\Bundle\CoreBundle\DependencyInjection\AbstractServiceSubscriber;
use WellCommerce\Bundle\CoreBundle\Helper\Router\RouterHelper;
use WellCommerce\Bundle\CoreBundle\Helper\Translator\TranslatorHelper;
use WellCommerce\Bundle\OrderBundle\Entity\Coupon;
use WellCommerce\Bundle\OrderBundle\Entity\Order;
use WellCommerce\Component\Form\Elements\Fieldset\FieldsetInterface;
use WellCommerce\Component\Form\Event\FormEvent;
/**
* Class ClientCouponSubscriber
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ClientCouponSubscriber extends AbstractServiceSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
'admin.client.pre_form_init' => ['onClientAdminFormInit', 10],
];
}
public function onClientAdminFormInit(FormEvent $event)
{
$resource = $event->getResource();
if ($resource instanceof Client) {
$form = $event->getForm();
$builder = $event->getFormBuilder();
/** @var FieldsetInterface $fieldset */
$fieldset = $form->addChild($builder->getElement('nested_fieldset', [
'name' => 'coupons',
'label' => 'client.fieldset.coupons',
]));
$orders = $this->getClientOrdersWithCoupons($resource);
if ($orders->count() === 0) {
$fieldset->addChild($builder->getElement('tip', [
'tip' => $this->getTranslatorHelper()->trans('client.flash.no_coupons'),
]));
} else {
$html = '<ul class="changes-detailed">';
$orders->map(function (Order $order) use ($form, $builder, &$html) {
$coupon = $order->getCoupon();
$couponUrl = $this->getRouterHelper()->generateUrl('admin.coupon.edit', ['id' => $coupon->getId()]);
$orderUrl = $this->getRouterHelper()->generateUrl('admin.order.edit', ['id' => $order->getId()]);
$html .= '<li style="border-bottom: 1px solid #dfdfdf;list-style: none;margin-bottom: 15px;">';
$html .= ' <p><strong>' . $this->getTranslatorHelper()->trans('order.email.title') . '</strong> <a href="' . $orderUrl . '">' . $order->getNumber() . '</a></p>';
$html .= ' <p><strong>' . $this->getTranslatorHelper()->trans('client.label.used_coupon') . '</strong> <a href="' . $couponUrl . '">' . $coupon->getCode() . '</a></p>';
$html .= '</li>';
});
$html .= '</ul>';
$fieldset->addChild($builder->getElement('static_text', [
'text' => $html,
]));
}
}
}
private function getClientOrdersWithCoupons(Client $client): Collection
{
return $client->getOrders()->filter(function (Order $order) {
return $order->getCoupon() instanceof Coupon;
});
}
}