AnyToString::valueToString()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Scalp\Conversion;
6
7
use function Scalp\Utils\type;
0 ignored issues
show
Bug introduced by
The type Scalp\Utils\type was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
final class AnyToString
10
{
11
    public function __invoke($any): string
12
    {
13
        return is_object($any)
14
                ? $this->objectToString($any)
15
                : $this->valueToString($any);
16
    }
17
18
    private function objectToString($object): string
19
    {
20
        $ro = new \ReflectionObject($object);
21
22
        if ($ro->hasMethod('toString')) {
23
            return $object->toString();
24
        }
25
26
        if ($ro->hasMethod('__toString')) {
27
            return (string) $object;
28
        }
29
30
        return spl_object_hash($object);
31
    }
32
33
    private function valueToString($value): string
34
    {
35
        $conversion = $this->implicitConversionFor($value);
36
37
        return  ($conversion !== '')
38
            ? $conversion($value)
39
            : (string) $value;
40
    }
41
42
    private function implicitConversionFor($any): string
43
    {
44
        $conversion = type($any).'ToString';
45
46
        foreach (get_defined_functions()['user'] as $function) {
47
            if (preg_match("/\\\\$conversion\$/i", $function)) {
48
                return $function;
49
            }
50
        }
51
52
        return '';
53
    }
54
}
55