GetterMetadata.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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;
  11. use Symfony\Component\Validator\Exception\ValidatorException;
  12. /**
  13. * Stores all metadata needed for validating a class property via its getter
  14. * method.
  15. *
  16. * A property getter is any method that is equal to the property's name,
  17. * prefixed with either "get" or "is". That method will be used to access the
  18. * property's value.
  19. *
  20. * The getter will be invoked by reflection, so the access of private and
  21. * protected getters is supported.
  22. *
  23. * This class supports serialization and cloning.
  24. *
  25. * @author Bernhard Schussek <bschussek@gmail.com>
  26. *
  27. * @see PropertyMetadataInterface
  28. */
  29. class GetterMetadata extends MemberMetadata
  30. {
  31. /**
  32. * @param string $class The class the getter is defined on
  33. * @param string $property The property which the getter returns
  34. * @param string|null $method The method that is called to retrieve the value being validated (null for auto-detection)
  35. *
  36. * @throws ValidatorException
  37. */
  38. public function __construct(string $class, string $property, string $method = null)
  39. {
  40. if (null === $method) {
  41. $getMethod = 'get'.ucfirst($property);
  42. $isMethod = 'is'.ucfirst($property);
  43. $hasMethod = 'has'.ucfirst($property);
  44. if (method_exists($class, $getMethod)) {
  45. $method = $getMethod;
  46. } elseif (method_exists($class, $isMethod)) {
  47. $method = $isMethod;
  48. } elseif (method_exists($class, $hasMethod)) {
  49. $method = $hasMethod;
  50. } else {
  51. throw new ValidatorException(sprintf('Neither of these methods exist in class "%s": "%s", "%s", "%s".', $class, $getMethod, $isMethod, $hasMethod));
  52. }
  53. } elseif (!method_exists($class, $method)) {
  54. throw new ValidatorException(sprintf('The "%s()" method does not exist in class "%s".', $method, $class));
  55. }
  56. parent::__construct($class, $method, $property);
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function getPropertyValue($object)
  62. {
  63. return $this->newReflectionMember($object)->invoke($object);
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. protected function newReflectionMember($objectOrClassName)
  69. {
  70. return new \ReflectionMethod($objectOrClassName, $this->getName());
  71. }
  72. }