StaticMethodLoader.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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(string $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. }