PropertyMetadata.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.
  14. *
  15. * The value of the property is obtained by directly accessing the property.
  16. * The property will be accessed by reflection, so the access of private and
  17. * protected properties is supported.
  18. *
  19. * This class supports serialization and cloning.
  20. *
  21. * @author Bernhard Schussek <bschussek@gmail.com>
  22. *
  23. * @see PropertyMetadataInterface
  24. */
  25. class PropertyMetadata extends MemberMetadata
  26. {
  27. /**
  28. * Constructor.
  29. *
  30. * @param string $class The class this property is defined on
  31. * @param string $name The name of this property
  32. *
  33. * @throws ValidatorException
  34. */
  35. public function __construct($class, $name)
  36. {
  37. if (!property_exists($class, $name)) {
  38. throw new ValidatorException(sprintf('Property %s does not exist in class %s', $name, $class));
  39. }
  40. parent::__construct($class, $name, $name);
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function getPropertyValue($object)
  46. {
  47. return $this->getReflectionMember($object)->getValue($object);
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. protected function newReflectionMember($objectOrClassName)
  53. {
  54. while (!property_exists($objectOrClassName, $this->getName())) {
  55. $objectOrClassName = get_parent_class($objectOrClassName);
  56. }
  57. $member = new \ReflectionProperty($objectOrClassName, $this->getName());
  58. $member->setAccessible(true);
  59. return $member;
  60. }
  61. }