Passed
Push — main ( 176f31...c75752 )
by Christopher
03:00
created

Util::silverStripeToPhpType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 11
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace CSoellinger\SilverStripe\ModelAnnotations\Util;
4
5
use ReflectionClass;
6
use ReflectionFunction;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Core\ClassInfo;
9
use SilverStripe\Core\Config\Configurable;
10
use SilverStripe\Core\Injector\Injectable;
11
12
/**
13
 * Helper class.
14
 */
15
class Util
16
{
17
    use Injectable;
18
19
    /**
20
     * Transform silver stripe db type to a php type.
21
     */
22
    public function silverStripeToPhpType(string $dataType): string
23
    {
24
        $dataType = strtolower($dataType);
25
        $dataType = preg_replace(
26
            '/^(varchar|htmltext|text|htmlfragment|time|datetime|date|htmlvarchar|enum).*/m',
27
            'string',
28
            $dataType
29
        );
30
        $dataType = (string) preg_replace('/^(percentage|decimal|currency).*/m', 'float', (string) $dataType);
31
32
        return str_replace('boolean', 'bool', $dataType);
33
    }
34
35
    /**
36
     * Get the file path by the full qualified class name.
37
     *
38
     * @param string $fqn Full qualified class name
39
     */
40
    public function fileByFqn(string $fqn): string
41
    {
42
        if (function_exists($fqn)) {
43
            $reflector = new ReflectionFunction($fqn);
44
        } elseif (class_exists($fqn)) {
45
            $reflector = new ReflectionClass($fqn);
46
        } else {
47
            return '';
48
        }
49
50
        return (string) $reflector->getFileName();
51
    }
52
53
    /**
54
     * Get namespace from class full qualified name.
55
     *
56
     * @param string $fqn Full qualified name
57
     */
58
    public function getNamespaceFromFqn(string $fqn): string
59
    {
60
        $pos = strrpos($fqn, '\\');
61
62
        if ($pos !== false) {
63
            return substr($fqn, 0, $pos);
64
        }
65
66
        return '\\';
67
    }
68
69
    /**
70
     * Get all classes from a namespace.
71
     *
72
     * @param string $namespace The namespace in which to search
73
     *
74
     * @return string[]
75
     */
76
    public function getClassesFromNamespace(string $namespace)
77
    {
78
        $namespace .= '\\';
79
80
        $classes = array_filter(ClassInfo::allClasses(), function (string $item) use ($namespace) {
81
            return substr($item, 0, strlen($namespace)) === $namespace;
82
        });
83
84
        /** @var string[] */
85
        return array_values($classes);
86
    }
87
}
88