Completed
Push — 15.x ( 321523...5df027 )
by Tim
05:03
created

ConfigurationFactory::getSerializerBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * TechDivision\Import\Configuration\Jms\ConfigurationFactory
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-configuration-jms
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Configuration\Jms;
22
23
use JMS\Serializer\SerializerBuilder;
24
use TechDivision\Import\ConfigurationFactoryInterface;
25
use TechDivision\Import\Configuration\Jms\Configuration\Params;
26
27
/**
28
 * The configuration factory implementation.
29
 *
30
 * @author    Tim Wagner <[email protected]>
31
 * @copyright 2016 TechDivision GmbH <[email protected]>
32
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
33
 * @link      https://github.com/techdivision/import-configuration-jms
34
 * @link      http://www.techdivision.com
35
 */
36
class ConfigurationFactory implements ConfigurationFactoryInterface
37
{
38
39
    /**
40
     * The configuration parser factory instance used to create a parser that
41
     * parsers and merges the configuration from different directories.
42
     *
43
     * @var \TechDivision\Import\Configuration\Jms\ConfigurationParserFactoryInterface
44
     */
45
    protected $configurationParserFactory;
46
47
    /**
48
     * The configuration class name to use.
49
     *
50
     * @var string
51
     */
52
    protected $configurationClassName;
53
54
    /**
55
     * The serializer builder instance.
56
     *
57
     * @var \JMS\Serializer\SerializerBuilder
58
     */
59
    protected $serializerBuilder;
60
61
    /**
62
     * Initializes the instance with the configuration parser factory instance.
63
     *
64
     * @param \TechDivision\Import\Configuration\Jms\ConfigurationParserFactoryInterface $configurationParserFactory The configuration parser factory instance
65
     * @param \JMS\Serializer\SerializerBuilder                                          $serializerBuilder          The serializer builder instance to use
66
     * @param string                                                                     $configurationClassName     The configuration class name to use
67
     */
68
    public function __construct(
69
        ConfigurationParserFactoryInterface $configurationParserFactory,
70
        SerializerBuilder $serializerBuilder,
71
        $configurationClassName = Configuration::class
72
    ) {
73
        $this->serializerBuilder = $serializerBuilder;
74
        $this->configurationClassName = $configurationClassName;
75
        $this->configurationParserFactory = $configurationParserFactory;
76
    }
77
78
    /**
79
     * Return's the configuration parser factory instance.
80
     *
81
     * @return \TechDivision\Import\Configuration\Jms\ConfigurationParserFactoryInterface The configuration parser factory instance
82
     */
83
    protected function getConfigurationParserFactory()
84
    {
85
        return $this->configurationParserFactory;
86
    }
87
88
    /**
89
     * Return's the configuration class name to use.
90
     *
91
     * @return string The configuration class name
92
     */
93
    protected function getConfigurationClassName()
94
    {
95
        return $this->configurationClassName;
96
    }
97
98
    /**
99
     * Return's the serializer builder instance to use.
100
     *
101
     * @return \JMS\Serializer\SerializerBuilder The serializer builder instance
102
     */
103
    protected function getSerializerBuilder()
104
    {
105
        return $this->serializerBuilder;
106
    }
107
108
    /**
109
     * Returns the configuration parser for the passed format.
110
     *
111
     * @param string $format The format of the configuration file to return the parser for (either one of json, yaml or xml)
112
     *
113
     * @return \TechDivision\Import\Configuration\Jms\ConfigurationParserInterface The configuration parser instance
114
     */
115
    protected function getConfigurationParser($format)
116
    {
117
        return $this->getConfigurationParserFactory()->factory($format);
118
    }
119
120
    /**
121
     * Factory implementation to create a new initialized configuration instance.
122
     *
123
     * @param string $filename   The configuration filename
124
     * @param string $format     The format of the configuration file, either one of json, yaml or xml
125
     * @param string $params     A serialized string with additional params that'll be passed to the configuration
126
     * @param string $paramsFile A filename that contains serialized data with additional params that'll be passed to the configuration
127
     *
128
     * @return \TechDivision\Import\Configuration\Jms\Configuration The configuration instance
129
     * @throws \Exception Is thrown, if the specified configuration file doesn't exist
130
     */
131
    public function factory($filename, $format = 'json', $params = null, $paramsFile = null)
132
    {
133
134
        // try to load the JSON data
135
        if ($data = file_get_contents($filename)) {
136
            // initialize the JMS serializer, load and return the configuration
137
            return $this->factoryFromString($data, $format, $params, $paramsFile);
138
        }
139
140
        // throw an exception if the data can not be loaded from the passed file
141
        throw new \Exception(sprintf('Can\'t load configuration file %s', $filename));
142
    }
143
144
    /**
145
     * Factory implementation to create a new initialized configuration instance from a file
146
     * with configurations that'll be parsed and merged.
147
     *
148
     * @param array  $directories An array with diretories to parse and merge
149
     * @param string $format      The format of the configuration file, either one of json, yaml or xml
150
     * @param string $params      A serialized string with additional params that'll be passed to the configuration
151
     * @param string $paramsFile  A filename that contains serialized data with additional params that'll be passed to the configuration
152
     *
153
     * @return void
154
     */
155
    public function factoryFromDirectories(array $directories = array(), $format = 'json', $params = null, $paramsFile = null)
156
    {
157
        return $this->factoryFromString($this->getConfigurationParser($format)->parse($directories), $format, $params, $paramsFile);
158
    }
159
160
    /**
161
     * Factory implementation to create a new initialized configuration instance.
162
     *
163
     * @param string $data       The configuration data
164
     * @param string $format     The format of the configuration data, either one of json, yaml or xml
165
     * @param string $params     A serialized string with additional params that'll be passed to the configuration
166
     * @param string $paramsFile A filename that contains serialized data with additional params that'll be passed to the configuration
167
     *
168
     * @return \TechDivision\Import\ConfigurationInterface The configuration instance
169
     */
170
    public function factoryFromString($data, $format = 'json', $params = null, $paramsFile = null)
171
    {
172
173
        // initialize the JMS serializer, load and return the configuration
174
        $data = $this->toArray($data, $this->getConfigurationClassName(), $format);
175
176
        // merge the params, if specified with the --params option
177
        if ($params) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $params of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
178
            $this->replaceParams(
179
                $data,
180
                $this->toArray(
181
                    $params,
182
                    Params::class,
183
                    $format
184
                )
185
            );
186
        }
187
188
        // merge the param loaded from the file, if specified with the --params-file option
189
        if ($paramsFile && is_file($paramsFile)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $paramsFile of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
190
            $this->replaceParams(
191
                $data,
192
                $this->toArray(
193
                    file_get_contents($paramsFile),
194
                    Params::class,
195
                    pathinfo($paramsFile, PATHINFO_EXTENSION)
196
                )
197
            );
198
        }
199
200
        // finally, create and return the configuration from the merge data
201
        return $this->getSerializerBuilder()->build()->fromArray($data, $this->getConfigurationClassName());
202
    }
203
204
    /**
205
     * Creates and returns an array/object tree from the passed array.
206
     *
207
     * @param array  $data The data to create the object tree from
208
     * @param string $type The object type to create
209
     *
210
     * @return mixed The array/object tree from the passed array
211
     */
212
    protected function fromArray(array $data, $type)
213
    {
214
        return $this->getSerializerBuilder()->build()->fromArray($data, $type);
215
    }
216
217
    /**
218
     * Deserializes the data, converts it into an array and returns it.
219
     *
220
     * @param string $data   The data to convert
221
     * @param string $type   The object type for the deserialization
222
     * @param string $format The data format, either one of JSON, XML or YAML
223
     *
224
     * @return array The data as array
225
     */
226
    protected function toArray($data, $type, $format)
227
    {
228
229
        // load the serializer builde
230
        $serializer = $this->getSerializerBuilder()->build();
231
232
        // deserialize the data, convert it into an array and return it
233
        return $serializer->toArray($serializer->deserialize($data, $type, $format));
234
    }
235
236
    /**
237
     * Merge the additional params in the passed configuration data and replaces existing ones with the same name.
238
     *
239
     * @param array $data   The array with configuration data
240
     * @param array $params The array with additional params to merge
241
     *
242
     * @return void
243
     */
244
    protected function replaceParams(&$data, $params)
245
    {
246
        $data = array_replace_recursive($data, $params);
247
    }
248
}
249