Completed
Push — 19.x ( 353011...e6f787 )
by Tim
01:49
created

ProductWebsiteObserver   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 208
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 19.61%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 5
dl 0
loc 208
ccs 10
cts 51
cp 0.1961
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getProductBunchProcessor() 0 4 1
A setCode() 0 4 1
A getCode() 0 4 1
A prepareAttributes() 0 17 1
A initializeProductWebsite() 0 4 1
A loadProductWebsitesBySku() 0 4 1
A persistProductWebsite() 0 4 1
A deleteProductWebsite() 0 4 1
A getStoreWebsiteIdByCode() 0 4 1
B process() 0 59 10
1
<?php
2
3
/**
4
 * TechDivision\Import\Product\Observers\ProductWebsiteObserver
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
use TechDivision\Import\Product\Utils\ConfigurationKeys;
27
28
/**
29
 * Observer that creates/updates the product's website relations.
30
 *
31
 * @author    Tim Wagner <[email protected]>
32
 * @copyright 2016 TechDivision GmbH <[email protected]>
33
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
34
 * @link      https://github.com/techdivision/import-product
35
 * @link      http://www.techdivision.com
36
 */
37
class ProductWebsiteObserver extends AbstractProductImportObserver
38
{
39
40
    /**
41
     * The product bunch processor instance.
42
     *
43
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
44
     */
45
    protected $productBunchProcessor;
46
47
    /**
48
     * Initialize the observer with the passed product bunch processor instance.
49
     *
50
     * @param \TechDivision\Import\Product\Services\ProductBunchProcessorInterface $productBunchProcessor The product bunch processor instance
51
     */
52 1
    public function __construct(ProductBunchProcessorInterface $productBunchProcessor)
53
    {
54 1
        $this->productBunchProcessor = $productBunchProcessor;
55 1
    }
56
57
    /**
58
     * Return's the product bunch processor instance.
59
     *
60
     * @return \TechDivision\Import\Product\Services\ProductBunchProcessorInterface The product bunch processor instance
61
     */
62
    protected function getProductBunchProcessor()
63
    {
64
        return $this->productBunchProcessor;
65
    }
66
67
    /**
68
     * The actual website code that has to be processed.
69
     *
70
     * @var string
71
     */
72
    protected $code;
73
74
    /**
75
     * Set's the actual website code that has to be processed.
76
     *
77
     * @param string $code The website code
78
     *
79
     * @return void
80
     */
81
    protected function setCode($code)
82
    {
83
        $this->code = $code;
84
    }
85
86
    /**
87
     * Return's the webiste code that has to be processed.
88
     *
89
     * @return string The website code
90
     */
91
    protected function getCode()
92
    {
93
        return $this->code;
94
    }
95
96
    /**
97
     * Process the observer's business logic.
98
     *
99
     * @return array The processed row
100
     */
101 1
    protected function process()
102
    {
103
104
        // query whether or not, we've found a new SKU => means we've found a new product
105 1
        if ($this->hasBeenProcessed($sku = $this->getValue(ColumnKeys::SKU))) {
106
            return;
107
        }
108
109
        // load the product => website relations
110 1
        $codes = $this->getValue(ColumnKeys::PRODUCT_WEBSITES, array(), array($this, 'explode'));
111
112
        // query whether or not we've to clean up existing website product relations
113 1
        if ($this->getSubject()->getConfiguration()->hasParam(ConfigurationKeys::CLEAN_UP_WEBSITE_PRODUCT_RELATIONS) &&
114 1
            $this->getSubject()->getConfiguration()->getParam(ConfigurationKeys::CLEAN_UP_WEBSITE_PRODUCT_RELATIONS)
115
        ) {
116
            // initialize the array for the website IDs
117
            $websiteIds = array();
118
119
            // prepare the website IDs
120
            foreach ($codes as $code) {
121
                $websiteIds[$code] = $this->getStoreWebsiteIdByCode($code);
122
            }
123
124
            // load the available product websites
125
            if ($productWebsites = $this->loadProductWebsitesBySku($sku)) {
126
                // iterate over the products websites
127
                foreach ($productWebsites as $productWebsite) {
128
                    // if the product websit relation is in the CSV file, do nothing
129
                    if (in_array($productWebsite[MemberNames::WEBSITE_ID], $websiteIds)) {
130
                        continue;
131
                    }
132
133
                    // delete it, because we don't need it any longer
134
                    $this->deleteProductWebsite(
135
                        array(
136
                            MemberNames::PRODUCT_ID => $productWebsite[MemberNames::PRODUCT_ID],
137
                            MemberNames::WEBSITE_ID => $productWebsite[MemberNames::WEBSITE_ID]
138
                        )
139
                    );
140
                }
141
            }
142
        }
143
144
        // append the product => website relations found
145 1
        foreach ($codes as $code) {
146
            // set the code of the website that has to be processed
147
            $this->setCode($code);
148
            // prepare the product website relation attributes
149
            $attr = $this->prepareAttributes();
150
151
            try {
152
                // create the product website relation
153
                $productWebsite = $this->initializeProductWebsite($attr);
154
                $this->persistProductWebsite($productWebsite);
155
            } catch (\RuntimeException $re) {
156
                $this->getSystemLogger()->debug($re->getMessage());
157
            }
158
        }
159 1
    }
160
161
    /**
162
     * Prepare the attributes of the entity that has to be persisted.
163
     *
164
     * @return array The prepared attributes
165
     */
166
    protected function prepareAttributes()
167
    {
168
169
        // load the ID of the product that has been created recently
170
        $lastEntityId = $this->getLastEntityId();
171
172
        // load the website ID to relate the product with
173
        $websiteId = $this->getStoreWebsiteIdByCode($this->getCode());
174
175
        // return the prepared product
176
        return $this->initializeEntity(
177
            array(
178
                MemberNames::PRODUCT_ID => $lastEntityId,
179
                MemberNames::WEBSITE_ID => $websiteId
180
            )
181
        );
182
    }
183
184
    /**
185
     * Initialize the product website with the passed attributes and returns an instance.
186
     *
187
     * @param array $attr The product website attributes
188
     *
189
     * @return array The initialized product website
190
     * @throws \RuntimeException Is thrown, if the attributes can not be initialized
191
     */
192
    protected function initializeProductWebsite(array $attr)
193
    {
194
        return $attr;
195
    }
196
197
    /**
198
     * Load's and return's the product website relations for the product with the passed SKU.
199
     *
200
     * @param string $sku The SKU to of the product to load the product website relations for
201
     *
202
     * @return array The product website relations
203
     */
204
    protected function loadProductWebsitesBySku($sku)
205
    {
206
        return $this->getProductBunchProcessor()->loadProductWebsitesBySku($sku);
207
    }
208
209
    /**
210
     * Persist's the passed product website data.
211
     *
212
     * @param array $productWebsite The product website data to persist
213
     *
214
     * @return void
215
     */
216
    protected function persistProductWebsite(array $productWebsite)
217
    {
218
        $this->getProductBunchProcessor()->persistProductWebsite($productWebsite);
219
    }
220
221
    /**
222
     * Delete's the passed product website data.
223
     *
224
     * @param array $productWebsite The product website data to delete
225
     *
226
     * @return void
227
     */
228
    protected function deleteProductWebsite(array $productWebsite)
229
    {
230
        $this->getProductBunchProcessor()->deleteProductWebsite($productWebsite);
231
    }
232
233
    /**
234
     * Return's the store website for the passed code.
235
     *
236
     * @param string $code The code of the store website to return the ID for
237
     *
238
     * @return integer The store website ID
239
     */
240
    protected function getStoreWebsiteIdByCode($code)
241
    {
242
        return $this->getSubject()->getStoreWebsiteIdByCode($code);
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 getStoreWebsiteIdByCode() does only exist in the following implementations of said interface: 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...
243
    }
244
}
245