-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[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
sfmok
wants to merge
1
commit into
symfony:7.4
Choose a base branch
from
sfmok:feat/new-constraints
base: 7.4
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
76
src/Symfony/Component/Validator/Constraints/XmlValidator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
5 changes: 5 additions & 0 deletions
5
src/Symfony/Component/Validator/Tests/Constraints/Fixtures/example.xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
11 changes: 11 additions & 0 deletions
11
src/Symfony/Component/Validator/Tests/Constraints/Fixtures/example.xsd
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
64
src/Symfony/Component/Validator/Tests/Constraints/XmlTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
117
src/Symfony/Component/Validator/Tests/Constraints/XmlValidatorTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/>'], | ||
]; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.