Completed
Pull Request — master (#48)
by Vladimir
02:37
created

DataItem::offsetUnset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 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
    public function __construct($filePath)
28
    {
29
        $this->namespace = '';
30
31
        parent::__construct($filePath);
32
    }
33
34
    public function getIterator()
35
    {
36
        return new \ArrayIterator($this->data);
37
    }
38
39
    public function getData()
40
    {
41
        return $this->data;
42
    }
43
44
    public function getName()
45
    {
46
        return $this->getBaseName();
47
    }
48
49
    public function evaluateFrontMatter($variables = array())
50
    {
51
        $workspace = array_merge($this->data, $variables);
52
        $parser = new Parser($workspace, array(
53
            'filename' => $this->getFileName(),
54
            'basename' => $this->getBaseName(),
55
        ));
56
57
        if (!is_null($parser) && $parser->hasExpansion())
58
        {
59
            throw new \LogicException('The permalink for this item has not been set.');
60
        }
61
62
        $permalink = $workspace['permalink'];
63
64 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...
65
        {
66
            $this->permalink = $permalink[0];
67
            array_shift($permalink);
68
            $this->redirects = $permalink;
69
        }
70
        else
71
        {
72
            $this->permalink = $permalink;
73
            $this->redirects = array();
74
        }
75
    }
76
77
    protected function buildPermalink()
78
    {
79
        return;
80
    }
81
82
    ///
83
    // Jailed Document implementation
84
    ///
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function createJail()
90
    {
91
        return new JailedDocument($this, array(
92
            'getExtension', 'getFilePath', 'getName', 'getRelativeFilePath'
93
        ));
94
    }
95
96
    ///
97
    // ArrayAccess implementation
98
    ///
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function offsetExists($offset)
104
    {
105
        return isset($this->data[$offset]);
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function offsetGet($offset)
112
    {
113
        return $this->data[$offset];
114
    }
115
116
    /**
117
     * {@inheritdoc}
118
     */
119
    public function offsetSet($offset, $value)
120
    {
121
        $this->data[$offset] = $value;
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127
    public function offsetUnset($offset)
128
    {
129
        unset($this->data[$offset]);
130
    }
131
132
    ///
133
    // Twig Document implementation
134
    ///
135
136
    public function getNamespace()
137
    {
138
        return $this->namespace;
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function setNamespace($namespace)
145
    {
146
        $this->namespace = $namespace;
147
    }
148
149
    /**
150
     * {@inheritdoc}
151
     */
152
    public function setPageView(&$pageView)
153
    {
154
        $this->pageView = &$pageView;
155
    }
156
157
    public function isDraft()
158
    {
159
        return false;
160
    }
161
162
    public function refreshFileContent()
163
    {
164
        // This function can be called after the initial object was created and the file may have been deleted since the
165
        // creation of the object.
166 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...
167
        {
168
            throw new FileNotFoundException(null, 0, null, $this->filePath);
169
        }
170
171
        $content = file_get_contents($this->getFilePath());
172
        $fxnName = 'from' . ucfirst($this->getExtension());
173
174
        if (method_exists(get_called_class(), $fxnName))
175
        {
176
            $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...
177
178
            return;
179
        }
180
181
        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...
182
    }
183
184
    ///
185
    // File parsing helpers
186
    ///
187
188
    /**
189
     * Convert from CSV into an associative array.
190
     *
191
     * @param string $content CSV formatted text
192
     *
193
     * @return array
194
     */
195
    private function fromCsv($content)
196
    {
197
        $rows = array_map('str_getcsv', explode("\n", trim($content)));
198
        $columns = array_shift($rows);
199
        $csv = array();
200
201
        foreach ($rows as $row)
202
        {
203
            $csv[] = array_combine($columns, $row);
204
        }
205
206
        return $csv;
207
    }
208
209
    /**
210
     * Convert from JSON into an associative array.
211
     *
212
     * @param string $content JSON formatted text
213
     *
214
     * @return array
215
     */
216
    private function fromJson($content)
217
    {
218
        return json_decode($content, true);
219
    }
220
221
    /**
222
     * Convert from XML into an associative array.
223
     *
224
     * @param string $content XML formatted text
225
     *
226
     * @return array
227
     */
228
    private function fromXml($content)
229
    {
230
        return json_decode(json_encode(simplexml_load_string($content)), true);
231
    }
232
233
    /**
234
     * Convert from YAML into an associative array.
235
     *
236
     * @param string $content YAML formatted text
237
     *
238
     * @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...
239
     */
240
    private function fromYaml($content)
241
    {
242
        return Yaml::parse($content, Yaml::PARSE_DATETIME);
243
    }
244
245
    /**
246
     * An alias for handling `*.yml` files.
247
     *
248
     * @param string $content YAML formatted text
249
     *
250
     * @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...
251
     */
252
    private function fromYml($content)
253
    {
254
        return $this->fromYaml($content);
255
    }
256
257
    /**
258
     * @param string $extension
259
     *
260
     * @todo 0.1.0 Create a help page on the main stakx website for this topic and link to it
261
     *
262
     * @throws DependencyMissingException
263
     */
264
    private function handleDependencies($extension)
265
    {
266
        if ($extension === 'xml' && !function_exists('simplexml_load_string'))
267
        {
268
            throw new DependencyMissingException('XML', 'XML support is not available with the current PHP installation.');
269
        }
270
    }
271
}
272