Completed
Push — master ( 89bfcf...4ab803 )
by Vladimir
02:41
created

DataItem::evaluateFrontMatter()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 27
Code Lines 15

Duplication

Lines 11
Ratio 40.74 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 11
loc 27
ccs 0
cts 15
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 3
nop 1
crap 20
1
<?php
2
3
/**
4
 * @copyright 2017 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Document;
9
10
use allejo\stakx\Exception\DependencyMissingException;
11
use allejo\stakx\Exception\UnsupportedDataTypeException;
12
use allejo\stakx\FrontMatter\Parser;
13
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
14
use Symfony\Component\Yaml\Yaml;
15
16
class DataItem extends PermalinkDocument implements
17
    RepeatableItem,
18
    TrackableDocument,
19
    TwigDocument
20
{
21
    protected $data;
22
23
    private $namespace;
24
    private $pageView;
25
26 8
    public function __construct($filePath)
27
    {
28 8
        $this->namespace = '';
29
30 8
        parent::__construct($filePath);
31 6
    }
32
33 4
    public function getData()
34
    {
35 4
        return $this->data;
36
    }
37
38 4
    public function getObjectName()
39
    {
40 4
        return $this->getBaseName();
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function evaluateFrontMatter($variables = array())
47
    {
48
        $workspace = array_merge($this->data, $variables);
49
        $parser = new Parser($workspace, array(
50
            'filename' => $this->getFileName(),
51
            'basename' => $this->getBaseName(),
52
        ));
53
54
        if (!is_null($parser) && $parser->hasExpansion())
55
        {
56
            throw new \LogicException('The permalink for this item has not been set.');
57
        }
58
59
        $permalink = $workspace['permalink'];
60
61 View Code Duplication
        if (is_array($permalink))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
62
        {
63
            $this->permalink = $permalink[0];
64
            array_shift($permalink);
65
            $this->redirects = $permalink;
66
        }
67
        else
68
        {
69
            $this->permalink = $permalink;
0 ignored issues
show
Documentation Bug introduced by
It seems like $permalink of type object or integer or double or string or null or boolean is incompatible with the declared type array of property $permalink.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
70
            $this->redirects = array();
71
        }
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    protected function buildPermalink()
78
    {
79
        return;
80
    }
81
82
    ///
83
    // Twig Document implementation
84
    ///
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 2
    public function getNamespace()
90
    {
91 2
        return $this->namespace;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 2
    public function setNamespace($namespace)
98
    {
99 2
        $this->namespace = $namespace;
100 2
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function setParentPageView(PageView &$pageView)
106
    {
107
        $this->pageView = &$pageView;
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113 2
    public function isDraft()
114
    {
115 2
        return false;
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     */
121 8
    public function refreshFileContent()
122
    {
123
        // This function can be called after the initial object was created and the file may have been deleted since the
124
        // creation of the object.
125 8 View Code Duplication
        if (!$this->fs->exists($this->filePath))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
        {
127 1
            throw new FileNotFoundException(null, 0, null, $this->filePath);
128
        }
129
130 7
        $content = file_get_contents($this->getFilePath());
131 7
        $fxnName = 'from' . ucfirst($this->getExtension());
132
133 7
        if (method_exists(get_called_class(), $fxnName))
134
        {
135 6
            $this->handleDependencies($this->getExtension());
136 6
            $this->data = (null !== ($c = $this->$fxnName($content))) ? $c : array();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $c. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
137
138 6
            return;
139
        }
140
141 1
        throw new UnsupportedDataTypeException($this->getExtension(), 'There is no support to handle this file extension.');
142
    }
143
144
    ///
145
    // File parsing helpers
146
    ///
147
148
    /**
149
     * Convert from CSV into an associative array.
150
     *
151
     * @param string $content CSV formatted text
152
     *
153
     * @return array
154
     */
155 1
    private function fromCsv($content)
156
    {
157 1
        $rows = array_map('str_getcsv', explode("\n", trim($content)));
158 1
        $columns = array_shift($rows);
159 1
        $csv = array();
160
161 1
        foreach ($rows as $row)
162
        {
163 1
            $csv[] = array_combine($columns, $row);
164
        }
165
166 1
        return $csv;
167
    }
168
169
    /**
170
     * Convert from JSON into an associative array.
171
     *
172
     * @param string $content JSON formatted text
173
     *
174
     * @return array
175
     */
176 1
    private function fromJson($content)
177
    {
178 1
        return json_decode($content, true);
179
    }
180
181
    /**
182
     * Convert from XML into an associative array.
183
     *
184
     * @param string $content XML formatted text
185
     *
186
     * @return array
187
     */
188 1
    private function fromXml($content)
189
    {
190 1
        return json_decode(json_encode(simplexml_load_string($content)), true);
191
    }
192
193
    /**
194
     * Convert from YAML into an associative array.
195
     *
196
     * @param string $content YAML formatted text
197
     *
198
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be string|array|\stdClass?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
199
     */
200 3
    private function fromYaml($content)
201
    {
202 3
        return Yaml::parse($content, Yaml::PARSE_DATETIME);
203
    }
204
205
    /**
206
     * An alias for handling `*.yml` files.
207
     *
208
     * @param string $content YAML formatted text
209
     *
210
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be string|array|\stdClass?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
211
     */
212 3
    private function fromYml($content)
213
    {
214 3
        return $this->fromYaml($content);
215
    }
216
217
    /**
218
     * Check for any dependencies needed to parse for a specific file extension
219
     *
220
     * @param string $extension
221
     *
222
     * @todo 0.1.0 Create a help page on the main stakx website for this topic and link to it
223
     *
224
     * @throws DependencyMissingException
225
     */
226 6
    private function handleDependencies($extension)
227
    {
228 6
        if ($extension === 'xml' && !function_exists('simplexml_load_string'))
229
        {
230
            throw new DependencyMissingException('XML', 'XML support is not available with the current PHP installation.');
231
        }
232 6
    }
233
234
    ///
235
    // Jailed Document implementation
236
    ///
237
238
    /**
239
     * {@inheritdoc}
240
     */
241 4
    public function createJail()
242
    {
243 4
        return new JailedDocument($this, array(
244 4
            'getExtension', 'getFilePath', 'getRelativeFilePath'
245
        ), array(
246 4
            'getName' => 'getObjectName'
247
        ));
248
    }
249
250
    ///
251
    // IteratorAggregate implementation
252
    ///
253
254
    /**
255
     * {@inheritdoc}
256
     */
257 1
    public function getIterator()
258
    {
259 1
        return new \ArrayIterator($this->data);
260
    }
261
262
    ///
263
    // ArrayAccess implementation
264
    ///
265
266
    /**
267
     * {@inheritdoc}
268
     */
269
    public function offsetExists($offset)
270
    {
271
        return isset($this->data[$offset]);
272
    }
273
274
    /**
275
     * {@inheritdoc}
276
     */
277 2
    public function offsetGet($offset)
278
    {
279 2
        return $this->data[$offset];
280
    }
281
282
    /**
283
     * {@inheritdoc}
284
     */
285
    public function offsetSet($offset, $value)
286
    {
287
        $this->data[$offset] = $value;
288
    }
289
290
    /**
291
     * {@inheritdoc}
292
     */
293
    public function offsetUnset($offset)
294
    {
295
        unset($this->data[$offset]);
296
    }
297
}
298