/
Loader.php
502 lines (410 loc) · 10.8 KB
/
Loader.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
<?php
namespace Message\Mothership\Commerce\Product;
use Message\Cog\DB\Query;
use Message\Cog\DB\Result;
use Message\Cog\DB\Entity\EntityLoaderCollection;
use Message\Cog\DB\Entity\EntityLoaderInterface;
use Message\Cog\Localisation\Locale;
use Message\Cog\ValueObject\DateTimeImmutable;
use Message\Mothership\FileManager\File\Loader as FileLoader;
use Message\Mothership\Commerce\Product\Image\TypeCollection as ImageTypes;
use Message\Mothership\Commerce\Product\Tax\Strategy\TaxStrategyInterface;
class Loader implements EntityLoaderInterface
{
/**
* @var Query
*/
protected $_query;
/**
* @var Locale
*/
protected $_locale;
/**
* @var bool
*/
protected $_includeDeleted = false;
/**
* @var bool
*/
protected $_returnArray;
/**
* @var Type\Collection
*/
protected $_productTypes;
/**
* @var Type\DetailLoader
*/
protected $_detailLoader;
/**
* @var EntityLoaderCollection
*/
protected $_entityLoaders;
/**
* @var TaxStrategyInterface
*/
protected $_taxStrategy;
/**
* @var array
*/
protected $_priceTypes;
/**
* @var Collection
*/
private $_productCache;
/**
* @var string
*/
private $_defaultCurrency;
public function __construct(
Query $query,
Locale $locale,
FileLoader $fileLoader,
Type\Collection $productTypes,
Type\DetailLoader $detailLoader,
EntityLoaderCollection $entityLoaders,
$priceTypes = array(),
$defaultCurrency,
TaxStrategyInterface $taxStrategy,
Collection $productCache
) {
$this->_query = $query;
$this->_locale = $locale;
$this->_productTypes = $productTypes;
$this->_detailLoader = $detailLoader;
$this->_priceTypes = $priceTypes;
$this->_fileLoader = $fileLoader;
$this->_entityLoaders = $entityLoaders;
$this->_defaultCurrency = $defaultCurrency;
$this->_taxStrategy = $taxStrategy;
$this->_productCache = $productCache;
}
public function getEntityLoader($entityName)
{
$loader = $this->_entityLoaders->get($entityName);
$loader->setProductLoader($this);
return $loader;
}
public function getEntityLoaders()
{
return $this->_entityLoaders;
}
public function getDefaultCurrency()
{
return $this->_defaultCurrency;
}
/**
* Sets $_includeDeleted
*
* @param bool $bool boolean $_includeDeleted is set to
* @return Loader returns $this for chainability
*/
public function includeDeleted($bool)
{
$this->_includeDeleted = (bool)$bool;
return $this;
}
public function getByID($productID)
{
$this->_returnArray = is_array($productID);
return $this->_loadProduct($productID);
}
public function getByUnitID($unitID)
{
$result = $this->_query->run(
'SELECT
product_id
FROM
product_unit
WHERE
unit_id = ?i',
array(
$unitID
)
);
$this->_returnArray = false;
return count($result) ? $this->_loadProduct($result->flatten()) : false;
}
public function getByCategory($name, $limit = null)
{
$this->_checkLimit($limit);
$result = $this->_query->run('
SELECT
product_id
FROM
product
WHERE
category = ?s
', $name);
$this->_returnArray = true;
return $this->_loadProduct($result->flatten(), $limit);
}
public function getByBrand($name, $limit = null)
{
$this->_checkLimit($limit);
$result = $this->_query->run('
SELECT
product_id
FROM
product
WHERE
brand = ?s
', $name);
$this->_returnArray = true;
return $this->_loadProduct($result->flatten(), $limit);
}
public function getBySupplier($supplier, $limit = null)
{
$this->_checkLimit($limit);
$result = $this->_query->run('
SELECT
product_id
FROM
product
WHERE
supplier_ref = ?s
', [
$supplier
]);
return $this->_loadProduct($result->flatten(), $limit);
}
public function getByType($type)
{
$result = $this->_query->run("
SELECT
product_id
FROM
product
WHERE
`type` = ?s
", $type);
$this->_returnArray = true;
return $this->_loadProduct($result->flatten());
}
public function getByDetail($detailName, $detailValue)
{
if ($detailValue instanceof \DateTime) {
$detailValue = $detailValue->getTimestamp();
}
$result = $this->_query->run("
SELECT
product_id
FROM
product
LEFT JOIN
product_detail AS d
USING
(product_id)
WHERE
d.name = :detailName?s
AND
d.value = :detailValue?s
", [
'detailName' => $detailName,
'detailValue' => $detailValue,
]);
$this->_returnArray = true;
return $this->_loadProduct($result->flatten());
}
public function getAll()
{
$result = $this->_query->run('
SELECT
product_id
FROM
product
');
$this->_returnArray = true;
return count($result) ? $this->_loadProduct($result->flatten()) : [];
}
public function getByLimit($limit)
{
$this->_checkLimit($limit);
$result = $this->_query->run('
SELECT
product_id
FROM
product
LIMIT
0, :limit?i
', [
'limit' => $limit,
]);
$this->_returnArray = true;
return count($result) ? $this->_loadProduct($result->flatten()) : [];
}
public function getBySearchTerms($terms, $limit = null)
{
$this->_checkLimit($limit);
$this->_returnArray = true;
$terms = explode(' ', $terms);
$minTermLength = 3;
$searchFields = [
'p.name',
'p.category',
'ui.sku',
];
$query = '(';
$where = [];
$searchParams = [];
foreach ($terms as $i => $term) {
if (strlen($term) >= $minTermLength) {
$terms[$i] = $term = strtolower($term);
$whereFields = [];
foreach ($searchFields as $j => $field) {
$whereFields[] = 'LOWER(' . $field . ') LIKE :term' . $i . '?s' . PHP_EOL;
$where[] = implode(' OR ', $whereFields);
}
$searchParams['term' . $i] = '%' . $term . '%';
}
}
$query .= implode(' OR ', $where ) . ')';
$query = 'SELECT
p.product_id
FROM
product AS p
LEFT JOIN
product_unit AS u
USING
(product_id)
LEFT JOIN
product_unit_info AS ui
USING
(unit_id)
WHERE
' . $query . '
';
$result = $this->_query->run($query, $searchParams);
$result = array_unique($result->flatten());
return $this->_loadProduct($result, $limit);
}
protected function _loadProduct($productIDs, $limit = null)
{
if (!is_array($productIDs)) {
$productIDs = (array) $productIDs;
}
if (0 === $this->_entityLoaders->count()) {
throw new \LogicException('Cannot load products when entity loaders are not set.');
}
$cachedProducts = [];
// Load products from cache if limit is not set. If limit is set this complicates the following query so
// this step is skipped.
if (null === $limit) {
foreach ($productIDs as $key => $id) {
if ($this->_productCache->exists($id)) {
$cachedProduct = $this->_productCache->get($id);
// Only load deleted products from the cache if `_includeDeleted` is set to true
if ($this->_includeDeleted || !$cachedProduct->authorship->isDeleted()) {
$cachedProducts[] = $cachedProduct;
unset($productIDs[$key]);
}
}
}
} else {
$this->_checkLimit($limit);
}
// If there are no uncached products remaining, return the cached product/s
if (count($productIDs) <= 0) {
return $this->_returnArray ? $cachedProducts : array_shift($cachedProducts);
}
$result = $this->_query->run(
'SELECT
product.product_id AS id,
product.product_id AS catalogueID,
product.created_at AS createdAt,
product.created_by AS createdBy,
product.updated_at AS updatedAt,
product.updated_by AS updatedBy,
product.deleted_at AS deletedAt,
product.deleted_by AS deletedBy,
product.brand AS brand,
product.type AS type,
product.name AS name,
product.category AS category,
product.tax_strategy AS taxStrategy,
product.tax_rate AS taxRate,
product.supplier_ref AS supplierRef,
product.weight_grams AS weight,
product_info.display_name AS displayName,
product_info.sort_name AS sortName,
product_info.description AS description,
product_info.short_description AS shortDescription,
product_info.notes AS notes,
product_export.export_description AS exportDescription,
product_export.export_value AS exportValue,
product_export.export_manufacture_country_id AS exportManufactureCountryID,
product_export.export_code AS exportCode
FROM
product
LEFT JOIN
product_info ON (product.product_id = product_info.product_id)
LEFT JOIN
product_export ON (product.product_id = product_export.product_id)
WHERE
product.product_id IN (?ij)
' . (!$this->_includeDeleted ? 'AND product.deleted_at IS NULL' : '' ) . '
' . ($limit ? 'LIMIT 0, ' . (int) $limit : '') . '
', array(
(array) $productIDs,
)
);
$tags = $this->_query->run(
'SELECT
product_tag.product_id AS id,
product_tag.name AS name
FROM
product_tag
WHERE
product_tag.product_id IN (?ij)
', array(
(array) $productIDs,
));
$products = $result->bindTo(
'Message\\Mothership\\Commerce\\Product\\ProductProxy',
[$this->_locale, $this->_priceTypes, $this->_defaultCurrency, $this->_entityLoaders, clone $this->_taxStrategy] // clone strategy as if inclusive, different base tax rates.
);
foreach ($result as $key => $data) {
// needs to set the product type if inclusive to get the base tax
if ($products[$key]->getTaxStrategy()->getName() === 'inclusive') {
$products[$key]->getTaxStrategy()->setProductType($data->type);
}
$data->taxRate = (float) $data->taxRate;
$data->exportValue = (float) $data->exportValue;
$products[$key]->authorship->create(new DateTimeImmutable(date('c',$data->createdAt)), $data->createdBy);
if ($data->updatedAt) {
$products[$key]->authorship->update(new DateTimeImmutable(date('c',$data->updatedAt)), $data->updatedBy);
}
if ($data->deletedAt) {
$products[$key]->authorship->delete(new DateTimeImmutable(date('c',$data->deletedAt)), $data->deletedBy);
}
foreach ($tags as $k => $tag) {
if ($tag->id == $data->id) {
$products[$key]->tags[$k] = $tag->name;
}
}
$this->_loadType($products[$key], $data->type);
// Add product to cache
$this->_productCache->add($products[$key]);
}
// Merge cached products and main products array
$products = array_merge($products, $cachedProducts);
return count($products) == 1 && !$this->_returnArray ? array_shift($products) : $products;
}
protected function _loadType(Product $product, $type)
{
$product->type = $this->_productTypes->get($type);
}
private function _isWholeNumber($value)
{
if (is_numeric($value)) {
$int = (int) $value;
return ($int == $value);
}
return false;
}
private function _checkLimit($limit)
{
if (null !== $limit && !$this->_isWholeNumber($limit)) {
throw new \InvalidArgumentException('Limit must be a whole number');
}
}
}