-
-
Save Grayda/fec0ed7487641645304dee668f2163ac to your computer and use it in GitHub Desktop.
Attempting to validate collections that aren't collections
This file contains 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
<?php | |
// Using Symfony 4 | |
require("vendor/autoload.php"); | |
use Symfony\Component\Validator\Validation; | |
use Symfony\Component\Validator\Constraints as Assert; | |
$goodData = array( | |
"format" => array( | |
"type" => "foo" | |
) | |
); | |
$badData = array( | |
"format" => array( | |
"type" => "not foo or bar" | |
) | |
); | |
$fatalData = array( | |
"format" => "uh oh" | |
); | |
validate($goodData, "Good Data"); // 0 violations | |
validate($badData, "Bad Data"); // 1 violation | |
validate($fatalData, "Fatal Data"); // Fatal error | |
function validate($data, $name) | |
{ | |
$validator = Validation::createValidator(); // New validator interface | |
$constraint = new Assert\Collection(array( | |
"fields" => array( | |
"format" => new Assert\Collection(array( | |
"fields" => array( | |
"type" => new Assert\Choice(["foo", "bar"]) | |
) | |
)) | |
) | |
)); | |
$violations = $validator->validate($data, $constraint); // Actually validate | |
echo "Checked $name. Number of violations: " . count($violations) . "<br />"; | |
// Loop through each validation | |
foreach ($violations as $v) { | |
// Add the error to the error list | |
echo $v->getMessage(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment