GetterMetadata.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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($class, $property, $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. }