Skip to content

Instantly share code, notes, and snippets.

@cornobils
Created April 17, 2018 10:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cornobils/e978f1cc9ca30d5ccda0b6e3c65b03b6 to your computer and use it in GitHub Desktop.
Save cornobils/e978f1cc9ca30d5ccda0b6e3c65b03b6 to your computer and use it in GitHub Desktop.
[Sylius] Zone based promotion rule
app.promotion_rule_checker.shipping_zone:
class: AppBundle\Checker\Rule\ShippingZoneRuleChecker
arguments:
- "@sylius.repository.zone"
tags:
- { name: sylius.promotion_rule_checker, type: shipping_zone,
label: Shipping zone, form_type: AppBundle\Form\Admin\Promotion\ShippingZoneConfigurationType }
<?php
namespace AppBundle\Form\Admin\Promotion;
use Sylius\Bundle\AddressingBundle\Form\Type\ZoneCodeChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
final class ShippingZoneConfigurationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('zone', ZoneCodeChoiceType::class)
;
}
public function getBlockPrefix()
{
return 'app_bundle_shipping_zone_configuration_type';
}
}
<?php
declare(strict_types=1);
namespace AppBundle\Checker\Rule;
use Sylius\Component\Promotion\Checker\Rule\RuleCheckerInterface;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Promotion\Exception\UnsupportedTypeException;
final class ShippingZoneRuleChecker implements RuleCheckerInterface
{
/** @var \Doctrine\ORM\EntityRepository */
private $zoneRepository;
public const TYPE = 'shipping_zone';
/**
* ShippingZoneRuleChecker constructor.
* @param \Doctrine\ORM\EntityRepository $zoneRepository
*/
public function __construct(\Doctrine\ORM\EntityRepository $zoneRepository)
{
$this->zoneRepository = $zoneRepository;
}
public function isEligible(PromotionSubjectInterface $subject, array $configuration): bool
{
if (!$subject instanceof OrderInterface) {
throw new UnsupportedTypeException($subject, OrderInterface::class);
}
if (null === $shipment = $subject->getShipments()[0]) {
return false;
}
$method = $shipment->getMethod();
if (null === $method) {
return false;
}
if (null === $zone = $method->getZone()) {
return false;
}
return $configuration['zone'] === $zone->getCode();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment