Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
class PromotionExpressionValidator extends ConstraintValidator
{
private $expressionLanguage;
private $loadDummyOrder;
public function __construct(
ExpressionLanguage $expressionLanguage,
LoadDummyOrder $loadDummyOrder
)
{
$this->expressionLanguage = $expressionLanguage;
$this->loadDummyOrder = $loadDummyOrder;
}
public function validate($value, Constraint $constraint)
{
try {
$this->expressionLanguage->parse(
$value['expression'],
[$value['itemBased'] ? 'item' : 'order']
);
} catch (SyntaxError $e) {
return $this->context->addViolationAt(
'expression',
$e->getMessage()
);
}
if ($value['itemBased']) {
$process = $this->runOnDummyOrderItem($value['expression']);
} else {
$process = $this->runOnDummyOrder($value['expression']);
}
if (0 !== $process->getExitCode() || null !== $process->getOutput()) {
return $this->context->addViolationAt(
'expression',
null === $process->getOutput() ? $constraint->message : trim($process->getOutput())
);
}
}
private function runOnDummyOrder($expression)
{
return $this->runOnObject(
'order',
$this->loadDummyOrder->load(),
$expression
);
}
private function runOnDummyOrderItem($expression)
{
return $this->runOnObject(
'item',
$this->loadDummyOrder->load()->getItems()->first(),
$expression
);
}
private function runOnObject($key, $value, $expression)
{
$process = new PhpProcess(sprintf("<?php
require __DIR__.'/../vendor/autoload.php';
ini_set('display_errors', 1);
(new %s())->evaluate(
\"%s\",
['%s' => unserialize('%s')]
);
",
get_class($this->expressionLanguage),
$expression,
$key,
serialize($value)
));
$process->run();
return $process;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment