Completed
Push — master ( a959b0...c973b9 )
by Joschi
03:02
created

RdfaliteElementProcessor::processVocab()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 9
c 1
b 0
f 0
ccs 6
cts 6
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
3
/**
4
 * rdfa-lite
5
 *
6
 * @category Jkphl
7
 * @package Jkphl\Rdfalite
8
 * @subpackage Jkphl\Rdfalite\Infrastructure
9
 * @author Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright Copyright © 2017 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2017 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Rdfalite\Infrastructure\Parser;
38
39
use Jkphl\Rdfalite\Application\Contract\ElementProcessorInterface;
40
use Jkphl\Rdfalite\Application\Parser\Context;
41
use Jkphl\Rdfalite\Domain\Property\Property;
42
use Jkphl\Rdfalite\Domain\Thing\Thing;
43
use Jkphl\Rdfalite\Domain\Thing\ThingInterface;
44
use Jkphl\Rdfalite\Domain\Vocabulary\Vocabulary;
45
use Jkphl\Rdfalite\Domain\Vocabulary\VocabularyInterface;
46
use Jkphl\Rdfalite\Infrastructure\Exceptions\OutOfBoundsException;
47
48
/**
49
 * RDFa Lite 1.1 element processor
50
 *
51
 * @package Jkphl\Rdfalite
52
 * @subpackage Jkphl\Rdfalite\Infrastructure
53
 */
