4 * This file is part of the JsonSchema package.
6 * For the full copyright and license information, please view the LICENSE
7 * file that was distributed with this source code.
10 namespace JsonSchema\Uri\Retrievers;
12 use JsonSchema\Exception\ResourceNotFoundException;
15 * Tries to retrieve JSON schemas from a URI using file_get_contents()
17 * @author Sander Coolen <sander@jibber.nl>
19 class FileGetContents extends AbstractRetriever
21 protected $messageBody;
26 * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve()
28 public function retrieve($uri)
31 set_error_handler(function ($errno, $errstr) use (&$errorMessage) {
32 $errorMessage = $errstr;
34 $response = file_get_contents($uri);
35 restore_error_handler();
38 throw new ResourceNotFoundException($errorMessage);
41 if (false === $response) {
42 throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
46 && substr($uri, 0, 7) == 'file://' && substr($uri, -1) == '/'
48 throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
51 $this->messageBody = $response;
52 if (!empty($http_response_header)) {
53 // $http_response_header cannot be tested, because it's defined in the method's local scope
54 // See http://php.net/manual/en/reserved.variables.httpresponseheader.php for more info.
55 $this->fetchContentType($http_response_header); // @codeCoverageIgnore
56 } else { // @codeCoverageIgnore
57 // Could be a "file://" url or something else - fake up the response
58 $this->contentType = null;
61 return $this->messageBody;
65 * @param array $headers HTTP Response Headers
67 * @return bool Whether the Content-Type header was found or not
69 private function fetchContentType(array $headers)
71 foreach ($headers as $header) {
72 if ($this->contentType = self::getContentTypeMatchInHeader($header)) {
81 * @param string $header
85 protected static function getContentTypeMatchInHeader($header)
87 if (0 < preg_match("/Content-Type:(\V*)/ims", $header, $match)) {
88 return trim($match[1]);