Passed
Pull Request — master (#143)
by Federico
02:13
created

ClassInfoTrait::getRealClassName()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 12
c 1
b 0
f 1
nc 3
nop 1
dl 0
loc 21
rs 9.8666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DH\DoctrineAuditBundle\Helper;
6
7
use Doctrine\Common\Persistence\Proxy;
8
9
/**
10
 * Retrieves information about a class.
11
 * taken input from here
12
 * https://github.com/api-platform/core/blob/master/src/Util/ClassInfoTrait.php#L38.
13
 */
14
trait ClassInfoTrait
15
{
16
    /**
17
     * Given a class name and a proxy namespace returns the proxy name.
18
     *
19
     * @param string $className
20
     * @param string $proxyNamespace
21
     *
22
     * @return string
23
     */
24
    public static function generateProxyClassName($className, $proxyNamespace): string
25
    {
26
        return rtrim($proxyNamespace, '\\').'\\'.Proxy::MARKER.'\\'.ltrim($className, '\\');
27
    }
28
29
    /**
30
     * Get class name of the given object.
31
     *
32
     * @param object $object
33
     *
34
     * @return string
35
     *
36
     * @author Kévin Dunglas <[email protected]>
37
     */
38
    private function getObjectClass($object): string
39
    {
40
        return $this->getRealClassName(\get_class($object));
41
    }
42
43
    /**
44
     * Get the real class name of a class name that could be a proxy.
45
     *
46
     * @param string $className
47
     *
48
     * @return string
49
     *
50
     * @author Kévin Dunglas <[email protected]>
51
     */
52
    private function getRealClassName(string $className): string
53
    {
54
        // __CG__: Doctrine Common Marker for Proxy (ODM < 2.0 and ORM < 3.0)
55
        // __PM__: Ocramius Proxy Manager (ODM >= 2.0)
56
        $positionCg = mb_strrpos($className, '\\__CG__\\');
57
        $positionPm = mb_strrpos($className, '\\__PM__\\');
58
        if ((false === $positionCg) &&
59
            (false === $positionPm)) {
60
            return $className;
61
        }
62
63
        if (false !== $positionCg) {
64
            return mb_substr($className, $positionCg + 8);
65
        }
66
67
        $className = ltrim($className, '\\');
68
69
        return mb_substr(
70
            $className,
71
            8 + $positionPm,
72
            mb_strrpos($className, '\\') - ($positionPm + 8)
73
        );
74
    }
75
}
76