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\Database;
16:
17: /**
18: * Type converter trait
19: */
20: trait TypeConverterTrait
21: {
22: /**
23: * Converts a give value to a suitable database value based on type
24: * and return relevant internal statement type
25: *
26: * @param mixed $value The value to cast
27: * @param \Cake\Database\Type|string $type The type name or type instance to use.
28: * @return array list containing converted value and internal type
29: */
30: public function cast($value, $type)
31: {
32: if (is_string($type)) {
33: $type = Type::build($type);
34: }
35: if ($type instanceof TypeInterface) {
36: $value = $type->toDatabase($value, $this->_driver);
37: $type = $type->toStatement($value, $this->_driver);
38: }
39:
40: return [$value, $type];
41: }
42:
43: /**
44: * Matches columns to corresponding types
45: *
46: * Both $columns and $types should either be numeric based or string key based at
47: * the same time.
48: *
49: * @param array $columns list or associative array of columns and parameters to be bound with types
50: * @param array $types list or associative array of types
51: * @return array
52: */
53: public function matchTypes($columns, $types)
54: {
55: if (!is_int(key($types))) {
56: $positions = array_intersect_key(array_flip($columns), $types);
57: $types = array_intersect_key($types, $positions);
58: $types = array_combine($positions, $types);
59: }
60:
61: return $types;
62: }
63: }
64: