Completed
Push — master ( 0c804e...18caae )
by Gaetano
30:48 queued 27:29
created

FieldHandlerManager::fieldValueToHash()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.7085

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 4
cts 7
cp 0.5714
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 4
crap 3.7085
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Core;
4
5
use Kaliop\eZMigrationBundle\API\FieldValueImporterInterface;
6
use Kaliop\eZMigrationBundle\API\FieldDefinitionConverterInterface;
7
use Kaliop\eZMigrationBundle\API\FieldValueConverterInterface;
8
use eZ\Publish\API\Repository\FieldTypeService;
9
10
class FieldHandlerManager
11
{
12
    /** @var FieldValueImporterInterface[][] */
13
    protected $fieldTypeMap;
14
    protected $fieldTypeService;
15
16 79
    public function __construct(FieldTypeService $fieldTypeService)
17
    {
18 79
        $this->fieldTypeService = $fieldTypeService;
19 79
    }
20
21
    /**
22
     * @param FieldValueImporterInterface $fieldHandler
23
     * @param string $fieldTypeIdentifier
24
     * @param string $contentTypeIdentifier
25
     * @throws \Exception
26
     */
27 79
    public function addFieldHandler($fieldHandler, $fieldTypeIdentifier, $contentTypeIdentifier = null)
28
    {
29
        // This is purely BC; at some point we will typehint to FieldValueImporterInterface
30 79
        if (!$fieldHandler instanceof FieldValueImporterInterface) {
31
            throw new \Exception("Can not register object of class '" . get_class($fieldHandler) . "' as field handler because it does not support the desired interface");
32
        }
33
34 79
        if ($contentTypeIdentifier == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $contentTypeIdentifier of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
35 79
            $contentTypeIdentifier = '*';
36
        }
37 79
        $this->fieldTypeMap[$contentTypeIdentifier][$fieldTypeIdentifier] = $fieldHandler;
38 79
    }
39
40
    /**
41
     * @param string $fieldTypeIdentifier
42
     * @param string $contentTypeIdentifier
43
     * @return bool
44
     */
45 20
    public function managesField($fieldTypeIdentifier, $contentTypeIdentifier)
46
    {
47 20
        return (isset($this->fieldTypeMap[$contentTypeIdentifier][$fieldTypeIdentifier]) ||
48 20
            isset($this->fieldTypeMap['*'][$fieldTypeIdentifier]));
49
    }
50
51
    /**
52
     * Returns true when a fieldHandler allows string refs to be pre-resolved for the field value it gets as hash.
53
     * "pre-resolved" means: resolved before the field-handler-specific propcessing kicks in
54
     *
55
     * @param string $fieldTypeIdentifier
56
     * @param string $contentTypeIdentifier
57
     */
58 1
    public function doPreResolveStringReferences($fieldTypeIdentifier, $contentTypeIdentifier)
59
    {
60 1
        if (!$this->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
61
            return true;
62
        }
63
64 1
        $fieldHandler = $this->getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier);
65
        // BC: not alwys defined
66 1
        if (is_callable(array($fieldHandler, 'doPreResolveStringReferences'))) {
67
            return $fieldHandler->doPreResolveStringReferences();
0 ignored issues
show
Bug introduced by
The method doPreResolveStringReferences() does not seem to exist on object<Kaliop\eZMigratio...ValueImporterInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
68
        }
69
70 1
        return true;
71
    }
72
73
    /**
74
     * @param string $fieldTypeIdentifier
75
     * @param string $contentTypeIdentifier
76
     * @param mixed $hashValue
77
     * @param array $context
78
     * @return mixed
79
     */
80 5
    public function hashToFieldValue($fieldTypeIdentifier, $contentTypeIdentifier, $hashValue, array $context = array())
81
    {
82 5
        if ($this->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
83 3
            $fieldHandler = $this->getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier);
84
            // BC
85 3
            if (!$fieldHandler instanceof FieldValueImporterInterface) {
86
                return $fieldHandler->createValue($hashValue, $context);
87
            }
88 3
            return $fieldHandler->hashToFieldValue($hashValue, $context);
89
        }
90
91 3
        $fieldType = $this->fieldTypeService->getFieldType($fieldTypeIdentifier);
92 3
        return $fieldType->fromHash($hashValue);
93
    }
