1<?php
2
3namespace FINDOLOGIC\Export\Data;
4
5use FINDOLOGIC\Export\Helpers\DataHelper;
6
7class DuplicateValueForUsergroupException extends \RuntimeException
8{
9    public function __construct($key, $usergroup)
10    {
11        parent::__construct(sprintf('Property "%s" already has a value for usergroup "%s".', $key, $usergroup));
12    }
13}
14
15class PropertyKeyNotAllowedException extends \RuntimeException
16{
17    public function __construct($key)
18    {
19        parent::__construct(sprintf('Property key "%s" is reserved for internal use and overwritten when importing.', $key));
20    }
21}
22
23class Property
24{
25    /**
26     * Reserved property keys for internal use which would be overwritten when importing
27     *
28     * /image\d+/: Image URLs of type default.
29     * /thumbnail\d+/: Image URLs of type thumbnail.
30     * /ordernumber/: The products first exported ordernumber.
31     */
32    const RESERVED_PROPERTY_KEYS = [
33        "/image\d+/",
34        "/thumbnail\d+/",
35        "/ordernumber/"
36    ];
37
38    private $key;
39    private $values;
40
41    /**
42     * @SuppressWarnings(PHPMD.StaticAccess)
43     */
44    public function __construct($key, $values = [])
45    {
46        foreach (self::RESERVED_PROPERTY_KEYS as $reservedPropertyKey) {
47            if (preg_match($reservedPropertyKey, $key)) {
48                throw new PropertyKeyNotAllowedException($key);
49            }
50        }
51
52        $this->key = DataHelper::checkForEmptyValue($key);
53        $this->setValues($values);
54    }
55
56    public function getKey()
57    {
58        return $this->key;
59    }
60
61    /**
62     * @SuppressWarnings(PHPMD.StaticAccess)
63     */
64    public function addValue($value, $usergroup = null)
65    {
66        if (array_key_exists($usergroup, $this->values)) {
67            throw new DuplicateValueForUsergroupException($this->key, $usergroup);
68        }
69
70        $this->values[$usergroup] = DataHelper::checkForEmptyValue($value);
71    }
72
73    protected function setValues($values)
74    {
75        $this->values = [];
76
77        foreach ($values as $usergroup => $value) {
78            $this->addValue($value, $usergroup);
79        }
80    }
81
82    public function getAllValues()
83    {
84        return $this->values;
85    }
86}
87