Skip to content

add 'Yaml', 'Xml, and 'Jwt' constraints #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ CHANGELOG

7.2
---

* Add the `Yaml`, `Xml` and `Jwt` constraints
* Make `PasswordStrengthValidator::estimateStrength()` public

7.1
Expand Down
32 changes: 32 additions & 0 deletions src/Symfony/Component/Validator/Constraints/AbstractFormat.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* Used for the format of values.
*
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
abstract class AbstractFormat extends Constraint
{
public string $format;
public string $message = 'This value should be valid {{ format }}.';

public function __construct(?string $message = null, ?array $options = null, ?array $groups = null, mixed $payload = null)
{
parent::__construct($options, $groups, $payload);

$this->message = $message ?? $this->message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;


use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
* Provides a base class for the validation of value format.
*
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
abstract class AbstractFormatValidator extends ConstraintValidator
{
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof AbstractFormat) {
throw new UnexpectedTypeException($constraint, AbstractFormat::class);
}

if (null === $value || '' === $value) {
return;
}

if (!\is_scalar($value) && !$value instanceof \Stringable) {
throw new UnexpectedValueException($value, 'string');
}

if ($this->validateFormat((string) $value)) {
return;
}

$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameter('{{ format }}', $constraint->format)
->setCode($this->getErrorCode())
->addViolation();
}

/**
* Validate format value
*/
abstract protected function validateFormat(string $value): bool;

abstract protected function getErrorCode(): string;
}
10 changes: 3 additions & 7 deletions src/Symfony/Component/Validator/Constraints/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,28 @@

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* Validates that a value has valid JSON syntax.
*
* @author Imad ZAIRIG <imadzairig@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Json extends Constraint
class Json extends AbstractFormat
{
public const INVALID_JSON_ERROR = '0789c8ad-2d2b-49a4-8356-e2ce63998504';

protected const ERROR_NAMES = [
self::INVALID_JSON_ERROR => 'INVALID_JSON_ERROR',
];

public string $message = 'This value should be valid JSON.';
public string $format = 'JSON';

/**
* @param array<string,mixed>|null $options
* @param string[]|null $groups
*/
public function __construct(?array $options = null, ?string $message = null, ?array $groups = null, mixed $payload = null)
{
parent::__construct($options, $groups, $payload);

$this->message = $message ?? $this->message;
parent::__construct($message, $options, $groups, $payload);
}
}
33 changes: 7 additions & 26 deletions src/Symfony/Component/Validator/Constraints/JsonValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,37 +11,18 @@

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
* @author Imad ZAIRIG <imadzairig@gmail.com>
*/
class JsonValidator extends ConstraintValidator
class JsonValidator extends AbstractFormatValidator
{
public function validate(mixed $value, Constraint $constraint): void
protected function validateFormat(string $value): bool
{
if (!$constraint instanceof Json) {
throw new UnexpectedTypeException($constraint, Json::class);
}

if (null === $value || '' === $value) {
return;
}

if (!\is_scalar($value) && !$value instanceof \Stringable) {
throw new UnexpectedValueException($value, 'string');
}

$value = (string) $value;
return json_validate($value);
}

if (!json_validate($value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Json::INVALID_JSON_ERROR)
->addViolation();
}
protected function getErrorCode(): string
{
return Json::INVALID_JSON_ERROR;
}
}
29 changes: 29 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Jwt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

/**
* Validates that a value is a valid jwt format.
*
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Jwt extends AbstractFormat
{
public const INVALID_JWT_ERROR = '8f14e45f-e6e5-4c6c-9c17-68f22a1f3dff';

protected const ERROR_NAMES = [
self::INVALID_JWT_ERROR => 'INVALID_JWT_ERROR',
];

public string $format = 'JWT';
}
48 changes: 48 additions & 0 deletions src/Symfony/Component/Validator/Constraints/JwtValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class JwtValidator extends AbstractFormatValidator
{
protected function validateFormat(string $value): bool
{
// Split the JWT into its three parts
$parts = explode('.', $value);

// JWT should have exactly three parts
if (count($parts) !== 3) {
return false;
}

[$header, $payload, $signature] = $parts;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$signature is unused

Suggested change
[$header, $payload, $signature] = $parts;
[$header, $payload] = $parts;


// Replace URL-safe characters with standard Base64 characters and decode
$decodedHeader = base64_decode(strtr($header, '-_', '+/'));
$decodedPayload = base64_decode(strtr($payload, '-_', '+/'));

// Check if the decoded header and payload are valid JSON
if (!json_validate($decodedHeader) || !json_validate($decodedPayload)) {
return false;
}

// At this point, it looks like a JWT
return true;
Comment on lines +35 to +41

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Check if the decoded header and payload are valid JSON
if (!json_validate($decodedHeader) || !json_validate($decodedPayload)) {
return false;
}
// At this point, it looks like a JWT
return true;
return json_validate($decodedHeader) && json_validate($decodedPayload)

}

protected function getErrorCode(): string
{
return Jwt::INVALID_JWT_ERROR;
}
}
29 changes: 29 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Xml.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

/**
* Validates that a value is a valid xml format.
*
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Xml extends AbstractFormat
{
public const INVALID_XML_ERROR = '0355230a-97b8-49da-b8cd-985bf3345bcf';

protected const ERROR_NAMES = [
self::INVALID_XML_ERROR => 'INVALID_XML_ERROR',
];

public string $format = 'XML';
}
28 changes: 28 additions & 0 deletions src/Symfony/Component/Validator/Constraints/XmlValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class XmlValidator extends AbstractFormatValidator
{
protected function validateFormat(string $value): bool
{
return false !== @simplexml_load_string($value);
}

protected function getErrorCode(): string
{
return Xml::INVALID_XML_ERROR;
}
}
45 changes: 45 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Yaml.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Exception\LogicException;
use Symfony\Component\Yaml\Yaml as SymfonyYaml;

/**
* Validates that a value is a valid yaml format.
*
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Yaml extends AbstractFormat
{
public const INVALID_YAML_ERROR = '8f14e45f-e6e5-4c6c-9c17-68f22a1f3dff';

protected const ERROR_NAMES = [
self::INVALID_YAML_ERROR => 'INVALID_YAML_ERROR',
];

public string $format = 'YAML';

/**
* @param string[]|null $groups
* @param array<string,mixed> $options
*/
public function __construct(?array $options = null, ?string $message = null, ?array $groups = null, mixed $payload = null)
{
if (!class_exists(SymfonyYaml::class)) {
throw new LogicException('The Yaml component is required to use the Yaml constraint. Try running "composer require symfony/yaml".');
}

parent::__construct($message, $options, $groups, $payload);
}
}
Loading
Loading