Passed
Pull Request — master (#225)
by
unknown
12:53 queued 04:52
created

EzCountry   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 20
c 1
b 0
f 1
dl 0
loc 54
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A loadFieldSettings() 0 5 1
A __construct() 0 4 1
A hashToFieldValue() 0 23 6
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core\FieldHandler;
4
5
use eZ\Publish\API\Repository\ContentTypeService;
6
use eZ\Publish\Core\FieldType\Country\Value as CountryValue;
7
use eZ\Publish\Core\FieldType\Selection\Value as SelectionValue;
8
use Kaliop\eZMigrationBundle\API\FieldValueImporterInterface;
9
10
class EzCountry extends AbstractFieldHandler implements FieldValueImporterInterface
11
{
12
    private $contentTypeService;
13
14
    private $countries;
15
16
    public function __construct(ContentTypeService $contentTypeService, array $countries)
17
    {
18
        $this->contentTypeService = $contentTypeService;
19
        $this->countries = $countries;
20
    }
21
22
    /**
23
     * Creates a value object to use as the field value when setting a country field type.
24
     *
25
     * @param $fieldValue string|string[] should work
26
     * @param array $context The context for execution of the current migrations. Contains f.e. the path to the migration
27
     * @return CountryValue
28
     */
29
    public function hashToFieldValue($fieldValue, array $context = array())
30
    {
31
        if ($fieldValue === null) {
32
            return new CountryValue();
33
        }
34
35
        $fieldSettings = $this->loadFieldSettings($context['contentTypeIdentifier'], $context['fieldIdentifier']);
36
37
        $countries = [];
38
        if (!$fieldSettings['isMultiple'] && is_string($fieldValue)) {
39
            $countries = [$fieldValue => $this->countries[$fieldValue]];
40
            return new CountryValue($countries);
41
        }
42
43
        if (is_string($fieldValue)) {
44
            $fieldValue = array($fieldValue);
45
        }
46
47
        foreach ($fieldValue as $countryCode) {
48
            $countries[$countryCode] = $this->countries[$countryCode];
49
        }
50
51
        return new CountryValue($countries);
52
    }
53
54
    /**
55
     * @param string $contentTypeIdentifier
56
     * @param string $fieldIdentifier
57
     * @return mixed
58
     */
59
    protected function loadFieldSettings($contentTypeIdentifier, $fieldIdentifier)
60
    {
61
        $contentType = $this->contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier);
62
        $fieldDefinition = $contentType->fieldDefinitionsByIdentifier[$fieldIdentifier];
63
        return $fieldDefinition->fieldSettings;
64
    }
65
}
66