Completed
Pull Request — master (#67)
by Tim
08:20
created

ProductInventoryObserver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
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\ProductInventoryObserver
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\Utils\ColumnKeys;
24
use TechDivision\Import\Product\Utils\MemberNames;
25
use TechDivision\Import\Product\Observers\AbstractProductImportObserver;
26
use TechDivision\Import\Product\Services\ProductBunchProcessorInterface;
27
28
/**
29
 * Observer that creates/updates the product's inventory.
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 ProductInventoryObserver extends AbstractProductImportObserver
38
{
39
40
    /**
41
     * The product bunch processor instance.
42
     *
43
     * @var \TechDivision\Import\Product\Services\ProductBunchProcessorInterface
44 1
     */
45
    protected $productBunchProcessor;
46
47
    /**
48 1
     * 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
    public function __construct(ProductBunchProcessorInterface $productBunchProcessor)
53 1
    {
54 1
        $this->productBunchProcessor = $productBunchProcessor;
55 1
    }
56
57
    /**
58
     * Return's the product bunch processor instance.
59
     *
60
     * @return \TechDivision\Import\Services\ProductBunchProcessorInterface The product bunch processor instance
61
     */
62 1
    protected function getProductBunchProcessor()
63
    {
64
        return $this->productBunchProcessor;
65
    }
66 1
67
    /**
68
     * Process the observer's business logic.
69 1
     *
70 1
     * @return array The processed row
71
     */
72
    protected function process()
73 1
    {
74
75 1
        // query whether or not, we've found a new SKU => means we've found a new product
76 1
        if ($this->hasBeenProcessed($this->getValue(ColumnKeys::SKU))) {
77 1
            return;
78 1
        }
79 1
80
        // prepare, initialize and persist the stock status/item
81
        $this->persistStockStatus($this->initializeStockStatus($this->prepareStockStatusAttributes()));
82
        $this->persistStockItem($this->initializeStockItem($this->prepareStockItemAttributes()));
83
    }
84
85
    /**
86
     * Prepare the stock status attributes of the entity that has to be persisted.
87
     *
88
     * @return array The prepared stock status attributes
89
     */
90
    protected function prepareStockStatusAttributes()
91 1
    {
92
93 1
        // load the ID of the product that has been created recently
94
        $lastEntityId = $this->getLastEntityId();
95
96
        // initialize the stock status data
97
        $websiteId =  $this->getValue(ColumnKeys::WEBSITE_ID, 0);
98
        $qty = $this->castValueByBackendType('float', $this->getValue(ColumnKeys::QTY));
99
100
        // return the prepared stock status
101 1
        return $this->initializeEntity(
102
            array(
103
                MemberNames::PRODUCT_ID   => $lastEntityId,
104
                MemberNames::WEBSITE_ID   => $websiteId,
105 1
                MemberNames::STOCK_ID     => 1,
106
                MemberNames::STOCK_STATUS => $qty > 0 ? 1 : 0,
107
                MemberNames::QTY          => $qty
108 1
            )
109
        );
110
    }
111 1
112
    /**
113 1
     * Initialize the stock status with the passed attributes and returns an instance.
114 1
     *
115 1
     * @param array $attr The stock status attributes
116
     *
117
     * @return array The initialized stock status
118
     */
119
    protected function initializeStockStatus(array $attr)
120 1
    {
121 1
        return $attr;
122 1
    }
123 1
124
    /**
125
     * Prepare the stock item attributes of the entity that has to be persisted.
126
     *
127 1
     * @return array The prepared stock status item
128
     */
129
    protected function prepareStockItemAttributes()
130
    {
131
132
        // load the ID of the product that has been created recently
133
        $lastEntityId = $this->getLastEntityId();
134
135
        // initialize the stock status data
136
        $websiteId =  $this->getValue(ColumnKeys::WEBSITE_ID, 0);
137 1
138
        // initialize the stock item with the basic data
139 1
        $stockItem = $this->initializeEntity(
140
            array(
141
                MemberNames::PRODUCT_ID  => $lastEntityId,
142
                MemberNames::WEBSITE_ID  => $websiteId,
143
                MemberNames::STOCK_ID    => 1
144
            )
145
        );
146
147
        // append the row values to the stock item
148
        $headerStockMappings = $this->getHeaderStockMappings();
149 1
        foreach ($headerStockMappings as $columnName => $header) {
150
            list ($headerName, $backendType) = $header;
151 1
            $stockItem[$columnName] = $this->castValueByBackendType($backendType, $this->getValue($headerName));
152 1
        }
153
154
        // return the prepared stock item
155
        return $stockItem;
156
    }
157
158
    /**
159
     * Initialize the stock item with the passed attributes and returns an instance.
160
     *
161 1
     * @param array $attr The stock item attributes
162
     *
163 1
     * @return array The initialized stock item
164 1
     */
165
    protected function initializeStockItem(array $attr)
166
    {
167
        return $attr;
168
    }
169
170
    /**
171 1
     * Return's the appings for the table column => CSV column header.
172
     *
173 1
     * @return array The header stock mappings
174
     */
175
    protected function getHeaderStockMappings()
176
    {
177
        return $this->getSubject()->getHeaderStockMappings();
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 getHeaderStockMappings() does only exist in the following implementations of said interface: 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...
178
    }
179
180
    /**
181
     * Persist's the passed stock item data and return's the ID.
182
     *
183
     * @param array $stockItem The stock item data to persist
184
     *
185
     * @return void
186
     */
187
    protected function persistStockItem($stockItem)
188
    {
189
        $this->getProductBunchProcessor()->persistStockItem($stockItem);
190
    }
191
192
    /**
193
     * Persist's the passed stock status data and return's the ID.
194
     *
195
     * @param array $stockStatus The stock status data to persist
196
     *
197
     * @return void
198
     */
199
    protected function persistStockStatus($stockStatus)
200
    {
201
        $this->getProductBunchProcessor()->persistStockStatus($stockStatus);
202
    }
203
}
204