sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function withProtocolVersion($version) { if (!is_string($version)) { throw new \InvalidArgumentException("Expected protocol version to be a string"); } $this->protocolVersion = $version; $this->sendStatusHeader(); return $this; }
Set the protocol version @param string $version @return $this
entailment
public function getReasonPhrase() { $code = $this->getStatusCode(); return $this->code === $code && $this->phrase ? $this->phrase : (isset($this->defaultStatuses[$code]) ? $this->defaultStatuses[$code] : ''); }
Gets the response reason phrase associated with the status code. @return string
entailment
protected function setStatus($code, $reasonPhrase) { $this->assertHeadersNotSent(); parent::setStatus($code, $reasonPhrase); $this->sendStatusHeader(); }
Set the specified status code and reason phrase. @param int $code @param string $reasonPhrase
entailment
public function checkPermission($model, $member = null, $httpMethod) { if (is_string($model)) { $model = singleton($model); } // check permission depending on HTTP verb // default to true switch (strtoupper($httpMethod)) { case 'GET': return $model->canView($member); break; case 'POST': return $model->canCreate($member); break; case 'PUT': return $model->canEdit($member); break; case 'DELETE': return $model->canDelete($member); break; default: return true; break; } }
Checks if a given DataObject or Class can be accessed with a given API request by a Member @param string|DataObject $model Model's classname or DataObject to check permission for @param DataObject|null $member Member to check permission agains @param string $httpMethod API request HTTP method @return Boolean true or false if permission was given or not
entailment
public function only($method) { if (!is_array($method)) { $method = [ $method ]; } $this->only += $method; return $this; }
Specify the methods that the middleware applies to @param string|array $method @return Rareloop\Router\ControllerMiddlewareOptions
entailment
public function except($method) { if (!is_array($method)) { $method = [ $method ]; } $this->except += $method; return $this; }
Specify the methods that the middleware does not apply to @param string|array $method @return Rareloop\Router\ControllerMiddlewareOptions
entailment
public function excludedForMethod($method) : bool { if (empty($this->only) && empty($this->except)) { return false; } return (!empty($this->only) && !in_array($method, $this->only)) || (!empty($this->except) && in_array($method, $this->except)); }
Is a specific method excluded by the options set on this object @param string $method @return bool
entailment
protected function assertHeaderValue($value) { if (!is_string($value) && (!is_array($value) || array_product(array_map('is_string', $value)) === 0)) { throw new \InvalidArgumentException("Header value should be a string or an array of strings"); } }
Assert that the header value is a string @param string|string[] $value @throws \InvalidArgumentException
entailment
protected function setHeaders(array $headers) { $this->headers = []; foreach ($headers as $name => $values) { $this->assertHeaderName($name); $this->assertHeaderValue($values); $key = strtolower($name); $this->headers[$key] = ['name' => $name, 'values' => (array)$values]; } }
Set the headers @param array $headers
entailment
public function getHeaders() { $headers = []; foreach ($this->headers as $header) { $headers[$header['name']] = $header['values']; } return $headers; }
Retrieves all message header values. The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header. // Represent the headers as a string foreach ($message->getHeaders() as $name => $values) { echo $name . ': ' . implode(', ', $values); } // Emit headers iteratively: foreach ($message->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } } @return string[][] Returns an associative array of the message's headers. Each key is a header name, and each value is an array of strings for that header.
entailment
public function hasHeader($name) { $this->assertHeaderName($name); return isset($this->headers[strtolower($name)]); }
Checks if a header exists by the given case-insensitive name. @param string $name Case-insensitive header field name. @return bool Returns true if any header names match the given header name using a case-insensitive string comparison. Returns false if no matching header name is found in the message.
entailment
public function getHeader($name) { $this->assertHeaderName($name); $key = strtolower($name); return isset($this->headers[$key]) ? $this->headers[$key]['values'] : []; }
Retrieves a message header value by the given case-insensitive name. This method returns an array of all the header values of the given case-insensitive header name. @param string $name Case-insensitive header field name. @return string[] An array of string values as provided for the given header. If the header does not appear in the message, this method MUST return an empty array.
entailment
public function withHeader($name, $value) { $this->assertHeaderName($name); $this->assertHeaderValue($value); $copy = clone $this; $copy->headers[strtolower($name)] = ['name' => $name, 'values' => (array)$value]; return $copy; }
Return an instance with the provided value replacing the specified header. While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders(). This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value. @param string $name Case-insensitive header field name. @param string|string[] $value Header value(s). @return static @throws \InvalidArgumentException for invalid header names or values.
entailment
public function withAddedHeader($name, $value) { $this->assertHeaderName($name); $this->assertHeaderValue($value); $copy = clone $this; $key = strtolower($name); if (!isset($copy->headers[$key])) { $copy->headers[$key] = ['name' => $name, 'values' => []]; } $copy->headers[$key]['values'] = array_merge($copy->headers[$key]['values'], (array)$value); return $copy; }
Return an instance with the specified header appended with the given value. Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added. @param string $name Case-insensitive header field name to add. @param string|string[] $value Header value(s). @return static @throws \InvalidArgumentException for invalid header names. @throws \InvalidArgumentException for invalid header values.
entailment
public function withoutHeader($name) { $this->assertHeaderName($name); $key = strtolower($name); if (!isset($this->headers[$key])) { return $this; } $copy = clone $this; unset($copy->headers[$key]); return $copy; }
Return an instance without the specified header. @param string $name Case-insensitive header field name to remove. @return static
entailment
public function init() { parent::init(); //catch preflight request if ($this->request->httpMethod() === 'OPTIONS') { $answer = $this->answer(null, true); $answer->output(); exit; } }
Controller inititalisation Catches CORS preflight request marked with HTTPMethod 'OPTIONS'
entailment
public function acl(HTTPRequest $request) { $action = $request->param('Action'); if ($this->authority) { $className = get_class($this->authority); $allowedActions = Config::inst()->get($className, 'allowed_actions'); if (!$allowedActions) { $allowedActions = array(); } if (in_array($action, $allowedActions)) { if (method_exists($this->authority, $action)) { $response = $this->authority->$action($request); $response = $this->serializer->serialize($response); return $this->answer($response); } else { //let's be shady here instead return $this->error(new RESTfulAPIError(403, "Action '$action' not allowed." )); } } else { return $this->error(new RESTfulAPIError(403, "Action '$action' not allowed." )); } } }
Handles Access Control methods get response from API PermissionManager then passes it on to $answer() @param HTTPRequest $request HTTP request @return HTTPResponse
entailment
public function index(HTTPRequest $request) { //check authentication if enabled if ($this->authenticator) { $policy = $this->config()->authentication_policy; $authALL = $policy === true; $authMethod = is_array($policy) && in_array($request->httpMethod(), $policy); if ($authALL || $authMethod) { $authResult = $this->authenticator->authenticate($request); if ($authResult instanceof RESTfulAPIError) { //Authentication failed return error to client return $this->error($authResult); } } } //pass control to query handler $data = $this->queryHandler->handleQuery($request); //catch + return errors if ($data instanceof RESTfulAPIError) { return $this->error($data); } //serialize response $json = $this->serializer->serialize($data); //catch + return errors if ($json instanceof RESTfulAPIError) { return $this->error($json); } //all is good reply normally return $this->answer($json); }
Main API hub switch All requests pass through here and are redirected depending on HTTP verb and params @todo move authentication check to another methode @param HTTPRequest $request HTTP request @return string json object of the models found
entailment
public function answer($json = null, $corsPreflight = false) { $answer = new HTTPResponse(); //set response body if (!$corsPreflight) { $answer->setBody($json); } //set CORS if needed $answer = $this->setAnswerCORS($answer); $answer->addHeader('Content-Type', $this->serializer->getcontentType()); // save controller's response then return/output $this->response = $answer; return $answer; }
Output the API response to client then exit. @param string $json Response body @param boolean $corsPreflight Set to true if this is a XHR preflight request answer. CORS shoud be enabled. @return HTTPResponse
entailment
public function error(RESTfulAPIError $error) { $answer = new HTTPResponse(); $body = $this->serializer->serialize($error->body); $answer->setBody($body); $answer->setStatusCode($error->code, $error->message); $answer->addHeader('Content-Type', $this->serializer->getcontentType()); $answer = $this->setAnswerCORS($answer); // save controller's response then return/output $this->response = $answer; return $answer; }
Handles formatting and output error message then exit. @param RESTfulAPIError $error Error object to return @return HTTPResponse
entailment
private function setAnswerCORS(HTTPResponse $answer) { $cors = Config::inst()->get(self::class, 'cors'); // skip if CORS is not enabled if (!$cors['Enabled']) { return $answer; } //check if Origin is allowed $allowedOrigin = $cors['Allow-Origin']; $requestOrigin = $this->request->getHeader('Origin'); if ($requestOrigin) { if ($cors['Allow-Origin'] === '*') { $allowedOrigin = $requestOrigin; } elseif (is_array($cors['Allow-Origin'])) { if (in_array($requestOrigin, $cors['Allow-Origin'])) { $allowedOrigin = $requestOrigin; } } } $answer->addHeader('Access-Control-Allow-Origin', $allowedOrigin); //allowed headers $allowedHeaders = ''; $requestHeaders = $this->request->getHeader('Access-Control-Request-Headers'); if ($cors['Allow-Headers'] === '*') { $allowedHeaders = $requestHeaders; } else { $allowedHeaders = $cors['Allow-Headers']; } $answer->addHeader('Access-Control-Allow-Headers', $allowedHeaders); //allowed method $answer->addHeader('Access-Control-Allow-Methods', $cors['Allow-Methods']); //max age $answer->addHeader('Access-Control-Max-Age', $cors['Max-Age']); return $answer; }
Apply the proper CORS response heardes to an HTTPResponse @param HTTPResponse $answer The updated response if CORS are neabled @return HTTPResponse
entailment
public static function api_access_control($model, $httpMethod = 'GET') { $policy = self::config()->access_control_policy; if ($policy === false) { return true; } // if access control is disabled, skip else { $policy = constant('self::' . $policy); } if ($policy === self::ACL_CHECK_MODEL_ONLY) { $access = true; } else { $access = false; } if ($policy === self::ACL_CHECK_CONFIG_ONLY || $policy === self::ACL_CHECK_CONFIG_AND_MODEL) { if (!is_string($model)) { $className = get_class($model); } else { $className = $model; } $access = self::api_access_config_check($className, $httpMethod); } if ($policy === self::ACL_CHECK_MODEL_ONLY || $policy === self::ACL_CHECK_CONFIG_AND_MODEL) { if ($access) { $access = self::model_permission_check($model, $httpMethod); } } return $access; }
Checks a class or model api access depending on access_control_policy and the provided model. - 1st config check - 2nd permission check if config access passes @param string|DataObject $model Model's classname or DataObject @param string $httpMethod API request HTTP method @return boolean true if access is granted, false otherwise
entailment
private static function api_access_config_check($className, $httpMethod = 'GET') { $access = false; $api_access = singleton($className)->stat('api_access'); if (is_string($api_access)) { $api_access = explode(',', strtoupper($api_access)); if (in_array($httpMethod, $api_access)) { $access = true; } else { $access = false; } } elseif ($api_access === true) { $access = true; } return $access; }
Checks a model's api_access config. api_access config can be: - unset|false, access is always denied - true, access is always granted - comma separated list of allowed HTTP methods @param string $className Model's classname @param string $httpMethod API request HTTP method @return boolean true if access is granted, false otherwise
entailment
private static function model_permission_check($model, $httpMethod = 'GET') { $access = true; $apiInstance = self::$instance; if ($apiInstance->authenticator && $apiInstance->authority) { $request = $apiInstance->request; $member = $apiInstance->authenticator->getOwner($request); if (!$member instanceof Member) { $member = null; } $access = $apiInstance->authority->checkPermission($model, $member, $httpMethod); if (!is_bool($access)) { $access = true; } } return $access; }
Checks a Model's permission for the currently authenticated user via the Permission Manager dependency. For permissions to actually be checked, this means the RESTfulAPI must have both authenticator and authority dependencies defined. If the authenticator component does not return an instance of the Member null will be passed to the authority component. This default to true. @param string|DataObject $model Model's classname or DataObject to check permission for @param string $httpMethod API request HTTP method @return boolean true if access is granted, false otherwise
entailment
public function write() { // Crete the file if it does not exist $this->makeFile($this->formatter->getFileName()); // Contents of the original file $fileContent = file_get_contents($this->formatter->getFileName()); // Final log $log = join("\n", (array) $this->formatter->generate())."\n"; // Include the breakpoint if (false === empty($this->break) && 1 === preg_match("/^{$this->break}/m", $fileContent)) { $splitFileContent = preg_split("/^{$this->break}/m", $fileContent); file_put_contents($this->formatter->getFileName(), $splitFileContent[0].$this->break."\n".$log.$splitFileContent[1]); return true; } file_put_contents($this->formatter->getFileName(), $log.$fileContent); return true; }
Writes the output to a file. @return bool
entailment
public function setInput($input) { $inputArray = explode(' ', $input); array_shift($inputArray); $this->input = join(' ', $inputArray); }
Set the input. @param $input string
entailment
public function parse() { $this->handler->parse($this->input); $output = $this->handler->getOptions(); if (false === isset($output['from'])) { throw new \BadMethodCallException('The --from argument is required.'); } if (false === isset($output['release'])) { throw new \BadMethodCallException('The --release argument is required.'); } return $this->handler; }
Parses the input and returns the Getopt handler. @return Getopt
entailment
protected function groupUploadedFiles(array $array, $groupKey, $assertIsUploadedFile) { $files = []; foreach ($array as $key => $values) { $parameterKey = isset($groupKey) ? "{$groupKey}[{$key}]" : $key; if (!is_array($values['error'])) { $files[$key] = $this->createUploadedFile($values, $parameterKey, $assertIsUploadedFile); continue; } $rearranged = []; foreach ($values as $property => $propertyValues) { foreach ($propertyValues as $subkey => $value) { $rearranged[$subkey][$property] = $value; } } $files[$key] = $this->groupUploadedFiles($rearranged, $parameterKey, $assertIsUploadedFile); } return $files; }
Group data as provided by $_FILES @param array $array @param string $groupKey @param boolean $assertIsUploadedFile Assert that the file is actually uploaded @return array An array tree of UploadedFileInterface instances
entailment
protected function setUploadedFiles(array &$files) { $isUploadedFiles = ($files === $_FILES); $this->files =& $files; $this->uploadedFiles = $this->groupUploadedFiles($files, null, $isUploadedFiles); }
Set uploaded files @global array $_FILES @param array $files
entailment
protected function ungroupUploadedFiles(array $uploadedFiles) { foreach (array_keys($this->files) as $key) { unset($this->files[$key]); } foreach ($uploadedFiles as $key => $item) { if (is_array($item)) { $group = array_fill_keys(['name', 'type', 'size', 'tmp_name', 'error'], []); $this->ungroupUploadedFilesDeep($item, $group['name'], $group['type'], $group['size'], $group['tmp_name'], $group['error']); $this->files[$key] = $group; } elseif ($item instanceof UploadedFileInterface) { try { $stream = $item->getStream(); } catch (\RuntimeException $e) { $stream = null; } $this->files[$key] = [ 'name' => $item->getClientFilename(), 'type' => $item->getClientMediaType(), 'size' => $item->getSize(), 'tmp_name' => $stream ? $stream->getMetadata('uri') : null, 'error' => $item->getError() ]; } } }
Ungroup uploaded files and set $_FILES @param array $uploadedFiles
entailment
protected function ungroupUploadedFilesDeep(array $uploadedFiles, &$name, &$type, &$size, &$tmpName, &$error) { foreach ($uploadedFiles as $key => $item) { if (is_array($item)) { $name[$key] = []; $type[$key] = []; $size[$key] = []; $tmpName[$key] = []; $error[$key] = []; $this->ungroupUploadedFilesDeep($item, $name[$key], $type[$key], $size[$key], $tmpName[$key], $error[$key]); } elseif ($item instanceof UploadedFileInterface) { try { $stream = $item->getStream(); } catch (\RuntimeException $e) { $stream = null; } $name[$key] = $item->getClientFilename(); $type[$key] = $item->getClientMediaType(); $size[$key] = $item->getSize(); $tmpName[$key] = $stream ? $stream->getMetadata('uri') : null; $error[$key] = $item->getError(); } } }
Ungroup uploaded files and set a child of $_FILES @param array $uploadedFiles @param array $name @param array $type @param array $size @param array $tmpName @param array $error
entailment
protected function assertUploadedFilesStructure(array $uploadedFiles, $groupKey = null) { foreach ($uploadedFiles as $key => $item) { $parameterKey = isset($groupKey) ? "{$groupKey}[{$key}]" : $key; if (is_array($item)) { $this->assertUploadedFilesStructure($item, $parameterKey); } elseif (!$item instanceof UploadedFileInterface) { throw new \InvalidArgumentException("'$parameterKey' is not an UploadedFileInterface object, but a " . (is_object($item) ? get_class($item) . ' ' : '') . gettype($item)); } } }
Assert that each leaf is an UploadedFileInterface @param array $uploadedFiles @param string $groupKey @throws \InvalidArgumentException if an invalid structure is provided.
entailment
public function withUploadedFiles(array $uploadedFiles) { $this->assertUploadedFilesStructure($uploadedFiles); $request = $this->copy(); $request->uploadedFiles = $uploadedFiles; if (isset($this->files)) { $this->ungroupUploadedFiles($uploadedFiles); } return $request; }
Create a new instance with the specified uploaded files. @param array $uploadedFiles An array tree of UploadedFileInterface instances. @return static @throws \InvalidArgumentException if an invalid structure is provided.
entailment
public function initHeaders() { if (!isset($this->headers)) { $this->headers = new HeadersObject($this->determineHeaders()); } return $this->headers; }
Public function to create header object @return HeadersInterface
entailment
public function withHeader($name, $value) { $headers = $this->initHeaders(); $clone = $this->copy(); $clone->headers = $headers->withHeader($name, $value); return $clone; }
Return an instance with the provided value replacing the specified header. While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders(). This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value. @param string $name Case-insensitive header field name. @param string|string[] $value Header value(s). @return static @throws \InvalidArgumentException for invalid header names or values.
entailment
public function withAddedHeader($name, $value) { $headers = $this->initHeaders(); $clone = $this->copy(); $clone->headers = $headers->withAddedHeader($name, $value); return $clone; }
Return an instance with the specified header appended with the given value. Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added. @param string $name Case-insensitive header field name to add. @param string|string[] $value Header value(s). @return static @throws \InvalidArgumentException for invalid header names. @throws \InvalidArgumentException for invalid header values.
entailment
public function withoutHeader($name) { $headers = $this->initHeaders(); if (!$headers->hasHeader($name)) { return $this; } $clone = $this->copy(); $clone->headers = $headers->withoutHeader($name); return $clone; }
Return an instance without the specified header. @param string $name Case-insensitive header field name to remove. @return static
entailment
protected function setUser($user) { if (!$this->isValidUsername($user)) { throw new \InvalidArgumentException("Invalid username '$user': double colon not allowed"); } $this->user = (string)$user; }
Set the username @param string $user @throws \InvalidArgumentException for invalid username.
entailment
public function withUserInfo($user, $password = null) { $uri = clone $this; $uri->setUser($user); $uri->setPass($password); return $uri; }
Return an instance with the specified user information. @param string $user The user name to use for authority. @param null|string $password The password associated with $user. @return static A new instance with the specified user information. @throws \InvalidArgumentException for invalid username.
entailment
public function run(array $options) { $this->generator = new ReadmeGen(new ConfigLoader()); $this->setupParser($options); // Extract useful log entries $logGrouped = $this->generator->setExtractor(new Extractor()) ->extractMessages($this->getLog()); $config = $this->generator->getConfig(); $formatterClassName = '\ReadmeGen\Output\Format\\' . ucfirst($config['format']); // Create the output formatter $formatter = new $formatterClassName; $formatter ->setRelease($options['release']) ->setFileName($config['output_file_name']) ->setDate($this->getToDate()); // Pass decorated log entries to the generator $this->generator->setDecorator(new Decorator($formatter)) ->getDecoratedMessages($logGrouped); $writer = new Writer($formatter); // If present, respect the breakpoint in the existing output file $break = $this->getBreak($options, $config); if (false === empty($break)) { $writer->setBreak($break); } // Write the output $this->generator->setOutputWriter($writer) ->writeOutput(); }
Generates the output file. @param array $options
entailment
protected function getBreak(array $options, array $config){ if (true === isset($options['break'])) { return $options['break']; } if (true === isset($config['break'])) { return $config['break']; } return null; }
Returns the breakpoint if set, null otherwise. @param array $options @param array $config @return null|string
entailment
public function withServerParams(array $params) { $request = $this->copy(); $request->serverParams = $params; $request->reset(); return $request; }
Return an instance with the specified server params. Resets all properties that can be derived from the server parameters. Note: this method is not part of the PSR-7 specs. @param array $params Array of key/value pairs server parameters. @return static
entailment
protected function setPort($port) { if ((string)$port !== '' && !$this->isValidPort($port)) { throw new \InvalidArgumentException("Invalid port '$port'"); } $this->port = $port ? (int)$port : null; }
Set the port @param int|null $port
entailment
public function setMessageGroups(array $messageGroups) { $this->messageGroups = $messageGroups; // Set the joined message groups as well foreach ($this->messageGroups as $header => $keywords) { $this->messageGroupsJoined[$header] = join('|', $keywords); } return $this; }
Message groups setter. @param array $messageGroups @return $this
entailment
public function extract() { foreach ($this->log as $line) { foreach ($this->messageGroupsJoined as $header => $keywords) { $pattern = $this->getPattern($keywords); if (preg_match($pattern, $line)) { $this->appendToGroup($header, $line, $pattern); } } } // Remove empty groups foreach (array_keys($this->messageGroups) as $groupKey) { if (true === empty($this->groups[$groupKey])) { unset($this->messageGroups[$groupKey]); } } // The array_merge sorts $messageGroups basing on $groups return array_merge($this->messageGroups, $this->groups); }
Groups messages and returns them. @return array
entailment
protected function appendToGroup($groupHeader, $text, $pattern) { $this->groups[$groupHeader][] = trim(preg_replace($pattern, '', $text)); }
Appends a message to a group @param string $groupHeader @param string $text @param string $pattern
entailment
protected function setPath($path) { if ($path !== '' && !$this->isValidPath($path)) { throw new \InvalidArgumentException("Invalid path '$path'"); } $this->path = (string)$path; }
Set the path @param string $path
entailment
protected function resetParsedBody() { if ($this->parseCondition !== false) { $this->parsedBody = null; $this->parseCondition = null; } }
Reset the parsed body, excepted if it was explicitly set
entailment
protected function parseBodyIsRequired() { return !isset($this->parseCondition) || (isset($this->parseCondition['content_type']) && $this->parseCondition['content_type'] !== $this->getContentType()) || (isset($this->parseCondition['size']) && $this->parseCondition['size'] !== $this->getBody()->getSize()); }
Check if the body needs to be (re-)parsed @return boolean
entailment
protected function shouldUsePostData() { if (!isset($this->postData)) { return false; } $contentType = $this->getContentType(); return in_array($contentType, ['application/x-www-form-urlencoded', 'multipart/form-data']) || empty($contentType) && !array_key_exists('SERVER_PROTOCOL', $this->getServerParams()); }
Check if we should use post data rather than parsing the body @return boolean
entailment
protected function parseBody() { $data = null; switch ($this->getContentType()) { case 'application/x-www-form-urlencoded': $data = $this->parseUrlEncodedBody(); break; case 'application/json': $data = $this->parseJsonBody(); break; case 'text/xml': case 'application/xml': $data = $this->parseXmlBody(); break; case 'multipart/form-data': throw new \RuntimeException("Parsing multipart/form-data isn't supported"); } return $data; }
Parse the body based on the content type. @return mixed @throws \RuntimeException if parsing isn't supported for the content-type
entailment
protected function parseJsonBody() { $data = json_decode($this->getBody(), true); if (!isset($data) && json_last_error()) { trigger_error("Failed to parse json body: " . json_last_error_msg(), E_USER_WARNING); } return $data; }
Parse json body @return array|mixed
entailment
public function getParsedBody() { if ($this->shouldUsePostData()) { return $this->postData; } if ($this->parseBodyIsRequired()) { $this->parsedBody = $this->parseBody(); $this->parseCondition = [ 'content_type' => $this->getContentType(), 'size' => $this->getBody()->getSize() ]; } return $this->parsedBody; }
Retrieve any parameters provided in the request body. If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, this method will return the contents of $_POST. Otherwise, this method returns the results of deserializing the request body content; as parsing returns structured content. This function assumes that the body is read only or append only, as it will only reparse the body if the size has changed. @return null|array|object|mixed The deserialized body parameters, if any. @throws \RuntimeException if parsing isn't supported for the content-type
entailment
public function withParsedBody($data) { $request = $this->copy(); $request->parseCondition = ($data === null ? null : false); if ($this->shouldUsePostData() && $data !== null) { $request->postData = $data; $request->parsedBody = null; } else { $request->parsedBody = $data; } return $request; }
Return an instance with the specified body parameters. Setting the parsed body to `null` means that the body will be (re-)parsed on `getParsedBody()`. @param null|array|object|mixed $data The deserialized body data. @return static
entailment
public function emit(EmitterInterface $emitter = null) { if ($this->isStale) { throw new \BadMethodCallException("Unable to emit a stale response object"); } if (!isset($emitter)) { $emitter = $this->createEmitter(); } if (isset($this->status) && !$this->status instanceof GlobalResponseStatus) { $emitter->emitStatus($this); } if (isset($this->headers) && !$this->headers instanceof GlobalResponseHeaders) { $emitter->emitHeaders($this); } if (isset($this->body) && $this->body->getMetadata('url') !== 'php://output') { $emitter->emitBody($this); } }
Emit the response @param EmitterInterface $emitter
entailment
public function withProtocolVersion($version) { $response = $this->_withProtocolVersion($version); if ($response->status instanceof GlobalResponseStatus) { $response->status = $response->status->withProtocolVersion($response->getProtocolVersion()); } return $response; }
Return an instance with the specified HTTP protocol version. The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). @param string @return static @throws \InvalidArgumentException for invalid versions
entailment
public function withGlobalEnvironment($bind = false) { if ($this->isStale) { throw new \BadMethodCallException("Unable to use a stale response. Did you mean to rivive it?"); } if ($this->isStale === false) { return $this->copy(); } $response = clone $this; $response->isStale = false; $response->status = $this->createGlobalResponseStatus(); $response->headers = $this->createGlobalResponseHeaders(); $response->setBody($this->createOutputBufferStream()); if (!$bind) { // This will copy the headers and body from the global environment $response = $response->withoutGlobalEnvironment(); } return $response; }
Use php://output stream and default php functions work with headers. Note: this method is not part of the PSR-7 specs. @param boolean $bind Bind to global environment @return static @throws RuntimeException if isn't not possible to open the 'php://output' stream
entailment
public function withoutGlobalEnvironment() { if ($this->isStale === null) { return $this; } $response = clone $this; $response->copy(); // explicitly make stale if ($response->body instanceof OutputBufferStream) { $response->body = $response->body->withLocalScope(); } $response->isStale = null; return $response; }
Return object that is disconnected from superglobals Note: this method is not part of the PSR-7 specs. @return static
entailment
protected function copy() { if ($this->isStale) { throw new \BadMethodCallException("Unable to modify a stale response object"); } $response = clone $this; if ($this->isStale === false) { $this->status = new ResponseStatus($this->status); $this->headers = new Headers($this->getHeaders()); $this->isStale = true; } return $response; }
Clone the response. Turn stale if the response is bound to the global environment. @return static A non-stale response @throws \BadMethodCallException when the response is stale
entailment
public function revive() { if ($this->isStale !== true) { return $this; } $response = clone $this; $response->status = $this->createGlobalResponseStatus($this->status) ->withProtocolVersion($this->getProtocolVersion()); $response->headers = $this->createGlobalResponseHeaders($this->getHeaders()); if ($response->body instanceof OutputBufferStream) { $response->body->useGlobally(); } $response->isStale = false; return $response; }
Revive a stale response @return $this
entailment
public function withStatus($code, $reasonPhrase = '') { if ( ((is_int($code) || is_string($code)) && $this->getStatusCode() === (int)$code) && (empty($reasonPhrase) || $this->getReasonPhrase() === $reasonPhrase) ) { return $this; } $status = $this->initStatus(); $response = $this->copy(); $response->status = $status->withStatus($code, $reasonPhrase); return $response; }
Return an instance with the specified status code and, optionally, reason phrase. If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code. This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase. @see http://tools.ietf.org/html/rfc7231#section-6 @see http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml @param int $code The 3-digit integer result code to set. @param string $reasonPhrase The reason phrase to use with the provided status code; if none is provided, implementations MAY use the defaults as suggested in the HTTP specification. @return static @throws \InvalidArgumentException For invalid status code arguments.
entailment
public function getProtocolVersion() { if (!isset($this->protocolVersion)) { $this->protocolVersion = $this->determineProtocolVersion(); } return $this->protocolVersion; }
Retrieves the HTTP protocol version as a string. @return string HTTP protocol version.
entailment
protected function assertProtocolVersion($version) { if (!is_string($version) && !is_numeric($version)) { throw new \InvalidArgumentException("HTTP version must be a string or float"); } if ($version != '' && $version !== "1.0" && $version !== "1.1" && $version !== "2") { throw new \InvalidArgumentException("Invalid HTTP protocol version '$version'"); } }
Set the HTTP protocol version. @param string $version HTTP protocol version @throws \InvalidArgumentException for invalid versions
entailment
public function withProtocolVersion($version) { if (is_numeric($version)) { $version = number_format((float)$version, $version < 2 ? 1 : 0, '.', ''); } $this->assertProtocolVersion($version); $request = $this->copy(); $request->protocolVersion = $version; return $request; }
Return an instance with the specified HTTP protocol version. The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0"). @param string @return static @throws \InvalidArgumentException for invalid versions
entailment
public function getAttributes() { $attributes = []; foreach ($this->attributes as $name => $attr) { $value = $attr instanceof \Closure || $attr instanceof DerivedAttributeInterface ? $attr($this) : $attr; $attributes[$name] = $value; } return $attributes; }
Retrieve attributes derived from the request. The request "attributes" may be used to allow injection of any parameters derived from the request: e.g., the results of path match operations; the results of decrypting cookies; the results of deserializing non-form-encoded message bodies; etc. Attribute names are automatically turned into snake_case. @return mixed[] Attributes derived from the request.
entailment
public function getAttribute($name, $default = null) { $key = \Jasny\snakecase($name); $attr = isset($this->attributes[$key]) ? $this->attributes[$key] : null; $value = $attr instanceof \Closure || $attr instanceof DerivedAttributeInterface ? $attr($this) : $attr; return isset($value) ? $value : $default; }
Retrieve a single derived request attribute. Retrieves a single derived request attribute as described in getAttributes(). If the attribute has not been previously set, returns the default value as provided. The attribute name is automatically turned into snake_case. @see getAttributes() @param string $name The attribute name. @param mixed $default Default value to return if the attribute does not exist. @return mixed
entailment
public function withAttribute($name, $value) { $request = $this->copy(); $key = \Jasny\snakecase($name); $request->attributes[$key] = $value; return $request; }
Return an instance with the specified derived request attribute. The attribute name is automatically turned into snake_case. @see getAttributes() @param string $name The attribute name. @param mixed $value The value of the attribute. @return static
entailment
public function withoutAttribute($name) { $request = $this->copy(); $key = \Jasny\snakecase($name); unset($request->attributes[$key]); return $request; }
Return an instance that removes the specified derived request attribute. This method allows removing a single derived request attribute as described in getAttributes(). @see getAttributes() @param string $name The attribute name. @return static
entailment
protected function setBody(StreamInterface $body) { if ($body instanceof OutputBufferStream && $this->isStale() === false) { $body->useGlobally(); } $this->body = $body; }
Set the body @param StreamInterface $body
entailment
protected function getStatusHeader($protocolVersion, $statusCode, $reasonPhrase) { if (empty($reasonPhrase)) { $reasonPhrase = (new ResponseStatus($statusCode))->getReasonPhrase(); } return "HTTP/{$protocolVersion} {$statusCode} {$reasonPhrase}"; }
Get the response header for a status code @param string $protocolVersion @param int $statusCode @param string $reasonPhrase @return string
entailment
public function emitStatus(ResponseInterface $response) { $this->assertHeadersNotSent(); $protocolVersion = $response->getProtocolVersion() ?: '1.1'; $statusCode = $response->getStatusCode() ?: 200; $reasonPhrase = $response->getReasonPhrase(); $header = $this->getStatusHeader($protocolVersion, $statusCode, $reasonPhrase); $this->header($header); }
Emit the HTTP status (and protocol version) @param ResponseInterface $response
entailment
public function emitHeaders(ResponseInterface $response) { foreach ($response->getHeaders() as $name => $values) { foreach (array_values((array)$values) as $i => $value) { $this->header("$name: $value", $i === 0); } } }
Emit the HTTP headers @param ResponseInterface $response
entailment
public function emitBody(ResponseInterface $response) { $output = $this->createOutputStream(); if (!$output) { throw new \RuntimeException("Failed to open output stream"); } $response->getBody()->rewind(); $handle = $response->getBody()->detach(); stream_copy_to_stream($handle, $output); }
Emit the HTTP body @param ResponseInterface $response @throws \RuntimeException
entailment
public function emit(ResponseInterface $response) { if ($response instanceof \Jasny\HttpMessage\Response) { $response->emit($this); return; } $this->emitStatus($response); $this->emitHeaders($response); $this->emitBody($response); }
Emit the full HTTP response @param ResponseInterface $response
entailment
public function getSize() { if (!$this->isClosed()) { $stat = fstat($this->handle); } return isset($stat['size']) ? $stat['size'] : null; }
Get the size of the stream if known. @return int|null Returns the size in bytes if known, or null if unknown.
entailment
public function tell() { if (!$this->isClosed()) { $pos = ftell($this->handle); } if (!isset($pos) || $pos === false) { throw new \RuntimeException("Failed to get the position of the stream"); } return $pos; }
Returns the current position of the file read/write handle @return int Position of the file handle @throws \RuntimeException on error.
entailment
public function seek($offset, $whence = SEEK_SET) { if (!$this->isSeekable()) { throw new \RuntimeException("Stream isn't seekable"); } $ret = fseek($this->handle, $offset, $whence); if ($ret === -1) { throw new \RuntimeException("Failed to get the seek to postion in the stream"); } }
Seek to a position in the stream. @see http://www.php.net/manual/en/function.fseek.php @param int $offset Stream offset @param int $whence Specifies how the cursor position will be calculated based on the seek offset. Valid values are identical to the built-in PHP $whence values for `fseek()`. SEEK_SET: Set position equal to offset bytes SEEK_CUR: Set position to current location plus offset SEEK_END: Set position to end-of-stream plus offset. @throws \RuntimeException on failure.
entailment
public function rewind() { // @codeCoverageIgnoreStart $meta = $this->getMetadata(); if ($meta['wrapper_type'] === 'PHP' && strtolower($meta['stream_type']) === 'input') { $this->handle = fopen($meta['uri'], $meta['mode']); } // @codeCoverageIgnoreEnd $this->seek(0, SEEK_SET); }
Seek to the beginning of the stream. If the stream is not seekable, this method will raise an exception; otherwise, it will perform a seek(0). @see seek() @see http://www.php.net/manual/en/function.fseek.php @throws \RuntimeException on failure.
entailment
public function write($string) { if (!$this->isWritable()) { throw new \RuntimeException("Stream isn't writable"); } $ret = fwrite($this->handle, $string); if ($ret === false) { throw new \RuntimeException("Failed to write to stream"); } return $ret; }
Write data to the stream. @param string $string The string that is to be written. @return int Returns the number of bytes written to the stream. @throws \RuntimeException on failure.
entailment
public function isReadable() { $mode = $this->getMetadata('mode'); return isset($mode) && ($mode[0] === 'r' || strpos($mode, '+') !== false); }
Returns whether or not the stream is readable. @return bool
entailment
public function getContents() { if (!$this->isReadable()) { throw new \RuntimeException("Stream isn't readable"); } $contents = ''; while (!$this->eof()) { $contents .= $this->read(512000); } return $contents; }
Returns the remaining contents in a string @return string @throws \RuntimeException if unable to read. @throws \RuntimeException if error occurs while reading.
entailment
public function getMetadata($key = null) { $meta = !$this->isClosed() ? stream_get_meta_data($this->handle) : null; if (isset($key)) { $meta = isset($meta[$key]) ? $meta[$key] : null; } return $meta; }
Get stream metadata as an associative array or retrieve a specific key. The keys returned are identical to the keys returned from PHP's stream_get_meta_data() function. @see http://php.net/manual/en/function.stream-get-meta-data.php @param string $key Specific metadata to retrieve. @return array|mixed|null Returns an associative array if no key is provided. Returns a specific key value if a key is provided and the value is found, or null if the key is not found.
entailment
public static function open($uri, $mode) { $fp = fopen($uri, $mode); if (!$fp) { throw new \RuntimeException("Failed to open the '$uri' stream in '$mode' mode"); } return new static($fp); }
Open a stream. @see http://php.net/manual/en/function.fopen.php @param string $uri URI or filename @param string $mode @return static @throws \RuntimeException
entailment
protected function determineProtocolVersion() { $params = $this->getServerParams(); if (isset($params['SERVER_PROTOCOL'])) { list($protocol, $version) = explode('/', $params['SERVER_PROTOCOL']) + [1 => null]; } return isset($protocol) && $protocol === 'HTTP' ? $version : "1.1"; }
Determine the protocol versions based on the server params @return string
entailment
public function run($command) { $this->command = escapeshellcmd($command); $this->process->setCommandLine($this->command); $this->process->run(); $this->validateRun(); return $this; }
Run a command as a process. @param string $command @return self
entailment
protected function validateRun() { $status = $this->process->getExitCode(); $error = $this->process->getErrorOutput(); if ($status !== 0 and $error !== '') { throw new \RuntimeException( sprintf( "The exit status code %s says something went wrong:\n stderr: %s\n stdout: %s\ncommand: %s.", $status, $error, $this->process->getOutput(), $this->command ) ); } }
Validate that a run process was successful. @throws \RuntimeException @return void
entailment
public function createFromView($view, $filename, $inline = false) { $this->generateFilePaths(); $this->generatePdf($view); $contentDisposition = $inline ? 'inline' : 'attachment'; return (new BinaryFileResponse($this->pdfPath)) ->setContentDisposition($contentDisposition, $filename) ->deleteFileAfterSend(true); }
Create a PDF from a view or string @param string|object $view @param string $filename @param bool $inline @return BinaryFileResponse
entailment
public function saveFromView($view, $path) { $this->generateFilePaths(); $this->generatePdf($view); rename($this->pdfPath, $path); }
Save a PDF file to the disk @param string|object $view @param string $path
entailment
protected function generateFilePaths() { $this->validateStoragePath(); $path = $this->storagePath . DIRECTORY_SEPARATOR; $this->htmlPath = $path . uniqid('pdf-', true).'.html'; $this->pdfPath = $path . uniqid('html-', true) . '.pdf'; }
Generate paths for the temporary files @throws \Exception
entailment
protected function validateStoragePath() { if (is_null($this->storagePath)) { throw new Exception('A storage path has not been set'); } if (! is_dir($this->storagePath) || ! is_writable($this->storagePath)) { throw new Exception('The specified storage path is not writable'); } }
Validate that the storage path is set and is writable @throws \Exception
entailment
protected function generatePdf($view) { $view = $this->viewToString($view); $this->saveHtml($view); $command = implode(' ', [ $this->getBinaryPath(), implode(' ', $this->commandLineOptions), $this->convertScript, $this->prefixHtmlPath($this->htmlPath), $this->pdfPath, implode(' ', $this->commandLineArguments), ]); $process = new Process($command, __DIR__); $process->setTimeout($this->timeout); $process->run(); if ($errorOutput = $process->getErrorOutput()) { throw new RuntimeException('PhantomJS: ' . $errorOutput); } // Remove temporary html file @unlink($this->htmlPath); }
Run the script with PhantomJS @param string $view
entailment
protected function insertBaseTag($view) { if (is_null($this->baseUrl)) { return $view; } return str_replace('<head>', '<head><base href="'.$this->baseUrl.'">', $view); }
Insert a base tag after the head tag to allow relative references to assets @param string $view @return string
entailment
public function parse($file) { $this->file = $file; $this->validateSelf(); $this->process->run("{$this->binary} {$this->file} -"); return $this; }
Parse a PDF file. @param string $file @throws PdfBinaryNotDefinedException @throws PdfNotFoundException @return self
entailment
public function register() { $this->mergeConfigFrom(__DIR__.'/../config/config.php', 'phantom-pdf'); $this->app->bind('phantom-pdf', function () { $generator = new PdfGenerator; $baseUrl = $this->app['config']['phantom-pdf.base_url']; $generator->setBaseUrl(is_null($baseUrl) ? null : url($baseUrl)); $generator->setBinaryPath($this->app['config']['phantom-pdf.binary_path']); $generator->setStoragePath($this->app['config']['phantom-pdf.temporary_file_path']); $generator->setTimeout($this->app['config']['phantom-pdf.timeout']); if ($this->app['config']['phantom-pdf.conversion_script']) { $generator->useScript($this->app['config']['phantom-pdf.conversion_script']); } foreach ($this->app['config']['phantom-pdf.command_line_options'] as $option) { $generator->addCommandLineOption($option); } return $generator; }); $this->app->alias('phantom-pdf', PdfGenerator::class); }
Register the service provider. @return void
entailment
public static function scan(LexerConfig $config, $input) { $tokens = []; $offset = 0; $position = 0; $matches = null; while (strlen($input)) { $anyMatch = false; foreach ($config->getTokenDefinitions() as $tokenDefinition) { if (preg_match($tokenDefinition->getRegex(), $input, $matches)) { $str = $matches[0]; $len = strlen($str); if (strlen($tokenDefinition->getName()) > 0) { $tokens[] = new Token($tokenDefinition->getName(), $str, $offset, $position); ++$position; } $input = substr($input, $len); $anyMatch = true; $offset += $len; break; } } if (!$anyMatch) { throw new UnknownTokenException(sprintf('At offset %s: %s', $offset, substr($input, 0, 16).'...')); } } return $tokens; }
@param LexerConfig $config @param string $input @return Token[]
entailment
public function isNextTokenAny(array $tokenNames) { return null !== $this->lookahead && in_array($this->lookahead->getName(), $tokenNames, true); }
@param string[] $tokenNames @return bool
entailment
public function peekWhileTokens(array $tokenNames) { while ($token = $this->peek()) { if (!in_array($token->getName(), $tokenNames, true)) { break; } } return $token; }
@param string[] $tokenNames @return null|Token
entailment
protected function initConstants($library_name) { if (!isset($this->params[$library_name]['constants'])) return; foreach ((array)$this->params[$library_name]['constants'] as $constant_name => $constant_value) defined($constant_name) or define($constant_name, $constant_value); }
Registering required constants @param string $library_name
entailment
protected function createStepsFromConfig() { $config = $this->app['config']; $stepClasses = $config->get('setup_wizard.steps'); if (empty($stepClasses)) throw new \RuntimeException('The setup wizard requires at least 1 step in configuration'); $steps = []; $i = 0; foreach ($stepClasses as $id => $stepClass) { $s = new $stepClass($id); $steps[$id] = $s; ++$i; } return $steps; }
Get configuration and create the step objects @return array The step objects, indexed by ID
entailment
public function submitStep(Request $request) { if ($request->has('wizard-action-next')) { return $this->nextStep($request); } if ($request->has('wizard-action-back')) { return $this->previousStep($request); } throw new \RuntimeException('Unknown wizard action'); }
Submit the wizard step currently shown with the specified action (next/back) @param Request $request @return Response
entailment