AnnotationDriver::getAllClassNames()   C
last analyzed

Complexity

Conditions 8
Paths 10

Size

Total Lines 40
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 40
rs 5.3846
cc 8
eloc 28
nc 10
nop 0
1
<?php
2
3
namespace Victoire\Bundle\BusinessEntityBundle\Annotation;
4
5
use Doctrine\Common\Annotations\AnnotationException;
6
use Doctrine\Common\Annotations\Reader;
7
use Doctrine\ORM\Mapping\Column;
8
use Doctrine\ORM\Mapping\Driver\AnnotationDriver as DoctrineAnnotationDriver;
9
use Doctrine\ORM\Mapping\MappingException;
10
use Psr\Log\LoggerInterface;
11
use Symfony\Component\Config\Definition\Exception\Exception;
12
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
13
use Symfony\Component\Validator\Constraints\NotBlank;
14
use Symfony\Component\Validator\Constraints\NotNull;
15
use Victoire\Bundle\BusinessEntityBundle\Entity\ReceiverProperty;
16
use Victoire\Bundle\CoreBundle\Annotations\ReceiverProperty as ReceiverPropertyAnnotation;
17
use Victoire\Bundle\WidgetBundle\Event\WidgetAnnotationEvent;
18
use Victoire\Bundle\WidgetBundle\Helper\WidgetHelper;
19
20
/**
21
 * Parse all files to get BusinessClasses.
22
 **/
23
class AnnotationDriver extends DoctrineAnnotationDriver
24
{
25
    public $reader;
26
    protected $eventDispatcher;
27
    protected $widgetHelper;
28
    protected $paths;
29
    protected $logger;
30
31
    /**
32
     * construct.
33
     *
34
     * @param Reader                   $reader
35
     * @param EventDispatcherInterface $eventDispatcher
36
     * @param WidgetHelper             $widgetHelper
37
     * @param array                    $paths           The paths where to search about Entities
38
     * @param LoggerInterface          $logger
39
     */
40
    public function __construct(
41
        Reader $reader,
42
        EventDispatcherInterface $eventDispatcher,
43
        $widgetHelper,
44
        $paths,
45
        LoggerInterface $logger
46
    ) {
47
        $this->reader = $reader;
48
        $this->eventDispatcher = $eventDispatcher;
49
        $this->widgetHelper = $widgetHelper;
50
        $this->paths = $paths;
51
        $this->logger = $logger;
52
    }
53
54
    /**
55
     * Get all class names.
56
     *
57
     * @throws MappingException
58
     *
59
     * @return array
60
     */
61
    public function getAllClassNames()
62
    {
63
        if (!$this->paths) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->paths of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
64
            throw MappingException::pathRequired();
65
        }
66
        $classes = [];
67
        $includedFiles = [];
68
        foreach ($this->paths as $path) {
69
            if (!is_dir($path)) {
70
                $this->logger->error(sprintf(
71
                    'The given path "%s" seems to be incorrect. You need to edit victoire_core.base_paths configuration.',
72
                    $path
73
                ));
74
                continue;
75
            }
76
            $iterator = new \RegexIterator(
77
                new \RecursiveIteratorIterator(
78
                    new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS),
79
                    \RecursiveIteratorIterator::LEAVES_ONLY
80
                ),
81
                '/^.+\/Entity\/.+\.php$/i',
82
                \RecursiveRegexIterator::GET_MATCH
83
            );
84
            foreach ($iterator as $file) {
85
                $sourceFile = realpath($file[0]);
86
                require_once $sourceFile;
87
                $includedFiles[] = $sourceFile;
88
            }
89
        }
90
        $declared = get_declared_classes();
91
        foreach ($declared as $className) {
92
            $rc = new \ReflectionClass($className);
93
            $sourceFile = $rc->getFileName();
94
            if (in_array($sourceFile, $includedFiles) && !$this->isTransient($className)) {
95
                $classes[] = $className;
96
            }
97
        }
98
99
        return $classes;
100
    }
101
102
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$class" missing
Loading history...
103
     * Parse the given Class to find some annotations related to BusinessEntities.
104
     */
105
    public function parse(\ReflectionClass $class)
