BusinessPageHelper::guessBestPatternIdForEntity()   D
last analyzed

Complexity

Conditions 10
Paths 32

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 27
nc 32
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Victoire\Bundle\BusinessPageBundle\Helper;
4
5
use Doctrine\DBAL\Schema\View;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityRepository;
8
use Doctrine\ORM\QueryBuilder;
9
use Victoire\Bundle\APIBusinessEntityBundle\Entity\APIBusinessEntity;
10
use Victoire\Bundle\APIBusinessEntityBundle\Resolver\APIBusinessEntityResolver;
11
use Victoire\Bundle\BusinessEntityBundle\Converter\ParameterConverter;
12
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity;
13
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntityInterface;
14
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessProperty;
15
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
16
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
17
use Victoire\Bundle\CoreBundle\Helper\UrlBuilder;
18
use Victoire\Bundle\ORMBusinessEntityBundle\Entity\ORMBusinessEntity;
19
use Victoire\Bundle\QueryBundle\Helper\QueryHelper;
20
use Victoire\Bundle\ViewReferenceBundle\Connector\ViewReferenceRepository;
21
use Victoire\Bundle\ViewReferenceBundle\ViewReference\BusinessPageReference;
22
23
/**
24
 * The business entity page pattern helper
25
 * ref: victoire_business_page.business_page_helper.
26
 */
