8000 [Validator] Add `Xml` constraint by sfmok · Pull Request #57365 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Add Xml constraint #57365

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.4
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
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ CHANGELOG
* Add support for multiple fields containing nested constraints in `Composite` constraints
* Add the `stopOnFirstError` option to the `Unique` constraint to validate all elements
* Add support for closures in the `When` constraint
* Add the `Xml` constraint for validating XML content

7.2
---
Expand Down
47 changes: 47 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Xml.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?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\Attribute\HasNamedArguments;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\InvalidArgumentException;

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

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

#[HasNamedArguments]
public function __construct(
public string $formatMessage = 'This value is not valid XML.',
public string $schemaMessage = 'This value is not conform to the XSD schema file.',
public ?string $schemaPath = null,
public int $schemaFlags = 0,
?array $groups = null,
mixed $payload = null,
) {
parent::__construct(null, $groups, $payload);

if (null !== $this->schemaPath && !is_readable($this->schemaPath)) {
throw new InvalidArgumentException(sprintf('The XSD schema file "%s" does not exist or is unreadable.', $this->schemaPath));
}
}
}
76 changes: 76 additions & 0 deletions src/Symfony/Component/Validator/Constraints/XmlValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?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;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class XmlValidator extends ConstraintValidator
{
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof Xml) {
throw new UnexpectedTypeException($constraint, Xml::class);
}

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

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

$value = (string) $value;

// First, check if XML is well-formed
$previousUseErrors = libxml_use_internal_errors(true);
$doc = simplexml_load_string($value);

if ($doc === false) {
$this->context->buildViolation($constraint->formatMessage)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Xml::INVALID_XML_ERROR)
->addViolation();

libxml_clear_errors();
libxml_use_internal_errors($previousUseErrors);

return;
}

// Second, validate against XML Schema if schemaPath provided
if ($constraint->schemaPath) {
$dom = \dom_import_simplexml($doc)->ownerDocument;

if (!$dom->schemaValidate($constraint->schemaPath, $constraint->schemaFlags)) {
$errors = libxml_get_errors();
libxml_clear_errors();

foreach ($errors as $error) {
$this->context->buildViolation($constraint->schemaMessage)
->setParameter('{{ error }}', $error->message)
->setParameter('{{ line }}', $error->line)
->setCode(Xml::INVALID_XML_ERROR)
->addViolation();
}
}
}

libxml_use_internal_errors($previousUseErrors);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<book>
<title>The Title</title>
<author>The Author</author>
</book>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
64 changes: 64 additions & 0 deletions src/Symfony/Component/Validator/Tests/Constraints/XmlTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?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\Tests\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Xml;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
class XmlTest extends TestCase
{
public function testAttributes()
{
$metadata = new ClassMetadata(XmlDummy::class);
$loader = new AttributeLoader();
self::assertTrue($loader->loadClassMetadata($metadata));

[$bConstraint] = $metadata->properties['b']->getConstraints();
self::assertSame('myMessage', $bConstraint->formatMessage);
self::assertSame('mySchemaMessage', $bConstraint->schemaMessage);
self::assertSame(LIBXML_NONET, $bConstraint->schemaFlags);
self::assertSame(['Default', 'XmlDummy'], $bConstraint->groups);

[$cConstraint] = $metadata->properties['c']->getConstraints();
self::assertSame(['my_group'], $cConstraint->groups);
self::assertSame('some attached data', $cConstraint->payload);
}

public function testInvalidSchemaPath()
{
$nonExistentFile = '/path/to/non-existent-file.xsd';

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('The XSD schema file "%s" does not exist or is unreadable.', $nonExistentFile));

new Xml(schemaPath: $nonExistentFile);
}

}

class XmlDummy
{
#[Xml]
private $a;

#[Xml(formatMessage: 'myMessage', schemaMessage: 'mySchemaMessage', schemaFlags: LIBXML_NONET)]
private $b;

#[Xml(groups: ['my_group'], payload: 'some attached data')]
private $c;
}
117 changes: 117 additions & 0 deletions src/Symfony/Component/Validator/Tests/Constraints/XmlValidatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?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\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Xml;
use Symfony\Component\Validator\Constraints\XmlValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
use Symfony\Component\Validator\Tests\Constraints\Fixtures\StringableValue;

/**
* @author Mokhtar Tlili <tlili.mokhtar@gmail.com>
*/
final class XmlValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator(): XmlValidator
{
return new XmlValidator();
}

/**
* @dataProvider getValidXmlFormatValues
*/
public function testValidXmlFormatValue($value)
{
$this->validator->validate($value, new Xml());
$this->assertNoViolation();
}

/**
* @dataProvider getInvalidXmlFormatValues
*/
public function testInvalidXmlFormatValue($value)
{
$constraint = new Xml(formatMessage: 'myMessage');
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->setCode(Xml::INVALID_XML_ERROR)
->assertRaised();
}

public function testValidXmlSchema()
{
$xml = file_get_contents(__DIR__.'/Fixtures/example.xml');

$constraint = new Xml(schemaPath: __DIR__.'/Fixtures/example.xsd');

$this->validator->validate($xml, $constraint);
$this->assertNoViolation();
}

public function testInvalidXmlSchema()
{
// Missing the required <author> element
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<book>
<title>The Title</title>
</book>
XML;

$constraint = new Xml(schemaPath: __DIR__.'/Fixtures/example.xsd');

$this->validator->validate($xml, $constraint);

// Since the exact error message depends on libxml, we'll just check that a violation was raised
// with the correct error code
$violations = $this->context->getViolations();
$this->assertCount(1, $violations);
$this->assertEquals(Xml::INVALID_XML_ERROR, $violations[0]->getCode());
}

public function testXmlSchemaWithFlags()
{
$xml = file_get_contents(__DIR__.'/Fixtures/example.xml');

// Use LIBXML_NONET flag to disallow network access during validation
$constraint = new Xml(schemaPath: __DIR__.'/Fixtures/example.xsd', schemaFlags: LIBXML_NONET);

$this->validator->validate($xml, $constraint);
$this->assertNoViolation();
}

public static function getValidXmlFormatValues(): array
{
return [
['<?xml version="1.0" encoding="utf-8" ?><code></code>'],
['<code></code>'],
['<test/>'],
[file_get_contents(__DIR__.'/Fixtures/example.xml')],
[new StringableValue('<test>test</test>')],
];
}

public static function getInvalidXmlFormatValues(): array
{
return [
['test'],
['<?xml version="1" ?><code></code>'],
['<?xml version="1.0" encoding="" ?>'],
['<test><test>'],
['<test><test/'],
['<test>'],
['</test>'],
['<test><test/>'],
];
}
}
Loading
0