Key.php 1.2 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 Respect\Validation\Exceptions\ComponentException;
  9. use Respect\Validation\Validatable;
  10. use function array_key_exists;
  11. use function is_array;
  12. use function is_scalar;
  13. /**
  14. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  15. * @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class Key extends AbstractRelated
  19. {
  20. /**
  21. * @param mixed $reference
  22. */
  23. public function __construct($reference, ?Validatable $rule = null, bool $mandatory = true)
  24. {
  25. if (!is_scalar($reference) || $reference === '') {
  26. throw new ComponentException('Invalid array key name');
  27. }
  28. parent::__construct($reference, $rule, $mandatory);
  29. }
  30. /**
  31. * {@inheritDoc}
  32. */
  33. public function getReferenceValue($input)
  34. {
  35. return $input[$this->getReference()];
  36. }
  37. /**
  38. * {@inheritDoc}
  39. */
  40. public function hasReference($input): bool
  41. {
  42. return is_array($input) && array_key_exists($this->getReference(), $input);
  43. }
  44. }