コード例 #1
0
ファイル: Ruler.php プロジェクト: pierredup/ruler
 /**
  * @param mixed $context
  *
  * @return mixed
  * @throws \Exception
  */
 public function decide($context = null)
 {
     if (null === $context) {
         $context = [];
     }
     $visitor = new ClosureExpressionVisitor();
     foreach ($this->rules as $rule) {
         $expression = $rule->getExpression();
         if ($expression instanceof Expression) {
             if (null === $this->el) {
                 $this->el = new ExpressionLanguage();
             }
             $response = $this->el->evaluate($expression, $context);
         } else {
             $filter = $visitor->dispatch($expression);
             $response = $filter($context);
         }
         if ($response) {
             $return = $rule->getReturn();
             if (is_callable($return)) {
                 return call_user_func($return, $context);
             }
             return $return;
         }
     }
     throw new InvalidRuleException('No rules matched');
 }
コード例 #2
0
 /**
  * @param  string $expression
  * @param  mixed  $data
  * @return mixed
  */
 public function evaluate($expression, $data)
 {
     if (!is_string($expression)) {
         return $expression;
     }
     $key = $expression;
     if (!array_key_exists($key, $this->cache)) {
         if (!preg_match(self::EXPRESSION_REGEX, $expression, $matches)) {
             $this->cache[$key] = false;
         } else {
             $expression = $matches['expression'];
             $context = $this->context;
             $context['object'] = $data;
             $this->cache[$key] = $this->expressionLanguage->parse($expression, array_keys($context));
         }
     }
     if (false !== $this->cache[$key]) {
         if (!isset($context)) {
             $context = $this->context;
             $context['object'] = $data;
         }
         return $this->expressionLanguage->evaluate($this->cache[$key], $context);
     }
     return $expression;
 }
コード例 #3
0
 /**
  * @see MetaborStd\Statemachine.ConditionInterface::checkCondition()
  */
 public function checkCondition($subject, \ArrayAccess $context)
 {
     $values = $this->values;
     $values['subject'] = $subject;
     $values['context'] = $context;
     return (bool) $this->expressionLanguage->evaluate($this->getExpression(), $values);
 }
コード例 #4
0
 /**
  * {@inheritdoc}
  */
 public function provide($entity, $name)
 {
     try {
         return $this->expressionLanguage->evaluate($name, ['object' => $entity, 'translator' => $this->translator]);
     } catch (\Exception $e) {
         throw new CannotEvaluateTokenException($name, $entity, $e);
     }
 }
コード例 #5
0
 /**
  * @param Rule          $rule
  * @param WorkingMemory $workingMemory
  *
  * @return bool
  */
 public function checkCondition(Rule $rule, WorkingMemory $workingMemory)
 {
     try {
         return (bool) $this->expressionLanguage->evaluate($rule->getCondition(), $workingMemory->getAllFacts());
     } catch (SyntaxError $e) {
         return false;
     }
 }
コード例 #6
0
 public function handle($arg)
 {
     $expressionDetected = preg_match('/expr\\((.+)\\)/', $arg, $matches);
     if (1 !== $expressionDetected) {
         throw new NotResolvableValueException($arg);
     }
     return $this->expressionLanguage->evaluate($matches[1], $this->expressionContext->getData());
 }
コード例 #7
0
ファイル: ParametersParser.php プロジェクト: loic425/Sylius
 /**
  * @param string $expression
  * @param Request $request
  *
  * @return string
  */
 private function parseRequestValueExpression($expression, Request $request)
 {
     $expression = preg_replace_callback('/(\\$\\w+)/', function ($matches) use($request) {
         $variable = $request->get(substr($matches[1], 1));
         return is_string($variable) ? sprintf('"%s"', $variable) : $variable;
     }, $expression);
     return $this->expression->evaluate($expression, ['container' => $this->container]);
 }
コード例 #8
0
 /**
  * {@inheritdoc}
  */
 public function evaluate(RuleInterface $rule, RuleSubjectInterface $subject)
 {
     try {
         return (bool) $this->expression->evaluate($rule->getExpression(), [$subject->getSubjectType() => $subject]);
     } catch (\Exception $e) {
         $this->logger->error(sprintf('%s Trace: %s', $e->getMessage(), $e->getTraceAsString()));
     }
     return false;
 }
コード例 #9
0
 /**
  * @param InterceptionInterface    $interception
  * @param CacheAnnotationInterface $annotation
  *
  * @return string
  * @throws \Phpro\AnnotatedCache\Exception\UnsupportedKeyParameterException
  */
 public function generateKey(InterceptionInterface $interception, CacheAnnotationInterface $annotation) : string
 {
     $format = property_exists($annotation, 'key') ? $annotation->key : '';
     $parameters = array_merge($interception->getParams(), ['interception' => $interception]);
     if ($format && ($result = $this->language->evaluate($format, $parameters))) {
         return sha1(serialize($result));
     }
     return $this->keyGenerator->generateKey($interception, $annotation);
 }
