Completed
Push — 22.x ( bcdba3...51a4b7 )
by Tim
01:41
created

BundleSelectionObserver::loadRawEntity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Bundle\Observers\BundleSelectionObserver
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-product-bundle
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Bundle\Observers;
22
23
use TechDivision\Import\Utils\EntityStatus;
24
use TechDivision\Import\Utils\StoreViewCodes;
25
use TechDivision\Import\Utils\BackendTypeKeys;
26
use TechDivision\Import\Observers\StateDetectorInterface;
27
use TechDivision\Import\Observers\AttributeLoaderInterface;
28
use TechDivision\Import\Observers\DynamicAttributeObserverInterface;
29
use TechDivision\Import\Observers\EntityMergers\EntityMergerInterface;
30
use TechDivision\Import\Product\Bundle\Utils\ColumnKeys;
31
use TechDivision\Import\Product\Bundle\Utils\MemberNames;
32
use TechDivision\Import\Product\Bundle\Utils\EntityTypeCodes;
33
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
34
use TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface;
35
36
/**
37
 * Oberserver that provides functionality for the bundle selection replace operation.
38
 *
39
 * @author    Tim Wagner <[email protected]>
40
 * @copyright 2016 TechDivision GmbH <[email protected]>
41
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
42
 * @link      https://github.com/techdivision/import-product-bundle
43
 * @link      http://www.techdivision.com
44
 */
