EntityResolver::getClassesFromName()   B
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 3
nop 4
1
<?php
2
3
namespace Knp\FriendlyContexts\Doctrine;
4
5
use Doctrine\Common\Inflector\Inflector;
6
use Doctrine\Common\Persistence\ObjectManager;
7
use Doctrine\ORM\Mapping\ClassMetadata;
8
use Knp\FriendlyContexts\Reflection\ObjectReflector;
9
use Knp\FriendlyContexts\Utils\TextFormater;
10
11
class EntityResolver
12
{
13
    const CASE_CAMEL      = 'CamelCase';
14
    const CASE_UNDERSCORE = 'UnderscoreCase';
15
16
    protected $reflector;
17
    protected $formater;
18
19
    public function __construct(ObjectReflector $reflector, TextFormater $formater)
20
    {
21
        $this->reflector = $reflector;
22
        $this->formater  = $formater;
23
    }
24
25
    public function resolve(ObjectManager $entityManager, $name, $namespaces = '')
26
    {
27
        $results = [];
28
29
        $namespaces = is_array($namespaces) ? $namespaces : [ $namespaces ];
30
31
        foreach ($namespaces as $namespace) {
32
            $results = $this->getClassesFromName($entityManager, $name, $namespace, $results);
33
        }
34
35
        if (0 === count($results)) {
36
37
            return;
38
        }
39
40
        return $results;
41
    }
42
43
    protected function getClassesFromName(ObjectManager $entityManager, $name, $namespace, array $results = [])
44
    {
45
        if (!empty($results)) {
46
47
            return $results;
48
        }
49
50
        $allMetadata = $entityManager->getMetadataFactory()->getAllMetadata();
51
        $allClass = $this->reflector->getReflectionsFromMetadata($allMetadata);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
52
        foreach ($this->entityNameProposal($name) as $name) {
53
            $class = array_filter(
54
                $allClass,
55
                function ($e) use ($namespace, $name) {
56
                    $nameValid = strtolower($e->getShortName()) === strtolower($name);
57
58
                    return '' === $namespace
59
                        ? $nameValid
60
                        : $namespace === substr($e->getNamespaceName(), 0, strlen($namespace)) && $nameValid
61
                    ;
62
                }
63
            );
64
            $results = array_merge($results, $class);
65
        }
66
67
        return $results;
68
    }
69
70
    public function getMetadataFromProperty(ObjectManager $entityManager, $entity, $property)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
71
    {
72
        $metadata = $this->getMetadataFromObject($entityManager, $entity);
73
74
        if (null !== $map = $this->getMappingFromMetadata($metadata, $property)) {
0 ignored issues
show
Compatibility introduced by
$metadata of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ORM\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
75
            return $map;
76
        }
77
78
        if ($this->asAccessForCase($entity, $property, self::CASE_CAMEL) || $this->asAccessForCase($entity, $property, self::CASE_UNDERSCORE)) {
79
            return false;
80
        }
81
82
        throw new \RuntimeException(
83
            sprintf(
84
                'Can\'t find property %s or %s in class %s',
85
                $this->formater->toCamelCase(strtolower($property)),
86
                $this->formater->toUnderscoreCase(strtolower($property)),
87
                get_class($entity)
88
            )
89
        );
90
    }
91
92
    public function getMetadataFromObject(ObjectManager $entityManager, $object)
93
    {
94
        return $entityManager
95
            ->getMetadataFactory()
96
            ->getMetadataFor(get_class($object)
97
        );
98
    }
99
100
    public function entityNameProposal($name)
101
    {
102
        $name = strtolower(str_replace(" ", "", $name));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
103
104
        $results = [Inflector::singularize($name), Inflector::pluralize($name), $name];
105
106
        return array_unique($results);
107
    }
108
109
    public function asAccessForCase($entity, $property, $case)
110
    {
111
        $method = sprintf('to%s', $case);
112
113
        return property_exists($entity, $this->formater->{$method}($property)) || method_exists($entity, 'set' . $this->formater->{$method}($property));
114
    }
115
116
    protected function getMappingFromMetadata(ClassMetadata $metadata, $property)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
117
    {
118
        if (null !== $map = $this->getMappingFromMetadataPart($metadata->fieldMappings, $property)) {
119
            return $map;
120
        }
121
122
        if (null !== $map = $this->getMappingFromMetadataPart($metadata->associationMappings, $property)) {
123
            return $map;
124
        }
125
    }
126
127
    protected function getMappingFromMetadataPart($metadata, $property)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
128
    {
129
        $property = trim($property);
130
131
        foreach ($metadata as $id => $map) {
132
            switch (strtolower($id)) {
133
                case strtolower($property):
134
                case strtolower($this->formater->toCamelCase($property)):
135
                case strtolower($this->formater->toUnderscoreCase($property)):
136
                    return $map;
137
            }
138
        }
139
140
        return null;
141
    }
142
143
}
144