evaluate example

$this->assertTrue($condition->execute(), 'The request path matches an aliased path');
    $this->assertEquals('Return true on the following pages: /my/pass/page, /my/pass/page2, /foo', $condition->summary(), 'The condition summary matches for an aliased path');

    // Test a wildcard path.     $this->aliasManager->addAlias('/my/pass/page3', '/my/pass/page3');
    $this->currentPath->setPath('/my/pass/page3', $request);
    $this->requestStack->pop();
    $this->requestStack->push($request);

    $condition->setConfig('pages', '/my/pass/*');

    $this->assertTrue($condition->evaluate(), 'The system_path my/pass/page3 passes for wildcard paths.');
    $this->assertEquals('Return true on the following pages: /my/pass/*', $condition->summary(), 'The condition summary matches for a wildcard path');

    // Test a missing path.     $this->requestStack->pop();
    $this->requestStack->push($request);
    $this->currentPath->setPath('/my/fail/page4', $request);

    $condition->setConfig('pages', '/my/pass/*');

    $this->aliasManager->addAlias('/my/fail/page4', '/my/fail/page4');

    
++$expectedCalls;
            $expectedStartCalls[] = [$this->equalTo($eventName), 'template'];
            $expectedStopCalls[] = [$this->equalTo($eventName)];
        }

        $stopwatch
            ->expects($this->exactly($expectedCalls))
            ->method('start')
            ->willReturnCallback(function Dstring $name, string $category) use (&$expectedStartCalls) {
                [$expectedName$expectedCategory] = array_shift($expectedStartCalls);

                $expectedName->evaluate($name);
                $this->assertSame($expectedCategory$category);

                return $this->createMock(StopwatchEvent::class);
            })
        ;

        $stopwatch
            ->expects($this->exactly($expectedCalls))
            ->method('stop')
            ->willReturnCallback(function Dstring $name) use (&$expectedStopCalls) {
                [$expectedName] = array_shift($expectedStopCalls);
                
public function validate(mixed $value, Constraint $constraint): void
    {
        if (!$constraint instanceof When) {
            throw new UnexpectedTypeException($constraint, When::class);
        }

        $context = $this->context;
        $variables = $constraint->values;
        $variables['value'] = $value;
        $variables['this'] = $context->getObject();

        if ($this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) {
            $context->getValidator()->inContext($context)
                ->validate($value$constraint->constraints);
        }
    }

    private function getExpressionLanguage(): ExpressionLanguage
    {
        if (!class_exists(ExpressionLanguage::class)) {
            throw new LogicException(sprintf('The "symfony/expression-language" component is required to use the "%s" validator. Try running "composer require symfony/expression-language".', __CLASS__));
        }

        
->compile($this->nodes['expr2'])
            ->raw('))')
        ;
    }

    public function evaluate(array $functions, array $values): mixed
    {
        if ($this->nodes['expr1'] instanceof GetAttrNode) {
            $this->nodes['expr1']->attributes['is_null_coalesce'] = true;
        }

        return $this->nodes['expr1']->evaluate($functions$values) ?? $this->nodes['expr2']->evaluate($functions$values);
    }

    public function toArray(): array
    {
        return ['(', $this->nodes['expr1'], ') ?? (', $this->nodes['expr2'], ')'];
    }
}
$series = [
                $this->equalTo((new RequestContext())->fromRequest($request)->setParameter('_locale', $request->getLocale())),
                $currentRequestContext,
            ];

            $this->router->expects($this->exactly(2))
                ->method('setContext')
                ->willReturnCallback(function DRequestContext $context) use (&$series) {
                    $expectedContext = array_shift($series);

                    if ($expectedContext instanceof Constraint) {
                        $expectedContext->evaluate($context);
                    } else {
                        $this->assertSame($expectedContext$context);
                    }
                });
        }

        $loginLink = $this->createLinker([]array_keys($extraProperties))->createLoginLink($user$request);
        $this->assertSame('https://example.com/login/verify?user=weaverryan&hash=abchash&expires=1601235000', $loginLink->getUrl());
    }

    public static function provideCreateLoginLinkData()
    {
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Test\Constraint\ResponseHasCookie;

class ResponseHasCookieTest extends TestCase
{
    public function testConstraint()
    {
        $response = new Response();
        $response->headers->setCookie(Cookie::create('foo', 'bar'));
        $constraint = new ResponseHasCookie('foo');
        $this->assertTrue($constraint->evaluate($response, '', true));
        $constraint = new ResponseHasCookie('bar');
        $this->assertFalse($constraint->evaluate($response, '', true));

        try {
            $constraint->evaluate($response);
        } catch (ExpectationFailedException $e) {
            $this->assertEquals("Failed asserting that the Response has cookie \"bar\".\n", TestFailure::exceptionToString($e));

            return;
        }

        

            if (isset($rule['attrName']) && is_array($rule['attrName']) && !in_array($attr->localName, $rule['attrName'], true)) {
                continue;
            }
            if (isset($rule['xpath'])) {
                $xp = $this->getXPath($attr);
                if (isset($rule['prefixes'])) {
                    foreach ($rule['prefixes'] as $nsPrefix => $ns) {
                        $xp->registerNamespace($nsPrefix$ns);
                    }
                }
                if (!$xp->evaluate($rule['xpath']$attr)) {
                    continue;
                }
            }

            return true;
        }

        return false;
    }

    private function getXPath(\DOMNode $node)
    {
$parsedExpression = $expressionLanguage->parse('1 + 1', []);
        $this->assertSame($savedParsedExpression$parsedExpression);

        $parsedExpression = $expressionLanguage->parse('1 + 1', []);
        $this->assertSame($savedParsedExpression$parsedExpression);
    }

    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")'));
    }

    public function testEnumFunctionWithConstantThrows()
    {
        $this->expectException(\TypeError::class);
        $this->expectExceptionMessage('The string "PHP_VERSION" is not the name of a valid enum case.');
        $expressionLanguage = new ExpressionLanguage();
        $expressionLanguage->evaluate('enum("PHP_VERSION")');
    }
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\DomCrawler\Test\Constraint\CrawlerSelectorAttributeValueSame;

