-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Validator] Add MacAddress
constraint for validating MAC address
#51862
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
Merged
Merged
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
52 changes: 52 additions & 0 deletions
52
src/Symfony/Component/Validator/Constraints/MacAddress.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,52 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* 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\Exception\InvalidArgumentException; | ||
|
||
/** | ||
* Validates that a value is a valid MAC address. | ||
* | ||
* @author Ninos Ego <[email protected]> | ||
*/ | ||
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] | ||
class MacAddress extends Constraint | ||
{ | ||
public const INVALID_MAC_ERROR = 'a183fbff-6968-43b4-82a2-cc5cf7150036'; | ||
|
||
protected const ERROR_NAMES = [ | ||
self::INVALID_MAC_ERROR => 'INVALID_MAC_ERROR', | ||
]; | ||
|
||
public string $message = 'This is not a valid MAC address.'; | ||
Ninos marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** @var callable|null */ | ||
public $normalizer; | ||
|
||
public function __construct( | ||
array $options = null, | ||
string $message = null, | ||
callable $normalizer = null, | ||
array $groups = null, | ||
mixed $payload = null, | ||
) { | ||
parent::__construct($options, $groups, $payload); | ||
|
||
$this->message = $message ?? $this->message; | ||
$this->normalizer = $normalizer ?? $this->normalizer; | ||
|
||
if (null !== $this->normalizer && !\is_callable($this->normalizer)) { | ||
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', get_debug_type($this->normalizer))); | ||
} | ||
} | ||
} |
53 changes: 53 additions & 0 deletions
53
src/Symfony/Component/Validator/Constraints/MacAddressValidator.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,53 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* 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; | ||
|
||
/** | ||
* Validates whether a value is a valid MAC address. | ||
* | ||
* @author Ninos Ego <[email protected]> | ||
*/ | ||
class MacAddressValidator extends ConstraintValidator | ||
{ | ||
public function validate(mixed $value, Constraint $constraint): void | ||
{ | ||
if (!$constraint instanceof MacAddress) { | ||
throw new UnexpectedTypeException($constraint, MacAddress::class); | ||
} | ||
|
||
if (null === $value || '' === $value) { | ||
return; | ||
} | ||
|
||
if (!\is_scalar($value) && !$value instanceof \Stringable) { | ||
throw new UnexpectedValueException($value, 'string'); | ||
} | ||
|
||
$value = (string) $value; | ||
|
||
if (null !== $constraint->normalizer) { | ||
$value = ($constraint->normalizer)($value); | ||
} | ||
|
||
if (!filter_var($value, \FILTER_VALIDATE_MAC)) { | ||
$this->context->buildViolation($constraint->message) | ||
->setParameter('{{ value }}', $this->formatValue($value)) | ||
->setCode(MacAddress::INVALID_MAC_ERROR) | ||
->addViolation(); | ||
} | ||
} | ||
} |
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
70 changes: 70 additions & 0 deletions
70
src/Symfony/Component/Validator/Tests/Constraints/MacAddressTest.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,70 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* 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\MacAddress; | ||
use Symfony\Component\Validator\Exception\InvalidArgumentException; | ||
use Symfony\Component\Validator\Mapping\ClassMetadata; | ||
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader; | ||
|
||
/** | ||
* @author Ninos Ego <[email protected]> | ||
*/ | ||
class MacAddressTest extends TestCase | ||
{ | ||
public function testNormalizerCanBeSet() | ||
{ | ||
$mac = new MacAddress(['normalizer' => 'trim']); | ||
|
||
$this->assertEquals('trim', $mac->normalizer); | ||
} | ||
|
||
public function testInvalidNormalizerThrowsException() | ||
{ | ||
$this->expectException(InvalidArgumentException::class); | ||
$this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).'); | ||
new MacAddress(['normalizer' => 'Unknown Callable']); | ||
} | ||
|
||
public function testInvalidNormalizerObjectThrowsException() | ||
{ | ||
$this->expectException(InvalidArgumentException::class); | ||
$this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).'); | ||
new MacAddress(['normalizer' => new \stdClass()]); | ||
} | ||
|
||
public function testAttributes() | ||
{ | ||
$metadata = new ClassMetadata(MacAddressDummy::class); | ||
$loader = new AttributeLoader(); | ||
self::assertTrue($loader->loadClassMetadata($metadata)); | ||
|
||
[$aConstraint] = $metadata->properties['a']->getConstraints(); | ||
self::assertSame('myMessage', $aConstraint->message); | ||
self::assertSame('trim', $aConstraint->normalizer); | ||
self::assertSame(['Default', 'MacAddressDummy'], $aConstraint->groups); | ||
|
||
[$bConstraint] = $metadata->properties['b']->getConstraints(); | ||
self::assertSame(['my_group'], $bConstraint->groups); | ||
self::assertSame('some attached data', $bConstraint->payload); | ||
} | ||
} | ||
|
||
class MacAddressDummy | ||
{ | ||
#[MacAddress(message: 'myMessage', normalizer: 'trim')] | ||
private $a; | ||
|
||
#[MacAddress(groups: ['my_group'], payload: 'some attached data')] | ||
private $b; | ||
} |
125 changes: 125 additions & 0 deletions
125
src/Symfony/Component/Validator/Tests/Constraints/MacAddressValidatorTest.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,125 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* 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\MacAddress; | ||
use Symfony\Component\Validator\Constraints\MacAddressValidator; | ||
use Symfony\Component\Validator\Exception\UnexpectedValueException; | ||
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; | ||
|
||
/** | ||
* @author Ninos Ego <[email protected]> | ||
*/ | ||
class MacAddressValidatorTest extends ConstraintValidatorTestCase | ||
{ | ||
protected function createValidator(): MacAddressValidator | ||
{ | ||
return new MacAddressValidator(); | ||
} | ||
|
||
public function testNullIsValid() | ||
{ | ||
$this->validator->validate(null, new MacAddress()); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
public function testEmptyStringIsValid() | ||
{ | ||
$this->validator->validate('', new MacAddress()); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
public function testExpectsStringCompatibleType() | ||
{ | ||
$this->expectException(UnexpectedValueException::class); | ||
$this->validator->validate(new \stdClass(), new MacAddress()); | ||
} | ||
|
||
/** | ||
* @dataProvider getValidMacs | ||
*/ | ||
public function testValidMac($mac) | ||
{ | ||
$this->validator->validate($mac, new MacAddress()); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
public static function getValidMacs(): array | ||
{ | ||
return [ | ||
['00:00:00:00:00:00'], | ||
['00-00-00-00-00-00'], | ||
['ff:ff:ff:ff:ff:ff'], | ||
['ff-ff-ff-ff-ff-ff'], | ||
['FF:FF:FF:FF:FF:FF'], | ||
['FF-FF-FF-FF-FF-FF'], | ||
]; | ||
} | ||
|
||
/** | ||
* @dataProvider getValidMacsWithWhitespaces | ||
*/ | ||
public function testValidMacsWithWhitespaces($mac) | ||
{ | ||
$this->validator->validate($mac, new MacAddress([ | ||
'normalizer' => 'trim', | ||
])); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
public static function getValidMacsWithWhitespaces(): array | ||
{ | ||
return [ | ||
["\x2000:00:00:00:00:00"], | ||
["\x09\x0900-00-00-00-00-00"], | ||
["ff:ff:ff:ff:ff:ff\x0A"], | ||
["ff-ff-ff-ff-ff-ff\x0D\x0D"], | ||
["\x00FF:FF:FF:FF:FF:FF\x00"], | ||
["\x0B\x0BFF-FF-FF-FF-FF-FF\x0B\x0B"], | ||
]; | ||
} | ||
|
||
/** | ||
* @dataProvider getInvalidMacs | ||
*/ | ||
public function testInvalidMacs($mac) | ||
{ | ||
$constraint = new MacAddress([ | ||
'message' => 'myMessage', | ||
]); | ||
|
||
$this->validator->validate($mac, $constraint); | ||
|
||
$this->buildViolation('myMessage') | ||
->setParameter('{{ value }}', '"'.$mac.'"') | ||
->setCode(MacAddress::INVALID_MAC_ERROR) | ||
->assertRaised(); | ||
} | ||
|
||
public static function getInvalidMacs(): array | ||
{ | ||
return [ | ||
['0'], | ||
['00:00'], | ||
['00:00:00'], | ||
['00:00:00:00'], | ||
['00:00:00:00:00'], | ||
['00:00:00:00:00:000'], | ||
['-00:00:00:00:00:00'], | ||
['foobar'], | ||
]; | ||
} | ||
} |
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.