StaticMethodLoader.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Mapping\Loader;
  11. use Symfony\Component\Validator\Exception\MappingException;
  12. use Symfony\Component\Validator\Mapping\ClassMetadata;
  13. /**
  14. * Loads validation metadata by calling a static method on the loaded class.
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class StaticMethodLoader implements LoaderInterface
  19. {
  20. protected $methodName;
  21. /**
  22. * Creates a new loader.
  23. *
  24. * @param string $methodName The name of the static method to call
  25. */
  26. public function __construct($methodName = 'loadValidatorMetadata')
  27. {
  28. $this->methodName = $methodName;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function loadClassMetadata(ClassMetadata $metadata)
  34. {
  35. /** @var \ReflectionClass $reflClass */
  36. $reflClass = $metadata->getReflectionClass();
  37. if (!$reflClass->isInterface() && $reflClass->hasMethod($this->methodName)) {
  38. $reflMethod = $reflClass->getMethod($this->methodName);
  39. if ($reflMethod->isAbstract()) {
  40. return false;
  41. }
  42. if (!$reflMethod->isStatic()) {
  43. throw new MappingException(sprintf('The method %s::%s should be static', $reflClass->name, $this->methodName));
  44. }
  45. if ($reflMethod->getDeclaringClass()->name != $reflClass->name) {
  46. return false;
  47. }
  48. $reflMethod->invoke(null, $metadata);
  49. return true;
  50. }
  51. return false;
  52. }
  53. }