45
class BundleSelectionObserver extends AbstractProductImportObserver implements DynamicAttributeObserverInterface
46
{
47
48
    /**
49
     * The product bundle processor instance.
50
     *
51
     * @var \TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface
52
     */
53
    protected $productBundleProcessor;
54
55
    /**
56
     * The attribute loader instance.
57
     *
58
     * @var \TechDivision\Import\Observers\AttributeLoaderInterface
59
     */
60
    protected $attributeLoader;
61
62
    /**
63
     * The entity merger instance.
64
     *
65
     * @var \TechDivision\Import\Observers\EntityMergers\EntityMergerInterface
66
     */
67
    protected $entityMerger;
68
69
    /**
70
     * Initialize the "dymanmic" columns.
71
     *
72
     * @var array
73
     */
74
    protected $columns = array(
75
        MemberNames::POSITION                 => array(ColumnKeys::BUNDLE_VALUE_SELECTION_POSITION, BackendTypeKeys::BACKEND_TYPE_INT),
76
        MemberNames::IS_DEFAULT               => array(ColumnKeys::BUNDLE_VALUE_DEFAULT, BackendTypeKeys::BACKEND_TYPE_INT),
77
        MemberNames::SELECTION_PRICE_VALUE    => array(ColumnKeys::BUNDLE_VALUE_PRICE, BackendTypeKeys::BACKEND_TYPE_FLOAT),
78
        MemberNames::SELECTION_CAN_CHANGE_QTY => array(ColumnKeys::BUNDLE_VALUE_CAN_CHANGE_QTY, BackendTypeKeys::BACKEND_TYPE_INT)
79
    );
80
81
    /**
82
     * Initialize the observer with the passed product bundle processor instance.
83
     *
84
     * @param \TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface $productBundleProcessor The product bundle processor instance
85
     * @param \TechDivision\Import\Observers\AttributeLoaderInterface|null                 $attributeLoader        The attribute loader instance
86
     * @param \TechDivision\Import\Observers\EntityMergers\EntityMergerInterface           $entityMerger           The entity merger instance
87
     * @param \TechDivision\Import\Observers\StateDetectorInterface|null                   $stateDetector          The state detector instance
88
     */
89 View Code Duplication
    public function __construct(
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...
90
        ProductBundleProcessorInterface $productBundleProcessor,
91
        AttributeLoaderInterface $attributeLoader = null,
92
        EntityMergerInterface $entityMerger = null,
93
        StateDetectorInterface $stateDetector = null
94
    ) {
95
96
        // initialize the product bundle processor and the attribute loader instance
97
        $this->productBundleProcessor = $productBundleProcessor;
98
        $this->attributeLoader = $attributeLoader;
99
        $this->entityMerger = $entityMerger;
100
101
        // pass the state detector to the parent method
102
        parent::__construct($stateDetector);
103
    }
104
105
    /**
106
     * Return's the product bundle processor instance.
107
     *
108
     * @return \TechDivision\Import\Product\Bundle\Services\ProductBundleProcessorInterface The product bundle processor instance
109
     */
110
    protected function getProductBundleProcessor()
111
    {
112
        return $this->productBundleProcessor;
113
    }
114
115
    /**
116
     * Process the observer's business logic.
117
     *
118
     * @return array The processed row
119
     */
120
    protected function process()
121
    {
122
123
        // prepare the store view code
124
        $this->prepareStoreViewCode($this->getRow());
0 ignored issues
show
Unused Code introduced by
The call to BundleSelectionObserver::prepareStoreViewCode() has too many arguments starting with $this->getRow().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
125
126
        // return immediately if we're have no store view code set
127
        if (StoreViewCodes::ADMIN !== $this->getStoreViewCode(StoreViewCodes::ADMIN)) {
128
            return;
129
        }
130
131
        // prepare, initialize and persist the product bundle selection data
132
        $productBundleSelection = $this->initializeBundleSelection($this->prepareDynamicAttributes());
133
        $selectionId = $this->persistProductBundleSelection($productBundleSelection);
134
135
        // add the mapping for the child SKU => selection ID
136
        $this->addChildSkuSelectionIdMapping($this->getValue(ColumnKeys::BUNDLE_VALUE_SKU), $selectionId);
137
    }
138
139
    /**
140
     * Appends the dynamic attributes to the static ones and returns them.
141
     *
142
     * @return array The array with all available attributes
143
     */
144
    protected function prepareDynamicAttributes() : array
145
    {
146
        return array_merge($this->prepareAttributes(), $this->attributeLoader ? $this->attributeLoader->load($this, $this->columns) : array());
147
    }
148
149
    /**
150
     * Prepare the attributes of the entity that has to be persisted.
151
     *
152
     * @return array The prepared attributes
153
     */
154
    protected function prepareAttributes()
155
    {
156
157
        // load the actual option ID
158
        $optionId = $this->getLastOptionId();
159
160
        try {
161
            // load and map the parent SKU
162
            $parentId = $this->mapSku($this->getValue(ColumnKeys::BUNDLE_PARENT_SKU));
163
        } catch (\Exception $e) {
164
            throw $this->wrapException(array(ColumnKeys::BUNDLE_PARENT_SKU), $e);
0 ignored issues
show
Documentation introduced by
array(\TechDivision\Impo...eys::BUNDLE_PARENT_SKU) is of type array<integer,?>, but the function expects a string.

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...
165
        }
166
167
        try {
168
            // try to load the child ID
169
            $childId = $this->mapSkuToEntityId($this->getValue(ColumnKeys::BUNDLE_VALUE_SKU));
170
        } catch (\Exception $e) {
171
            throw $this->wrapException(array(ColumnKeys::BUNDLE_VALUE_SKU), $e);
0 ignored issues
show
Documentation introduced by
array(\TechDivision\Impo...Keys::BUNDLE_VALUE_SKU) is of type array<integer,?>, but the function expects a string.

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...
172
        }
173
174
        try {
175
            // try to load the selection price type
176
            $selectionPriceType = $this->mapPriceType($this->getValue(ColumnKeys::BUNDLE_VALUE_PRICE_TYPE));
177
        } catch (\Exception $e) {
178
            throw $this->wrapException(array(ColumnKeys::BUNDLE_VALUE_PRICE_TYPE), $e);
0 ignored issues
show
Documentation introduced by
array(\TechDivision\Impo...UNDLE_VALUE_PRICE_TYPE) is of type array<integer,?>, but the function expects a string.

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...
179
        }
180
181
        // load the default values
182
        $selectionQty = $this->getValue(ColumnKeys::BUNDLE_VALUE_DEFAULT_QTY);
183
184
        // prepare the product bundle selection data
185
        return $this->initializeEntity(
186
            $this->loadRawEntity(
187
                array(
188
                    MemberNames::OPTION_ID            => $optionId,
189
                    MemberNames::PARENT_PRODUCT_ID    => $parentId,
190
                    MemberNames::PRODUCT_ID           => $childId,
191
                    MemberNames::SELECTION_QTY        => $selectionQty,
192
                    MemberNames::SELECTION_PRICE_TYPE => $selectionPriceType
193
                )
194
            )
195
        );
196
    }
197
198
    /**
199
     * Merge's and return's the entity with the passed attributes and set's the
200
     * passed status.
201
     *
202
     * @param array       $entity        The entity to merge the attributes into
203
     * @param array       $attr          The attributes to be merged
204
     * @param string|null $changeSetName The change set name to use
205
     *
206
     * @return array The merged entity
207
     * @todo https://github.com/techdivision/import/issues/179
208
     */
209 View Code Duplication
    protected function mergeEntity(array $entity, array $attr, $changeSetName = null)
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...
210
    {
211
        return array_merge(
212
            $entity,
213
            $this->entityMerger ? $this->entityMerger->merge($this, $entity, $attr) : $attr,
214
            array(EntityStatus::MEMBER_NAME => $this->detectState($entity, $attr, $changeSetName))
215
        );
216
    }
217
218
    /**
219
     * Load's and return's a raw entity without primary key but the mandatory members only and nulled values.
220
     *
221
     * @param array $data An array with data that will be used to initialize the raw entity with
222
     *
223
     * @return array The initialized entity
224
     */
225
    protected function loadRawEntity(array $data = array())
226
    {
227
        return $this->getProductBundleProcessor()->loadRawEntity(EntityTypeCodes::CATALOG_PRODUCT_BUNDLE_SELECTION, $data);
228
    }
229
230
    /**
231
     * Initialize the bundle selection with the passed attributes and returns an instance.
232
     *
233
     * @param array $attr The bundle selection attributes
234
     *
235
     * @return array The initialized bundle selection
236
     */
237
    protected function initializeBundleSelection(array $attr)
238
    {
239
        return $attr;
240
    }
241
242
    /**
243
     * Return's the last created option ID.
244
     *
245
     * @return integer $optionId The last created option ID
246
     */
247
    protected function getLastOptionId()
248
    {
249
        return $this->getSubject()->getLastOptionId();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method getLastOptionId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
250
    }
251
252
    /**
253
     * Save's the mapping of the child SKU and the selection ID.
254
     *
255
     * @param string  $childSku    The child SKU of the selection
256
     * @param integer $selectionId The selection ID to save
257
     *
258
     * @return void
259
     */
260
    protected function addChildSkuSelectionIdMapping($childSku, $selectionId)
261
    {
262
        $this->getSubject()->addChildSkuSelectionIdMapping($childSku, $selectionId);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method addChildSkuSelectionIdMapping() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
263
    }
264
265
    /**
266
     * Returns the acutal value of the position counter and raise's it by one.
267
     *
268
     * @return integer The actual value of the position counter
269
     * @deprecated Since 22.0.0
270
     */
271
    protected function raisePositionCounter()
272
    {
273
        return $this->getSubject()->raisePositionCounter();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method raisePositionCounter() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
274
    }
275
276
    /**
277
     * Return's the mapping for the passed price type.
278
     *
279
     * @param string $priceType The price type to map
280
     *
281
     * @return integer The mapped price type
282
     * @throws \Exception Is thrown, if the passed price type can't be mapped
283
     */
284
    protected function mapPriceType($priceType)
285
    {
286
        return $this->getSubject()->mapPriceType($priceType);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method mapPriceType() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject.

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...
287
    }
288
289
    /**
290
     * Return the entity ID for the passed SKU.
291
     *
292
     * @param string $sku The SKU to return the entity ID for
293
     *
294
     * @return integer The mapped entity ID
295
     * @throws \Exception Is thrown if the SKU is not mapped yet
296
     */
297
    protected function mapSku($sku)
298
    {
299
        return $this->getSubject()->mapSkuToEntityId($sku);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method mapSkuToEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject.

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...
300
    }
301
302
    /**
303
     * Return the entity ID for the passed SKU.
304
     *
305
     * @param string $sku The SKU to return the entity ID for
306
     *
307
     * @return integer The mapped entity ID
308
     * @throws \Exception Is thrown if the SKU is not mapped yet
309
     */
310
    protected function mapSkuToEntityId($sku)
311
    {
312
        return $this->getSubject()->mapSkuToEntityId($sku);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Subjects\SubjectInterface as the method mapSkuToEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Prod...\Subjects\BundleSubject, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject.

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...
313
    }
314
315
    /**
316
     * Persist's the passed product bundle selection data and return's the ID.
317
     *
318
     * @param array $productBundleSelection The product bundle selection data to persist
319
     *
320
     * @return string The ID of the persisted entity
321
     */
322
    protected function persistProductBundleSelection($productBundleSelection)
323
    {
324
        return $this->getProductBundleProcessor()->persistProductBundleSelection($productBundleSelection);
325
    }
326
}
327