Debian Codegraph @

vendor/ramsey/collection/src/Tool/ValueToStringTrait.php

raw
1 <?php
2
3 /**
4 * This file is part of the ramsey/collection library
5 *
6 * For the full copyright and license information, please view the LICENSE
7 * file that was distributed with this source code.
8 *
9 * @copyright Copyright (c) Ben Ramsey <[email protected]>
10 * @license http://opensource.org/licenses/MIT MIT
11 */
12
13 declare(strict_types=1);
14
15 namespace Ramsey\Collection\Tool;
16
17 use DateTimeInterface;
18
19 use function assert;
20 use function get_resource_type;
21 use function is_array;
22 use function is_bool;
23 use function is_callable;
24 use function is_object;
25 use function is_resource;
26 use function is_scalar;
27
28 /**
29 * Provides functionality to express a value as string
30 */
31 trait ValueToStringTrait
32 {
33 /**
34 * Returns a string representation of the value.
35 *
36 * - null value: `'NULL'`
37 * - boolean: `'TRUE'`, `'FALSE'`
38 * - array: `'Array'`
39 * - scalar: converted-value
40 * - resource: `'(type resource #number)'`
41 * - object with `__toString()`: result of `__toString()`
42 * - object DateTime: ISO 8601 date
43 * - object: `'(className Object)'`
44 * - anonymous function: same as object
45 *
46 * @param mixed $value the value to return as a string.
47 */
48 protected function toolValueToString(mixed $value): string
49 {
50 // null
51 if ($value === null) {
52 return 'NULL';
53 }
54
55 // boolean constants
56 if (is_bool($value)) {
57 return $value ? 'TRUE' : 'FALSE';
58 }
59
60 // array
61 if (is_array($value)) {
62 return 'Array';
63 }
64
65 // scalar types (integer, float, string)
66 if (is_scalar($value)) {
67 return (string) $value;
68 }
69
70 // resource
71 if (is_resource($value)) {
72 return '(' . get_resource_type($value) . ' resource #' . (int) $value . ')';
73 }
74
75 // From here, $value should be an object.
76 assert(is_object($value));
77
78 // __toString() is implemented
79 if (is_callable([$value, '__toString'])) {
80 /** @var string */
81 return $value->__toString();
82 }
83
84 // object of type \DateTime
85 if ($value instanceof DateTimeInterface) {
86 return $value->format('c');
87 }
88
89 // unknown type
90 return '(' . $value::class . ' Object)';
91 }
92 }