Completed
Push — master ( 2009ba...6871c4 )
by Joschi
03:48
created

AbstractElementProcessor::getThing()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 3
crap 1
1
<?php
2
3
/**
4
 * rdfa-lite-microdata
5
 *
6
 * @category Jkphl
7
 * @package Jkphl\RdfaLiteMicrodata
8
 * @subpackage Jkphl\RdfaLiteMicrodata\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\RdfaLiteMicrodata\Infrastructure\Parser;
38
39
use Jkphl\RdfaLiteMicrodata\Application\Context\ContextInterface;
40
use Jkphl\RdfaLiteMicrodata\Application\Contract\ElementProcessorInterface;
41
use Jkphl\RdfaLiteMicrodata\Domain\Property\Property;
42
use Jkphl\RdfaLiteMicrodata\Domain\Thing\Thing;
43
use Jkphl\RdfaLiteMicrodata\Domain\Thing\ThingInterface;
44
use Jkphl\RdfaLiteMicrodata\Domain\Type\Type;
45
use Jkphl\RdfaLiteMicrodata\Domain\Vocabulary\VocabularyInterface;
46
use Jkphl\RdfaLiteMicrodata\Infrastructure\Exceptions\OutOfBoundsException;
47
use Jkphl\RdfaLiteMicrodata\Infrastructure\Exceptions\RuntimeException;
48
49
/**
50
 * Abstract element processor
51
 *
52
 * @package Jkphl\RdfaLiteMicrodata
53
 * @subpackage Jkphl\RdfaLiteMicrodata\Infrastructure
54
 */