コード例 #10
0
 /**
  * @return string
  */
 public function __invoke()
 {
     if (empty($this->keys)) {
         $values = array();
     } else {
         $args = func_get_args();
         $values = array_combine($this->keys, $args);
     }
     return $this->expressionLanguage->evaluate($this->getExpression(), $values);
 }
コード例 #11
0
 /**
  * @param  string $expression
  * @param  mixed  $data
  * @return mixed
  */
 public function evaluate($expression, $data)
 {
     if (!preg_match(self::EXPRESSION_REGEX, $expression, $matches)) {
         return $expression;
     }
     $expression = $matches['expression'];
     $context = array_merge($this->context, array('object' => $data));
     $parsedExpression = $this->expressionLanguage->parse($expression, array_keys($context));
     return $this->expressionLanguage->evaluate($parsedExpression, $context);
 }
コード例 #12
0
 /**
  * Evaluate value
  *
  * @param string $value
  * @param array  $attributes
  *
  * @return mixed
  */
 private function evaluateValue($value, array $attributes)
 {
     if ($value[0] == '@') {
         if (!$this->expressionLanguage) {
             throw new \LogicException('Can not evaluate expression language. Please inject ExpressionLanguage to ORMParameterConverter.');
         }
         $value = substr($value, 1);
         $value = $this->expressionLanguage->evaluate($value, $attributes);
     }
     return $value;
 }
コード例 #13
0
ファイル: Analyser.php プロジェクト: Bluetel-Solutions/Warden
 /**
  * Checks the limits against the actual recorded values and determines whether they have exceeded
  *
  * @return void
  */
 public function checkResults()
 {
     $data = $this->params->all();
     foreach ($data as $key => $value) {
         $failed = $this->expression->evaluate($value['expression'], array('value' => $value['value'], 'limit' => $value['limit']));
         if ($failed) {
             // We throw the exception because the limit has been breached.
             throw new Exceptions\LimitExceededException($value['value'], $value['limit'], $key);
         }
     }
 }
コード例 #14
0
 /**
  * @inheritdoc
  */
 public function resolve($func)
 {
     if (!is_array($func)) {
         return null;
     }
     $key = key($func);
     $expression = array_shift($func);
     return function ($item) use($key, $expression, $func) {
         return $this->expressionLanguage->evaluate($expression, array_merge($func, [$key => $item]));
     };
 }
コード例 #15
0
ファイル: Filter.php プロジェクト: advmaker/LamantinParser
 /**
  * @param array $input
  */
 public function filterPrice(array $input = [])
 {
     if (empty($input) || $this->collection->isEmpty()) {
         return null;
     }
     foreach ($input as $nested) {
         list($operand, $value) = array_values($this->getOperandAndValue($nested));
         $this->collection = $this->collection->filter(function (array $entry) use($operand, $value) {
             return $this->expression->evaluate("entry['price'] {$operand} value", compact('entry', 'value'));
         });
     }
 }
 /**
  * @param Condition $condition
  * @param mixed $subject
  * @return bool
  */
 public function evaluate(Condition $condition, $subject)
 {
     try {
         /** @var ExpressionLanguageCondition $condition */
         return (bool) $this->expressionLanguage->evaluate($condition->expression(), ['subject' => $subject]);
     } catch (SyntaxError $syntaxError) {
         if ($this->evaluateSyntaxErrorsToFalse) {
             return false;
         }
         throw $syntaxError;
     }
 }
コード例 #17
0
 function it_should_parse_expression_with_parameters(ContainerInterface $container, ExpressionLanguage $expression, Request $request)
 {
     $request->get('foo')->willReturn('bar');
     $request->get('baz')->willReturn(1);
     $expression->evaluate('service("demo_service")', ['container' => $container])->willReturn('demo_object');
     $this->parseRequestValues(['factory' => ['method' => 'createByParameter', 'arguments' => ['expr:service("demo_service")']]], $request)->shouldReturn(['factory' => ['method' => 'createByParameter', 'arguments' => ['demo_object']]]);
     $expression->evaluate('service("demo_service")->getWith("bar")', ['container' => $container])->willReturn('demo_object->getWith("bar")');
     $this->parseRequestValues(['factory' => ['method' => 'createByParameter', 'arguments' => ['expr:service("demo_service")->getWith($foo)']]], $request)->shouldReturn(['factory' => ['method' => 'createByParameter', 'arguments' => ['demo_object->getWith("bar")']]]);
     $expression->evaluate('service("demo_service")->getWith("bar", 1)', ['container' => $container])->willReturn('demo_object->getWith("bar", 1)');
     $this->parseRequestValues(['factory' => ['method' => 'createByParameter', 'arguments' => ['expr:service("demo_service")->getWith($foo, $baz)']]], $request)->shouldReturn(['factory' => ['method' => 'createByParameter', 'arguments' => ['demo_object->getWith("bar", 1)']]]);
     $expression->evaluate('service("demo_service")->getWith("bar")->andGet(1)', ['container' => $container])->willReturn('demo_object->getWith("bar")->andGet(1)');
     $this->parseRequestValues(['factory' => ['method' => 'createByParameter', 'arguments' => ['expr:service("demo_service")->getWith($foo)->andGet($baz)']]], $request)->shouldReturn(['factory' => ['method' => 'createByParameter', 'arguments' => ['demo_object->getWith("bar")->andGet(1)']]]);
 }
