Completed
Pull Request — master (#48)
by Vladimir
03:17
created

DataItem::fromXml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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
    \ArrayAccess,
18
    \IteratorAggregate,
19
    TwigDocumentInterface,
20
    JailedDocumentInterface
21
{
22
    protected $data;
23
24
    private $namespace;
25
    private $pageView;
26
27 6
    public function __construct($filePath)
28
    {
29 6
        $this->namespace = '';
30
31 6
        parent::__construct($filePath);
32 4
    }
33
34 4
    public function getData()
35
    {
36 4
        return $this->data;
37
    }
38
39 2
    public function getName()
40
    {
41 2
        return $this->getBaseName();
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function evaluateFrontMatter($variables = array())
48
    {
49
        $workspace = array_merge($this->data, $variables);
50
        $parser = new Parser($workspace, array(
51
            'filename' => $this->getFileName(),
52
            'basename' => $this->getBaseName(),
53
        ));
54
55
        if (!is_null($parser) && $parser->hasExpansion())
56
        {
57
            throw new \LogicException('The permalink for this item has not been set.');
58
        }
59
60
        $permalink = $workspace['permalink'];
61
62 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...
63
        {
64
            $this->permalink = $permalink[0];
65
            array_shift($permalink);
66
            $this->redirects = $permalink;
67
        }
68
        else
69
        {
70
            $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...
71
            $this->redirects = array();
72
        }
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    protected function buildPermalink()
79
    {
80
        return;
81
    }
82
83
    ///
84
    // Twig Document implementation
85
    ///
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function getNamespace()
91
    {
92
        return $this->namespace;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function setNamespace($namespace)
99
    {
100
        $this->namespace = $namespace;
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function setPageView(&$pageView)
107
    {
108
        $this->pageView = &$pageView;
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function isDraft()
115
    {
116
        return false;
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 6
    public function refreshFileContent()
123
    {
124
        // This function can be called after the initial object was created and the file may have been deleted since the
125
        // creation of the object.
126 6 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...
127
        {
128 1
            throw new FileNotFoundException(null, 0, null, $this->filePath);
129
        }
130
131 5
        $content = file_get_contents($this->getFilePath());
132 5
        $fxnName = 'from' . ucfirst($this->getExtension());
133
134 5
        if (method_exists(get_called_class(), $fxnName))
135
        {
136 4
            $this->handleDependencies($this->getExtension());
137 4
            $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...
138
139 4
            return;
140
        }
141
142 1
        throw new UnsupportedDataTypeException($this->getExtension(), "There is no support to handle this file extension.");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal There is no support to handle this file extension. does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
143
    }
144
145
    ///
146
    // File parsing helpers
147
    ///
148
149
    /**
150
     * Convert from CSV into an associative array.
151
     *
152
     * @param string $content CSV formatted text
153
     *
154
     * @return array
155
     */
156 1
    private function fromCsv($content)
157
    {
158 1
        $rows = array_map('str_getcsv', explode("\n", trim($content)));
159 1
        $columns = array_shift($rows);
160 1
        $csv = array();
161
162 1
        foreach ($rows as $row)
163
        {
164 1
            $csv[] = array_combine($columns, $row);
165
        }
166
167 1
        return $csv;
168
    }
169
170
    /**
171
     * Convert from JSON into an associative array.
172
     *
173
     * @param string $content JSON formatted text
174
     *
175
     * @return array
176
     */
177 1
    private function fromJson($content)
178
    {
179 1
        return json_decode($content, true);
180
    }
181
182
    /**
183
     * Convert from XML into an associative array.
184
     *
185
     * @param string $content XML formatted text
186
     *
187
     * @return array
188
     */
189 1
    private function fromXml($content)
190
    {
191 1
        return json_decode(json_encode(simplexml_load_string($content)), true);
192
    }
193
194
    /**
195
     * Convert from YAML into an associative array.
196
     *
197
     * @param string $content YAML formatted text
198
     *
199
     * @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...
200
     */
201 1
    private function fromYaml($content)
202
    {
203 1
        return Yaml::parse($content, Yaml::PARSE_DATETIME);
204
    }
205
206
    /**
207
     * An alias for handling `*.yml` files.
208
     *
209
     * @param string $content YAML formatted text
210
     *
211
     * @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...
212
     */
213 1
    private function fromYml($content)
214
    {
215 1
        return $this->fromYaml($content);
216
    }
217
218
    /**
219
     * Check for any dependencies needed to parse for a specific file extension
220
     *
221
     * @param string $extension
222
     *
223
     * @todo 0.1.0 Create a help page on the main stakx website for this topic and link to it
224
     *
225
     * @throws DependencyMissingException
226
     */
227 4
    private function handleDependencies($extension)
228
    {
229 4
        if ($extension === 'xml' && !function_exists('simplexml_load_string'))
230
        {
231
            throw new DependencyMissingException('XML', 'XML support is not available with the current PHP installation.');
232
        }
233 4
    }
234
235
    ///
236
    // Jailed Document implementation
237
    ///
238
239
    /**
240
     * {@inheritdoc}
241
     */
242 1
    public function createJail()
243
    {
244 1
        return new JailedDocument($this, array(
245 1
            'getExtension', 'getFilePath', 'getName', 'getRelativeFilePath'
246
        ));
247
    }
248
249
    ///
250
    // IteratorAggregate implementation
251
    ///
252
253 1
    public function getIterator()
254
    {
255 1
        return new \ArrayIterator($this->data);
256
    }
257
258
    ///
259
    // ArrayAccess implementation
260
    ///
261
262
    /**
263
     * {@inheritdoc}
264
     */
265
    public function offsetExists($offset)
266
    {
267
        return isset($this->data[$offset]);
268
    }
269
270
    /**
271
     * {@inheritdoc}
272
     */
273 2
    public function offsetGet($offset)
274
    {
275 2
        return $this->data[$offset];
276
    }
277
278
    /**
279
     * {@inheritdoc}
280
     */
281
    public function offsetSet($offset, $value)
282
    {
283
        $this->data[$offset] = $value;
284
    }
285
286
    /**
287
     * {@inheritdoc}
288
     */
289
    public function offsetUnset($offset)
290
    {
291
        unset($this->data[$offset]);
292
    }
293
}
294