55
abstract class AbstractElementProcessor implements ElementProcessorInterface
56
{
57
    /**
58
     * Tag name / attribute map
59
     *
60
     * @var array
61
     */
62
    protected static $tagNameAttributes = [
63
        'META' => 'content',
64
        'AUDIO' => 'src',
65
        'EMBED' => 'src',
66
        'IFRAME' => 'src',
67
        'IMG' => 'src',
68
        'SOURCE' => 'src',
69
        'TRACK' => 'src',
70
        'VIDEO' => 'src',
71
        'A' => 'href',
72
        'AREA' => 'href',
73
        'LINK' => 'href',
74
        'OBJECT' => 'data',
75
        'DATA' => 'value',
76
        'METER' => 'value',
77
        'TIME' => 'datetime'
78
    ];
79
    /**
80
     * HTML mode
81
     *
82
     * @var boolean
83
     */
84
    protected $html;
85
86
    /**
87
     * Element processor constructor
88
     *
89
     * @param bool $html HTML mode
90
     */
91 13
    public function __construct($html = false)
92
    {
93 13
        $this->html = boolval($html);
94 13
    }
95
96
    /**
97
     * Process a DOM element's child
98
     *
99
     * @param \DOMElement $element DOM element
100
     * @param ContextInterface $context Context
101
     * @return ContextInterface Context for children
102
     */
103 13
    public function processElementChildren(\DOMElement $element, ContextInterface $context)
104
    {
105
        // Process a child
106 13
        return $this->processChild($element, $context);
107
    }
108
109
    /**
110
     * Create a nested child
111
     *
112
     * @param \DOMElement $element DOM element
113
     * @param ContextInterface $context Context
114
     * @return ContextInterface Context for children
115
     */
116
    abstract protected function processChild(\DOMElement $element, ContextInterface $context);
117
118
    /**
119
     * Create a property
120
     *
121
     * @param \DOMElement $element DOM element
122
     * @param ContextInterface $context Inherited Context
123
     * @return ContextInterface Local context for this element
124
     */
125
    abstract protected function processProperty(\DOMElement $element, ContextInterface $context);
126
127
    /**
128
     * Split a property into prefix and name
129
     *
130
     * @param string $property Prefixed property
131
     * @return array Prefix and name
132
     */
133 5
    protected function splitProperty($property)
134
    {
135 5
        $property = explode(':', $property);
136 5
        $name = strval(array_pop($property));
137 5
        $prefix = strval(array_pop($property));
138 5
        return [$prefix, $name];
139
    }
140
141
    /**
142
     * Create a property by prefix and name
143
     *
144
     * @param string $prefix Property prefix
145
     * @param string $name Property name
146
     * @param \DOMElement $element DOM element
147
     * @param ContextInterface $context Inherited Context
148
     * @return ContextInterface Local context for this element
149
     */
150 7
    protected function processPropertyPrefixName($prefix, $name, \DOMElement $element, ContextInterface $context)
151
    {
152 7
        $vocabulary = $this->getVocabulary($prefix, $context);
153 7
        if ($vocabulary instanceof VocabularyInterface) {
154 7
            $context = $this->addProperty($element, $context, $name, $vocabulary);
155 6
        }
156
157 6
        return $context;
158
    }
159
160
161
    /**
162
     * Return a vocabulary by prefix with fallback to the default vocabulary
163
     *
164
     * @param string $prefix Vocabulary prefix
165
     * @param ContextInterface $context Context
166
     * @return VocabularyInterface Vocabulary
167
     */
168
    abstract protected function getVocabulary($prefix, ContextInterface $context);
169
170
    /**
171
     * Add a single property
172
     *
173
     * @param \DOMElement $element DOM element
174
     * @param ContextInterface $context Inherited Context
175
     * @param string $name Property name
176
     * @param VocabularyInterface $vocabulary Property vocabulary
177
     * @return ContextInterface Local context for this element
178
     */
179 7
    protected function addProperty(
180
        \DOMElement $element,
181
        ContextInterface $context,
182
        $name,
183
        VocabularyInterface $vocabulary
184
    ) {
185 7
        $resourceId = $this->getResourceId($element);
186
187
        // Get the property value
188 7
        $propertyValue = $this->getPropertyValue($element, $context);
189 7
        $property = new Property($name, $vocabulary, $propertyValue, $resourceId);
190
191
        // Add the property to the current parent thing
192 6
        $context->getParentThing()->addProperty($property);
193
194
        // If the property value is a thing
195 6
        if ($propertyValue instanceof ThingInterface) {
196
            // Set the thing as parent thing for nested iterations
197 3
            $context = $context->setParentThing($propertyValue);
198 3
        }
199
200 6
        return $context;
201
    }
202
203
    /**
204
     * Return the resource ID
205
     *
206
     * @param \DOMElement $element DOM element
207
     * @return string|null Resource ID
208
     */
209
    abstract protected function getResourceId(\DOMElement $element);
210
211
    /**
212
     * Return a property value (type and tag name dependent)
213
     *
214
     * @param \DOMElement $element DOM element
215
     * @param ContextInterface $context Context
216
     * @return ThingInterface|string Property value
217
     */
218
    abstract protected function getPropertyValue(\DOMElement $element, ContextInterface $context);
219
220
    /**
221
     * Return a thing by typeof value
222
     *
223
     * @param string $typeof Thing type
224
     * @param string $resourceId Resource ID
225
     * @param ContextInterface $context Context
226
     * @return Thing Thing
227
     */
228 13
    protected function getThing($typeof, $resourceId, ContextInterface $context)
229
    {
230 13
        $typeof = explode(':', $typeof);
231 13
        $type = array_pop($typeof);
232 13
        $prefix = array_pop($typeof);
233
234 13
        return $this->getThingByPrefixType($prefix, $type, $resourceId, $context);
235
    }
236
237
    /**
238
     * Return a thing by prefix and type
239
     *
240
     * @param string $prefix Prefix
241
     * @param string $typeName Type
242
     * @param string $resourceId Resource ID
243
     * @param ContextInterface $context Context
244
     * @return Thing Thing
245
     * @throws RuntimeException If the default vocabulary is empty
246
     * @throws OutOfBoundsException If the vocabulary prefix is unknown
247
     */
248 13
    protected function getThingByPrefixType($prefix, $typeName, $resourceId, ContextInterface $context)
249
    {
250
        // Determine the vocabulary to use
251
        try {
252 13
            $vocabulary = $this->getVocabulary($prefix, $context);
253 10
            if ($vocabulary instanceof VocabularyInterface) {
254 7
                $type = new Type($typeName, $vocabulary);
255 7
                return new Thing($type, $resourceId);
256
            }
257
258
            // If the default vocabulary is empty
259 3
            if (empty($prefix)) {
260 3
                throw new RuntimeException(
261 3
                    RuntimeException::EMPTY_DEFAULT_VOCABULARY_STR,
262
                    RuntimeException::EMPTY_DEFAULT_VOCABULARY
263 3
                );
264
            }
265 6
        } catch (\Jkphl\RdfaLiteMicrodata\Application\Exceptions\OutOfBoundsException $e) {
266
            // Promote to client level exception
267
        }
268
269 3
        throw new OutOfBoundsException(
270 3
            sprintf(OutOfBoundsException::UNKNOWN_VOCABULARY_PREFIX_STR, $prefix),
271
            OutOfBoundsException::UNKNOWN_VOCABULARY_PREFIX
272 3
        );
273
    }
274
275
    /**
276
     * Return a property value (type and tag name dependent)
277
     *
278
     * @param \DOMElement $element DOM element
279
     * @return ThingInterface|string Property value
280
     */
281 7
    protected function getPropertyStringValue(\DOMElement $element)
282
    {
283
        // If HTML mode is active
284 7
        if ($this->html) {
285 6
            $tagName = strtoupper($element->tagName);
286
287
            // Map to an attribute (if applicable)
288 6
            if (array_key_exists($tagName, self::$tagNameAttributes)) {
289 5
                $value = strval($element->getAttribute(self::$tagNameAttributes[$tagName]));
290 5
                if (($tagName != 'TIME') || !empty($value)) {
291 5
                    return $value;
292
                }
293
            }
294 6
        }
295
296
        // Return the text content
297 7
        return $element->textContent;
298
    }
299
}
300