secure-custom-fields
/
vendor
/
justinrainbow
/
json-schema
/
src
/
JsonSchema
/
Uri
/
Retrievers
/
Curl.php
secure-custom-fields
/
vendor
/
justinrainbow
/
json-schema
/
src
/
JsonSchema
/
Uri
/
Retrievers
Last commit date
AbstractRetriever.php
9 months ago
Curl.php
9 months ago
FileGetContents.php
9 months ago
PredefinedArray.php
9 months ago
UriRetrieverInterface.php
9 months ago
Curl.php
84 lines
| 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\RuntimeException; |
| 13 | use JsonSchema\Validator; |
| 14 | |
| 15 | /** |
| 16 | * Tries to retrieve JSON schemas from a URI using cURL library |
| 17 | * |
| 18 | * @author Sander Coolen <sander@jibber.nl> |
| 19 | */ |
| 20 | class Curl extends AbstractRetriever |
| 21 | { |
| 22 | protected $messageBody; |
| 23 | |
| 24 | public function __construct() |
| 25 | { |
| 26 | if (!function_exists('curl_init')) { |
| 27 | // Cannot test this, because curl_init is present on all test platforms plus mock |
| 28 | throw new RuntimeException('cURL not installed'); // @codeCoverageIgnore |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * {@inheritdoc} |
| 34 | * |
| 35 | * @see \JsonSchema\Uri\Retrievers\UriRetrieverInterface::retrieve() |
| 36 | */ |
| 37 | public function retrieve($uri) |
| 38 | { |
| 39 | $ch = curl_init(); |
| 40 | |
| 41 | curl_setopt($ch, CURLOPT_URL, $uri); |
| 42 | curl_setopt($ch, CURLOPT_HEADER, true); |
| 43 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
| 44 | curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: ' . Validator::SCHEMA_MEDIA_TYPE)); |
| 45 | |
| 46 | $response = curl_exec($ch); |
| 47 | if (false === $response) { |
| 48 | throw new \JsonSchema\Exception\ResourceNotFoundException('JSON schema not found'); |
| 49 | } |
| 50 | |
| 51 | $this->fetchMessageBody($response); |
| 52 | $this->fetchContentType($response); |
| 53 | |
| 54 | curl_close($ch); |
| 55 | |
| 56 | return $this->messageBody; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * @param string $response cURL HTTP response |
| 61 | */ |
| 62 | private function fetchMessageBody($response) |
| 63 | { |
| 64 | preg_match("/(?:\r\n){2}(.*)$/ms", $response, $match); |
| 65 | $this->messageBody = $match[1]; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * @param string $response cURL HTTP response |
| 70 | * |
| 71 | * @return bool Whether the Content-Type header was found or not |
| 72 | */ |
| 73 | protected function fetchContentType($response) |
| 74 | { |
| 75 | if (0 < preg_match("/Content-Type:(\V*)/ims", $response, $match)) { |
| 76 | $this->contentType = trim($match[1]); |
| 77 | |
| 78 | return true; |
| 79 | } |
| 80 | |
| 81 | return false; |
| 82 | } |
| 83 | } |
| 84 |