FieldPresenceEnhancer.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /*
  3. * This file is part of the Symfony CMF package.
  4. *
  5. * (c) 2011-2015 Symfony CMF
  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\Cmf\Component\Routing\Enhancer;
  11. use Symfony\Component\HttpFoundation\Request;
  12. /**
  13. * This enhancer sets a field to a fixed value. You can specify a source field
  14. * name to only set the target field if the source is present.
  15. *
  16. * @author David Buchmann
  17. */
  18. class FieldPresenceEnhancer implements RouteEnhancerInterface
  19. {
  20. /**
  21. * Field name for the source field that must exist. If null, the target
  22. * field is always set if not already present.
  23. *
  24. * @var string|null
  25. */
  26. protected $source;
  27. /**
  28. * Field name to write the value into.
  29. *
  30. * @var string
  31. */
  32. protected $target;
  33. /**
  34. * Value to set the target field to.
  35. *
  36. * @var string
  37. */
  38. private $value;
  39. /**
  40. * @param null|string $source the field name of the class, null to disable the check
  41. * @param string $target the field name to set from the map
  42. * @param string $value value to set target field to if source field exists
  43. */
  44. public function __construct($source, $target, $value)
  45. {
  46. $this->source = $source;
  47. $this->target = $target;
  48. $this->value = $value;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function enhance(array $defaults, Request $request)
  54. {
  55. if (isset($defaults[$this->target])) {
  56. // no need to do anything
  57. return $defaults;
  58. }
  59. if (null !== $this->source && !isset($defaults[$this->source])) {
  60. return $defaults;
  61. }
  62. $defaults[$this->target] = $this->value;
  63. return $defaults;
  64. }
  65. }