Completed
Push — v2 ( 3135e6...5d3e3a )
by Joschi
04:42 queued 10s
created

DocumentFactory::createFromUri()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 2
1
<?php
2
3
/**
4
 * micrometa
5
 *
6
 * @category Jkphl
7
 * @package Jkphl\Micrometa
8
 * @subpackage Jkphl\Micrometa\Infrastructure\Factory
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\Infrastructure\Factory;
38
39
use Guzzle\Common\Exception\InvalidArgumentException as GuzzleInvalidArgumentException;
40
use Guzzle\Common\Exception\RuntimeException as GuzzleRuntimeException;
41
use Guzzle\Http\Client;
42
use Guzzle\Http\Url;
43
use Jkphl\Micrometa\Ports\Exceptions\InvalidArgumentException;
44
use Jkphl\Micrometa\Ports\Exceptions\RuntimeException;
45
46
/**
47
 * DOM document factory
48
 *
49
 * @package Jkphl\Micrometa
50
 * @subpackage Jkphl\Micrometa\Infrastructure
51
 */
52
class DocumentFactory
53
{
54
    /**
55
     * Create a DOM document from a URI
56
     *
57
     * @param string $url HTTP / HTTPS URL
58
     * @return \DOMDocument DOM document
59
     */
60 6
    public static function createFromUri($url)
61
    {
62 6
        return extension_loaded('curl') ? self::createViaHttpClient($url) : self::createViaStreamWrapper($url);
63
    }
64
65
    /**
66
     * Create a DOM document using a HTTP client implementation
67
     *
68
     * @param string $url HTTP / HTTPS URL
69
     * @return \DOMDocument DOM document
70
     * @throws RuntimeException If the request wasn't successful
71
     * @throws InvalidArgumentException If an argument was invalid
72
     * @throws RuntimeException If a runtime exception occurred
73
     */
74 5
    protected static function createViaHttpClient($url)
75
    {
76
        try {
77 5
            $guzzleUrl = Url::factory($url);
78 4
            $client = new Client(['timeout' => 10.0]);
0 ignored issues
show
Documentation introduced by
array('timeout' => 10.0) is of type array<string,double,{"timeout":"double"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
79 4
            $request = $client->get($guzzleUrl);
80 4
            $response = $client->send($request);
81 4
            return self::createFromString(strval($response->getBody()));
82
83
            // If an argument was invalid
84 3
        } catch (GuzzleInvalidArgumentException $e) {
85 1
            throw new InvalidArgumentException($e->getMessage(), $e->getCode());
86
87
            // If a runtime exception occurred
88 2
        } catch (GuzzleRuntimeException $e) {
89 1
            throw new RuntimeException($e->getMessage(), $e->getCode());
90
        }
91
    }
92
93
    /**
94
     * Create a DOM document from a string
95
     *
96
     * @param string $str String
97
     * @return \DOMDocument DOM document
98
     */
99 4
    public static function createFromString($str)
100
    {
101 4
        $source = mb_convert_encoding($str, 'HTML-ENTITIES', mb_detect_encoding($str));
102 4
        $dom = new \DOMDocument();
103
104
        // Try to load the source as XML document first, then as HTML document
105 4
        if (!$dom->loadXML($source, LIBXML_NOWARNING | LIBXML_NOERROR)) {
106 4
            libxml_use_internal_errors(true);
107 4
            $dom->loadHTML($source, LIBXML_NOWARNING);
108 4
            $errors = libxml_get_errors();
109 4
            libxml_use_internal_errors(false);
110
111
            // If an error occurred
112 4
            if (count($errors)) {
113 1
                $error = array_pop($errors);
114 1
                throw new InvalidArgumentException(
115 1
                    sprintf(InvalidArgumentException::INVALID_DATA_SOURCE_STR, trim($error->message)),
116
                    InvalidArgumentException::INVALID_DATA_SOURCE
117 1
                );
118
            }
119 3
        }
120
121 3
        return $dom;
122
    }
123
124
    /**
125
     * Create a DOM document via the PHP stream wrapper
126
     *
127
     * @param string $url URL
128
     * @return \DOMDocument DOM document
129
     */
130 1
    protected static function createViaStreamWrapper($url)
131
    {
132
        $opts = array(
133
            'http' => array(
134 1
                'method' => 'GET',
135 1
                'protocol_version' => 1.1,
136 1
                'user_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.466.4 Safari/534.3',
137 1
                'max_redirects' => 10,
138 1
                'timeout' => 120,
139 1
                'header' => "Accept-language: en\r\n",
140
            )
141 1
        );
142 1
        $context = stream_context_create($opts);
143 1
        $response = @file_get_contents($url, false, $context);
144 1
        return self::createFromString($response);
145
    }
146
}
147