Debian Codegraph @

vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.php

raw
1 <?php
2
3 /*
4 * This file is part of the JsonSchema package.
5 *
6 * For the full copyright and license information, please view the LICENSE
7 * file that was distributed with this source code.
8 */
9
10 namespace JsonSchema\Uri\Retrievers;
11
12 use JsonSchema\Exception\ResourceNotFoundException;
13
14 /**
15 * Tries to retrieve JSON schemas from a URI using file_get_contents()
16 *
17 * @author Sander Coolen <[email protected]>
18 */
19 class FileGetContents extends AbstractRetriever
20 {
21 protected $messageBody;
22
23 /**
24 * {@inheritdoc}
25 *
26 * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve()
27 */
28 public function retrieve($uri)
29 {
30 $errorMessage = null;
31 set_error_handler(function ($errno, $errstr) use (&$errorMessage) {
32 $errorMessage = $errstr;
33 });
34 $response = file_get_contents($uri);
35 restore_error_handler();
36
37 if ($errorMessage) {
38 throw new ResourceNotFoundException($errorMessage);
39 }
40
41 if (false === $response) {
42 throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
43 }
44
45 if ($response == ''
46 && substr($uri, 0, 7) == 'file://' && substr($uri, -1) == '/'
47 ) {
48 throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
49 }
50
51 $this->messageBody = $response;
52 if (function_exists('http_get_last_response_headers')) {
53 // Use http_get_last_response_headers() for BC compatibility with PHP 8.5+
54 // where $http_response_header is deprecated.
55 $http_response_header = http_get_last_response_headers();
56 }
57 if (!empty($http_response_header)) {
58 // $http_response_header cannot be tested, because it's defined in the method's local scope
59 // See http://php.net/manual/en/reserved.variables.httpresponseheader.php for more info.
60 $this->fetchContentType($http_response_header); // @codeCoverageIgnore
61 } else { // @codeCoverageIgnore
62 // Could be a "file://" url or something else - fake up the response
63 $this->contentType = null;
64 }
65
66 return $this->messageBody;
67 }
68
69 /**
70 * @param array $headers HTTP Response Headers
71 *
72 * @return bool Whether the Content-Type header was found or not
73 */
74 private function fetchContentType(array $headers)
75 {
76 foreach ($headers as $header) {
77 if ($this->contentType = self::getContentTypeMatchInHeader($header)) {
78 return true;
79 }
80 }
81
82 return false;
83 }
84
85 /**
86 * @param string $header
87 *
88 * @return string|null
89 */
90 protected static function getContentTypeMatchInHeader($header)
91 {
92 if (0 < preg_match("/Content-Type:(\V*)/ims", $header, $match)) {
93 return trim($match[1]);
94 }
95
96 return null;
97 }
98 }