106
    {
107
        $classPath = dirname($class->getFileName());
108
        $inPaths = false;
109
        foreach ($this->paths as $key => $_path) {
110
            //Check the entity path is in watching paths
111
            if (strpos($classPath, realpath($_path)) === 0) {
112
                $inPaths = true;
113
            }
114
        }
115
        if ($inPaths) {
116
            $classAnnotations = $this->reader->getClassAnnotations($class);
117 View Code Duplication
            if (!empty($classAnnotations)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
                foreach ($classAnnotations as $key => $annot) {
119
                    if (!is_numeric($key)) {
120
                        continue;
121
                    }
122
                    $classAnnotations[get_class($annot)] = $annot;
123
                }
124
            }
125
126
            //check if the entity is a widget (extends (in depth) widget class)
127
            $parentClass = $class->getParentClass();
128
            $isWidget = false;
129
            while ($parentClass && ($parentClass = $parentClass->getParentClass()) && !$isWidget && $parentClass->name != null) {
130
                $isWidget = $parentClass->name === 'Victoire\\Bundle\\WidgetBundle\\Model\\Widget';
131
            }
132
            if ($isWidget) {
133
                if ($this->widgetHelper->isEnabled(new $class->name())) {
0 ignored issues
show
introduced by
Use parentheses when instantiating classes
Loading history...
134
                    $event = new WidgetAnnotationEvent(
135
                        $this->widgetHelper->getWidgetName(new $class->name()),
0 ignored issues
show
introduced by
Use parentheses when instantiating classes
Loading history...
136
                        $this->loadReceiverProperties($class)
137
                    );
138
                    //dispatch victoire.widget_annotation_load to save receiverProperties in cache
139
                    $this->eventDispatcher->dispatch('victoire.widget_annotation_load', $event);
140
                } else {
141
                    error_log(sprintf('Widget name not found for widget %s. Is this widget declared in AppKernel ?', $class->name));
142
                }
143
            }
144
        }
145
    }
146
147
    /**
148
     * Load receiver properties and NotBlank constraints from ReflectionClass.
149
     *
150
     * @param \ReflectionClass $class
151
     *
152
     * @throws AnnotationException
153
     *
154
     * @return array
155
     */
156
    protected function loadReceiverProperties(\ReflectionClass $class)
157
    {
158
        $receiverPropertiesTypes = [];
159
        $properties = $class->getProperties();
160
        //Store receiver properties
161
        foreach ($properties as $property) {
162
            $annotations = $this->reader->getPropertyAnnotations($property);
163
            foreach ($annotations as $key => $annotationObj) {
164
                if ($annotationObj instanceof ReceiverPropertyAnnotation && !in_array($class, $receiverPropertiesTypes)) {
165
                    if (!$annotations[$key]->getTypes()) {
166
                        $message = $class->name.':$'.$property->name.'" field';
167
                        throw AnnotationException::requiredError('type', 'ReceiverProperty annotation', $message, 'array or string');
168
                    }
169
                    foreach ($annotations[$key]->getTypes() as $type) {
170
                        $receiverProperty = new ReceiverProperty();
171
                        $receiverProperty->setFieldName($property->name);
172
                        $receiverPropertiesTypes[$type][] = $receiverProperty;
173
                    }
174
                }
175
            }
176
        }
177
        //Set receiver properties as required if necessary
178
        foreach ($receiverPropertiesTypes as $type => $receiverProperties) {
179
            /* @var ReceiverProperty[] $receiverProperties */
180
            foreach ($receiverProperties as $receiverProperty) {
181
                $receiverPropertyName = $receiverProperty->getFieldName();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $receiverPropertyName is correct as $receiverProperty->getFieldName() (which targets Victoire\Bundle\Business...roperty::getFieldName()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
182
                $refProperty = $class->getProperty($receiverPropertyName);
183
                $annotations = $this->reader->getPropertyAnnotations($refProperty);
184
                foreach ($annotations as $key => $annotationObj) {
185
                    if ($annotationObj instanceof Column && $annotationObj->nullable === false) {
186
                        throw new Exception(sprintf(
187
                            'Property "%s" in class "%s" has a @ReceiverProperty annotation and by consequence must have "nullable=true" for ORM\Column annotation',
188
                            $refProperty->name,
189
                            $refProperty->class
190
                        ));
191
                    } elseif ($annotationObj instanceof NotBlank) {
192
                        throw new Exception(sprintf(
193
                            'Property "%s" in class "%s" has a @ReceiverProperty annotation and by consequence can not use NotBlank annotation',
194
                            $refProperty->name,
195
                            $refProperty->class
196
                        ));
197
                    } elseif ($annotationObj instanceof NotNull) {
198
                        throw new Exception(sprintf(
199
                            'Property "%s" in class "%s" has a @ReceiverProperty annotation and by consequence can not use NotNull annotation',
200
                            $refProperty->name,
201
                            $refProperty->class
202
                        ));
203
                    } elseif ($annotationObj instanceof ReceiverPropertyAnnotation && $annotationObj->isRequired()) {
204
                        $receiverProperty->setRequired(true);
205
                    }
206
                }
207
            }
208
        }
209
210
        return $receiverPropertiesTypes;
211
    }
212
}
213