コード例 #18
0
 /**
  * {@inheritdoc}
  */
 public function validate($value)
 {
     $errors = array();
     $this->addVariable('value', $value);
     // Sometime ExpressionValueValidator is constructed without the
     // ExpressionLanguage object, so it can be cached. ExpressionLanguage
     // can't be cached because of closures.
     $this->expressionLanguage = $this->expressionLanguage ?: new ExpressionLanguage();
     if (!$this->expressionLanguage->evaluate($this->expression, $this->variables)) {
         $errors[] = new Error($this->options['message']);
     }
     return $errors;
 }
コード例 #19
0
ファイル: Toggle.php プロジェクト: niborb/php-feature-toggle
 /**
  * @param FeatureExpressionInterface $feature
  * @param array $context
  *
  * @throws \RuntimeException if expression could not be validated
  *
  * @return bool|string
  */
 private function validate(FeatureExpressionInterface $feature, array $context = [])
 {
     $expression = $feature->getExpression();
     if ('' !== $expression && $this->expressionLanguage instanceof ExpressionLanguage) {
         try {
             return (bool) $this->expressionLanguage->evaluate($expression, $context);
         } catch (\Exception $e) {
             throw new \RuntimeException("Could not evaluate expression " . $expression, 0, $e);
         }
     }
     return true;
     // no expression to validate
 }
コード例 #20
0
 /**
  * Returns the objects filtered by the given path value.
  *
  * @param array  $objects
  * @param string $expression
  *
  * @return array
  */
 public function filter(array $objects, $expression)
 {
     $filteredObjects = array();
     foreach ($objects as $key => $object) {
         try {
             if (@$this->language->evaluate('object.' . $expression, array('object' => $object))) {
                 $filteredObjects[] = $object;
             }
         } catch (\Exception $exception) {
             // Property does not exist: ignore this item
         }
     }
     return $filteredObjects;
 }
コード例 #21
0
ファイル: SumExtension.php プロジェクト: wucdbm/wucdbm-bundle
 public function count($arrayOrObject, $expression = null)
 {
     $count = 0;
     foreach ($arrayOrObject as $value) {
         $shouldSum = true;
         if (null !== $expression) {
             $shouldSum = $this->language->evaluate($expression, array('value' => $value));
         }
         if ($shouldSum) {
             $count++;
         }
     }
     return $count;
 }
コード例 #22
0
ファイル: PolicyModel.php プロジェクト: stevedien/gatekeeper
 public function evaluate($data, $expression = null)
 {
     if ($this->id === null) {
         throw new \InvalidArgumentException('Policy not loaded!');
     }
     $expression = $expression === null ? $this->expression : $expression;
     if (!is_array($data)) {
         $data = array($data);
     }
     $context = array();
     foreach ($data as $index => $item) {
         if (is_numeric($index)) {
             // Resolve it to a class name
             $ns = explode('\\', get_class($item));
             $index = str_replace('Model', '', array_pop($ns));
         }
         $context[strtolower($index)] = $item;
     }
     $language = new ExpressionLanguage();
     try {
         return $language->evaluate($expression, $context);
     } catch (\Exception $e) {
         throw new Exception\InvalidExpressionException($e->getMessage());
     }
 }
コード例 #23
0
 public function testConstantFunction()
 {
     $expressionLanguage = new ExpressionLanguage();
     $this->assertEquals(PHP_VERSION, $expressionLanguage->evaluate('constant("PHP_VERSION")'));
     $expressionLanguage = new ExpressionLanguage();
     $this->assertEquals('constant("PHP_VERSION")', $expressionLanguage->compile('constant("PHP_VERSION")'));
 }