94
95
    /**
96
     * @param string $fieldTypeIdentifier
97
     * @param string $contentTypeIdentifier
98
     * @param \eZ\Publish\SPI\FieldType\Value $value
99
     * @param array $context
100
     * @return mixed
101
     */
102 6
    public function fieldValueToHash($fieldTypeIdentifier, $contentTypeIdentifier, $value, array $context = array())
103
    {
104 6
        if ($this->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
105
            $fieldHandler = $this->getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier);
106
            if ($fieldHandler instanceof FieldValueConverterInterface) {
107
                return $fieldHandler->fieldValueToHash($value, $context);
108
            }
109
        }
110
111 6
        $fieldType = $this->fieldTypeService->getFieldType($fieldTypeIdentifier);
112 6
        return $fieldType->toHash($value);
113
    }
114
115
    /**
116
     * @param string $fieldTypeIdentifier
117
     * @param string $contentTypeIdentifier
118
     * @return bool
119
     */
120 7
    public function managesFieldDefinition($fieldTypeIdentifier, $contentTypeIdentifier)
121
    {
122 7
        if (!$this->managesField($fieldTypeIdentifier, $contentTypeIdentifier)) {
123 7
            return false;
124
        }
125
126 6
        $fieldHandler = $this->getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier);
127 6
        return ($fieldHandler instanceof FieldDefinitionConverterInterface);
128
    }
129
130
    /**
131
     * @param string $fieldTypeIdentifier
132
     * @param string $contentTypeIdentifier
133
     * @param mixed $fieldSettingsHash
134
     * @param array $context
135
     * @return mixed
136
     */
137 1
    public function hashToFieldSettings($fieldTypeIdentifier, $contentTypeIdentifier, $fieldSettingsHash, array $context = array())
138
    {
139 1
        if ($this->managesFieldDefinition($fieldTypeIdentifier, $contentTypeIdentifier)) {
140 1
            return $this->getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier)->hashToFieldSettings($fieldSettingsHash, $context);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...dValueImporterInterface as the method hashToFieldSettings() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...ldHandler\EzDateAndTime, Kaliop\eZMigrationBundle...FieldHandler\EzRelation, Kaliop\eZMigrationBundle...ieldHandler\EzSelection, Kaliop\eZMigrationBundle...\FieldHandler\EzXmlText.

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...
141
        }
142
143
        return $fieldSettingsHash;
144
    }
145
146
    /**
147
     * @param string $fieldTypeIdentifier
148
     * @param string $contentTypeIdentifier
149
     * @param mixed $fieldSettings
150
     * @param array $context
151
     * @return mixed
152
     */
153 5
    public function fieldSettingsToHash($fieldTypeIdentifier, $contentTypeIdentifier, $fieldSettings, array $context = array())
154
    {
155 5
        if ($this->managesFieldDefinition($fieldTypeIdentifier, $contentTypeIdentifier)) {
156 1
            return $this->getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier)->fieldSettingsToHash($fieldSettings, $context);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Kaliop\eZMigrationBundle...dValueImporterInterface as the method fieldSettingsToHash() does only exist in the following implementations of said interface: Kaliop\eZMigrationBundle...ldHandler\EzDateAndTime, Kaliop\eZMigrationBundle...FieldHandler\EzRelation, Kaliop\eZMigrationBundle...ieldHandler\EzSelection, Kaliop\eZMigrationBundle...\FieldHandler\EzXmlText.

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...
157
        }
158
159 5
        return $fieldSettings;
160
    }
161
162
    /**
163
     * @param string $fieldTypeIdentifier
164
     * @param string $contentTypeIdentifier
165
     * @return FieldValueImporterInterface
166
     * @throws \Exception
167
     */
168 7
    protected function getFieldHandler($fieldTypeIdentifier, $contentTypeIdentifier) {
169 7
        if (isset($this->fieldTypeMap[$contentTypeIdentifier][$fieldTypeIdentifier])) {
170
            return $this->fieldTypeMap[$contentTypeIdentifier][$fieldTypeIdentifier];
171 7
        } else if (isset($this->fieldTypeMap['*'][$fieldTypeIdentifier])) {
172 7
            return $this->fieldTypeMap['*'][$fieldTypeIdentifier];
173
        }
174
175
        throw new \Exception("No complex field handler registered for field '$fieldTypeIdentifier' in content type '$contentTypeIdentifier'");
176
    }
177
}
178