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