コード例 #24
0
ファイル: AnalysisCommand.php プロジェクト: ftdysa/insight
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $api = $this->getApplication()->getApi();
     $analysis = $api->getProject($input->getArgument('project-uuid'))->getLastAnalysis();
     if (!$analysis) {
         $output->writeln('<error>There are no analyses</error>');
         return 1;
     }
     $helper = new DescriptorHelper($api->getSerializer());
     $helper->describe($output, $analysis, $input->getOption('format'));
     if ('txt' === $input->getOption('format') && OutputInterface::VERBOSITY_VERBOSE > $output->getVerbosity()) {
         $output->writeln('');
         $output->writeln('Re-run this command with <comment>-v</comment> option to get the full report');
     }
     if (!($expr = $input->getOption('fail-condition'))) {
         return;
     }
     $el = new ExpressionLanguage();
     $counts = array();
     foreach ($analysis->getViolations() as $violation) {
         if (!isset($counts[$violation->getCategory()])) {
             $counts[$violation->getCategory()] = 0;
         }
         ++$counts[$violation->getCategory()];
         if (!isset($counts[$violation->getSeverity()])) {
             $counts[$violation->getSeverity()] = 0;
         }
         ++$counts[$violation->getSeverity()];
     }
     $vars = array('analysis' => $analysis, 'counts' => (object) $counts);
     if ($el->evaluate($expr, $vars)) {
         return 70;
     }
 }
コード例 #25
0
ファイル: ConfigLoader.php プロジェクト: radvance/radvance
 private function postProcessConfigString($string, $parameters)
 {
     $language = new ExpressionLanguage();
     $language->register('env', function ($str) {
         // This implementation is only needed if you want to compile
         // not needed when simply using the evaluator
         throw new RuntimeException("The 'env' method is not yet compilable.");
     }, function ($arguments, $str, $required = false) {
         $res = getenv($str);
         if (!$res && $required) {
             throw new RuntimeException("Required environment variable '{$str}' is not defined");
         }
         return $res;
     });
     preg_match_all('~\\{\\{(.*?)\\}\\}~', $string, $matches);
     $variables = array();
     //$variables['hello']='world';
     foreach ($matches[1] as $match) {
         $out = $language->evaluate($match, $variables);
         $string = str_replace('{{' . $match . '}}', $out, $string);
     }
     // Inject parameters for strings between % characters
     if (substr($string, 0, 1) == '%' && substr($string, -1, 1) == '%') {
         $string = trim($string, '%');
         if (!isset($parameters[$string])) {
             throw new RuntimeException("Required parameter '{$string}' not defined");
         }
         $string = $parameters[$string];
     }
     return $string;
 }
コード例 #26
0
 /**
  * @param $step
  * @return bool|string
  */
 private function executeCondition(WizardStep $step)
 {
     if (null !== $step->getCondition()) {
         return $this->expressionLanguage->evaluate($step->getCondition(), $this->getValues());
     }
     return true;
 }
コード例 #27
0
 public function it_evaluates_the_rule_based_on_subject_to_false_when_exception_is_thrown(RuleInterface $rule, RuleSubjectInterface $subject, LoggerInterface $logger, ExpressionLanguage $expression)
 {
     $rule->getExpression()->shouldBeCalled();
     $subject->getSubjectType()->shouldBeCalled();
     $expression->evaluate(Argument::type('string'), Argument::type('array'))->willReturn(false);
     $logger->error(Argument::type('string'))->shouldBeCalled();
     $this->evaluate($rule, $subject)->shouldReturn(false);
 }
コード例 #28
0
 public function testCachingForOverriddenVariableNames()
 {
     $expressionLanguage = new ExpressionLanguage();
     $expression = 'a + b';
     $expressionLanguage->evaluate($expression, array('a' => 1, 'b' => 1));
     $result = $expressionLanguage->compile($expression, array('a', 'B' => 'b'));
     $this->assertSame('($a + $B)', $result);
 }
 /**
  * Prepares the fake parameters
  *
  * @param array $pathVariables
  * @param array $fakeParameters
  *
  * @return array
  */
 public function prepareFakeParameters(array $pathVariables, array $fakeParameters = [])
 {
     $placeholders = [];
     foreach ($pathVariables as $pathVariable) {
         if (isset($fakeParameters[$pathVariable])) {
             try {
                 $placeholders[$pathVariable] = $this->language->evaluate($fakeParameters[$pathVariable], $this->expressionContext);
             } catch (SyntaxError $e) {
                 // if the compilation fails, we just use the text as string
                 // this allows arbitrary strings, which weren't meant as expression
                 $placeholders[$pathVariable] = $fakeParameters[$pathVariable];
             }
         } else {
             $placeholders[$pathVariable] = 1;
         }
     }
     return $placeholders;
 }
コード例 #30
0
 /**
  * Evaluates expression
  *
  * @param $expression
  *
  * @return string
  * @throws BuildException
  */
 private function evaluate($expression)
 {
     try {
         $evaluatedExpression = $this->expressionLanguage->evaluate($expression, $this->data);
     } catch (\Exception $e) {
         throw new BuildException($e->getMessage());
     }
     return $evaluatedExpression;
 }