ExpressionTypeCasterTrait.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.3.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Type;
  16. use Cake\Database\Type;
  17. use Cake\Database\Type\ExpressionTypeInterface;
  18. /**
  19. * Offers a method to convert values to ExpressionInterface objects
  20. * if the type they should be converted to implements ExpressionTypeInterface
  21. *
  22. */
  23. trait ExpressionTypeCasterTrait
  24. {
  25. /**
  26. * Conditionally converts the passed value to an ExpressionInterface object
  27. * if the type class implements the ExpressionTypeInterface. Otherwise,
  28. * returns the value unmodified.
  29. *
  30. * @param mixed $value The value to converto to ExpressionInterface
  31. * @param string $type The type name
  32. * @return mixed
  33. */
  34. protected function _castToExpression($value, $type)
  35. {
  36. if (empty($type)) {
  37. return $value;
  38. }
  39. $baseType = str_replace('[]', '', $type);
  40. $converter = Type::build($baseType);
  41. if (!$converter instanceof ExpressionTypeInterface) {
  42. return $value;
  43. }
  44. $multi = $type !== $baseType;
  45. if ($multi) {
  46. return array_map([$converter, 'toExpression'], $value);
  47. }
  48. return $converter->toExpression($value);
  49. }
  50. /**
  51. * Returns an array with the types that require values to
  52. * be casted to expressions, out of the list of type names
  53. * passed as parameter.
  54. *
  55. * @param array $types List of type names
  56. * @return array
  57. */
  58. protected function _requiresToExpressionCasting($types)
  59. {
  60. $result = [];
  61. $types = array_filter($types);
  62. foreach ($types as $k => $type) {
  63. $object = Type::build($type);
  64. if ($object instanceof ExpressionTypeInterface) {
  65. $result[$k] = $object;
  66. }
  67. }
  68. return $result;
  69. }
  70. }