MappingRule.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\Form\Extension\Validator\ViolationMapper;
  11. use Symfony\Component\Form\Exception\ErrorMappingException;
  12. use Symfony\Component\Form\FormInterface;
  13. /**
  14. * @author Bernhard Schussek <bschussek@gmail.com>
  15. */
  16. class MappingRule
  17. {
  18. private $origin;
  19. private $propertyPath;
  20. private $targetPath;
  21. public function __construct(FormInterface $origin, string $propertyPath, string $targetPath)
  22. {
  23. $this->origin = $origin;
  24. $this->propertyPath = $propertyPath;
  25. $this->targetPath = $targetPath;
  26. }
  27. /**
  28. * @return FormInterface
  29. */
  30. public function getOrigin()
  31. {
  32. return $this->origin;
  33. }
  34. /**
  35. * Matches a property path against the rule path.
  36. *
  37. * If the rule matches, the form mapped by the rule is returned.
  38. * Otherwise this method returns false.
  39. *
  40. * @return FormInterface|null The mapped form or null
  41. */
  42. public function match(string $propertyPath)
  43. {
  44. return $propertyPath === $this->propertyPath ? $this->getTarget() : null;
  45. }
  46. /**
  47. * Matches a property path against a prefix of the rule path.
  48. *
  49. * @return bool Whether the property path is a prefix of the rule or not
  50. */
  51. public function isPrefix(string $propertyPath)
  52. {
  53. $length = \strlen($propertyPath);
  54. $prefix = substr($this->propertyPath, 0, $length);
  55. $next = $this->propertyPath[$length] ?? null;
  56. return $prefix === $propertyPath && ('[' === $next || '.' === $next);
  57. }
  58. /**
  59. * @return FormInterface
  60. *
  61. * @throws ErrorMappingException
  62. */
  63. public function getTarget()
  64. {
  65. $childNames = explode('.', $this->targetPath);
  66. $target = $this->origin;
  67. foreach ($childNames as $childName) {
  68. if (!$target->has($childName)) {
  69. throw new ErrorMappingException(sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName()));
  70. }
  71. $target = $target->get($childName);
  72. }
  73. return $target;
  74. }
  75. }