54
class RdfaliteElementProcessor implements ElementProcessorInterface
55
{
56
    /**
57
     * Process a DOM element
58
     *
59
     * @param \DOMElement $element DOM element
60
     * @param Context $context Inherited Context
61
     * @return Context Local context for this element
62
     */
63 2
    public function processElement(\DOMElement $element, Context $context)
64
    {
65
        // Process default vocabulary registrations
66 2
        $context = $this->processVocab($element, $context);
67
68
        // Register vocabulary prefixes
69 2
        $context = $this->processPrefix($element, $context);
70
71
        // Create properties
72 2
        $context = $this->processProperty($element, $context);
73 2
        return $context;
74
    }
75
76
    /**
77
     * Process a DOM element's children
78
     *
79
     * @param \DOMElement $element DOM element
80
     * @param Context $context Context
81
     * @return Context Context for children
82
     */
83 2
    public function processElementChildren(\DOMElement $element, Context $context)
84
    {
85
        // Process nested children
86 2
        return $this->processTypeof($element, $context);
87
    }
88
89
    /**
90
     * Process changes of the default vocabulary
91
     *
92
     * @param \DOMElement $element DOM element
93
     * @param Context $context Inherited Context
94
     * @return Context Local context for this element
95
     */
96 2
    protected function processVocab(\DOMElement $element, Context $context)
97
    {
98 2
        if ($element->hasAttribute('vocab')) {
99 2
            $defaultVocabulary = new Vocabulary($element->getAttribute('vocab'));
100 2
            $context = $context->setDefaultVocabulary($defaultVocabulary);
101 2
        }
102
103 2
        return $context;
104
    }
105
106
    /**
107
     * Process vocabulary prefixes
108
     *
109
     * @param \DOMElement $element DOM element
110
     * @param Context $context Inherited Context
111
     * @return Context Local context for this element
112
     */
113 2
    protected function processPrefix(\DOMElement $element, Context $context)
114
    {
115 2
        if ($element->hasAttribute('prefix')) {
116 2
            $prefixes = preg_split('/\s+/', $element->getAttribute('prefix'));
117 2
            while (count($prefixes)) {
118 2
                $prefix = rtrim(array_shift($prefixes), ':');
119 2
                $uri = array_shift($prefixes);
120 2
                $context = $context->registerVocabulary($prefix, $uri);
121 2
            }
122 2
        }
123
124 2
        return $context;
125
    }
126
127
    /**
128
     * Create properties
129
     *
130
     * @param \DOMElement $element DOM element
131
     * @param Context $context Inherited Context
132
     * @return Context Local context for this element
133
     */
134 2
    protected function processProperty(\DOMElement $element, Context $context)
135
    {
136 2
        if ($element->hasAttribute('property') && ($context->getParentThing() instanceof ThingInterface)) {
137 2
            $property = explode(':', $element->getAttribute('property'));
138 2
            $name = strval(array_pop($property));
139 2
            $prefix = strval(array_pop($property));
140
141
            // Determine the vocabulary to use
142 2
            $vocabulary = empty($prefix) ? $context->getDefaultVocabulary() : $context->getVocabulary($prefix);
143 2
            if ($vocabulary instanceof VocabularyInterface) {
144
                // Try to get a resource ID
145 2
                $resourceId = trim($element->getAttribute('resource')) ?: null;
146
147
                // Add the property to the current parent thing
148 2
                $property = new Property($name, $vocabulary, $this->getPropertyValue($element, $context), $resourceId);
0 ignored issues
show
Bug introduced by
It seems like $this->getPropertyValue($element, $context) targeting Jkphl\Rdfalite\Infrastru...sor::getPropertyValue() can also be of type object<Jkphl\Rdfalite\Do...n\Thing\ThingInterface>; however, Jkphl\Rdfalite\Domain\Pr...Property::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
149 2
                $context->getParentThing()->addProperty($property);
150 2
            }
151 2
        }
152
153 2
        return $context;
154
    }
155
156
    /**
157
     * Return a property value (type and tag name dependent)
158
     *
159
     * @param \DOMElement $element DOM element
160
     * @param Context $context Context
161
     * @return ThingInterface|string Property value
162
     */
163 2
    protected function getPropertyValue(\DOMElement $element, Context $context)
164
    {
165
        // If the property creates a new type: Return the element itself
166 2
        if ($element->hasAttribute('typeof')) {
167
            return $this->getThing(
168
                $element->getAttribute('typeof'),
169
                trim($element->getAttribute('resource')) ?: null,
170
                $context
171
            );
172
        }
173
174
        // Else: Depend on the tag name
175 2
        switch (strtoupper($element->tagName)) {
176 2
            case 'META':
177
                return strval($element->getAttribute('content'));
178 2
            case 'AUDIO':
179 2
            case 'EMBED':
180 2
            case 'IFRAME':
181 2
            case 'IMG':
182 2
            case 'SOURCE':
183 2
            case 'TRACK':
184 2
            case 'VIDEO':
185 2
                return strval($element->getAttribute('src'));
186 2
            case 'A':
187 2
            case 'AREA':
188 2
            case 'LINK':
189
                return strval($element->getAttribute('href'));
190 2
            case 'OBJECT':
191
                return strval($element->getAttribute('data'));
192 2
            case 'DATA':
193
                return strval($element->getAttribute('value'));
194 2
            case 'TIME':
195
                $datetime = $element->getAttribute('datetime');
196
                if (!empty($datetime)) {
197
                    return strval($datetime);
198
                }
199
            // fall through
200 2
            default:
201
//              trigger_error(sprintf('RDFa Lite 1.1 element processor: Unhandled tag name "%s"', $element->tagName), E_USER_WARNING);
202 2
                return $element->textContent;
203 2
        }
204
    }
205
206
    /**
207
     * Return a property value (type and tag name dependent)
208
     *
209
     * @param string $typeof Thing type
210
     * @param string $resourceId Resource ID
211
     * @param Context $context Context
212
     * @return ThingInterface Thing
213
     * @throws OutOfBoundsException If the default vocabulary is empty
214
     * @throws OutOfBoundsException If the vocabulary prefix is unknown
215
     */
216 2
    protected function getThing($typeof, $resourceId, Context $context)
217
    {
218 2
        $typeof = explode(':', $typeof);
219 2
        $type = array_pop($typeof);
220 2
        $prefix = array_pop($typeof);
221
222
        // Determine the vocabulary to use
223 2
        $vocabulary = empty($prefix) ? $context->getDefaultVocabulary() : $context->getVocabulary($prefix);
224 2
        if ($vocabulary instanceof VocabularyInterface) {
225
            // Return a new thing
226 2
            return new Thing($type, $vocabulary, $resourceId);
227
        }
228
229
        // If the default vocabulary is empty
230
        if (empty($prefix)) {
231
            throw new OutOfBoundsException(
232
                OutOfBoundsException::EMPTY_DEFAULT_VOCABULARY_STR,
233
                OutOfBoundsException::EMPTY_DEFAULT_VOCABULARY
234
            );
235
        }
236
237
        throw new OutOfBoundsException(
238
            sprintf(OutOfBoundsException::UNKNOWN_VOCABULARY_PREFIX_STR, $prefix),
239
            OutOfBoundsException::UNKNOWN_VOCABULARY_PREFIX
240
        );
241
    }
242
243
    /**
244
     * Create nested children
245
     *
246
     * @param \DOMElement $element DOM element
247
     * @param Context $context Context
248
     * @return Context Context for children
249
     */
250 2
    protected function processTypeof(\DOMElement $element, Context $context)
251
    {
252 2
        if ($element->hasAttribute('typeof')) {
253 2
            $thing = $this->getThing(
254 2
                $element->getAttribute('typeof'),
255 2
                trim($element->getAttribute('resource')) ?: null,
256
                $context
257 2
            );
258
259 2
            if ($thing instanceof ThingInterface) {
260
                // Add the new thing as a child to the current context
261 2
                $context->addChild($thing);
262
263
                // Set the thing as parent thing for nested iterations
264 2
                $context = $context->setParentThing($thing);
265 2
            }
266 2
        }
267
268 2
        return $context;
269
    }
270
}
271