Passed
Branch master (6dc83b)
by Oguzhan
02:11
created

ReflectionTrait::getClassFromClassProperty()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 3
eloc 5
nc 3
nop 2
1
<?php
2
namespace Pbxg33k\Traits;
3
4
/**
5
 * Class ReflectionTrait
6
 *
7
 * This trait adds methods to retrieve properties easily using PHP Reflection
8
 *
9
 * @author  Oguzhan Uysal <[email protected]>
10
 * @package Pbxg33k\Traits
11
 */
12
trait ReflectionTrait
13
{
14
    public function getClassFromClassProperty($class, $property)
15
    {
16
        if(!class_exists($class)) {
17
            throw new \Exception($class. ' not found or does not exist');
18
        }
19
        
20
        if(!property_exists($class, $property)) {
21
            throw new \Exception($class . ' has no property with the name ' . $property);
22
        }
23
    }
24
    
25
    /**
26
     * Tries to get the correct class name from the given docBlock for Reflection
27
     *
28
     * @param string $comment the docblock
29
     * @param bool $includeNamespaces
30
     * @param null|\ReflectionClass $reflectionClass
31
     *
32
     * @return bool|string
33
     */
34
    public static function getClassFromDocComment($comment, $includeNamespaces = true, $reflectionClass = null)
35
    {
36
        if (preg_match('~\@var[\s]+([A-Za-z0-9\\\\]+)~', $comment, $matches)) {
37
            if ($includeNamespaces) {
38
                if ($reflectionClass instanceof \ReflectionClass && !in_array($matches[1], HydratableTrait::$nonObjectTypes)) {
39
                    if($reflectionClass->getNamespaceName()) {
40
                        return sprintf('\%s\%s', $reflectionClass->getNamespaceName(), $matches[1]);
41
                    } else {
42
                        return sprintf('\%s', $matches[1]);
43
                    }
44
                } else {
45
                    return $matches[1];
46
                }
47
            } else {
48
                return join('', array_slice(explode('\\', $matches[1]), -1));
49
            }
50
        }
51
52
        return false;
53
    }
54
}