Completed
Push — master ( 7785c8...07cf23 )
by Gaetano
09:22
created

ObjectStateGroupManager::matchObjectStateGroups()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 21
Ratio 100 %

Importance

Changes 0
Metric Value
dl 21
loc 21
c 0
b 0
f 0
rs 8.7624
cc 5
eloc 11
nc 4
nop 1
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Collection\ObjectStateGroupCollection;
6
use Kaliop\eZMigrationBundle\Core\Matcher\ObjectStateGroupMatcher;
7
8
class ObjectStateGroupManager extends RepositoryExecutor
9
{
10
    /**
11
     * @var array
12
     */
13
    protected $supportedStepTypes = array('object_state_group');
14
15
    /**
16
     * @var ObjectStateGroupMatcher
17
     */
18
    protected $objectStateGroupMatcher;
19
20
    /**
21
     * @param ObjectStateGroupMatcher $objectStateGroupMatcher
22
     */
23
    public function __construct(ObjectStateGroupMatcher $objectStateGroupMatcher)
24
    {
25
        $this->objectStateGroupMatcher = $objectStateGroupMatcher;
26
    }
27
28
    /**
29
     * Handle the create step of object state group migrations
30
     *
31
     * @todo add support for flexible defaultLanguageCode
32
     */
33
    protected function create()
34
    {
35 View Code Duplication
        foreach(array('names', 'identifier') as $key) {
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...
36
            if (!isset($this->dsl[$key])) {
37
                throw new \Exception("The '$key' key is missing in a object state group creation definition");
38
            }
39
        }
40
41
        $objectStateService = $this->repository->getObjectStateService();
42
43
        $objectStateGroupCreateStruct = $objectStateService->newObjectStateGroupCreateStruct($this->dsl['identifier']);
44
        $objectStateGroupCreateStruct->defaultLanguageCode = self::DEFAULT_LANGUAGE_CODE;
45
46
        foreach ($this->dsl['names'] as $languageCode => $name) {
47
            $objectStateGroupCreateStruct->names[$languageCode] = $name;
48
        }
49
        if (isset($this->dsl['descriptions'])) {
50
            foreach ($this->dsl['descriptions'] as $languageCode => $description) {
51
                $objectStateGroupCreateStruct->descriptions[$languageCode] = $description;
52
            }
53
        }
54
55
        $objectStateGroup = $objectStateService->createObjectStateGroup($objectStateGroupCreateStruct);
56
57
        $this->setReferences($objectStateGroup);
58
59
        return $objectStateGroup;
60
    }
61
62
    /**
63
     * Handle the update step of object state group migrations
64
     *
65
     * @todo add support for defaultLanguageCode
66
     */
67 View Code Duplication
    protected function update()
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...
68
    {
69
        $objectStateService = $this->repository->getObjectStateService();
70
71
        $groupsCollection = $this->matchObjectStateGroups('update');
72
73
        if (count($groupsCollection) > 1 && isset($this->dsl['references'])) {
74
            throw new \Exception("Can not execute Object State Group update because multiple groups match, and a references section is specified in the dsl. References can be set when only 1 state group matches");
75
        }
76
77
        if (count($groupsCollection) > 1 && isset($this->dsl['identifier'])) {
78
            throw new \Exception("Can not execute Object State Group update because multiple groups match, and an identifier is specified in the dsl.");
79
        }
80
81
        foreach ($groupsCollection as $objectStateGroup) {
0 ignored issues
show
Bug introduced by
The expression $groupsCollection of type object<Kaliop\eZMigratio...teGroupCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
82
            //$objectStateGroup = $objectStateService->loadObjectStateGroup($this->dsl['id']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% 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...
83
84
            $objectStateGroupUpdateStruct = $objectStateService->newObjectStateGroupUpdateStruct();
85
86
            if (isset($this->dsl['identifier'])) {
87
                $objectStateGroupUpdateStruct->identifier = $this->dsl['identifier'];
88
            }
89
            if (isset($this->dsl['names'])) {
90
                foreach ($this->dsl['names'] as $languageCode => $name) {
91
                    $objectStateGroupUpdateStruct->names[$languageCode] = $name;
92
                }
93
            }
94
            if (isset($this->dsl['descriptions'])) {
95
                foreach ($this->dsl['descriptions'] as $languageCode => $description) {
96
                    $objectStateGroupUpdateStruct->descriptions[$languageCode] = $description;
97
                }
98
            }
99
            $objectStateGroup = $objectStateService->updateObjectStateGroup($objectStateGroup, $objectStateGroupUpdateStruct);
100
101
            $this->setReferences($objectStateGroup);
102
        }
103
104
        return $groupsCollection;
105
    }
106
107
    /**
108
     * Handle the delete step of object state group migrations
109
     */
110
    protected function delete()
111
    {
112
        $groupsCollection = $this->matchObjectStateGroups('delete');
113
114
        $objectStateService = $this->repository->getObjectStateService();
115
116
        foreach ($groupsCollection as $objectStateGroup) {
0 ignored issues
show
Bug introduced by
The expression $groupsCollection of type object<Kaliop\eZMigratio...teGroupCollection>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
117
            $objectStateService->deleteObjectStateGroup($objectStateGroup);
118
        }
119
120
        return $groupsCollection;
121
    }
122
123
    /**
124
     * @param string $action
125
     * @return ObjectStateGroupCollection
126
     * @throws \Exception
127
     */
128 View Code Duplication
    protected function matchObjectStateGroups($action)
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...
129
    {
130
        if (!isset($this->dsl['match'])) {
131
            throw new \Exception("A match condition is required to $action an ObjectStateGroup.");
132
        }
133
134
        $match = $this->dsl['match'];
135
136
        // convert the references passed in the match
137
        foreach ($match as $condition => $values) {
138
            if (is_array($values)) {
139
                foreach ($values as $position => $value) {
140
                    $match[$condition][$position] = $this->referenceResolver->resolveReference($value);
141
                }
142
            } else {
143
                $match[$condition] = $this->referenceResolver->resolveReference($values);
144
            }
145
        }
146
147
        return $this->objectStateGroupMatcher->match($match);
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    protected function setReferences($objectStateGroup)
154
    {
155
        if (!array_key_exists('references', $this->dsl)) {
156
            return false;
157
        }
158
159
        foreach ($this->dsl['references'] as $reference) {
160
            switch ($reference['attribute']) {
161
                case 'object_state_group_id':
162
                case 'id':
163
                    $value = $objectStateGroup->id;
164
                    break;
165
                case 'object_state_group_identifier':
166
                case 'identifier':
167
                    $value = $objectStateGroup->id;
168
                    break;
169
                default:
170
                    throw new \InvalidArgumentException('Object State Group Manager does not support setting references for attribute ' . $reference['attribute']);
171
            }
172
173
            $this->referenceResolver->addReference($reference['identifier'], $value);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...erenceResolverInterface as the method addReference() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...eResolver\ChainResolver, Kaliop\eZMigrationBundle...CustomReferenceResolver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
174
        }
175
176
        return true;
177
    }
178
}
179