RulesProvider.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Validation;
  16. use ReflectionClass;
  17. /**
  18. * A Proxy class used to remove any extra arguments when the user intended to call
  19. * a method in another class that is not aware of validation providers signature
  20. */
  21. class RulesProvider
  22. {
  23. /**
  24. * The class/object to proxy.
  25. *
  26. * @var string|object
  27. */
  28. protected $_class;
  29. /**
  30. * The proxied class' reflection
  31. *
  32. * @var \ReflectionClass
  33. */
  34. protected $_reflection;
  35. /**
  36. * Constructor, sets the default class to use for calling methods
  37. *
  38. * @param string|object $class the default class to proxy
  39. * @throws \ReflectionException
  40. */
  41. public function __construct($class = Validation::class)
  42. {
  43. $this->_class = $class;
  44. $this->_reflection = new ReflectionClass($class);
  45. }
  46. /**
  47. * Proxies validation method calls to the Validation class.
  48. *
  49. * The last argument (context) will be sliced off, if the validation
  50. * method's last parameter is not named 'context'. This lets
  51. * the various wrapped validation methods to not receive the validation
  52. * context unless they need it.
  53. *
  54. * @param string $method the validation method to call
  55. * @param array $arguments the list of arguments to pass to the method
  56. * @return bool whether or not the validation rule passed
  57. */
  58. public function __call($method, $arguments)
  59. {
  60. $method = $this->_reflection->getMethod($method);
  61. $argumentList = $method->getParameters();
  62. if (array_pop($argumentList)->getName() !== 'context') {
  63. $arguments = array_slice($arguments, 0, -1);
  64. }
  65. $object = is_string($this->_class) ? null : $this->_class;
  66. return $method->invokeArgs($object, $arguments);
  67. }
  68. }