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': ...
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...
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' ...
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...
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 ...
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 a...
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...
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. @par...
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) { $allow...
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);...
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('...
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->getcontent...
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']; ...
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); } ...
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 ...
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, $...
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 ...
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->getOwn...
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 ...
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->forma...
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'])) { ...
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'])) { ...
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', 'siz...
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] = []; ...
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->assertUploadedFilesStructu...
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); ...
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 a...
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. @par...
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 = $...
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...
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); ...
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->parseC...
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($...
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->parseJsonB...
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(),...
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...
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 { ...
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...
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()); } ret...
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(); } $r...
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->...
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); ...
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->hea...
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...
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...
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") ...
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 = ...
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...
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 automa...
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; r...
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 ...
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 = $t...
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()...
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 g...
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 ...
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 $th...
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"); ...
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...
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 === 'H...
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 w...
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($contentDisp...
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 ...
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...
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_n...
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_ma...
@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; f...
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 wiza...
Submit the wizard step currently shown with the specified action (next/back) @param Request $request @return Response
entailment