27
class BusinessPageHelper
28
{
29
    protected $queryHelper = null;
30
    protected $viewReferenceRepository = null;
31
    protected $businessEntityHelper = null;
32
    protected $parameterConverter = null;
33
    protected $urlBuilder = null;
34
    /**
35
     * @var APIBusinessEntityResolver
36
     */
37
    private $apiBusinessEntityResolver;
38
39
    /**
40
     * @param QueryHelper               $queryHelper
41
     * @param ViewReferenceRepository   $viewReferenceRepository
42
     * @param EntityRepository          $businessEntityRepository
43
     * @param BusinessEntityHelper      $businessEntityHelper
44
     * @param ParameterConverter        $parameterConverter
45
     * @param UrlBuilder                $urlBuilder
46
     * @param APIBusinessEntityResolver $apiBusinessEntityResolver
47
     */
48
    public function __construct(QueryHelper $queryHelper, ViewReferenceRepository $viewReferenceRepository, EntityRepository $businessEntityRepository, BusinessEntityHelper $businessEntityHelper, ParameterConverter $parameterConverter, UrlBuilder $urlBuilder, APIBusinessEntityResolver $apiBusinessEntityResolver)
49
    {
50
        $this->queryHelper = $queryHelper;
51
        $this->viewReferenceRepository = $viewReferenceRepository;
52
        $this->businessEntityRepository = $businessEntityRepository;
0 ignored issues
show
Bug introduced by
The property businessEntityRepository does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
53
        $this->businessEntityHelper = $businessEntityHelper;
54
        $this->parameterConverter = $parameterConverter;
55
        $this->urlBuilder = $urlBuilder;
56
        $this->apiBusinessEntityResolver = $apiBusinessEntityResolver;
57
    }
58
59
    /**
60
     * Is the entity allowed for the business entity page.
61
     *
62
     * @param BusinessTemplate $businessTemplate
63
     * @param object|null      $entity
64
     * @param EntityManager    $em
65
     *
66
     * @throws \Exception
67
     *
68
     * @return bool
69
     */
70
    public function isEntityAllowed(BusinessTemplate $businessTemplate, $entity, EntityManager $em = null)
71
    {
72
        if ($businessTemplate->getBusinessEntity()->getType() === APIBusinessEntity::TYPE) {
73
            return true;
74
        }
75
        $allowed = true;
76
77
        //test that an entity is given
78
        if ($entity === null) {
79
            throw new \Exception('The entity is required.');
80
        }
81
82
        $queryHelper = $this->queryHelper;
83
84
        //the page id
85
        $entityId = $entity->getId();
86
87
        //the base of the query
88
        $baseQuery = $queryHelper->getQueryBuilder($businessTemplate, $em);
0 ignored issues
show
Bug introduced by
It seems like $em defined by parameter $em on line 70 can be null; however, Victoire\Bundle\QueryBun...lper::getQueryBuilder() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
89
90
        $baseQuery->andWhere('main_item.id = '.$entityId);
91
92
        //filter with the query of the page
93
        $items = $queryHelper->buildWithSubQuery($businessTemplate, $baseQuery, $em)
0 ignored issues
show
Bug introduced by
It seems like $em defined by parameter $em on line 70 can be null; however, Victoire\Bundle\QueryBun...er::buildWithSubQuery() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
94
            ->getQuery()->getResult();
95
96
        //only one page can be found because we filter on the
97
        if (count($items) > 1) {
98
            throw new \Exception('More than 1 item was found, there should not be more than 1 item with this query.');
99
        }
100
101
        if (count($items) === 0) {
102
            $allowed = false;
103
        }
104
105
        return $allowed;
106
    }
107
108
    /**
109
     * Get the list of entities allowed for the BusinessTemplate page.
110
     *
111
     * @param BusinessTemplate $businessTemplate
112
     * @param EntityManager    $em
113
     *
114
     * @return array
115
     */
116
    public function getEntitiesAllowed(BusinessTemplate $businessTemplate, EntityManager $em)
117
    {
118
        $businessEntity = $businessTemplate->getBusinessEntity();
119
        if ($businessEntity->getType() === ORMBusinessEntity::TYPE) {
120
            return $this->getEntitiesAllowedQueryBuilder($businessTemplate, $em)
121
                ->getQuery()
122
                ->getResult();
123
        }
124
        if ($businessEntity->getType() === APIBusinessEntity::TYPE) {
125
            return $this->apiBusinessEntityResolver->getBusinessEntities($businessEntity);
126
        }
127
    }
128
129
    /**
130
     * Get the list of entities allowed for the BusinessTemplate page.
131
     *
132
     * @param BusinessTemplate $businessTemplate
133
     * @param EntityManager    $em
134
     *
135
     * @throws \Exception
136
     *
137
     * @return QueryBuilder
138
     */
139
    public function getEntitiesAllowedQueryBuilder(BusinessTemplate $businessTemplate, EntityManager $em)
140
    {
141
        //the base of the query
142
        $baseQuery = $this->queryHelper->getQueryBuilder($businessTemplate, $em);
143
144
        // add this fake condition to ensure that there is always a "where" clause.
145
        // In query mode, usage of "AND" will be always valid instead of "WHERE"
146
        $baseQuery->andWhere('1 = 1');
147
148
        //filter with the query of the page
149
        return $this->queryHelper->buildWithSubQuery($businessTemplate, $baseQuery, $em);
150
    }
151
152
    /**
153
     * Get the list of business properties usable for the url.
154
     *
155
     * @param BusinessEntity $businessEntity
156
     *
157
     * @return BusinessProperty[] The list of business properties
158
     */
159 View Code Duplication
    public function getBusinessProperties(BusinessEntity $businessEntity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
160
    {
161
        //the business properties usable in a url
162
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
163
164
        //the business properties usable in a url
165
        $seoBusinessProps = $businessEntity->getBusinessPropertiesByType('seoable');
166
167
        //the business properties are the identifier and the seoables properties
168
        $businessProperties = array_merge($businessProperties->toArray(), $seoBusinessProps->toArray());
169
170
        return $businessProperties;
171
    }
172
173
    /**
174
     * Get the position of the identifier in the url of a business entity page pattern.
175
     *
176
     * @param BusinessTemplate $businessTemplate
177
     *
178
     * @return array The position
179
     */
180
    public function getIdentifierPositionInUrl(BusinessTemplate $businessTemplate)
181
    {
182
        $position = null;
183
184
        $url = $businessTemplate->getUrl();
0 ignored issues
show
Bug introduced by
The method getUrl() does not seem to exist on object<Victoire\Bundle\B...ntity\BusinessTemplate>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
185
186
        // split on the / character
187
        $keywords = preg_split("/\//", $url);
188
        // preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $url, $matches);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
189
190
        //the business property link to the page
191
        $businessEntityId = $businessTemplate->getBusinessEntityName();
192
193
        $businessEntity = $this->businessEntityRepository->findBy(['name' => $businessEntityId]);
194
195
        //the business properties usable in a url
196
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
197
198
        //we parse the words of the url
199
        foreach ($keywords as $index => $keyword) {
200
            foreach ($businessProperties as $businessProperty) {
201
                $entityProperty = $businessProperty->getEntityProperty();
202
                $searchWord = '{{item.'.$entityProperty.'}}';
203
204
                if ($searchWord === $keyword) {
205
                    //the array start at index 0 but we want the position to start at 1
206
                    $position = [
207
                        'position'         => $index + 1,
208
                        'businessProperty' => $businessProperty,
209
                    ];
210
                }
211
            }
212
        }
213
214
        return $position;
215
    }
216
217
    /**
218
     * Guess the best pattern to represent given reflectionClass.
219
     *
220
     * @param int           $entity
221
     * @param EntityManager $em
222
     * @param string        $originalRefClassName When digging into parentClass, we do not have to forget originalClass to be able to get reference after all
223
     *
224
     * @throws \Exception
225
     *
226
     * @return View
227
     */
228
    public function guessBestPatternIdForEntity($entity, $em, $originalRefClassName = null)
229
    {
230
        $entityId = $entity->getId();
231
        $templateId = null;
232
        $viewReference = null;
233
        $businessEntity = null;
234
        $refClass = null;
235
        if (is_array($entity) && array_key_exists('_businessEntity', $entity)) {
236
            $businessEntity = $entity['_businessEntity'];
237
        } elseif ($entity instanceof BusinessEntityInterface) {
238
            $refClass = new \ReflectionClass($entity);
239
            $refClassName = $em->getClassMetadata($refClass->name)->name;
240
241
            if (!$originalRefClassName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $originalRefClassName of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
242
                $originalRefClassName = $refClassName;
243
            }
244
245
            $businessEntity = $this->businessEntityHelper->findByEntityClassname($refClassName);
246
        }
247
248
        if ($businessEntity) {
249
            $parameters = [
250
                'entityId'        => $entityId,
251
                'businessEntity'  => $businessEntity->getId(),
252
            ];
253
            $viewReference = $this->viewReferenceRepository->getOneReferenceByParameters($parameters);
254
        }
255
256
        if (!$viewReference) {
257
            if ($refClass && $parentRefClass = $refClass->getParentClass()) {
258
                $templateId = $this->guessBestPatternIdForEntity($parentRefClass, $em, $originalRefClassName);
0 ignored issues
show
Documentation introduced by
$parentRefClass is of type object, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
259
            } else {
260
                throw new \Exception(sprintf('Cannot find a BusinessTemplate that can display the requested BusinessEntity ("%s", "%s".)', $refClassName, $entityId));
261
            }
262
        } elseif ($viewReference instanceof BusinessPageReference) {
263
            $templateId = $viewReference->getTemplateId();
264
        }
265
266
        return $templateId;
267
    }
268
}
269