class CrawlerSelectorAttributeValueSameTest extends TestCase
{
    public function testConstraint()
    {
        $constraint = new CrawlerSelectorAttributeValueSame('input[name="username"]', 'value', 'Fabien');
        $this->assertTrue($constraint->evaluate(new Crawler('<html><body><form><input type="text" name="username" value="Fabien">'), '', true));
        $this->assertFalse($constraint->evaluate(new Crawler('<html><body><form><input type="text" name="username">'), '', true));
        $this->assertFalse($constraint->evaluate(new Crawler('<html><head><title>Bar'), '', true));

        try {
            $constraint->evaluate(new Crawler('<html><head><title>Bar'));
        } catch (ExpectationFailedException $e) {
            $this->assertEquals("Failed asserting that the Crawler has a node matching selector \"input[name=\"username\"]\" with attribute \"value\" of value \"Fabien\".\n", TestFailure::exceptionToString($e));

            return;
        }

        


        $args = [
            $this->getUniqueToken($key),
            time(),
            $ttlInSecond,
            $key->getLimit(),
            $key->getWeight(),
        ];

        if (!$this->evaluate($scriptsprintf('{%s}', $key)$args)) {
            throw new SemaphoreAcquiringException($key, 'the script return false');
        }
    }

    /** * @return void */
    public function putOffExpiration(Key $key, float $ttlInSecond)
    {
        if (0 > $ttlInSecond) {
            throw new InvalidArgumentException("The TTL should be greater than 0, '$ttlInSecond' given.");
        }
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\Constraint\CommandIsSuccessful;

final class CommandIsSuccessfulTest extends TestCase
{
    public function testConstraint()
    {
        $constraint = new CommandIsSuccessful();

        $this->assertTrue($constraint->evaluate(Command::SUCCESS, '', true));
        $this->assertFalse($constraint->evaluate(Command::FAILURE, '', true));
        $this->assertFalse($constraint->evaluate(Command::INVALID, '', true));
    }

    /** * @dataProvider providesUnsuccessful */
    public function testUnsuccessfulCommand(string $expectedException, int $exitCode)
    {
        $constraint = new CommandIsSuccessful();

        
/** * @author Kévin Dunglas <kevin@dunglas.fr> */
class ResponseFormatSameTest extends TestCase
{
    public function testConstraint()
    {
        $request = new Request();
        $request->setFormat('custom', ['application/vnd.myformat']);

        $constraint = new ResponseFormatSame($request, 'custom');
        $this->assertTrue($constraint->evaluate(new Response('', 200, ['Content-Type' => 'application/vnd.myformat']), '', true));
        $this->assertFalse($constraint->evaluate(new Response(), '', true));

        try {
            $constraint->evaluate(new Response('', 200, ['Content-Type' => 'application/ld+json']));
        } catch (ExpectationFailedException $e) {
            $this->assertStringContainsString("Failed asserting that the Response format is custom.\nHTTP/1.0 200 OK", TestFailure::exceptionToString($e));

            return;
        }

        $this->fail();
    }
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Test\Constraint\ResponseIsUnprocessable;

class ResponseIsUnprocessableTest extends TestCase
{
    public function testConstraint()
    {
        $constraint = new ResponseIsUnprocessable();

        $this->assertTrue($constraint->evaluate(new Response('', 422), '', true));
        $this->assertFalse($constraint->evaluate(new Response(), '', true));
    }
}
$class = $value->getClass();

            if ($class && isset(self::BUILTIN_TYPES[strtolower($class)])) {
                $class = strtolower($class);
            } elseif (!$class || (!$this->autoload && !class_exists($class, false) && !interface_exists($class, false))) {
                return;
            }
        } elseif ($value instanceof Parameter) {
            $value = $this->container->getParameter($value);
        } elseif ($value instanceof Expression) {
            try {
                $value = $this->getExpressionLanguage()->evaluate($value['container' => $this->container]);
            } catch (\Exception) {
                // If a service from the expression cannot be fetched from the container, we skip the validation.                 return;
            }
        } elseif (\is_string($value)) {
            if ('%' === ($value[0] ?? '') && preg_match('/^%([^%]+)%$/', $value$match)) {
                $value = $this->container->getParameter(substr($value, 1, -1));
            }

            if ($envPlaceholderUniquePrefix && \is_string($value) && str_contains($value, 'env_')) {
                // If the value is an env placeholder that is either mixed with a string or with another env placeholder, then its resolved value will always be a string, so we don't need to resolve it.
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\DomCrawler\Test\Constraint\CrawlerAnySelectorTextContains;

class CrawlerAnySelectorTextContainsTest extends TestCase
{
    public function testConstraint()
    {
        $constraint = new CrawlerAnySelectorTextContains('ul li', 'Foo');

        self::assertTrue($constraint->evaluate(new Crawler('<ul><li>Foo</li>'), '', true));
        self::assertTrue($constraint->evaluate(new Crawler('<ul><li>Bar</li><li>Foo'), '', true));
        self::assertTrue($constraint->evaluate(new Crawler('<ul><li>Bar</li><li>Foo Bar Baz'), '', true));
        self::assertFalse($constraint->evaluate(new Crawler('<ul><li>Bar</li><li>Baz'), '', true));

        try {
            $constraint->evaluate(new Crawler('<ul><li>Bar</li><li>Baz'));

            self::fail();
        } catch (ExpectationFailedException $e) {
            self::assertEquals("Failed asserting that the text of any node matching selector \"ul li\" contains \"Foo\".\n", TestFailure::exceptionToString($e));
        }

        
Home | Imprint | This part of the site doesn't use cookies.