1
|
|
|
<?php |
2
|
|
|
namespace Wambo\Catalog\Mapper; |
3
|
|
|
|
4
|
|
|
use Wambo\Catalog\Exception\ProductException; |
5
|
|
|
use Wambo\Catalog\Model\Product; |
6
|
|
|
use Wambo\Catalog\Model\SKU; |
7
|
|
|
use Wambo\Catalog\Model\Slug; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class ProductMapper creates \Wambo\Model\Product models from data bags with product data. |
11
|
|
|
* |
12
|
|
|
* @package Wambo\Mapper |
13
|
|
|
*/ |
14
|
|
|
class ProductMapper |
15
|
|
|
{ |
16
|
|
|
const FIELD_SKU = "sku"; |
17
|
|
|
const FIELD_SLUG = "slug"; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array $mandatoryFields A list of all mandatory fields of a Product |
21
|
|
|
*/ |
22
|
|
|
private $mandatoryFields = [self::FIELD_SKU, self::FIELD_SLUG]; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var ContentMapper |
26
|
|
|
*/ |
27
|
|
|
private $contentMapper; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Creates a new ProductMapper instance |
31
|
|
|
* |
32
|
|
|
* @param ContentMapper $contentMapper A class for mapping product content |
33
|
|
|
*/ |
34
|
7 |
|
public function __construct(ContentMapper $contentMapper) |
35
|
|
|
{ |
36
|
7 |
|
$this->contentMapper = $contentMapper; |
37
|
7 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Get a Catalog model from an array of unstructured product data |
41
|
|
|
* |
42
|
|
|
* @param array $productData An array containing product attributes |
43
|
|
|
* |
44
|
|
|
* @return Product |
45
|
|
|
* |
46
|
|
|
* @throws ProductException If a mandatory field is missing |
47
|
|
|
* @throws ProductException If the no Product could be created from the given product data |
48
|
|
|
*/ |
49
|
7 |
|
public function getProduct(array $productData) |
50
|
|
|
{ |
51
|
|
|
// check if all mandatory fields are present |
52
|
7 |
|
foreach ($this->mandatoryFields as $mandatoryField) { |
53
|
7 |
|
if (!array_key_exists($mandatoryField, $productData)) { |
54
|
7 |
|
throw new ProductException("The field '$mandatoryField' is missing in the given product data"); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// try to create a product from the available data |
59
|
|
|
try { |
60
|
|
|
|
61
|
|
|
// sku |
62
|
3 |
|
$sku = new SKU($productData[self::FIELD_SKU]); |
63
|
|
|
|
64
|
|
|
// slug |
65
|
2 |
|
$slug = new Slug($productData[self::FIELD_SLUG]); |
66
|
|
|
|
67
|
|
|
// product content |
68
|
1 |
|
$content = $this->contentMapper->getContent($productData); |
69
|
|
|
|
70
|
1 |
|
$product = new Product($sku, $slug, $content); |
71
|
1 |
|
return $product; |
72
|
|
|
|
73
|
2 |
|
} catch (\Exception $productException) { |
74
|
2 |
|
throw new ProductException(sprintf("Failed to create a product from the given data: %s", |
75
|
2 |
|
$productException->getMessage()), $productException); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |