Completed
Pull Request — master (#76)
by Tim
05:58 queued 03:58
created

ProductObserver::loadProduct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Observers\ProductObserver
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
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Product\Observers;
22
23
use TechDivision\Import\Product\Services\ProductBunchProcessorInterface;
24
use TechDivision\Import\Product\Utils\ColumnKeys;
25
use TechDivision\Import\Product\Utils\MemberNames;
26
27
/**
28
 * Observer that create's the product itself.
29
 *
30
 * @author    Tim Wagner <[email protected]>
31
 * @copyright 2016 TechDivision GmbH <[email protected]>
32
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
33
 * @link      https://github.com/techdivision/import-product
34
 * @link      http://www.techdivision.com
35
 */
36
class ProductObserver extends AbstractProductImportObserver
37
{
38
39
    /**
40
     * The product bunch processor instance.
41
     *
42
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
43
     */
44
    protected $productBunchProcessor;
45
46
    /**
47
     * Initialize the observer with the passed product bunch processor instance.
48
     *
49
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor The product bunch processor instance
50
     */
51 1
    public function __construct(ProductBunchProcessorInterface $productBunchProcessor)
52
    {
53 1
        $this->productBunchProcessor = $productBunchProcessor;
54 1
    }
55
56
    /**
57
     * Return's the product bunch processor instance.
58
     *
59
     * @return \TechDivision\Import\Product\Services\ProductBunchProcessorInterface The product bunch processor instance
60
     */
61 1
    protected function getProductBunchProcessor()
62
    {
63 1
        return $this->productBunchProcessor;
64
    }
65
66
    /**
67
     * Process the observer's business logic.
68
     *
69
     * @return void
70
     */
71 1
    protected function process()
72
    {
73
74
        // query whether or not, we've found a new SKU => means we've found a new product
75 1
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::SKU))) {
76
            return;
77
        }
78
79
        // prepare the static entity values
80 1
        $product = $this->initializeProduct($this->prepareAttributes());
81
82
        // insert the entity and set the entity ID
83 1
        $this->setLastEntityId($this->persistProduct($product));
84 1
    }
85
86
    /**
87
     * Prepare the attributes of the entity that has to be persisted.
88
     *
89
     * @return array The prepared attributes
90
     */
91 1
    protected function prepareAttributes()
92
    {
93
94
        // prepare the date format for the created at/updated at dates
95 1
        $createdAt = $this->getValue(ColumnKeys::CREATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
96 1
        $updatedAt = $this->getValue(ColumnKeys::UPDATED_AT, date('Y-m-d H:i:s'), array($this, 'formatDate'));
97
98
        // initialize the product values
99 1
        $sku = $this->getValue(ColumnKeys::SKU);
100 1
        $productType = $this->getValue(ColumnKeys::PRODUCT_TYPE);
101
102
        // load the product's attribute set ID
103 1
        $attributeSet = $this->getAttributeSet();
104 1
        $attributeSetId = $attributeSet[MemberNames::ATTRIBUTE_SET_ID];
105
106
        // return the prepared product
107 1
        return $this->initializeEntity(
108
            array(
109 1
                MemberNames::SKU              => $sku,
110 1
                MemberNames::CREATED_AT       => $createdAt,
111 1
                MemberNames::UPDATED_AT       => $updatedAt,
112 1
                MemberNames::HAS_OPTIONS      => 0,
113 1
                MemberNames::REQUIRED_OPTIONS => 0,
114 1
                MemberNames::TYPE_ID          => $productType,
115 1
                MemberNames::ATTRIBUTE_SET_ID => $attributeSetId
116
            )
117
        );
118
    }
119
120
    /**
121
     * Initialize the product with the passed attributes and returns an instance.
122
     *
123
     * @param array $attr The product attributes
124
     *
125
     * @return array The initialized product
126
     */
127 1
    protected function initializeProduct(array $attr)
128
    {
129
130
        // load the product with the passed SKU and merge it with the attributes
131 1
        if ($entity = $this->loadProduct($attr[MemberNames::SKU])) {
132 1
            return $this->mergeEntity($entity, $attr);
133
        }
134
135
        // otherwise simply return the attributes
136
        return $attr;
137
    }
138
139
    /**
140
     * Load's and return's the product with the passed SKU.
141
     *
142
     * @param string $sku The SKU of the product to load
143
     *
144
     * @return array The product
145
     */
146 1
    protected function loadProduct($sku)
147
    {
148 1
        return $this->getProductBunchProcessor()->loadProduct($sku);
149
    }
150
151
    /**
152
     * Persist's the passed product data and return's the ID.
153
     *
154
     * @param array $product The product data to persist
155
     *
156
     * @return string The ID of the persisted entity
157
     */
158 1
    protected function persistProduct($product)
159
    {
160 1
        return $this->getProductBunchProcessor()->persistProduct($product);
161
    }
162
163
    /**
164
     * Return's the attribute set of the product that has to be created.
165
     *
166
     * @return array The attribute set
167
     */
168 1
    protected function getAttributeSet()
169
    {
170 1
        return $this->getSubject()->getAttributeSet();
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 getAttributeSet() does only exist in the following implementations of said interface: TechDivision\Import\Observers\EntitySubjectImpl, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Subjects\AbstractEavSubject.

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...
171
    }
172
173
    /**
174
     * Set's the ID of the product that has been created recently.
175
     *
176
     * @param string $lastEntityId The entity ID
177
     *
178
     * @return void
179
     */
180 1
    protected function setLastEntityId($lastEntityId)
181
    {
182 1
        $this->getSubject()->setLastEntityId($lastEntityId);
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 setLastEntityId() does only exist in the following implementations of said interface: TechDivision\Import\Plugins\ExportableSubjectImpl, TechDivision\Import\Prod...\AbstractProductSubject, TechDivision\Import\Product\Subjects\BunchSubject, TechDivision\Import\Subjects\ExportableTraitImpl.

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...
183 1
    }
184
}
185