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.1.2
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Database\Type;
16:
17: use Cake\Database\Driver;
18: use Cake\Database\Type;
19: use Cake\Database\TypeInterface;
20: use InvalidArgumentException;
21: use PDO;
22:
23: /**
24: * String type converter.
25: *
26: * Use to convert string data between PHP and the database types.
27: */
28: class StringType extends Type implements OptionalConvertInterface, TypeInterface
29: {
30:
31: /**
32: * Convert string data into the database format.
33: *
34: * @param mixed $value The value to convert.
35: * @param \Cake\Database\Driver $driver The driver instance to convert with.
36: * @return string|null
37: */
38: public function toDatabase($value, Driver $driver)
39: {
40: if ($value === null || is_string($value)) {
41: return $value;
42: }
43:
44: if (is_object($value) && method_exists($value, '__toString')) {
45: return $value->__toString();
46: }
47:
48: if (is_scalar($value)) {
49: return (string)$value;
50: }
51:
52: throw new InvalidArgumentException(sprintf(
53: 'Cannot convert value of type `%s` to string',
54: getTypeName($value)
55: ));
56: }
57:
58: /**
59: * Convert string values to PHP strings.
60: *
61: * @param mixed $value The value to convert.
62: * @param \Cake\Database\Driver $driver The driver instance to convert with.
63: * @return string|null
64: */
65: public function toPHP($value, Driver $driver)
66: {
67: if ($value === null) {
68: return null;
69: }
70:
71: return (string)$value;
72: }
73:
74: /**
75: * Get the correct PDO binding type for string data.
76: *
77: * @param mixed $value The value being bound.
78: * @param \Cake\Database\Driver $driver The driver.
79: * @return int
80: */
81: public function toStatement($value, Driver $driver)
82: {
83: return PDO::PARAM_STR;
84: }
85:
86: /**
87: * Marshalls request data into PHP strings.
88: *
89: * @param mixed $value The value to convert.
90: * @return string|null Converted value.
91: */
92: public function marshal($value)
93: {
94: if ($value === null) {
95: return null;
96: }
97: if (is_array($value)) {
98: return '';
99: }
100:
101: return (string)$value;
102: }
103:
104: /**
105: * {@inheritDoc}
106: *
107: * @return boolean False as database results are returned already as strings
108: */
109: public function requiresToPhpCast()
110: {
111: return false;
112: }
113: }
114: