Completed
Pull Request — master (#81)
by
unknown
28:56
created

QueryManager::setReferences()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 11
nc 3
nop 1
1
<?php
2
/**
3
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
4
 * @license For full copyright and license information view LICENSE file distributed with this source code.
5
 */
6
namespace Kaliop\eZMigrationBundle\Core\Executor;
7
8
use eZ\Publish\API\Repository\Values\Content\Search\SearchResult;
9
use Kaliop\eZMigrationBundle\API\Event\BeforeStepExecutionEvent;
10
use Kaliop\eZMigrationBundle\API\Event\StepExecutedEvent;
11
use Kaliop\eZMigrationBundle\API\ExecutorInterface;
12
use Kaliop\eZMigrationBundle\API\MatcherInterface;
13
use Kaliop\eZMigrationBundle\API\Value\MigrationStep;
14
use Kaliop\eZMigrationBundle\Core\Matcher\QueryTypeMatcher;
15
use Kaliop\eZMigrationBundle\Core\MigrationService;
16
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
17
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
18
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
19
20
class QueryManager extends RepositoryExecutor
21
{
22
    protected $supportedStepTypes = ['query'];
23
    protected $supportedActions = ['content', 'location', 'contentInfo'];
24
25
    /**
26
     * @var MatcherInterface[]
27
     */
28
    protected $matchers;
29
30
    /**
31
     * @var \eZ\Publish\API\Repository\SearchService
32
     */
33
    protected $searchService;
34
35
    /**
36
     * @var MigrationService
37
     */
38
    private $migrationService;
39
40
    /**
41
     * @var ExecutorInterface[]
42
     */
43
    private $executors;
44
45
    /**
46
     * @var EventDispatcherInterface
47
     */
48
    private $dispatcher;
49
50
    public function __construct(array $matchers, MigrationService $migrationService, EventDispatcherInterface $eventDispatcher)
51
    {
52
        foreach ($matchers as $matcher) {
53
            if (!$matcher instanceof MatcherInterface) {
54
                throw new \Exception("Invalid matcher type, expected MatcherInterface");
55
            }
56
            $this->matchers[] = $matcher;
57
        }
58
        $this->migrationService = $migrationService;
59
        $this->dispatcher = $eventDispatcher;
60
    }
61
62
    public function addExecutor(ExecutorInterface $executor)
63
    {
64
        foreach($executor->supportedTypes() as $type) {
65
            $this->executors[$type] = $executor;
66
        }
67
    }
68
69
    /**
70
     * Runs a location query.
71
     */
72
    protected function location($dsl)
73
    {
74
        $searchResult = $this->getSearchService()->findLocations($this->getQuery($dsl));
75
        $this->setReferences(['collection' => $dsl['collection'], 'results' => $searchResult]);
76
        $this->walk($dsl);
77
    }
78
79
    /**
80
     * Runs a content query.
81
     */
82
    protected function content($dsl)
83
    {
84
        $searchResult = $this->getSearchService()->findContent($this->getQuery($dsl));
85
        $this->setReferences(['collection' => $dsl['collection'], 'results' => $searchResult]);
86
        $this->walk($dsl);
87
    }
88
89
    /**
90
     * Runs a contentInfo query.
91
     */
92
    protected function contentInfo($dsl)
93
    {
94
        $searchResult = $this->getSearchService()->findContentInfo($this->getQuery($dsl));
0 ignored issues
show
Bug introduced by
The method findContentInfo() does not exist on eZ\Publish\API\Repository\SearchService. Did you maybe mean findContent()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
95
        $this->setReferences(['collection' => $dsl['collection'], 'results' => $searchResult]);
96
        $this->walk($dsl);
97
    }
98
99
    /**
100
     * Iterates over the collection, and executes the sub-dsl.
101
     */
102
    protected function walk($dsl)
103
    {
104
        foreach ($this->getCollection($dsl['collection']) as $collectionItem) {
105
            $this->referenceResolver->addReference('collection_item_' . $dsl['collection'], $collectionItem, true);
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...
106
107
            foreach ($dsl['walk'] as $walkDSL) {
108
                $step = new MigrationStep($walkDSL['type'], $walkDSL);
109
                $executor = $this->executors[$step->type];
110
                $this->dispatcher->dispatch('ez_migration.before_execution', new BeforeStepExecutionEvent($step, $executor));
111
                $result = $executor->execute($step);
112
                $this->dispatcher->dispatch('ez_migration.step_executed', new StepExecutedEvent($step, $result));
113
            }
114
        }
115
    }
116
117
    protected function getCollection($collection)
118
    {
119
        return $this->referenceResolver->getReferenceValue('reference:collection_' . $collection);
120
    }
121
122
    /**
123
     * Method that each executor (subclass) has to implement.
124
     *
125
     * It is used to set references based on the DSL instructions executed in the current step, for later steps to reuse.
126
     *
127
     * @throws \InvalidArgumentException when trying to set a reference to an unsupported attribute.
128
     * @param $searchResult
129
     * @return boolean
130
     */
131
    protected function setReferences($args)
132
    {
133
        extract($args);
134
135
        if (!isset($collection)) {
136
            throw new \Exception('Missing collection argument');
137
        }
138
139
        if (!isset($results) || !$results instanceof SearchResult) {
140
            throw new \Exception('Invalid result type, SearchResult expected');
141
        }
142
143
        $value = array_map(
144
            function ($searchHit) {
145
                return $searchHit->valueObject;
146
            },
147
            $results->searchHits
148
        );
149
150
        $this->referenceResolver->addReference('collection_' . $collection, $value, true);
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...
151
    }
152
153
    protected function getQuery($dsl)
154
    {
155
        foreach ($this->matchers as $matcher) {
156
            $result = $matcher->match($dsl['match']);
157
            if (count($result) == 1) {
158
                return $result[0];
159
            }
160
        }
161
162
        throw new \Exception("No query matched");
163
    }
164
165
    protected function getSearchService()
166
    {
167
        return $this->repository->getSearchService();
168
    }
169
}
170