Completed
Push — master ( af52c9...e1b19f )
by Gaetano
06:54
created

SectionManager::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\Executor;
4
5
use Kaliop\eZMigrationBundle\API\Collection\SectionCollection;
6
use Kaliop\eZMigrationBundle\Core\Matcher\SectionMatcher;
7
8
/**
9
 * Implements the actions for managing (create/update/delete) section in the system through
10
 * migrations and abstracts away the eZ Publish Public API.
11
 */
12
class SectionManager extends RepositoryExecutor
13
{
14
    protected $supportedStepTypes = array('section');
15
16
    /** @var SectionMatcher $sectionMatcher */
17
    protected $sectionMatcher;
18
19
    /**
20
     * @param SectionMatcher $sectionMatcher
21
     */
22
    public function __construct(SectionMatcher $sectionMatcher)
23
    {
24
        $this->sectionMatcher = $sectionMatcher;
25
    }
26
27
    /**
28
     * Handle the section create migration action
29
     */
30
    protected function create()
31
    {
32
        $sectionService = $this->repository->getSectionService();
33
34
        $sectionCreateStruct = $sectionService->newSectionCreateStruct();
35
36
        $sectionCreateStruct->identifier = $this->dsl['identifier'];
37
        $sectionCreateStruct->name = $this->dsl['name'];
38
39
        $section = $sectionService->createSection($sectionCreateStruct);
40
41
        $this->setReferences($section);
42
43
        return $section;
44
    }
45
46
    /**
47
     * Handle the section update migration action
48
     */
49
    protected function update()
50
    {
51
        $sectionCollection = $this->matchSections('update');
52
53
        if (count($sectionCollection) > 1 && array_key_exists('references', $this->dsl)) {
54
            throw new \Exception("Can not execute Section update because multiple types match, and a references section is specified in the dsl. References can be set when only 1 section matches");
55
        }
56
57
        $sectionService = $this->repository->getSectionService();
58
        foreach ($sectionCollection as $key => $section) {
0 ignored issues
show
Bug introduced by
The expression $sectionCollection of type object<Kaliop\eZMigratio...SectionCollection>|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...
59
            $sectionUpdateStruct = $sectionService->newSectionUpdateStruct();
60
61
            if (isset($this->dsl['identifier'])) {
62
                $sectionUpdateStruct->identifier = $this->dsl['identifier'];
63
            }
64
            if (isset($this->dsl['identifier'])) {
65
                $sectionUpdateStruct->name = $this->dsl['name'];
66
            }
67
68
            $section = $sectionService->updateSection($section, $sectionUpdateStruct);
69
70
            $sectionCollection[$key] = $section;
71
        }
72
73
        $this->setReferences($sectionCollection);
0 ignored issues
show
Bug introduced by
It seems like $sectionCollection defined by $this->matchSections('update') on line 51 can be null; however, Kaliop\eZMigrationBundle...anager::setReferences() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
74
75
        return $sectionCollection;
76
    }
77
78
    /**
79
     * Handle the section delete migration action
80
     */
81
    protected function delete()
82
    {
83
        $sectionCollection = $this->matchSections('delete');
84
85
        $sectionService = $this->repository->getSectionService();
86
87
        foreach ($sectionCollection as $section) {
0 ignored issues
show
Bug introduced by
The expression $sectionCollection of type object<Kaliop\eZMigratio...SectionCollection>|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...
88
            $sectionService->deleteSection($section);
89
        }
90
91
        return $sectionCollection;
92
    }
93
94
    /**
95
     * @param string $action
96
     * @return SectionCollection
97
     * @throws \Exception
98
     */
99 View Code Duplication
    protected function matchSections($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...
100
    {
101
        if (!isset($this->dsl['match'])) {
102
            throw new \Exception("A match condition is required to $action a section.");
103
        }
104
105
        $match = $this->dsl['match'];
106
107
        // convert the references passed in the match
108
        foreach ($match as $condition => $values) {
109
            if (is_array($values)) {
110
                foreach ($values as $position => $value) {
111
                    $match[$condition][$position] = $this->referenceResolver->resolveReference($value);
112
                }
113
            } else {
114
                $match[$condition] = $this->referenceResolver->resolveReference($values);
115
            }
116
        }
117
118
        return $this->sectionMatcher->match($match);
119
    }
120
121
    /**
122
     * Sets references to certain section attributes.
123
     *
124
     * @param \eZ\Publish\API\Repository\Values\Content\Section|SectionCollection $section
125
     * @throws \InvalidArgumentException When trying to set a reference to an unsupported attribute
126
     * @return boolean
127
     */
128 View Code Duplication
    protected function setReferences($section)
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 (!array_key_exists('references', $this->dsl)) {
131
            return false;
132
        }
133
134
        if ($section instanceof SectionCollection) {
135
            if (count($section) > 1) {
136
                throw new \InvalidArgumentException('Section Manager does not support setting references for creating/updating of multiple sections');
137
            }
138
            $section = reset($section);
139
        }
140
141
        foreach ($this->dsl['references'] as $reference) {
142
143
            switch ($reference['attribute']) {
144
                case 'section_id':
145
                case 'id':
146
                    $value = $section->id;
147
                    break;
148
                case 'section_identifier':
149
                case 'identifier':
150
                    $value = $section->identifier;
151
                    break;
152
                case 'section_name':
153
                case 'name':
154
                    $value = $section->name;
155
                    break;
156
                default:
157
                    throw new \InvalidArgumentException('Section Manager does not support setting references for attribute ' . $reference['attribute']);
158
            }
159
160
            $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...ver\ChainPrefixResolver, Kaliop\eZMigrationBundle...ver\ChainRegexpResolver, 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...
161
        }
162
163
        return true;
164
    }
165
}
166