<?php
namespace App\Ecommerce\PriceSystem\PriceSystemRule;
use App\Ecommerce\PriceSystem\PriceSystemRuleContract;
use App\Model\Customer;
use Factory\SupportBundle\Contract\Model\Ecommerce\AddressContract;
use Pimcore\Bundle\EcommerceFrameworkBundle\EnvironmentInterface;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
class Processor
{
const ACTION_CLASS_DEFAULT = 'actionClass';
const ACTION_CLASS_EMPTY = 'emptyActionClass';
/**
* @var EnvironmentInterface
*/
protected $environment;
/**
* @var array
*/
protected $options = [];
/**
* @var array
*/
protected $customrGroupIds = [];
protected $customer;
public function __construct(EnvironmentInterface $environment, array $options = [])
{
$this->environment = $environment;
$this->options = $this->processOptions($options);
$this->customrGroupIds = [];
}
protected function processOptions(array $options)
{
return array_merge(
[
'actionClass' => Action::class,
'emptyActionClass' => EmptyAction::class
],
$options
);
}
protected function createActionClass(string $type, $data, PriceSystemRuleContract $priceSystemRule)
{
return new $this->options[$type]($data, $priceSystemRule, $this);
}
public function getMatchingAction(PriceSystemRuleContract $priceSystemRule): ActionContract
{
if (!$priceSystemRule->getActions()) {
return $this->createActionClass(self::ACTION_CLASS_EMPTY, null, $priceSystemRule);
}
foreach ($priceSystemRule->getActions() as $action) {
$actionClass = $this->createActionClass(self::ACTION_CLASS_DEFAULT, $action, $priceSystemRule);
if (!$this->match($actionClass)) {
continue;
}
return $actionClass;
}
return $this->createActionClass(self::ACTION_CLASS_EMPTY, null, $priceSystemRule);
}
protected function match(ActionContract $action)
{
$user = \Pimcore\Tool\Admin::getCurrentUser();
if (!$this->getCustomer() && !$user) {
return false;
}
if ($action->getNotIn()) {
if (!in_array($this->getCountryCode(), $action->getCountries())) {
return $action;
}
}
if (in_array($this->getCountryCode(), $action->getCountries())) {
return $action;
}
return false;
}
protected function getCustomer(): ?Customer
{
if (!$this->customer) {
$this->customer = Customer::getById($this->environment->getCurrentUserId());
}
return $this->customer;
}
protected function getCountryCode()
{
$env = Factory::getInstance()->getEnvironment();
if (!$env->getBillingAddress()) {
return null;
}
if ($env->getBillingAddress() instanceof AddressContract) {
return $env->getBillingAddress()->getCountryCode();
}
// We will replace all addresses with `AddressContract`
return $env->getBillingAddress()->getCountry();
}
}