Created
June 4, 2015 07:54
-
-
Save umpirsky/41511a179daeb0fff323 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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