Attribute.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use ReflectionException;
  9. use ReflectionProperty;
  10. use Respect\Validation\Validatable;
  11. use function is_object;
  12. use function property_exists;
  13. /**
  14. * Validates an object attribute, event private ones.
  15. *
  16. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  17. * @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
  18. * @author Henrique Moody <henriquemoody@gmail.com>
  19. */
  20. final class Attribute extends AbstractRelated
  21. {
  22. public function __construct(string $reference, ?Validatable $rule = null, bool $mandatory = true)
  23. {
  24. parent::__construct($reference, $rule, $mandatory);
  25. }
  26. /**
  27. * {@inheritDoc}
  28. *
  29. * @throws ReflectionException
  30. */
  31. public function getReferenceValue($input)
  32. {
  33. $propertyMirror = new ReflectionProperty($input, (string) $this->getReference());
  34. $propertyMirror->setAccessible(true);
  35. return $propertyMirror->getValue($input);
  36. }
  37. /**
  38. * {@inheritDoc}
  39. */
  40. public function hasReference($input): bool
  41. {
  42. return is_object($input) && property_exists($input, (string) $this->getReference());
  43. }
  44. }