Completed
Push — master ( 0eab77...b2f729 )
by Paul
05:35
created

BusinessPageHelper::guessBestPatternIdForEntity()   D

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\BusinessEntityRepository;
15
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessProperty;
16
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
17
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
18
use Victoire\Bundle\CoreBundle\Helper\UrlBuilder;
19
use Victoire\Bundle\ORMBusinessEntityBundle\Entity\ORMBusinessEntity;
20
use Victoire\Bundle\QueryBundle\Helper\QueryHelper;
21
use Victoire\Bundle\ViewReferenceBundle\Connector\ViewReferenceRepository;
22
use Victoire\Bundle\ViewReferenceBundle\ViewReference\BusinessPageReference;
23
24
/**
25
 * The business entity page pattern helper
26
 * ref: victoire_business_page.business_page_helper.
27
 */
28
class BusinessPageHelper
29
{
30
    protected $queryHelper = null;
31
    protected $viewReferenceRepository = null;
32
    protected $businessEntityHelper = null;
33
    protected $parameterConverter = null;
34
    protected $urlBuilder = null;
35
    /**
36
     * @var APIBusinessEntityResolver
37
     */
38
    private $apiBusinessEntityResolver;
39
40
    /**
41
     * @param QueryHelper               $queryHelper
42
     * @param ViewReferenceRepository   $viewReferenceRepository
43
     * @param EntityRepository          $businessEntityRepository
44
     * @param BusinessEntityHelper      $businessEntityHelper
45
     * @param ParameterConverter        $parameterConverter
46
     * @param UrlBuilder                $urlBuilder
47
     * @param APIBusinessEntityResolver $apiBusinessEntityResolver
48
     */
49
    public function __construct(QueryHelper $queryHelper, ViewReferenceRepository $viewReferenceRepository, EntityRepository $businessEntityRepository, BusinessEntityHelper $businessEntityHelper, ParameterConverter $parameterConverter, UrlBuilder $urlBuilder, APIBusinessEntityResolver $apiBusinessEntityResolver)
50
    {
51
        $this->queryHelper = $queryHelper;
52
        $this->viewReferenceRepository = $viewReferenceRepository;
53
        $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...
54
        $this->businessEntityHelper = $businessEntityHelper;
55
        $this->parameterConverter = $parameterConverter;
56
        $this->urlBuilder = $urlBuilder;
57
        $this->apiBusinessEntityResolver = $apiBusinessEntityResolver;
58
    }
59
60
    /**
61
     * Is the entity allowed for the business entity page.
62
     *
63
     * @param BusinessTemplate $businessTemplate
64
     * @param object|null      $entity
65
     * @param EntityManager    $em
66
     *
67
     * @throws \Exception
68
     *
69
     * @return bool
70
     */
71
    public function isEntityAllowed(BusinessTemplate $businessTemplate, $entity, EntityManager $em = null)
72
    {
73
        if ($businessTemplate->getBusinessEntity()->getType() === APIBusinessEntity::TYPE) {
74
            return true;
75
        }
76
        $allowed = true;
77
78
        //test that an entity is given
79
        if ($entity === null) {
80
            throw new \Exception('The entity is required.');
81
        }
82
83
        $queryHelper = $this->queryHelper;
84
85
        //the page id
86
        $entityId = $entity->getId();
87
88
        //the base of the query
89
        $baseQuery = $queryHelper->getQueryBuilder($businessTemplate, $em);
0 ignored issues
show
Bug introduced by
It seems like $em defined by parameter $em on line 71 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...
90
91
        $baseQuery->andWhere('main_item.id = '.$entityId);
92
93
        //filter with the query of the page
94
        $items = $queryHelper->buildWithSubQuery($businessTemplate, $baseQuery, $em)
0 ignored issues
show
Bug introduced by
It seems like $em defined by parameter $em on line 71 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...
95
            ->getQuery()->getResult();
96
97
        //only one page can be found because we filter on the
98
        if (count($items) > 1) {
99
            throw new \Exception('More than 1 item was found, there should not be more than 1 item with this query.');
100
        }
101
102
        if (count($items) === 0) {
103
            $allowed = false;
104
        }
105
106
        return $allowed;
107
    }
108
109
    /**
110
     * Get the list of entities allowed for the BusinessTemplate page.
111
     *
112
     * @param BusinessTemplate $businessTemplate
113
     * @param EntityManager    $em
114
     *
115
     * @return array
116
     */
117
    public function getEntitiesAllowed(BusinessTemplate $businessTemplate, EntityManager $em)
118
    {
119
        $businessEntity = $businessTemplate->getBusinessEntity();
120
        if ($businessEntity->getType() === ORMBusinessEntity::TYPE) {
121
            return $this->getEntitiesAllowedQueryBuilder($businessTemplate, $em)
122
                ->getQuery()
123
                ->getResult();
124
        }
125
        if ($businessEntity->getType() === APIBusinessEntity::TYPE) {
126
            return $this->apiBusinessEntityResolver->getBusinessEntities($businessEntity);
127
        }
128
    }
129
130
    /**
131
     * Get the list of entities allowed for the BusinessTemplate page.
132
     *
133
     * @param BusinessTemplate $businessTemplate
134
     * @param EntityManager    $em
135
     *
136
     * @throws \Exception
137
     *
138
     * @return QueryBuilder
139
     */
140
    public function getEntitiesAllowedQueryBuilder(BusinessTemplate $businessTemplate, EntityManager $em)
141
    {
142
        //the base of the query
143
        $baseQuery = $this->queryHelper->getQueryBuilder($businessTemplate, $em);
144
145
        // add this fake condition to ensure that there is always a "where" clause.
146
        // In query mode, usage of "AND" will be always valid instead of "WHERE"
147
        $baseQuery->andWhere('1 = 1');
148
149
        //filter with the query of the page
150
        return $this->queryHelper->buildWithSubQuery($businessTemplate, $baseQuery, $em);
151
    }
152
153
    /**
154
     * Get the list of business properties usable for the url.
155
     *
156
     * @param BusinessEntity $businessEntity
157
     *
158
     * @return BusinessProperty[] The list of business properties
159
     */
160 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...
161
    {
162
        //the business properties usable in a url
163
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
164
165
        //the business properties usable in a url
166
        $seoBusinessProps = $businessEntity->getBusinessPropertiesByType('seoable');
167
168
        //the business properties are the identifier and the seoables properties
169
        $businessProperties = array_merge($businessProperties->toArray(), $seoBusinessProps->toArray());
170
171
        return $businessProperties;
172
    }
173
174
    /**
175
     * Get the position of the identifier in the url of a business entity page pattern.
176
     *
177
     * @param BusinessTemplate $businessTemplate
178
     *
179
     * @return array The position
180
     */
181
    public function getIdentifierPositionInUrl(BusinessTemplate $businessTemplate)
182
    {
183
        $position = null;
184
185
        $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...
186
187
        // split on the / character
188
        $keywords = preg_split("/\//", $url);
189
        // 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...
190
191
        //the business property link to the page
192
        $businessEntityId = $businessTemplate->getBusinessEntityName();
193
194
        $businessEntity = $this->businessEntityRepository->findBy(['name' => $businessEntityId]);
195
196
        //the business properties usable in a url
197
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
198
199
        //we parse the words of the url
200
        foreach ($keywords as $index => $keyword) {
201
            foreach ($businessProperties as $businessProperty) {
202
                $entityProperty = $businessProperty->getEntityProperty();
203
                $searchWord = '{{item.'.$entityProperty.'}}';
204
205
                if ($searchWord === $keyword) {
206
                    //the array start at index 0 but we want the position to start at 1
207
                    $position = [
208
                        'position'         => $index + 1,
209
                        'businessProperty' => $businessProperty,
210
                    ];
211
                }
212
            }
213
        }
214
215
        return $position;
216
    }
217
218
    /**
219
     * Guess the best pattern to represent given reflectionClass.
220
     *
221
     * @param \ReflectionClass $refClass
0 ignored issues
show
Documentation introduced by
There is no parameter named $refClass. Did you maybe mean $originalRefClassName?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
222
     * @param int              $entityId
0 ignored issues
show
Documentation introduced by
There is no parameter named $entityId. Did you maybe mean $entity?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
223
     * @param EntityManager    $em
224
     * @param string           $originalRefClassName When digging into parentClass, we do not have to forget originalClass to be able to get reference after all
225
     *
226
     * @throws \Exception
227
     *
228
     * @return View
229
     */
230
    public function guessBestPatternIdForEntity($entity, $em, $originalRefClassName = null)
231
    {
232
        $entityId = $entity->getId();
233
        $templateId = null;
234
        $viewReference = null;
235
        $businessEntity = null;
236
        $refClass = null;
237
        if (is_array($entity) && array_key_exists('_businessEntity', $entity)) {
238
            $businessEntity = $entity['_businessEntity'];
239
        } elseif ($entity instanceof BusinessEntityInterface) {
240
            $refClass = new \ReflectionClass($entity);
241
            $refClassName = $em->getClassMetadata($refClass->name)->name;
242
243
            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...
244
                $originalRefClassName = $refClassName;
245
            }
246
247
            $businessEntity = $this->businessEntityHelper->findByEntityClassname($refClassName);
248
        }
249
250
        if ($businessEntity) {
251
            $parameters = [
252
                'entityId'        => $entityId,
253
                'businessEntity'  => $businessEntity->getId(),
254
            ];
255
            $viewReference = $this->viewReferenceRepository->getOneReferenceByParameters($parameters);
256
        }
257
258
        if (!$viewReference) {
259
            if ($refClass && $parentRefClass = $refClass->getParentClass()) {
260
                $templateId = $this->guessBestPatternIdForEntity($parentRefClass, $em, $originalRefClassName);
261
            } else {
262
                throw new \Exception(sprintf('Cannot find a BusinessTemplate that can display the requested BusinessEntity ("%s", "%s".)', $refClassName, $entityId));
263
            }
264
        } elseif ($viewReference instanceof BusinessPageReference) {
265
            $templateId = $viewReference->getTemplateId();
266
        }
267
268
        return $templateId;
269
    }
270
}
271