Skip to content

Instantly share code, notes, and snippets.

@Grayda
Last active February 10, 2018 01:03
Show Gist options
  • Save Grayda/fec0ed7487641645304dee668f2163ac to your computer and use it in GitHub Desktop.
Save Grayda/fec0ed7487641645304dee668f2163ac to your computer and use it in GitHub Desktop.
Attempting to validate collections that aren't collections
<?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