<?php

namespace Dywee\OrderBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Dywee\CoreBundle\Model\ProductInterface;
use Dywee\ProductBundle\Entity\Product;

/**
 * OrderElement
 *
 * @ORM\Table(name="offer_elements")
 * @ORM\Entity(repositoryClass="Dywee\OrderBundle\Repository\OrderElementRepository")
 */
class OfferElement
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Dywee\OrderBundle\Entity\Offer", inversedBy="offerElements")
     * @ORM\JoinColumn(nullable=false)
     */
    private $offer;

    /**
     * @ORM\ManyToOne(targetEntity="Dywee\CoreBundle\Model\ProductInterface")
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;

    /**
     * @var integer
     *
     * @ORM\Column(name="quantity", type="smallint")
     */
    private $quantity = 1;

    /**
     * @var float
     *
     * @ORM\Column(name="unitPrice", type="float")
     */
    private $unitPrice;

    /**
     * @var float
     *
     * @ORM\Column(name="TotalPrice", type="float")
     */
    private $totalPrice;

    /**
     * @var integer
     *
     * @ORM\Column(name="locationCoeff", type="float")
     */
    private $locationCoeff = 1;

    /**
     * @var float
     *
     * @ORM\Column(name="discountRate", type="float")
     */
    private $discountRate = 0;

    /**
     * @var float
     *
     * @ORM\Column(name="discountValue", type="float")
     */
    private $discountValue = 0;

    /**
     * @var integer
     *
     * @ORM\Column(name="duration", type="smallint")
     */
    private $duration = 1;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="beginAt", type="datetime", nullable=true)
     */
    private $beginAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="endAt", type="datetime", nullable=true)
     */
    private $endAt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set quantity
     *
     * @param integer $quantity
     *
     * @return OfferElement
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    /**
     * Get quantity
     *
     * @return integer
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * Set unitPrice
     *
     * @param float $unitPrice
     *
     * @return OfferElement
     */
    public function setUnitPrice($unitPrice)
    {
        $this->unitPrice = $unitPrice;

        return $this;
    }

    /**
     * Get unitPrice
     *
     * @return float
     */
    public function getUnitPrice()
    {
        return $this->unitPrice;
    }

    /**
     * Set totalPrice
     *
     * @param float $totalPrice
     *
     * @return OfferElement
     */
    public function setTotalPrice($totalPrice)
    {
        $this->totalPrice = $totalPrice;

        return $this;
    }

    /**
     * Get totalPrice
     *
     * @return float
     */
    public function getTotalPrice()
    {
        return $this->totalPrice;
    }

    /**
     * Set offer
     *
     * @param \Dywee\OrderBundle\Entity\Offer $offer
     *
     * @return OfferElement
     */
    public function setOffer(\Dywee\OrderBundle\Entity\Offer $offer)
    {
        $this->offer = $offer;

        return $this;
    }

    /**
     * Get offer
     *
     * @return \Dywee\OrderBundle\Entity\Offer
     */
    public function getOffer()
    {
        return $this->offer;
    }

    /**
     * Set product
     *
     * @param ProductInterface $product
     *
     * @return OfferElement
     */
    public function setProduct(ProductInterface $product)
    {
        $this->product = $product;
        $this->setUnitPrice($product->getPrice());

        $this->calculateTotalPrice();

        return $this;
    }

    /**
     * @return $this
     */
    public function calculateTotalPrice()
    {
        $price = $this->getUnitPrice() * $this->getQuantity() * $this->getLocationCoeff();
        $price -= $this->getDiscountValue();
        $this->setTotalPrice($price);

        return $this;
    }

    /**
     * Get product
     *
     * @return ProductInterface
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * Set locationCoeff
     *
     * @param integer $locationCoeff
     *
     * @return OfferElement
     */
    public function setLocationCoeff($locationCoeff)
    {
        $this->locationCoeff = $locationCoeff;

        $this->calculateTotalPrice();

        return $this;
    }

    /**
     * Get locationCoeff
     *
     * @return integer
     */
    public function getLocationCoeff()
    {
        return $this->locationCoeff;
    }

    /**
     * Set discountRate
     *
     * @param float $discountRate
     *
     * @return OfferElement
     */
    public function setDiscountRate($discountRate, $fromValue = false)
    {
        $this->discountRate = $discountRate;

        if ($this->getTotalPrice() > 0 && $fromValue == false && $discountRate > 0) {
            $this->setDiscountValue(($this->getTotalPrice() / $this->discountRate), true);
        }

        return $this;
    }

    /**
     * Get discountRate
     *
     * @return float
     */
    public function getDiscountRate()
    {
        return $this->discountRate;
    }

    /**
     * Set discountValue
     *
     * @param float $discountValue
     *
     * @return OfferElement
     */
    public function setDiscountValue($discountValue, $fromRate = false)
    {
        $this->discountValue = $discountValue;

        if ($this->getTotalPrice() > 0) {
            if ($fromRate == false)
                $this->setDiscountRate(($this->discountValue / $this->getTotalPrice()), true);

            $this->calculateTotalPrice();
        }

        return $this;
    }

    /**
     * Get discountValue
     *
     * @return float
     */
    public function getDiscountValue()
    {
        return $this->discountValue;
    }

    /**
     * Set duration
     *
     * @param integer $duration
     *
     * @return OfferElement
     */
    public function setDuration($duration)
    {
        $this->duration = $duration;

        $data = [
            0  => 1,
            1  => 1,
            2  => 1.9,
            3  => 2.7,
            4  => 3.2,
            5  => 3.6,
            6  => 3.8,
            7  => 4,
            8  => 4.5,
            9  => 5,
            10 => 5.5,
            11 => 6,
            12 => 6.5,
            13 => 7,
            14 => 7.5,
            15 => 7.9,
            16 => 8.3,
            17 => 8.7,
            18 => 9.1,
            19 => 9.5,
            20 => 9.9,
            21 => 10.3,
            22 => 10.6,
            23 => 10.9,
            24 => 11.2,
            25 => 11.5,
            26 => 11.8,
            27 => 12.1,
            28 => 12.4,
            29 => 12.7,
            30 => 13,
        ];

        return $this->setLocationCoeff($data[$duration]);
    }

    /**
     * Get duration
     *
     * @return integer
     */
    public function getDuration()
    {
        return $this->duration;
    }

    /**
     * Set beginAt
     *
     * @param \DateTime $beginAt
     *
     * @return OfferElement
     */
    public function setBeginAt(\DateTime $beginAt = null)
    {
        $this->beginAt = $beginAt;
        $this->timeInterval();

        return $this;
    }

    /**
     * Get beginAt
     *
     * @return \DateTime
     */
    public function getBeginAt()
    {
        return $this->beginAt;
    }

    /**
     * Set endAt
     *
     * @param \DateTime $endAt
     *
     * @return OfferElement
     */
    public function setEndAt(\DateTime $endAt)
    {
        $this->endAt = $endAt;
        $this->timeInterval();

        return $this;
    }

    /**
     * Get endAt
     *
     * @return \DateTime
     */
    public function getEndAt()
    {
        return $this->endAt;
    }

    public function timeInterval()
    {
        if ($this->getBeginAt() && $this->getEndAt()) {
            $int = (int)$this->getBeginAt()->diff($this->getEndAt(), true)->format('%a');
            $this->setDuration($int + 1);
        }
    }
}


<?php

namespace Dywee\OrderBundle\Controller;

use Dywee\OrderBundle\Entity\BaseOrder;
use Dywee\OrderBundle\Entity\BaseOrderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class OrderAdminController extends Controller
{
    /**
     * @param string $state
     * @param int    $limit
     * @param int    $offset
     *
     * @return Response
     */
    public function listAction($state = BaseOrder::STATE_IN_PROGRESS, $limit = 10, $offset = 0)
    {
        $or = $this->getDoctrine()->getManager()->getRepository('DyweeOrderBundle:BaseOrder');

        $os = $or->findBy(
            ['state' => $state],
            ['createdAt' => 'desc'],
            $limit,
            $offset
        );

        return $this->render('DyweeOrderBundle:Admin:orderTableRaw.html.twig', ['orderList' => $os]);
    }

    public function viewAction(BaseOrder $order)
    {
        return $this->render('DyweeOrderBundle:Order:view.html.twig', ['order' => $order]);
    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Handler;

use RevisionTen\Forms\Command\FormCreateCommand;
use RevisionTen\Forms\Event\FormCreateEvent;
use RevisionTen\Forms\Model\Form;
use RevisionTen\CQRS\Interfaces\AggregateInterface;
use RevisionTen\CQRS\Interfaces\CommandInterface;
use RevisionTen\CQRS\Interfaces\EventInterface;
use RevisionTen\CQRS\Interfaces\HandlerInterface;
use RevisionTen\CQRS\Message\Message;

final class FormCreateHandler extends FormBaseHandler implements HandlerInterface
{
    /**
     * {@inheritdoc}
     *
     * @var Form $aggregate
     */
    public function execute(CommandInterface $command, AggregateInterface $aggregate): AggregateInterface
    {
        $payload = $command->getPayload();

        // Change Aggregate state.
        // Get each public property from the aggregate and update it If a new value exists in the payload.
        $reflect = new \ReflectionObject($aggregate);
        foreach ($reflect->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
            $propertyName = $property->getName();
            if (array_key_exists($propertyName, $payload)) {
                $aggregate->{$propertyName} = $payload[$propertyName];
            }
        }

        return $aggregate;
    }

    /**
     * {@inheritdoc}
     */
    public static function getCommandClass(): string
    {
        return FormCreateCommand::class;
    }

    /**
     * {@inheritdoc}
     */
    public function createEvent(CommandInterface $command): EventInterface
    {
        return new FormCreateEvent($command);
    }

    /**
     * {@inheritdoc}
     */
    public function validateCommand(CommandInterface $command, AggregateInterface $aggregate): bool
    {
        $payload = $command->getPayload();

        if (0 !== $aggregate->getVersion()) {
            $this->messageBus->dispatch(new Message(
                'Aggregate already exists',
                CODE_CONFLICT,
                $command->getUuid(),
                $command->getAggregateUuid()
            ));

            return false;
        }

        if (empty($payload['title'])) {
            $this->messageBus->dispatch(new Message(
                'You must enter a title',
                CODE_BAD_REQUEST,
                $command->getUuid(),
                $command->getAggregateUuid()
            ));

            return false;
        }

        return true;
    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Handler;

use RevisionTen\Forms\Command\FormCloneCommand;
use RevisionTen\Forms\Event\FormCloneEvent;
use RevisionTen\Forms\Model\Form;
use RevisionTen\CQRS\Interfaces\AggregateInterface;
use RevisionTen\CQRS\Interfaces\CommandInterface;
use RevisionTen\CQRS\Interfaces\EventInterface;
use RevisionTen\CQRS\Interfaces\HandlerInterface;
use RevisionTen\CQRS\Message\Message;

final class FormCloneHandler extends FormBaseHandler implements HandlerInterface
{
    /**
     * {@inheritdoc}
     *
     * @var Form $aggregate
     */
    public function execute(CommandInterface $command, AggregateInterface $aggregate): AggregateInterface
    {
        $payload = $command->getPayload();

        $originalUuid = $payload['originalUuid'];
        $originalVersion = $payload['originalVersion'];

        if ($this->aggregateFactory) {
            // Build original aggregate and use its state as a starting point.
            /** @var Form $originalAggregate */
            $originalAggregate = $this->aggregateFactory->build($originalUuid, Form::class, (int) $originalVersion);

            // Override title.
            $originalAggregate->title .= ' duplicate';

            // Override aggregate meta info.
            $originalAggregate->setUuid($aggregate->getUuid());
            $originalAggregate->setVersion($aggregate->getVersion() ?? 1);
            $originalAggregate->setStreamVersion($aggregate->getStreamVersion() ?? 1);
            $originalAggregate->setSnapshotVersion(null);
            $originalAggregate->setCreated(new \DateTimeImmutable());
            $originalAggregate->setModified(new \DateTimeImmutable());
            $originalAggregate->setHistory([]);

            $aggregate = $originalAggregate;
        }

        return $aggregate;
    }

    /**
     * {@inheritdoc}
     */
    public static function getCommandClass(): string
    {
        return FormCloneCommand::class;
    }

    /**
     * {@inheritdoc}
     */
    public function createEvent(CommandInterface $command): EventInterface
    {
        return new FormCloneEvent($command);
    }

    /**
     * {@inheritdoc}
     */
    public function validateCommand(CommandInterface $command, AggregateInterface $aggregate): bool
    {
        $payload = $command->getPayload();

        if (0 !== $aggregate->getVersion()) {
            $this->messageBus->dispatch(new Message(
                'Aggregate already exists',
                CODE_CONFLICT,
                $command->getUuid(),
                $command->getAggregateUuid()
            ));

            return false;
        }

        if (empty($payload['originalUuid']) || empty($payload['originalVersion'])) {
            $this->messageBus->dispatch(new Message(
                'You must provide an original uuid and version',
                CODE_BAD_REQUEST,
                $command->getUuid(),
                $command->getAggregateUuid()
            ));

            return false;
        }

        return true;
    }
}


<?php
/**
 * MIT License <https://opensource.org/licenses/mit>
 *
 * Copyright (c) 2015 Kerem Güneş
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
declare(strict_types=1);

namespace froq\util\traits;

/**
 * One run trait.
 * @package froq\util\traits
 * @object  froq\util\traits\OneRunTrait
 * @author  Kerem Güneş <k-gun@mail.com>
 * @since   3.0
 */
trait OneRunTrait
{
    /**
     * Run.
     * @var bool
     */
    private static $___run = false;

    /**
     * Check run.
     * @param  \Exception $exception
     * @return void
     * @throws \Exception
     */
    public final function ___checkRun(\Exception $exception): void
    {
        if (self::$___run) {
            throw $exception;
        }
        self::$___run = true;
    }
}


<?php

namespace RevisionTen\Forms\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class FormsExtension extends Extension implements PrependExtensionInterface
{
    /**
     * Merge all forms configs in reverse order.
     * First (user defined) config is most important.
     *
     * @param array $configs
     *
     * @return array
     */
    private static function mergeFormsConfig(array $configs): array
    {
        $configs = array_reverse($configs);
        $config = [];
        foreach ($configs as $subConfig) {
            $config = array_merge($config, $subConfig);
        }

        return $config;
    }

    public function load(array $configs, ContainerBuilder $container)
    {
        $config = self::mergeFormsConfig($configs);

        $container->setParameter('forms', $config);
    }

    public function prepend(ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('config.yaml');

        $configs = $container->getExtensionConfig('forms');

        $loadEasyAdminConfig = true;
        foreach ($configs as $config) {
            if (isset($config['load_easyadmin_config'])) {
                $loadEasyAdminConfig = $config['load_easyadmin_config'];
                break;
            }
        }

        if ($loadEasyAdminConfig) {
            // Load EasyAdmin configuration.
            $loader->load('easyadmin.yml');
        }

        if (empty($configs) || (count($configs) === 1 && empty($configs[0]))) {
            // Load default forms bundle config.
            $loader->load('forms.yaml');
        }
    }
}


<?php

namespace Railken\Amethyst\Schemas;

use Railken\Amethyst\Managers\TaxonomyManager;
use Railken\Lem\Attributes;
use Railken\Lem\Contracts\EntityContract;
use Railken\Lem\Schema;

class TaxonomableSchema extends Schema
{
    /**
     * Get all the attributes.
     *
     * @var array
     */
    public function getAttributes()
    {
        return [
            Attributes\IdAttribute::make(),
            Attributes\TextAttribute::make('relation')
                ->setDefault(function (EntityContract $entity) {
                    return 'default';
                }),
            Attributes\BelongsToAttribute::make('taxonomy_id')
                ->setRelationName('taxonomy')
                ->setRelationManager(TaxonomyManager::class)
                ->setRequired(true),
            Attributes\EnumAttribute::make('taxonomable_type', app('amethyst')->getMorphListable('taxonomable', 'taxonomable'))
                ->setRequired(true),
            Attributes\MorphToAttribute::make('taxonomable_id')
                ->setRelationKey('taxonomable_type')
                ->setRelationName('taxonomable')
                ->setRelations(app('amethyst')->getMorphRelationable('taxonomable', 'taxonomable'))
                ->setRequired(true),
            Attributes\CreatedAtAttribute::make(),
            Attributes\UpdatedAtAttribute::make(),
            Attributes\DeletedAtAttribute::make(),
        ];
    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Handler;

use RevisionTen\Forms\Model\Form;
use RevisionTen\CQRS\Handler\Handler;

abstract class FormBaseHandler extends Handler
{
    /**
     * Checks of the provided item matches or its child items.
     *
     * @param array    $item
     * @param string   $itemUuid
     * @param callable $callable
     * @param array    $collection
     *
     * @return mixed
     */
    private static function getMatching(array &$item, string $itemUuid, callable $callable = null, array &$collection)
    {
        // Return true if this item is the one we are looking for.
        if (isset($item['uuid']) && $item['uuid'] === $itemUuid) {
            if ($callable) {
                $callable($item, $collection);
            }

            return $item;
        }

        // Look in child items.
        if (isset($item['items']) && \is_array($item['items'])) {
            foreach ($item['items'] as &$subItem) {
                if ($c = self::getMatching($subItem, $itemUuid, $callable, $item['items'])) {
                    return $c;
                }
            }
        }

        return false;
    }

    /**
     * Executes a function on a matching item.
     *
     * @param Form     $aggregate
     * @param string   $itemUuid
     * @param callable $callable
     */
    public static function onItem(Form $aggregate, string $itemUuid, callable $callable): void
    {
        foreach ($aggregate->items as &$item) {
            if ($c = self::getMatching($item, $itemUuid, $callable, $aggregate->items)) {
                return;
            }
        }
    }

    /**
     * Gets a item by its uuid from the aggregate.
     *
     * @param Form   $aggregate
     * @param string $itemUuid
     *
     * @return mixed
     */
    public static function getItem(Form $aggregate, string $itemUuid)
    {
        foreach ($aggregate->items as &$item) {
            if ($c = self::getMatching($item, $itemUuid, null, $aggregate->items)) {
                return $c;
            }
        }

        return null;
    }
}


<?php

namespace Dywee\OrderBundle\Service;

use Doctrine\ORM\EntityManager;
use Dywee\OrderBundle\Entity\BaseOrder;
use Dywee\OrderBundle\Entity\Shipment;
use Dywee\OrderBundle\Entity\ShipmentElement;
use Dywee\OrderBundle\Entity\ShipmentRule;

class ShipmentRuleManager
{
    /** @var \Doctrine\ORM\EntityRepository|\Dywee\OrderBundle\Repository\ShipmentRuleRepository */
    protected $repository;

    /** @var  BaseOrder */
    protected $order;

    /**
     * ShipmentRuleManager constructor.
     *
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->repository = $em->getRepository(ShipmentRule::class);
    }

    /**
     * @param BaseOrder $order
     *
     * @return bool
     */
    public function handleOrder(BaseOrder $order)
    {
        $this->order = $order;

        $mustBeUnique = $this->handleUniqProduct();
        $this->handleQuantity();
        $this->handleWeight();

        if (!$mustBeUnique) {
            $this->reconciliateShipmentElements();
        }

        return true;
    }

    protected function reconciliateShipmentElements()
    {

    }

    protected function ruleOnWeight()
    {

    }

    /**
     * @param $valueToCheck
     * @param $operator
     * @param $value
     *
     * @return bool
     */
    protected function checkRule($valueToCheck, $operator, $value)
    {
        switch ($operator) {
            case '<':
                return $valueToCheck < $value;
            case '<=':
                return $valueToCheck <= $value;
            case '===';
            case '==';
            case '=';
                return $valueToCheck === $value;
            case '>':
                return $valueToCheck > $value;
            case '>=':
                return $valueToCheck >= $value;
            default:
                return false;
        }

    }

    protected function handleWeight()
    {

    }

    protected function handleQuantity()
    {
        /** @var ShipmentRule[] $rules */
        $rules = $this->repository->findForQuantityMax(['mappedKey' => 'quantity', 'operator' => '<']);

        if (count($rules) === 0) {
            return;
        }

        $max = 0;

        if (count($rules) === 1) {
            $max = $rules[0]->getValue();
        } else {
            foreach ($rules as $rule) {
                if ($rule->getValue() < $max) {
                    $max = $rule->getValue();
                }
            }
        }

        $shipmentToAdd = new Shipment();
        foreach ($this->order->getShipments() as $shipment) {
            if (!$shipment->getSendingIndex() || $shipment->getSendingIndex() === 1) {
                $shipmentToAdd = clone $shipment;
                break;
            }
        }

        foreach ($this->order->getShipments() as $shipment) {
            if ($shipment->countElements() > $max) {
                foreach ($shipment->getShipmentElements() as $shipmentElement) {
                    if ($shipmentElement->getQuantity() > $max) {
                        $rest = $shipmentElement->getQuantity() - $max;
                        $shipmentElement->setQuantity($max)->setWeight($shipmentElement->getProduct()->getWeight() * $max);
                        $shipment->canBeReconciliated();

                        while ($rest >= $max) {
                            $shipmentElementToAdd = new ShipmentElement();
                            $shipmentElementToAdd
                                ->setProduct($shipmentElement->getProduct())
                                ->setQuantity($max - $shipmentToAdd->countElements())
                                ->setWeight($shipmentElementToAdd->getProduct()->getWeight() * $max);
                            $shipmentToAdd->addShipmentElement($shipmentElementToAdd);
                            $shipmentToAdd->canBeReconciliated();
                            $rest -= $shipmentToAdd->countElements();
                            $this->order->addShipment($shipmentToAdd);
                            $shipmentToAdd = clone $shipment;
                        }

                        if ($rest > 0) {
                            $shipmentElementToAdd = clone $shipmentElement;
                            $shipmentElementToAdd
                                ->setProduct($shipmentElement->getProduct())
                                ->setQuantity($rest)
                                ->setWeight($shipmentElementToAdd->getProduct()->getWeight() * $rest);
                            $shipmentToAdd->addShipmentElement($shipmentElementToAdd);
                        }
                    }

                    if ($shipmentToAdd->countElements() === $max) {
                        $this->order->addShipment($shipmentToAdd);
                        $shipmentToAdd = clone $shipmentToAdd;
                    }
                }
            }

            //If the first manipulation does'nt resolve the rule
            if ($shipment->countElements() > $max) {
                $quantity = 0;
                foreach ($shipment->getShipmentElements() as $shipmentElement) {
                    $quantity += $shipmentElement->getQuantity();
                    if ($quantity > $max) {
                        $quantity = $shipmentElement->getQuantity();
                        $shipmentToAdd = new Shipment();
                    }
                }
            }
        }

        if ($shipmentToAdd->countElements() > 0) {
            $this->order->addShipment($shipmentToAdd);
        }
    }

    /**
     * @return bool
     */
    protected function handleUniqProduct()
    {
        $rule = $this->repository->findOneBy(['mappedKey' => 'product', 'operator' => '==', 'value' => '[self]']);

        if (!$rule) {
            return false;
        }

        // We link one and only one product to one shipment
        // TODO check why we have $product = null and if $product != null after that
        foreach ($this->order->getShipments() as $shipment) {
            $product = null;
            foreach ($shipment->getShipmentElements() as $shipmentElement) {
                if ($product !== null && $shipmentElement->getProduct() !== $product) {
                    $shipment->removeShipmentElement($shipmentElement);

                    $shipmentToAdd = new Shipment();
                    $shipmentToAdd->addShipmentElement($shipmentElement);
                }
            }
        }

        return true;
    }
}


<?php

namespace Gobline\Filter\Validator;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class Boolean extends AbstractValidator
{
    private $value;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        $this->resetMessages();

        $this->value = $value;

        if (!is_scalar($value)) {
            $this->addMessage();

            return false;
        }

        $value = (string) $value;

        if ($value !== '1' && $value !== '0' && $value !== '') {
            $this->addMessage();

            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageTemplates()
    {
        return ['The input is not valid'];
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageVariables()
    {
        return ['value' => $this->value];
    }
}


<?php

namespace Gobline\Filter\Sanitizer;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class LTrim implements SanitizerInterface
{
    private $chars;

    /**
     * @param string $chars
     */
    public function __construct($chars = ' ')
    {
        $this->chars = (string) $chars;
    }

    /**
     * {@inheritdoc}
     */
    public function sanitize($value)
    {
        if (!is_scalar($value)) {
            throw new \InvalidArgumentException('Unexpected type: '.gettype($value));
        }

        return ltrim($value, $this->chars);
    }
}


<?php

namespace Dywee\OrderBundle\Service;

use Dywee\CoreBundle\Model\ProductInterface;
use Dywee\OrderBundle\Entity\BaseOrder;
use Dywee\OrderBundle\Entity\OrderElement;

class OrderElementManager
{
    /**
     * @param BaseOrder        $order
     * @param ProductInterface $product
     * @param                  $quantity
     * @param int              $locationCoeff
     */
    public function addProduct(BaseOrder $order, ProductInterface $product, $quantity, $locationCoeff = 1)
    {
        $exist = false;
        // Check if the product has been ordered at least once
        foreach ($order->getOrderElements() as $key => $orderElement) {
            if ($orderElement->getProduct()->getId() === $product->getId()) {
                // If yes, we increment the quantity
                $orderElement->setQuantity($orderElement->getQuantity() + $quantity);
                if ($orderElement->getQuantity() <= 0) {
                    $order->removeOrderElement($orderElement);
                }
                $exist = $key;
                break;
            }
        }

        // If not, we add it
        if (!is_numeric($exist)) {
            $orderElement = new OrderElement();

            $orderElement->setProduct($product);
            $orderElement->setQuantity($quantity);
            $orderElement->setLocationCoeff($locationCoeff);
            $orderElement->setUnitPrice($product->getPrice());

            $order->addOrderElement($orderElement);
        }

        $order->forcePriceCalculation();
        $order->setMustRecalculShipments(true);
    }

    /**
     * @param BaseOrder        $order
     * @param ProductInterface $product
     * @param int              $quantity
     */
    public function removeProduct(BaseOrder $order, ProductInterface $product, int $quantity = 0)
    {
        if (!$quantity) {
            $this->addProduct($order, $product, -1 * $this->countProductQuantity($order, $product));
        } elseif($quantity < 0) {
            $this->addProduct($order, $product, $quantity);
        } else {
            $this->addProduct($order, $product, -1 * $quantity);
        }
    }

    public function updateProductQuantity(BaseOrder $order, ProductInterface $product, $quantity)
    {
        // Check if the product has been ordered at least once
        foreach ($order->getOrderElements() as $key => $orderElement) {
            if ($orderElement->getProduct()->getId() === $product->getId()) {
                // If yes, we increment the quantity
                $orderElement->setQuantity($quantity);

                $order->forcePriceCalculation();
                $order->setMustRecalculShipments(true);

                break;
            }
        }
    }

    /**
     * @param BaseOrder        $order
     * @param ProductInterface $product
     *
     * @return int
     */
    public function countProductQuantity(BaseOrder $order, ProductInterface $product)
    {
        foreach ($order->getOrderElements() as $orderElement) {
            if ($orderElement->getProduct()->getId() === $product->getId()) {
                return $orderElement->getQuantity();
            }
        }

        return 0;
    }
}


<?php

namespace Dywee\OrderBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Dywee\CoreBundle\Traits\TimeDelimitableEntity;
use Dywee\OrderBundle\Entity\BaseOrderInterface;
use Dywee\OrderBundle\Entity\ShipmentElement;
use Dywee\OrderBundle\Entity\ShippingMethod;
use Gedmo\Timestampable\Traits\TimestampableEntity;

/**
 * Shipment
 *
 * @ORM\Table(name="shipments")
 * @ORM\Entity(repositoryClass="Dywee\OrderBundle\Repository\ShipmentRepository")
 */
class Shipment
{

    const STATE_NOT_PREPARED = 'shipment.state.not_prepared';
    const STATE_PREPARING = 'shipment.state.preparing';
    const STATE_WAITING = 'shipment.state.waiting';
    const STATE_SHIPPING = 'shipment.state.shipping';
    const STATE_SHIPPED = 'shipment.state.shipped';
    const STATE_WAITING_CUSTOMER = 'shipment.state.waiting_customer';
    const STATE_ARRIVED = 'shipment.state.arrived';
    const STATE_RETURNED = 'shipment.state.returned';

    const MAIL_STEP_PREPARED = 'shipment.mail.prepared';
    const MAIL_STEP_SHIPPED = 'shipment.mail.shipped';
    const MAIL_STEP_ARRIVED = 'shipment.mail.arrived';

    use TimestampableEntity;
    use TimeDelimitableEntity;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(type="smallint", nullable=true)
     */
    private $sendingIndex;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $tracingInfos;

    /**
     * @var integer
     *
     * @ORM\Column(type="text", length=255)
     */
    private $status = self::STATE_NOT_PREPARED;

    /**
     * @ORM\OneToMany(targetEntity="ShipmentElement", mappedBy="shipment", cascade={"persist", "remove"})
     */
    private $shipmentElements;

    /**
     * @ORM\ManyToOne(targetEntity="Dywee\OrderBundle\Entity\BaseOrder", inversedBy="shipments")
     * @ORM\JoinColumn(nullable=true)
     */
    private $order;

    /**
     * @ORM\Column(type="smallint")
     */
    private $mailStep = 0;

    /**
     * @ORM\Column(name="weight", type="decimal", precision=10, scale=3)
     */
    private $weight = 0;

    /**
     * @ORM\ManyToOne(targetEntity="ShippingMethod")
     */
    private $shippingMethod;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set sendingIndex
     *
     * @param integer $sendingIndex
     *
     * @return Shipment
     */
    public function setSendingIndex($sendingIndex)
    {
        $this->sendingIndex = $sendingIndex;

        return $this;
    }

    /**
     * Get sendingIndex
     *
     * @return integer
     */
    public function getSendingIndex()
    {
        return $this->sendingIndex;
    }

    /**
     * Set tracingInfos
     *
     * @param string $tracingInfos
     *
     * @return Shipment
     */
    public function setTracingInfos($tracingInfos)
    {
        $this->tracingInfos = $tracingInfos;

        return $this;
    }

    /**
     * Get tracingInfos
     *
     * @return string
     */
    public function getTracingInfos()
    {
        return $this->tracingInfos;
    }

    /**
     * Set state
     *
     * @param integer $status
     *
     * @return Shipment
     */
    public function setStatus($status)
    {
        if ($status !== $this->status) {
            $this->status = $status;
            $this->setMailStep(0);
        }

        return $this;
    }

    /**
     * Get status
     *
     * @return integer
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->shipmentElements = new ArrayCollection();
    }

    /**
     * Add shipmentElements
     *
     * @param ShipmentElement $shipmentElements
     *
     * @return Shipment
     */
    public function addShipmentElement(ShipmentElement $shipmentElements)
    {
        $this->shipmentElements[] = $shipmentElements;
        $shipmentElements->setShipment($this);

        return $this;
    }

    /**
     * Remove shipmentElements
     *
     * @param ShipmentElement $shipmentElements
     */
    public function removeShipmentElement(ShipmentElement $shipmentElements)
    {
        $this->shipmentElements->removeElement($shipmentElements);
    }

    /**
     * Get shipmentElements
     *
     * @return \Doctrine\Common\Collections\Collection|ShipmentElement[]
     */
    public function getShipmentElements()
    {
        return $this->shipmentElements;
    }

    public function clearShipmentElements()
    {
        $this->shipmentElements = new ArrayCollection();

        return $this;
    }

    /**
     * Get order
     *
     * @return BaseOrderInterface
     */
    public function getOrder()
    {
        return $this->order;
    }

    /**
     * Set order
     *
     * @param BaseOrderInterface $order
     *
     * @return Shipment
     */
    public function setOrder(BaseOrderInterface $order = null)
    {
        $this->order = $order;

        return $this;
    }

    /**
     * Set weight
     *
     * @param float $weight
     *
     * @return Shipment
     */
    public function setWeight($weight)
    {
        $this->weight = $weight;

        return $this;
    }

    /**
     * Get weight
     *
     * @return float
     */
    public function getWeight()
    {
        return $this->weight;
    }

    public function calculWeight()
    {
        $weight = 0;
        foreach ($this->getShipmentElements() as $shipmentElement)
            $weight += $shipmentElement->getWeight();

        $this->setWeight($weight);
    }

    /**
     * Set mailStep
     *
     * @param int $mailStep
     *
     * @return Shipment
     */
    public function setMailStep($mailStep)
    {
        $this->mailStep = $mailStep;

        return $this;
    }

    /**
     * Get mailStep
     *
     * @return int
     */
    public function getMailStep()
    {
        return $this->mailStep;
    }

    /**
     * alias
     *
     * @param $date
     *
     * @return TimeDelimitableEntity
     */
    public function setDepartureAt($date)
    {
        return $this->setBeginAt($date);
    }

    /**
     * alias
     *
     * @return \DateTime
     */
    public function getDepartureAt()
    {
        return $this->getBeginAt();
    }

    /**
     * @return mixed
     */
    public function getShippingMethod()
    {
        return $this->shippingMethod;
    }

    /**
     * @param ShippingMethod $shippingMethod
     *
     * @return Shipment
     */
    public function setShippingMethod(ShippingMethod $shippingMethod)
    {
        $this->shippingMethod = $shippingMethod;

        return $this;
    }

    /**
     * @return bool
     */
    public function canBeReconciliated()
    {
        foreach ($this->getShipmentElements() as $element) {
            if ($element->canBeReconciliated()) {
                return true;
            }
        }

        return false;
    }

    /**
     * @return int
     */
    public function countElements()
    {
        $sum = 0;
        foreach ($this->getShipmentElements() as $shipmentElement) {
            $sum += $shipmentElement->getQuantity();
        }

        return $sum;
    }

    public function __clone()
    {
        $this->id = null;
        $this->shipmentElements = new ArrayCollection();
    }

}


<?php
/**
 * This file is part of Berlioz framework.
 *
 * @license   https://opensource.org/licenses/MIT MIT License
 * @copyright 2017 Ronan GIRON
 * @author    Ronan GIRON <https://github.com/ElGigi>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code, to the root.
 */

declare(strict_types=1);

namespace Berlioz\Config;

use Berlioz\Config\Exception\ConfigException;

/**
 * Class AbstractConfig.
 *
 * @package Berlioz\Config
 */
abstract class AbstractConfig implements ConfigInterface
{
    const TAG = '%';
    /** @var array Configuration */
    protected $configuration;
    /** @var array Default variables */
    protected $defaultVariables = ['best_framework'      => 'BERLIOZ',
                                   'php_version'         => PHP_VERSION,
                                   'php_version_id'      => PHP_VERSION_ID,
                                   'php_major_version'   => PHP_MAJOR_VERSION,
                                   'php_minor_version'   => PHP_MINOR_VERSION,
                                   'php_release_version' => PHP_RELEASE_VERSION,
                                   'php_sapi'            => PHP_SAPI,
                                   'system_os'           => PHP_OS];
    /** @var array User defined variables */
    private $userDefinedVariables = [];

    /**
     * AbstractConfig constructor.
     */
    public function __construct()
    {
        if ((version_compare(PHP_VERSION, '7.2.0') >= 0)) {
            $this->defaultVariables['system_os_family'] = PHP_OS_FAMILY;
        }
    }

    /**
     * PHP magic method __debugInfo().
     *
     * @return array
     */
    public function __debugInfo()
    {
        return [];
    }

    /////////////
    /// MERGE ///
    /////////////

    /**
     * @inheritdoc
     */
    public function merge(ConfigInterface ...$config)
    {
        foreach ($config as $aConfig) {
            $this->configuration = b_array_merge_recursive($this->configuration, $aConfig->original());
            $this->userDefinedVariables = array_replace($this->userDefinedVariables, $aConfig->getVariables());
        }

        return $this;
    }

    //////////////
    /// GETTER ///
    //////////////

    /**
     * @inheritdoc
     */
    public function original(): array
    {
        return $this->configuration ?? [];
    }

    /**
     * @inheritdoc
     */
    public function get(string $key = null, $default = null)
    {
        try {
            $value = $this->configuration;
            if (!is_null($key)) {
                $value = b_array_traverse_get($value, $key);

                if (is_null($value)) {
                    $value = $default;
                }
            }

            // Do replacement of variables names
            if (is_array($value)) {
                array_walk_recursive($value, [$this, 'replaceVariables']);
            } else {
                $this->replaceVariables($value);
            }

            return $value;
        } catch (\Exception $e) {
            throw new ConfigException(sprintf('Unable to get "%s" key in configuration file', $key));
        }
    }

    /**
     * @inheritdoc
     */
    public function has(string $key = null): bool
    {
        try {
            return !is_null(b_array_traverse_get($this->configuration, $key));
        } catch (\Exception $e) {
            return false;
        }
    }

    /////////////////
    /// VARIABLES ///
    /////////////////

    /**
     * @inheritdoc
     */
    public function setVariables(array $variables)
    {
        $this->userDefinedVariables = $variables;

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setVariable(string $name, $value)
    {
        $this->userDefinedVariables[$name] = $value;

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getVariables(): array
    {
        return $this->userDefinedVariables ?? [];
    }

    /**
     * @inheritdoc
     *
     * Some variables are already defined:
     *   - php_version
     *   - php_version_id
     *   - php_major_version
     *   - php_minor_version
     *   - php_release_version
     *   - php_sapi
     *   - system_os
     *   - system_os_family
     */
    public function getVariable(string $name, $default = null)
    {
        return $this->defaultVariables[$name] ??
               $this->userDefinedVariables[$name] ??
               $default;
    }

    /**
     * Replace variables.
     *
     * @param mixed $value
     *
     * @throws \Berlioz\Config\Exception\ConfigException
     */
    protected function replaceVariables(&$value)
    {
        if (!is_string($value)) {
            return;
        }

        // Variables
        $matches = [];
        if (preg_match_all(sprintf('/%1$s(?<var>[\w\-\.\,\s]+)%1$s/i', preg_quote(self::TAG)), $value, $matches, PREG_SET_ORDER) == 0) {
            return;
        }

        foreach ($matches as $match) {
            // Is variable ?
            if (is_null($subValue = $this->getVariable($match['var']))) {
                $subValue = $this->get($match['var']);
            }

            // Booleans
            if ($subValue === true) {
                $subValue = 'true';
            }
            if ($subValue === false) {
                $subValue = 'false';
            }

            $value = str_replace(sprintf('%2$s%1$s%2$s', $match['var'], self::TAG), $subValue, $value);
        }

        if (in_array($value, ['true', 'false'], true)) {
            $value = $value == 'true';
        } else {
            if (filter_var($value, FILTER_VALIDATE_INT) !== false) {
                $value = intval($value);
            } else {
                if (filter_var($value, FILTER_VALIDATE_FLOAT) !== false) {
                    $value = floatval($value);
                }
            }
        }

        $this->replaceVariables($value);
    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Form\Items;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

class EntityItem extends Item
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * EntityItem constructor.
     *
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $entityClasses = [];
        $metaData = $this->entityManager->getMetadataFactory()->getAllMetadata();

        /** @var ClassMetadata $entityMetaData */
        foreach ($metaData as $entityMetaData) {
            $namespace = $entityMetaData->namespace;
            $isAppNamespace = 'AppBundle\Entity' === $namespace || 'App\Entity' === $namespace;
            $isNotComponent = !strpos($entityMetaData->getName(), 'Component');
            if ($isAppNamespace && $isNotComponent && $entityMetaData->hasField('title')) {
                $className = str_replace($namespace.'\\', '', $entityMetaData->getName());
                $entityClasses[$className] = $entityMetaData->getName();
            }
        }

        $builder->add('entity_class', ChoiceType::class, [
            'label' => 'Entity Class',
            'required' => true,
            'choices' => $entityClasses,
        ]);

        /*$builder->add('choice_label', TextType::class, [
            'label' => 'Choice Label Field',
            'required' => false,
        ]);*/

        $builder->add('placeholder', TextType::class, [
            'label' => 'Placeholder',
            'required' => false,
        ]);

        $builder->add('expanded', CheckboxType::class, [
            'label' => 'Expanded',
            'required' => false,
        ]);

        $builder->add('multiple', CheckboxType::class, [
            'label' => 'Multiple',
            'required' => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public static function getItem(FormBuilderInterface $builder, array $item)
    {
        $attributes = [];

        if (isset($item['read_only']) && $item['read_only']) {
            $attributes['readonly'] = true;
        }

        if (isset($item['twig_variable']) && $item['twig_variable']) {
            $attributes['twig_variable'] = $item['twig_variable'];
        }

        if (isset($item['popover']) && trim($item['popover'])) {
            $attributes['data-toggle'] = 'popover';
            $attributes['data-placement'] = 'top';
            $attributes['data-trigger'] = 'focus';
            $attributes['data-html'] = 'true';
            $attributes['data-content'] = $item['popover'];
        }

        $entityClass = $item['entity_class'];

        $options = [
            'label' => !empty($item['hideLabel']) && $item['hideLabel'] ? false : $item['label'],
            'required' => $item['required'],
            'attr' => $attributes,
            'expanded' => $item['expanded'] ?? false,
            'multiple' => $item['multiple'] ?? false,
            'class' => $entityClass,
            'choice_label' => $item['choice_label'] ?? 'title',
            'placeholder' => $item['placeholder'] ?? $item['label'],
        ];

        if (isset($item['required']) && $item['required']) {
            $options['constraints'] = new NotBlank();
        }

        $builder->add($item['name'], EntityType::class, $options);
    }

    /**
     * {@inheritdoc}
     */
    public static function getVariables(array $item): array
    {
        $var = $item['multiple'] ? $item['name']."|join(', ')" : $item['name'];

        return [$var];
    }
}


<?php

namespace Gobline\Filter\Sanitizer;

use Gobline\Filter\Validator;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class Cast implements SanitizerInterface
{
    private $type;

    /**
     * @param string $allowedChars
     */
    public function __construct($type)
    {
        $type = (string) $type;

        switch ($type) {
            default:
                throw new \InvalidArgumentException('invalid type "'.$type.'"');
            case 'bool':
            case 'boolean':
            case 'int':
            case 'integer':
            case 'float':
            case 'string':
            case 'null':
        }

        $this->type = $type;
    }

    /**
     * {@inheritdoc}
     */
    public function sanitize($value)
    {
        if (!is_scalar($value)) {
            throw new \InvalidArgumentException('Unexpected type: '.gettype($value));
        }

        switch ($this->type) {
            case 'bool':
            case 'boolean':
                if ((new Validator\Boolean())->isValid($value)) {
                    return (bool) $value;
                }
                break;
            case 'int':
            case 'integer':
                if ((new Validator\Float(true))->isValid($value) || is_bool($value)) {
                    return (int) $value;
                }
                break;
            case 'float':
                if ((new Validator\Float(true))->isValid($value) || is_bool($value)) {
                    return (float) $value;
                }
                break;
            case 'string':
                if (is_bool($value)) {
                    return $value ? '1' : '0';
                }

                return (string) $value;
            case 'null':
                return null;
        }

        throw new \RuntimeException('Cannot cast "'.$value.'" to '.$this->type);
    }
}


<?php

namespace Railken\Amethyst\Schemas;

use Railken\Amethyst\Attributes\TaxonomyAttribute;
use Railken\Amethyst\Managers\TaxonomyManager;
use Railken\Lem\Attributes;
use Railken\Lem\Schema;

class TaxonomySchema extends Schema
{
    /**
     * Get all the attributes.
     *
     * @var array
     */
    public function getAttributes()
    {
        return [
            Attributes\IdAttribute::make(),
            Attributes\TextAttribute::make('name')
                ->setRequired(true),
            Attributes\LongTextAttribute::make('description'),
            Attributes\LongTextAttribute::make('notes'),
            Attributes\BooleanAttribute::make('enabled'),
            TaxonomyAttribute::make('parent_id')
                ->setRelationName('parent')
                ->setRelationManager(TaxonomyManager::class),
            Attributes\CreatedAtAttribute::make(),
            Attributes\UpdatedAtAttribute::make(),
            Attributes\DeletedAtAttribute::make(),
        ];
    }
}


<?php

namespace Gobline\Filter\Validator;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class Alpha extends AbstractValidator
{
    private $value;
    private $allowedChars;

    /**
     * @param string $allowedChars
     */
    public function __construct($allowedChars = '')
    {
        parent::__construct();

        $this->allowedChars = (string) $allowedChars;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        $this->resetMessages();

        $this->value = $value;

        if (!is_string($value)) {
            $this->addMessage();

            return false;
        }

        if ($this->allowedChars !== '') {
            $value = str_replace(str_split($this->allowedChars), '', $value);
        }

        if (!ctype_alpha($value)) {
            $this->addMessage();

            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageTemplates()
    {
        if ($this->allowedChars === '') {
            return ['The input must contain only letters'];
        } else {
            return ['The input contains invalid characters'];
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageVariables()
    {
        return ['value' => $this->value];
    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Form\Items;

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

class CheckboxItem extends Item
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->remove('hideLabel');
        $builder->remove('popover');
    }

    /**
     * {@inheritdoc}
     */
    public static function getItem(FormBuilderInterface $builder, array $item)
    {
        $attributes = [];

        if (isset($item['read_only']) && $item['read_only']) {
            $attributes['readonly'] = true;
        }

        if (isset($item['twig_variable']) && $item['twig_variable']) {
            $attributes['twig_variable'] = $item['twig_variable'];
        }

        if (isset($item['popover']) && trim($item['popover'])) {
            $attributes['data-toggle'] = 'popover';
            $attributes['data-placement'] = 'top';
            $attributes['data-trigger'] = 'focus';
            $attributes['data-html'] = 'true';
            $attributes['data-content'] = $item['popover'];
        }

        $options = [
            'label' => $item['label'],
            'required' => $item['required'],
            'attr' => $attributes,
            'label_attr' => [
                'class' => 'checkbox-custom',
            ],
        ];

        if (isset($item['required']) && $item['required']) {
            $options['constraints'] = new NotBlank();
        }

        $builder->add($item['name'], CheckboxType::class, $options);
    }

    /**
     * {@inheritdoc}
     */
    public static function getVariables(array $item): array
    {
        return [$item['name']." ? 'Yes' : 'No'"];
    }
}


<?php
/**
 * MIT License <https://opensource.org/licenses/mit>
 *
 * Copyright (c) 2015 Kerem Güneş
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
declare(strict_types=1);

namespace froq\util\traits;

/**
 * Singleton trait.
 * @package froq\util\traits
 * @object  froq\util\traits\SingletonTrait
 * @author  Kerem Güneş <k-gun@mail.com>
 * @since   1.0
 */
trait SingletonTrait
{
    // Notice: Do not define '__construct' or '__clone'
    // methods as 'public' if you want a single use'r object.

    /**
     * Instances.
     * @var array
     */
    private static $___instances = [];

    /**
     * Forbids.
     */
    private function __clone() {}
    private function __construct() {}

    /**
     * Init.
     * @param  ... $arguments
     * @return object
     */
    public static final function init(...$arguments): object
    {
        $className = get_called_class();
        if (!isset(self::$___instances[$className])) {
            // init without constructor and call constructor with initial arguments
            // to prevent error: "Access to non-public constructor of class ...".
            // newInstance() nor newInstanceArgs() cannot do that.
            $classInstance = (new \ReflectionClass($className))->newInstanceWithoutConstructor();

            // no error, weird? (ô_ô)
            call_user_func_array([$classInstance, '__construct'], $arguments);

            self::$___instances[$className] = $classInstance;
        }

        return self::$___instances[$className];
    }
}


<?php

namespace Gobline\Filter\Validator;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class Regex extends AbstractValidator
{
    private $value;
    private $pattern;

    /**
     * @param string $pattern
     */
    public function __construct($pattern)
    {
        parent::__construct();

        $this->pattern = (string) $pattern;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        $this->resetMessages();

        $this->value = $value;

        if (!is_scalar($value) || is_bool($value)) {
            throw new \InvalidArgumentException('Unexpected type: '.gettype($value));
        }

        $value = (string) $value;

        $result = preg_match($this->pattern, $value);

        if ($result === false) {
            throw new \RuntimeException('Pattern "'.$this->pattern.'" gave an error for value "'.$value.'"');
        }

        if (!$result) {
            $this->addMessage();

            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageTemplates()
    {
        return ['The input is not valid'];
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageVariables()
    {
        return ['value' => $this->value];
    }
}


<?php
/**
 * This file is part of Berlioz framework.
 *
 * @license   https://opensource.org/licenses/MIT MIT License
 * @copyright 2017 Ronan GIRON
 * @author    Ronan GIRON <https://github.com/ElGigi>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code, to the root.
 */

declare(strict_types=1);

namespace Berlioz\Config;

use Berlioz\Config\Exception\ConfigException;
use Berlioz\Config\Exception\NotFoundException;

/**
 * Class JsonConfig.
 *
 * Offer basic configuration class to manage JSON configuration files.
 * Access to the values with get() method, uses 'key.subkey.something' for example.
 *
 * @package Berlioz\Core
 */
class JsonConfig extends AbstractConfig
{
    /**
     * JsonConfig constructor.
     *
     * @param string $json      JSON data
     * @param bool   $jsonIsUrl If JSON data is URL? (default: false)
     *
     * @throws \Berlioz\Config\Exception\ConfigException
     */
    public function __construct(string $json, bool $jsonIsUrl = false)
    {
        // Load configuration
        $this->configuration = $this->load($json, $jsonIsUrl);

        parent::__construct();
    }

    /**
     * Load configuration.
     *
     * @param string $json      JSON data
     * @param bool   $jsonIsUrl If JSON data is URL? (default: false)
     *
     * @return array
     * @throws \Berlioz\Config\Exception\ConfigException If unable to load configuration file
     */
    protected function load(string $json, bool $jsonIsUrl = false): array
    {
        if ($jsonIsUrl) {
            return $this->loadUrl($json);
        }

        return $this->loadJson($json);
    }

    /**
     * Load JSON data.
     *
     * @param string $json
     *
     * @return array
     * @throws \Berlioz\Config\Exception\ConfigException
     */
    protected function loadJson(string $json): array
    {
        $json = preg_replace('#^\s*//.*$\v?#mx', '', $json);
        $configuration = json_decode($json, true);

        if (!is_array($configuration)) {
            throw new ConfigException('Not a valid JSON data');
        }

        return $configuration;
    }

    /**
     * Load JSON file.
     *
     * @param string $jsonFile
     *
     * @return array
     * @throws \Berlioz\Config\Exception\NotFoundException
     * @throws \Berlioz\Config\Exception\ConfigException
     */
    protected function loadUrl(string $jsonFile): array
    {
        //Get real path of file
        if (($fileName = realpath($jsonFile)) === false) {
            throw new NotFoundException(sprintf('File "%s" not found', $jsonFile));
        }

        // Read file
        if (($json = @file_get_contents($fileName)) === false) {
            throw new ConfigException(sprintf('Unable to load configuration file "%s"', $fileName));
        }

        try {
            return $this->loadJson($json);
        } catch (ConfigException $e) {
            throw new ConfigException(sprintf('Not a valid JSON data for file "%s"', $fileName));
        }
    }
}


<?php

namespace Gobline\Filter\Validator;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class Length extends AbstractValidator
{
    private $value;
    private $min;
    private $max;

    const TOO_SHORT = 'TOO_SHORT';
    const TOO_LONG = 'TOO_LONG';

    /**
     * @param int $min
     * @param int $max
     */
    public function __construct($min, $max = null)
    {
        parent::__construct();

        $this->min = (int) $min;

        if ($this->min < 0) {
            throw new \InvalidArgumentException('$min must be a positive integer');
        }

        if ($max !== null) {
            $this->max = (int) $max;

            if ($this->max < 0) {
                throw new \InvalidArgumentException('$max must be a positive integer');
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        $this->resetMessages();

        $this->value = $value;

        if (!is_string($value)) {
            throw new \InvalidArgumentException('Unexpected type: '.gettype($value));
        }

        if (strlen($value) < $this->min) {
            $this->addMessage(self::TOO_SHORT);

            return false;
        }

        if ($this->max !== null && strlen($value) > $this->max) {
            $this->addMessage(self::TOO_LONG);

            return false;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageTemplates()
    {
        return [
            self::TOO_SHORT => 'The input is less than %min% characters long',
            self::TOO_LONG  => 'The input is more than %max% characters long',
        ];
    }

    /**
     * {@inheritdoc}
     */
    protected function getMessageVariables()
    {
        return [
            'value' => $this->value,
            'min' => $this->min,
            'max' => $this->max,
        ];
    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Form\Items;

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

class TextItem extends Item
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->add('placeholder', TextType::class, [
            'label' => 'Placeholder',
            'required' => false,
        ]);

        $builder->add('min', NumberType::class, [
            'label' => 'Min Length',
            'required' => false,
        ]);

        $builder->add('max', NumberType::class, [
            'label' => 'Max Length',
            'required' => false,
        ]);

        $builder->add('isSubject', CheckboxType::class, [
            'label' => 'Is Subject',
            'required' => false,
        ]);

        $builder->add('isFirstname', CheckboxType::class, [
            'label' => 'Is Firstname',
            'required' => false,
        ]);

        $builder->add('isName', CheckboxType::class, [
            'label' => 'Is Name',
            'required' => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public static function getItem(FormBuilderInterface $builder, array $item)
    {
        $attributes = [];

        if (isset($item['read_only']) && $item['read_only']) {
            $attributes['readonly'] = true;
        }

        if (isset($item['placeholder']) && $item['placeholder']) {
            $attributes['placeholder'] = $item['placeholder'];
        }

        if (isset($item['twig_variable']) && $item['twig_variable']) {
            $attributes['twig_variable'] = $item['twig_variable'];
        }

        if (isset($item['popover']) && trim($item['popover'])) {
            $attributes['data-toggle'] = 'popover';
            $attributes['data-placement'] = 'top';
            $attributes['data-trigger'] = 'focus';
            $attributes['data-html'] = 'true';
            $attributes['data-content'] = $item['popover'];
        }

        $options = [
            'label' => !empty($item['hideLabel']) && $item['hideLabel'] ? false : $item['label'],
            'required' => $item['required'] ?? false,
            'attr' => $attributes,
            'constraints' => [],
        ];

        if (isset($item['required']) && $item['required']) {
            $options['constraints'][] = new NotBlank();
        }

        if ((isset($item['min']) && $item['min']) || (isset($item['max']) && $item['max'])) {
            $min = $item['min'] ?? 0;
            $max = $item['max'] ?? null;
            $options['constraints'][] = new Length([
                'min' => $min,
                'max' => $max,
            ]);
        }

        $builder->add($item['name'], TextType::class, $options);
    }
}


<?php

namespace Dywee\OrderBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Dywee\OrderBundle\Entity\BaseOrder;

/**
 * BaseOrderRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class BaseOrderRepository extends EntityRepository
{
    /**
     * @param string|null $state
     *
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function findAllForPagination(string $state = null)
    {
        $qb = $this->createQueryBuilder('o');

        if($state)
        {
            $qb->where('o.state = :state');
            $qb->setParameter('state', $state);
        }

        $qb->orderBy('o.createdAt', 'desc');

        return $qb;
    }

    /**
     * @param $type
     * @param $data
     *
     * @return array
     */
    public function findAllByTypeAndData($type, $data)
    {
        $qb = $this->createQueryBuilder('o')
            ->where('o.createdAt < :date and o.state = 1')
            ->setParameter('date', new \DateTime());

        return $qb
            ->getQuery()
            ->getResult()
            ;
    }

    /**
     * @param string $state
     *
     * @return mixed
     */
    public function countByState($state = BaseOrder::STATE_IN_PROGRESS)
    {
        $qb = $this->createQueryBuilder('o')
            ->select('COUNT(o)')
            ->where('o.state = :state')
            ->setParameter('state', $state);

        return $qb->getQuery()->getSingleScalarResult();
    }

    /**
     * @param $month
     * @param $state
     *
     * @return array
     */
    public function findByMonth($month, $state)
    {
        $emConfig = $this->getEntityManager()->getConfiguration();
        $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
        $emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
        //$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');

        $today = getdate();
        $month = $today['mon'];
        $year = $today['year'];

        if($month == 'previous')
        {
            $month--;
            if($month == 0)
            {
                $month = 12;
                $year--;
            }
        }

        $qb = $this->createQueryBuilder('o');
        $qb
            ->where('YEAR(o.createdAt) > :year and MONTH(o.createdAt) = :month and o.createdAt and o.state = 2')
            ->setParameter('month', $month)
            ->setParameter('year', $year);

        return $qb
            ->getQuery()
            ->getResult()
            ;
    }
}


<?php

namespace Gobline\Filter\Sanitizer;

/**
 * @author Mathieu Decaffmeyer <mdecaffmeyer@gmail.com>
 */
class StripTags implements SanitizerInterface
{
    private $allowedTags;

    /**
     * @param string $allowedTags
     */
    public function __construct($allowedTags = '')
    {
        $this->allowedTags = (string) $allowedTags;
    }

    /**
     * {@inheritdoc}
     */
    public function sanitize($value)
    {
        if (!is_scalar($value)) {
            throw new \InvalidArgumentException('Unexpected type: '.gettype($value));
        }

        return strip_tags($value, $this->allowedTags);
    }
}


<?php

/**
 * This class is an LatLng object which should be returned by Drivers
 *
 * @package     Nails
 * @subpackage  module-geo-code
 * @category    Result
 * @author      Nails Dev Team
 * @link
 */

namespace Nails\GeoCode\Result;

class LatLng
{
    private $sAddress;
    private $sLat;
    private $sLng;

    // --------------------------------------------------------------------------

    /**
     * Define the LatLng object
     * @param string $sAddress
     * @param string $sLat
     * @param string $sLng
     */
    public function __construct($sAddress = '', $sLat = '', $sLng = '')
    {
        $this->sAddress = $sAddress;
        $this->sLat     = $sLat;
        $this->sLng     = $sLng;
    }

    // --------------------------------------------------------------------------

    /**
     * Set the address property
     * @param string $sAddress The address to set
     * @return $this
     */
    public function setAddress($sAddress)
    {
        $this->sAddress = $sAddress;
        return $this;
    }

    // --------------------------------------------------------------------------

    /**
     * Get the address
     * @return string
     */
    public function getAddress()
    {
        return $this->sAddress;
    }

    // --------------------------------------------------------------------------

    /**
     * Set the address's Latitude and Longitude
     * @param string $sLat The address's Latitude
     * @param string $sLng The address's Longitude
     * @return $this
     */
    public function setLatLng($sLat, $sLng)
    {
        $this->setLat($sLat);
        $this->setLng($sLng);
        return $this;
    }

    // --------------------------------------------------------------------------

    /**
     * Set the Latitude property
     * @param string $sLat The Latitude to set
     * @return $this
     */
    public function setLat($sLat)
    {
        $this->sLat = $sLat;
        return $this;
    }

    // --------------------------------------------------------------------------

    /**
     * Get the latitude
     * @return string
     */
    public function getLat()
    {
        return $this->sLat;
    }

    // --------------------------------------------------------------------------

    /**
     * Set the Longitude property
     * @param string $sLng The Longitude to set
     * @return $this
     */
    public function setLng($sLng)
    {
        $this->sLng = $sLng;
        return $this;
    }

    // --------------------------------------------------------------------------

    /**
     * Get the longitude
     * @return string
     */
    public function getLng()
    {
        return $this->sLng;
    }

    // --------------------------------------------------------------------------

    /**
     * Get the address's coordinates
     * @return \stdClass
     */
    public function getLatLng()
    {
        $oLatLng = new \stdClass();
        $oLatLng->lat = $this->sLat;
        $oLatLng->lng = $this->sLng;

        return $oLatLng;
    }
}


<?php

namespace Dywee\OrderBundle\Controller;

use Dywee\OrderBundle\Entity\ShippingMethod;
use Dywee\OrderBundle\Form\ShippingMethodType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class ShippingMethodController extends Controller
{
    /**
     * @return Response
     *
     * @Route(name="shipping_method_table", path="admin/shipment/method")
     */
    public function tableAction()
    {
        $dr = $this->getDoctrine()->getManager()->getRepository(ShippingMethod::class);
        $shipmentMethodList = $dr->findAll();

        return $this->render('DyweeOrderBundle:ShippingMethod:table.html.twig', array('shipmentMethods' => $shipmentMethodList));
    }

    /**
     * @param Request $request
     * @return mixed
     *
     * @Route(name="shipping_method_add", path="admin/shipment/method/add")
     */
    public function addAction(Request $request)
    {
        $shipmentMethod = new ShippingMethod();

        $form = $this->createForm(ShippingMethodType::class, $shipmentMethod);

        if($form->handleRequest($request)->isValid())
        {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($shipmentMethod);
            $em->flush();

            return $this->redirectToRoute('shipping_method_table');
        }

        return $this->render('DyweeOrderBundle:ShippingMethod:add.html.twig', array('form' => $form->createView()));
    }

    /**
     * @param ShippingMethod $shipmentMethod
     * @return Response
     *
     * @Route(name="shipping_method_view", path="admin/shipment/method/{id}")
     */
    public function viewAction(ShippingMethod $shipmentMethod)
    {
        return $this->render('DyweeOrderBundle:ShippingMethod:view.html.twig', array('shipmentMethods' => $shipmentMethod));
    }

    /**
     * @param ShippingMethod $shipmentMethod
     * @param Request $request
     *
     * @Route(name="shipping_method_update", path="admin/shipment/method/{id}/update")
     */
    public function updateAction(ShippingMethod $shipmentMethod, Request $request)
    {
        $form = $this->createForm(ShippingMethodType::class, $shipmentMethod);

        if($form->handleRequest($request)->isValid())
        {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($shipmentMethod);
            $em->flush();

            return $this->redirectToRoute('shipping_method_table');
        }

        return $this->render('DyweeOrderBundle:ShippingMethod:edit.html.twig', array('form' => $form->createView()));
    }

    public function searchAjaxAction()
    {
        $request = $this->container->get('request');
        if($request->isXmlHttpRequest())
        {
            $response = new Response();

            $country = $request->request->get('country');

            if(is_numeric($country))
            {
                $em = $this->getDoctrine()->getEntityManager();
                $smr = $em->getRepository(ShippingMethod::class);

                $order = $this->get('session')->get('order');
                $or = $em->getRepository('DyweeOrderBundle:BaseOrder');
                $order = $or->findOneById($order->getId());

                $mondialRelay24R = array('name' => 'Livraison en point relais', 'price' => false);
                $mondialRelayHOM = array('name' => 'Livraison à domicile', 'price' => false);
                $dpd = array('name' => 'Livraison à domicile', 'price' => false);

                /*foreach($order->getOrderElements as $orderElement)
                {
                    $shipmentMethods = $smr->myfindBy($country, $orderElement->getProduct()->getWeight()*$orderElement->getQuantity());
                }

                //$shipmentMethods = $smr->myfindBy($country, $order->getWeight()); //*/

                $order->shipmentsCalculation(true);

                $containsBeers = false;
                $beersWeight = 0;

                //$coeff = count($order->getShipments());
                $coeff = 0;
                $totalCoeff = 0;

                $options = array();

                foreach($order->getOrderElements() as $orderElement)
                {
                    if($orderElement->getProduct()->getProductType() == 1)
                    {
                        $coeff = 1;
                        $totalCoeff = 1;

                        if(!$containsBeers)
                        {
                            $containsBeers = true;
                            $shipmentMethods = $smr->myfindBy($country, $order->getWeight(1));
                        }
                    }
                    else $shipmentMethods = $smr->myfindBy($country, $orderElement->getProduct()->getWeight());

                    if($orderElement->getProduct()->getProductType() == 3)
                    {
                        $coeff = $orderElement->getProduct()->getRecurrence();
                        $totalCoeff += $orderElement->getProduct()->getRecurrence()*$orderElement->getQuantity();
                    }
                    else if($orderElement->getProduct()->getProductType() == 2)
                    {
                        $coeff = 1;
                        $totalCoeff = 1;
                    }

                    if(isset($shipmentMethods))
                    foreach($shipmentMethods as $shipmentMethod)
                    {
                        if($shipmentMethod->getDeliver()->getId() == 2 && $shipmentMethod->getType() == '24R')
                        {
                            $mondialRelay24R['price'] =
                                ($orderElement->getProduct()->getProductType() == 1)?
                                    $shipmentMethod->getPrice()*$coeff:
                                    $shipmentMethod->getPrice()*$coeff*$orderElement->getQuantity();
                            //echo $mondialRelay24R['price'];
                            if(array_key_exists('24R', $options))
                                $options['24R']['price'] += $mondialRelay24R['price'];
                            else $options['24R'] = $mondialRelay24R;

                        }
                        else if($shipmentMethod->getDeliver()->getId() == 2 && $shipmentMethod->getType() == 'HOM')
                        {
                            $mondialRelayHOM['price'] =
                                ($orderElement->getProduct()->getProductType() == 1)?
                                    $shipmentMethod->getPrice()*$coeff:
                                    $shipmentMethod->getPrice()*$coeff*$orderElement->getQuantity();
                            if(array_key_exists('HOM', $options))
                                $options['HOM']['price'] += $mondialRelayHOM['price'];
                            else $options['HOM'] = $mondialRelayHOM;
                        }
                        else if($shipmentMethod->getDeliver()->getId() == 3)
                        {
                            $dpd['price'] =
                                ($orderElement->getProduct()->getProductType() == 1)?
                                    $shipmentMethod->getPrice()*$coeff:
                                    $shipmentMethod->getPrice()*$coeff*$orderElement->getQuantity();
                            if(array_key_exists('dpd', $options))
                                $options['dpd']['price'] += $dpd['price'];
                            else $options['dpd'] = $dpd;
                        }
                    }
                }

                if($order->containsOnlyOneType(3))
                    foreach($options as $key => $value)
                        $options[$key]['priceByShipment'] = $options[$key]['price']/$totalCoeff;

                $response->setContent(json_encode(array(
                    'type' => 'success',
                    'shippingOptions' => $options,
                    'coeff' => $totalCoeff
                )));

            }
            else $response->setContent(json_encode(array(
                'Error' => 'Pays invalide',
            )));

            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }

    }
}


<?php

declare(strict_types=1);

namespace RevisionTen\Forms\Form\Items;

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

class EmailItem extends TextItem
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder->remove('isFirstname');
        $builder->remove('isName');

        $builder->add('replyTo', CheckboxType::class, [
            'label' => 'Reply to this Email',
            'required' => false,
        ]);

        $builder->add('isReceiver', CheckboxType::class, [
            'label' => 'Is Receiver',
            'required' => false,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public static function getItem(FormBuilderInterface $builder, array $item)
    {
        $attributes = [];

        if (isset($item['read_only']) && $item['read_only']) {
            $attributes['readonly'] = true;
        }

        if (isset($item['placeholder']) && $item['placeholder']) {
            $attributes['placeholder'] = $item['placeholder'];
        }

        if (isset($item['twig_variable']) && $item['twig_variable']) {
            $attributes['twig_variable'] = $item['twig_variable'];
        }

        if (isset($item['popover']) && trim($item['popover'])) {
            $attributes['data-toggle'] = 'popover';
            $attributes['data-placement'] = 'top';
            $attributes['data-trigger'] = 'focus';
            $attributes['data-html'] = 'true';
            $attributes['data-content'] = $item['popover'];
        }

        $options = [
            'label' => !empty($item['hideLabel']) && $item['hideLabel'] ? false : $item['label'],
            'required' => $item['required'],
            'attr' => $attributes,
        ];

        if (isset($item['required']) && $item['required']) {
            $options['constraints'] = new NotBlank();
        }

        $builder->add($item['name'], EmailType::class, $options);
    }
}