Completed
Branch master (6c7c3c)
by Joschi
02:33
created

Parser::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
crap 2
1
<?php
2
3
/**
4
 * micrometa
5
 *
6
 * @category Jkphl
7
 * @package Jkphl\Micrometa
8
 * @subpackage Jkphl\Micrometa\Ports
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\Micrometa\Ports;
38
39
use Jkphl\Domfactory\Ports\Dom;
40
use Jkphl\Micrometa\Application\Service\ExtractorService;
41
use Jkphl\Micrometa\Infrastructure\Factory\ItemFactory;
42
use Jkphl\Micrometa\Infrastructure\Factory\ParserFactory;
43
use Jkphl\Micrometa\Infrastructure\Logger\ExceptionLogger;
44
use Jkphl\Micrometa\Ports\Item\ItemInterface;
45
use Jkphl\Micrometa\Ports\Item\ItemObjectModel;
46
use Jkphl\Micrometa\Ports\Item\ItemObjectModelInterface;
47
use League\Uri\Schemes\Http;
48
use Psr\Log\LoggerInterface;
49
50
/**
51
 * Parser
52
 *
53
 * @package Jkphl\Micrometa
54
 * @subpackage Jkphl\Micrometa\Ports
55
 */
56
class Parser
57
{
58
    /**
59
     * Micro information formats
60
     *
61
     * @var int
62
     */
63
    protected $formats;
64
    /**
65
     * Logger
66
     *
67
     * @var LoggerInterface
68
     */
69
    protected $logger;
70
71
    /**
72
     * Parser constructor
73
     *
74
     * @param int $formats Micro information formats to extract
75
     * @param LoggerInterface|null $logger PSR-3 compatible logger
76
     * @api
77
     */
78 2
    public function __construct($formats = Format::ALL, LoggerInterface $logger = null)
79
    {
80 2
        $this->formats = $formats;
81 2
        $this->logger = $logger ?: new ExceptionLogger();
82 2
    }
83
84
    /**
85
     * Extract micro information items out of a URI or piece of source
86
     *
87
     * @param string $uri URI
88
     * @param string|null $source Source code
89
     * @param int $formats Micro information formats to extract
90
     * @param array $httpOptions HTTP request options
91
     * @return ItemObjectModelInterface Item object model
92
     * @api
93
     */
94 2
    public function __invoke($uri, $source = null, $formats = null, array $httpOptions = [])
95
    {
96 2
        $items = [];
97
98
        try {
99 2
            $parsers = ParserFactory::createParsersFromFormats(
100 2
                intval($formats ?: $this->formats),
101 2
                Http::createFromString($uri),
102 2
                $this->logger
103
            );
104 2
            $items = $this->extractItems($this->createDom($uri, $source, $httpOptions), $parsers);
105
106
            // In case of exceptions: Log if possible
107 1
        } catch (\Exception $e) {
108 1
            $this->logger->critical($e->getMessage(), ['exception' => $e]);
109
        }
110
111 1
        return new ItemObjectModel($items);
112
    }
113
114
    /**
115
     * Create the DOM document to parse
116
     *
117
     * @param string $uri URI
118
     * @param string|null $source Source code
119
     * @param array $httpOptions HTTP request options
120
     * @return \DOMDocument DOM document
121
     */
122 2
    protected function createDom($uri, $source = null, array $httpOptions = [])
123
    {
124 2
        return (($source !== null) && strlen(trim($source))) ?
125 2
            Dom::createFromString($source) : Dom::createFromUri($uri, $httpOptions);
126
    }
127
128
    /**
129
     * Extract all items from a DOM using particular parsers
130
     *
131
     * @param \DOMDocument $dom DOM document
132
     * @param \Generator $parsers Parsers
133
     * @return ItemInterface[] Items
134
     */
135 2
    protected function extractItems(\DOMDocument $dom, \Generator $parsers)
136
    {
137 2
        $items = [];
138 2
        $extractor = new ExtractorService();
139 2
        foreach ($parsers as $parser) {
140 2
            $results = $extractor->extract($dom, $parser);
141 1
            $items = array_merge($items, ItemFactory::createFromApplicationItems($results->getItems()));
142
        }
143 1
        return $items;
144
    }
145
}
146