protected function getExpressionLanguage() { $language = new ExpressionLanguage(); $language->register('ini', function ($value) { return $value; }, function ($arguments, $value) { return ini_get($value); }); return $language; }
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; } }
/** * @dataProvider shortCircuitProviderCompile */ public function testShortCircuitOperatorsCompile($expression, array $names, $expected) { $result = null; $expressionLanguage = new ExpressionLanguage(); eval(sprintf('$result = %s;', $expressionLanguage->compile($expression, $names))); $this->assertSame($expected, $result); }
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; }
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")')); }
/** * @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'); }
/** * @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); }
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()); } }
/** * Register a new new ExpressionLanguage function. * * @param ExpressionFunctionInterface $function * * @return ExpressionEvaluator */ public function registerFunction(ExpressionFunctionInterface $function) { $this->expressionLanguage->register($function->getName(), $function->getCompiler(), $function->getEvaluator()); foreach ($function->getContextVariables() as $name => $value) { $this->setContextVariable($name, $value); } return $this; }
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()); }
/** * @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; } }
/** * @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]); }
/** * {@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); } }
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); }
/** * {@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; }
/** * @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); }
/** * @param ContentView $contentView * @param string $queryParameterValue * * @return mixed */ private function evaluateExpression(ContentView $contentView, $queryParameterValue) { if (substr($queryParameterValue, 0, 2) === '@=') { $language = new ExpressionLanguage(); return $language->evaluate(substr($queryParameterValue, 2), ['view' => $contentView, 'location' => $contentView->getLocation(), 'content' => $contentView->getContent()]); } else { return $queryParameterValue; } }
/** * Registers new function to expression language * * @param ExpressionFunction $expressionFunction * * @return void */ public function registerFunction(ExpressionFunction $expressionFunction) { $functionToCall = $expressionFunction->expressionFunction(); $this->expressionReader->register($expressionFunction->name(), null, function () use($functionToCall) { $arguments = func_get_args(); array_shift($arguments); return $functionToCall($arguments); }); }
/** * Build root resource. * * @return array|\eZ\Publish\Core\REST\Common\Values\Root */ public function buildRootResource() { $language = new ExpressionLanguage(); $resources = array(); foreach ($this->resourceConfig as $name => $resource) { $resources[] = new Values\Resource($name, $resource['mediaType'], $language->evaluate($resource['href'], ['router' => $this->router, 'templateRouter' => $this->templateRouter])); } return new Root($resources); }
/** * {@inheritDoc} */ public function match($value, $pattern) { $language = new ExpressionLanguage(); preg_match(self::MATCH_PATTERN, $pattern, $matches); $expressionResult = $language->evaluate($matches[1], array('value' => $value)); if (!$expressionResult) { $this->error = sprintf("\"%s\" expression fails for value \"%s\".", $pattern, new String($value)); } return (bool) $expressionResult; }
/** * @return \Symfony\Component\ExpressionLanguage\ExpressionLanguage */ private function getExpressionLanguage() { $language = new ExpressionLanguage(); $language->register('has', function ($str) { return sprintf('(in_array(%1$s, scope))', $str); }, function ($arguments, $str) { return in_array($str, $arguments['scope']); }); return $language; }
public function apply($value) { $language = new ExpressionLanguage($this); $values = array(); foreach ($this->container as $name => $service) { $values[$name] = $service; } $values['value'] = $value; return $language->evaluate($this->expression, $values); }
/** * @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); }
/** * Register function. * * @param ExpressionLanguage $expressionLanguage Expression language */ public function registerFunction(ExpressionLanguage $expressionLanguage) { $expressionLanguage->register('p', function ($ids) { return sprintf('(purchasable.id in [%1$s])', $ids); }, function ($arguments, $ids) { $ids = explode(',', $ids); $purchasable = $arguments['purchasable']; return in_array($purchasable->getId(), $ids); }); }
/** * Returns true if object satisfies the specification * @param $spec * @return boolean */ public function isSatisfiedBy($spec) { $lang = new ExpressionLanguage(); // TODO: add caching $ret = $lang->evaluate($this->generator->generate(), $spec); if (!is_bool($ret)) { throw new NotBooleanExpression(); } return $ret; }
/** * {@inheritDoc} * * Loads the configuration from the yml file into container parameters */ protected function loadInternal(array $config, ContainerBuilder $container) { $language = new ExpressionLanguage(); // Evaluate match score modifiers -- this converts strings like "2/3" to // the corresponding number foreach ($config['league']['duration'] as &$modifier) { $modifier = $language->evaluate($modifier); } $this->store('bzion', $config); $container->getParameterBag()->add($this->conf); }
public function __construct(ExpressionLanguage $expressionLanguage) { $this->functionMapApply = array('mixin_add' => function ($operand, $row, $mixinName) { $node = $row->getNode(); $node->addMixin($mixinName); }, 'mixin_remove' => function ($operand, $row, $mixinName) { $node = $row->getNode(); if ($node->isNodeType($mixinName)) { $node->removeMixin($mixinName); } }); $this->functionMapSet = array('expr' => function ($operand, $row, $expression) use($expressionLanguage) { return $expressionLanguage->evaluate($expression, array('row' => $row)); }, 'array_replace' => function ($operand, $row, $v, $x, $y) { $operand->validateScalarArray($v); foreach ($v as $key => $value) { if ($value === $x) { $v[$key] = $y; } } return $v; }, 'array_remove' => function ($operand, $row, $v, $x) { foreach ($v as $key => $value) { if ($value === $x) { unset($v[$key]); } } return array_values($v); }, 'array_append' => function ($operand, $row, $v, $x) { $operand->validateScalarArray($v); $v[] = $x; return $v; }, 'array' => function () { $values = func_get_args(); // first argument is the operand array_shift($values); // second is the row array_shift($values); return $values; }, 'array_replace_at' => function ($operand, $row, $current, $index, $value) { if (!isset($current[$index])) { throw new \InvalidArgumentException(sprintf('Multivalue index "%s" does not exist', $index)); } if (null !== $value && !is_scalar($value)) { throw new \InvalidArgumentException('Cannot use an array as a value in a multivalue property'); } if (null === $value) { unset($current[$index]); } else { $current[$index] = $value; } return array_values($current); }); }
public function handle(RequestInterface $request, ParametersInterface $configuration, ContextInterface $context) { $condition = $configuration->get('condition'); $language = new ExpressionLanguage($this); $values = array('rateLimit' => new RateLimit($this->connection, $context), 'app' => $context->getApp(), 'routeId' => $context->getRouteId(), 'uriFragments' => $request->getUriFragments(), 'parameters' => $request->getParameters(), 'body' => new Accessor(new Validate(), $request->getBody())); if (!empty($condition) && $language->evaluate($condition, $values)) { return $this->processor->execute($configuration->get('true'), $request, $context); } else { return $this->processor->execute($configuration->get('false'), $request, $context); } }
/** * 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); } } }
/** * Filter array with given symfony-expression. * * @param array $collection * @param string $expression * @param array $context * * @return array */ public static function filter(array $collection, $expression, array $context = []) { $language = new ExpressionLanguage(); $result = []; foreach ($collection as $key => $item) { if ($language->evaluate($expression, array_merge($context, ['item' => $item, 'key' => $key]))) { $result[$key] = $item; } } return $result; }