ExpressionTypeCasterTrait.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.3.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Database\Type;
  17. use Cake\Database\TypeFactory;
  18. /**
  19. * Offers a method to convert values to ExpressionInterface objects
  20. * if the type they should be converted to implements ExpressionTypeInterface
  21. */
  22. trait ExpressionTypeCasterTrait
  23. {
  24. /**
  25. * Conditionally converts the passed value to an ExpressionInterface object
  26. * if the type class implements the ExpressionTypeInterface. Otherwise,
  27. * returns the value unmodified.
  28. *
  29. * @param mixed $value The value to convert to ExpressionInterface
  30. * @param string|null $type The type name
  31. * @return mixed
  32. */
  33. protected function _castToExpression($value, ?string $type = null)
  34. {
  35. if ($type === null) {
  36. return $value;
  37. }
  38. $baseType = str_replace('[]', '', $type);
  39. $converter = TypeFactory::build($baseType);
  40. if (!$converter instanceof ExpressionTypeInterface) {
  41. return $value;
  42. }
  43. $multi = $type !== $baseType;
  44. if ($multi) {
  45. /** @var \Cake\Database\Type\ExpressionTypeInterface $converter */
  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(array $types): array
  59. {
  60. $result = [];
  61. $types = array_filter($types);
  62. foreach ($types as $k => $type) {
  63. $object = TypeFactory::build($type);
  64. if ($object instanceof ExpressionTypeInterface) {
  65. $result[$k] = $object;
  66. }
  67. }
  68. return $result;
  69. }
  70. }