Callback.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Constraint callback option
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\Validator\Constraint\Option;
  9. class Callback implements \Magento\Framework\Validator\Constraint\OptionInterface
  10. {
  11. /**
  12. * @var callable
  13. */
  14. protected $_callable;
  15. /**
  16. * @var array
  17. */
  18. protected $_arguments;
  19. /**
  20. * @var bool
  21. */
  22. protected $_createInstance;
  23. /**
  24. * Create callback
  25. *
  26. * @param callable $callable
  27. * @param mixed $arguments
  28. * @param bool $createInstance If true than $callable[0] will be evaluated to new instance of class when get value
  29. */
  30. public function __construct($callable, $arguments = null, $createInstance = false)
  31. {
  32. $this->_callable = $callable;
  33. $this->setArguments($arguments);
  34. $this->_createInstance = $createInstance;
  35. }
  36. /**
  37. * Set callback arguments
  38. *
  39. * @param mixed $arguments
  40. * @return void
  41. */
  42. public function setArguments($arguments = null)
  43. {
  44. if (is_array($arguments)) {
  45. $this->_arguments = $arguments;
  46. } elseif (null !== $arguments) {
  47. $this->_arguments = [$arguments];
  48. } else {
  49. $this->_arguments = null;
  50. }
  51. }
  52. /**
  53. * Get callback value
  54. *
  55. * @return mixed
  56. * @throws \InvalidArgumentException
  57. */
  58. public function getValue()
  59. {
  60. $callable = $this->_callable;
  61. if (is_array($callable) && isset($callable[0]) && is_string($callable[0])) {
  62. if (!class_exists($callable[0])) {
  63. throw new \InvalidArgumentException(sprintf('Class "%s" was not found', $callable[0]));
  64. }
  65. if ($this->_createInstance) {
  66. $callable[0] = new $callable[0]();
  67. }
  68. } elseif ($this->_createInstance) {
  69. throw new \InvalidArgumentException('Callable expected to be an array with class name as first element');
  70. }
  71. if (!is_callable($callable)) {
  72. throw new \InvalidArgumentException('Callback does not callable');
  73. }
  74. if ($this->_arguments) {
  75. return call_user_func_array($callable, $this->_arguments);
  76. } else {
  77. return call_user_func($callable);
  78. }
  79. }
  80. }