sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function dereferenceProperty(...$properties) { foreach ((array)$properties as $property) { if (!property_exists($this, $property)) { continue; // @codeCoverageIgnore } $value = $this->$property; unset($this->$property); ...
Remove referencing from properties @param string[] $properties
entailment
public function withGlobalEnvironment($bind = false) { if ($this->isStale) { throw new \BadMethodCallException("Unable to use a stale server request. Did you mean to rivive it?"); } if ($this->isStale === false) { return $this->copy(); } ...
Use superglobals $_SERVER, $_COOKIE, $_GET, $_POST and $_FILES and the php://input stream. Note: this method is not part of the PSR-7 specs. @param boolean $bind Bind server request to global environment @return ServerRequest @throws RuntimeException if isn't not possible to open the 'php://input' stream
entailment
protected function buildGlobalEnvironment() { $request = clone $this; $request->serverParams =& $_SERVER; $request->cookies =& $_COOKIE; $request->queryParams =& $_GET; $request->setPostData($_POST); $request->setUploadedFiles($_FILES); ...
Build the global environment
entailment
public function withoutGlobalEnvironment() { if ($this->isStale !== false) { return $this; } $request = clone $this; $request->copy(); $request->isStale = null; return $request; }
Return object that is disconnected from superglobals @return ServerRequest
entailment
protected function copy() { if ($this->isStale) { throw new \BadMethodCallException("Unable to modify a stale server request object"); } $request = clone $this; if ($this->isStale === false) { $this->dereferenceProperty('serverParams', 'cooki...
Clone the server request. Turn stale if the request is bound to the global environment. @return ServerRequest A non-stale request @throws \BadMethodCallException when the request is stale
entailment
public function revive() { if ($this->isStale !== true) { return $this; } $request = $this->buildGlobalEnvironment(); return $request ->withServerParams($this->getServerParams()) ->withCookieParams($this->getCookieParams()) ...
Revive a stale server request @return ServerRequest
entailment
public function invoke(ServerRequestInterface $request, RouteParams $params) { $callable = $this->callable; // Controller Actions are lazy loaded so we need to call the factory to get the callable if ($this->isControllerAction()) { $callable = call_user_func($this->callable); ...
Invoke the action @param ServerRequestInterface $request @param RouteParams $params @return mixed
entailment
private function createCallableFromAction($action) : callable { // Check if this looks like it could be a class/method string if (!is_callable($action) && is_string($action)) { return $this->convertClassStringToFactory($action); } return $action; }
If the action is a Controller string, a factory callable is returned to allow for lazy loading @param mixed $action @return callable
entailment
private function getController() { if (empty($this->controllerName)) { return null; } if (isset($this->controller)) { return $this->controller; } $this->controller = $this->createControllerFromClassName($this->controllerName); return $this->...
Get the Controller for this action. The Controller will only be created once @return mixed Returns null if this is not a Controller based action
entailment
private function createControllerFromClassName($className) { // If we can, use the container to build the Controller so that Constructor params can // be injected where possible if ($this->invoker) { return $this->invoker->getContainer()->get($className); } retur...
Instantiate a Controller object from the provided class name @param string $className @return mixed
entailment
private function providesMiddleware() : bool { $controller = $this->getController(); if ($controller && ($controller instanceof ProvidesControllerMiddleware)) { return true; } return false; }
Can this action provide Middleware @return bool
entailment
public function getMiddleware() : array { if (!$this->providesMiddleware()) { return []; } $allControllerMiddleware = array_filter( $this->getController()->getControllerMiddleware(), function (ControllerMiddleware $middleware) { return !$m...
Get an array of Middleware @return array
entailment
private function convertClassStringToFactory($string) : Closure { $this->controllerName = null; $this->controllerMethod = null; @list($className, $method) = explode('@', $string); if (!isset($className) || !isset($method)) { throw new RouteClassStringParseException('Cou...
Create a factory Closure for the given Controller string @param string $string e.g. `MyController@myMethod` @return Closure
entailment
public function getActionName() { $callableName = null; if ($this->isControllerAction()) { return $this->controllerName . '@' . $this->controllerMethod; } if (is_callable($this->callable, false, $callableName)) { list($controller, $method) = explode('::', $c...
Get the human readable name of this action @return string
entailment
protected function assertTmpFile() { if (empty($this->tmpName)) { throw new \RuntimeException("There is no tmp_file for " . $this->getDesc() . ": " . $this->getErrorDescription()); } if (!file_exists($this->tmpName)) { throw new \RuntimeExcept...
Assert that the temp file exists and is an uploaded file @throws \RuntimeException if the file doesn't exist or is not an uploaded file.
entailment
public function moveTo($targetPath) { $this->assertTmpFile(); if (!$this->isValidPath($targetPath)) { throw new \InvalidArgumentException("Unable to move " . $this->getDesc() . ": " . "'$targetPath' is not a valid path"); } $fn = [$this, $this->a...
Move the uploaded file to a new location. Use this method as an alternative to move_uploaded_file(). This method is guaranteed to work in both SAPI and non-SAPI environments. Implementations must determine which environment they are in, and use the appropriate method (move_uploaded_file(), rename(), or a stream operat...
entailment
public function getErrorDescription() { if ($this->error === UPLOAD_ERR_OK) { return null; } $descs = static::ERROR_DESCRIPTIONS; return isset($descs[$this->error]) ? $descs[$this->error] : $descs[-1]; }
Retrieve the description of the error associated with the uploaded file. If the file was uploaded successfully, this method returns null. This method is not part of PSR-7. @return string|null
entailment
public function decorate() { foreach ($this->log as &$entries) { array_walk($entries, array($this, 'injectLinks')); } return $this->log; }
Decorates the output (e.g. adds linkgs to the issue tracker) @return self
entailment
public function generate() { if (true === empty($this->log)) { return array(); } $log = array(); // Iterate over grouped entries foreach ($this->log as $header => &$entries) { // Add a group header (e.g. Bugfixes) $log[] = sprintf("\n###...
Returns a write-ready log. @return array
entailment
protected function serverParamKeyToHeaderName($key) { $name = null; if (\Jasny\str_starts_with($key, 'HTTP_')) { $name = $this->headerCase(substr($key, 5)); } elseif (in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $name = $this->headerCase($key); ...
Turn a server parameter key to a header name @param string $key @return string|null
entailment
protected function determineHeaders() { $params = $this->getServerParams(); $headers = []; foreach ($params as $key => $value) { $name = $this->serverParamKeyToHeaderName($key); if (isset($name) && is_string($value)) { $headers[$n...
Determine the headers based on the server parameters @return array headers array with structure $key => [$value]
entailment
public function deserialize($json) { $data = json_decode($json, true); //catch JSON parsing error $error = RESTfulAPIError::get_json_error(); if ($error !== false) { return new RESTfulAPIError(400, $error); } if ($data) { $data = $this->unfor...
Convert client JSON data to an array of data ready to be consumed by SilverStripe Expects payload to be formatted: { "FieldName": "Field value", "Relations": [1] } @param string $data JSON to be converted to data ready to be consumed by SilverStripe @return array|false Formatted array representati...
entailment
protected function unformatPayloadData(array $data) { $unformattedData = array(); foreach ($data as $key => $value) { $newKey = $this->deserializeColumnName($key); if (is_array($value)) { $newValue = $this->unformatPayloadData($value); } else { ...
Process payload data from client and unformats columns/values recursively @param array $data Payload data (decoded JSON) @return array Paylaod data with all keys/values unformatted
entailment
public function parse($arrAttributes = null) { // Messages (passed on to fineuploader JS) $basicTextOptions = array( 'text' => array( 'formatProgress', 'failUpload', 'waitingForResponse', 'paused', ), ...
Add the labels and messages. @param null $arrAttributes
entailment
public function validateUpload() { \Message::reset(); $strTempName = $this->strName . '_fineuploader'; $objUploader = new \Haste\Util\FileUpload($this->strName); $blnIsChunk = isset($_POST['qqpartindex']); // Convert the $_FILES array to Contao format if (!empty($_FI...
Validate the upload @return string
entailment
protected function validator($varInput) { $varReturn = $this->blnIsMultiple ? array() : ''; $strDestination = $this->getDestinationFolder(); // Check if mandatory if ($varInput == '' && $this->mandatory) { $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], ...
Return an array if the "multiple" attribute is set @param mixed @return mixed
entailment
protected function getDestinationFolder() { $destination = \Config::get('uploadPath'); $folder = null; // Specify the target folder in the DCA (eval) if (isset($this->arrConfiguration['uploadFolder'])) { $folder = $this->arrConfiguration['uploadFolder']; } ...
Get the destination folder @return mixed
entailment
protected function validatorSingle($varFile, $strDestination) { // Move the temporary file if (!\Validator::isStringUuid($varFile) && is_file(TL_ROOT . '/' . $varFile)) { $varFile = $this->moveTemporaryFile($varFile, $strDestination); } // Convert uuid to binary format ...
Validate a single file. @param mixed @param string @return mixed
entailment
protected function moveTemporaryFile($strFile, $strDestination) { if (!is_file(TL_ROOT . '/' . $strFile)) { return ''; } // Do not store the file if (!$this->arrConfiguration['storeFile']) { return $strFile; } // The file is not temporary ...
Move the temporary file to its destination @param string @param string @return string
entailment
protected function getFileName($strFile, $strFolder) { if (!file_exists(TL_ROOT . '/' . $strFolder . '/' . $strFile)) { return $strFile; } $offset = 1; $pathinfo = pathinfo($strFile); $name = $pathinfo['filename']; $arrAll = scan(TL_ROOT . '/' . $strFold...
Get the new file name if it already exists in the folder @param string @param string @return string
entailment
protected function generateFileItem($strPath) { if (!is_file(TL_ROOT . '/' . $strPath)) { return ''; } $imageSize = $this->getImageSize(); $objFile = new \File($strPath, true); $strInfo = $strPath . ' <span class="tl_gray">(' . \System::getReadableSize($objFile->...
Generate a file item and return it as HTML string @param string @return string
entailment
public static function get_json_error() { $error = 'JSON - '; switch (json_last_error()) { case JSON_ERROR_NONE: $error = false; break; case JSON_ERROR_DEPTH: $error .= 'The maximum stack depth has been exceeded.'; ...
Check for the latest JSON parsing error and return the message if any More available for PHP >= 5.3.3 http://www.php.net/manual/en/function.json-last-error.php @return false|string Returns false if no error or a string with the error detail.
entailment
protected function setScheme($scheme) { $scheme = strtolower($scheme); if ($scheme !== '' && !$this->isSupportedScheme($scheme)) { throw new \InvalidArgumentException("Invalid or unsupported scheme '$scheme'"); } $this->scheme = $scheme; }
Set the scheme @param string $scheme @throws \InvalidArgumentException for invalid or unsupported schemes.
entailment
protected function setFragment($fragment) { if (!$this->isValidFragment($fragment)) { throw new \InvalidArgumentException("Invalid fragment '$fragment'"); } $this->fragment = (string)$fragment; }
Set the fragment @param string $fragment
entailment
public function useGlobally() { if (!isset($this->handle)) { throw new \RuntimeException("The stream is closed"); } if ($this->isGlobal()) { return $this; } $this->assertOutputBuffering(); $output = $this->createOutpu...
After change Response body work with global enviroment this function are copy all content from previous Stream body (like php://temp) and copy it into current php://output stream. @return $this @throws \RuntimeException
entailment
public function withLocalScope() { if ($this->isClosed()) { throw new \RuntimeException("The stream is closed"); } if (!$this->isGlobal()) { return $this; } $stream = clone $this; fwrite($stream->handle, (string)$this...
Get this stream in a local scope. If the stream is global, it will create a temp stream and copy the contents. @return OutputBufferStream @throws \RuntimeException
entailment
public function seek($offset, $whence = SEEK_SET) { if (!$this->isGlobal()) { return parent::seek($offset, $whence); } throw new \RuntimeException("Stream isn't seekable"); }
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 getBody() { if (!isset($this->body)) { $this->body = $this->createDefaultBody(); } return $this->body; }
Gets the body of the message. @return StreamInterface Returns the body as a stream.
entailment
public function withBody(StreamInterface $body) { $request = $this->copy(); $request->setBody($body); return $request; }
Return an instance with the specified message body. @param StreamInterface $body @return static
entailment
public function login(HTTPRequest $request) { $response = array(); if ($this->tokenConfig['owner'] === Member::class) { $email = $request->requestVar('email'); $pwd = $request->requestVar('pwd'); $member = false; if ($email && $pwd) { ...
Login a user into the Framework and generates API token Only works if the token owner is a Member @param HTTPRequest $request HTTP request containing 'email' & 'pwd' vars @return array login result with token
entailment
public function logout(HTTPRequest $request) { $email = $request->requestVar('email'); $member = Member::get()->filter(array('Email' => $email))->first(); if ($member) { //logout $member->logout(); if ($this->tokenConfig['owner'] === Member::class) { ...
Logout a user from framework and update token with an expired one if token owner class is a Member @param HTTPRequest $request HTTP request containing 'email' var
entailment
public function lostPassword(HTTPRequest $request) { $email = Convert::raw2sql($request->requestVar('email')); $member = DataObject::get_one(Member::class, "\"Email\" = '{$email}'"); if ($member) { $token = $member->generateAutologinTokenAndStoreHash(); $link = Secu...
Sends password recovery email @param HTTPRequest $request HTTP request containing 'email' vars @return array 'email' => false if email fails (Member doesn't exist will not be reported)
entailment
public function getToken($id) { if ($id) { $ownerClass = $this->tokenConfig['owner']; $owner = DataObject::get_by_id($ownerClass, $id); if ($owner) { $tokenDBColumn = $this->tokenConfig['DBColumn']; return $owner->{$tokenDBColumn}; ...
Return the stored API token for a specific owner @param integer $id ID of the token owner @return string API token for the owner
entailment
public function resetToken($id, $expired = false) { if ($id) { $ownerClass = $this->tokenConfig['owner']; $owner = DataObject::get_by_id($ownerClass, $id); if ($owner) { //generate token $tokenData = $this->generateToken($expired); ...
Reset an owner's token if $expired is set to true the owner's will have a new invalidated/expired token @param integer $id ID of the token owner @param boolean $expired if true the token will be invalidated
entailment
private function generateToken($expired = false) { $life = $this->tokenConfig['life']; if (!$expired) { $expire = time() + $life; } else { $expire = time() - ($life * 2); } $generator = new RandomGenerator(); $tokenString = $generator->random...
Generates an encrypted random token and an expiry date @param boolean $expired Set to true to generate an outdated token @return array token data array('token' => HASH, 'expire' => EXPIRY_DATE)
entailment
public function getOwner(HTTPRequest $request) { $owner = null; //get the token $token = $request->getHeader($this->tokenConfig['header']); if (!$token) { $token = $request->requestVar($this->tokenConfig['queryVar']); } if ($token) { $SQLToke...
Returns the DataObject related to the token that sent the authenticated request @param HTTPRequest $request HTTP API request @return null|DataObject null if failed or the DataObject token owner related to the request
entailment
public function authenticate(HTTPRequest $request) { //get the token $token = $request->getHeader($this->tokenConfig['header']); if (!$token) { $token = $request->requestVar($this->tokenConfig['queryVar']); } if ($token) { //check token validity ...
Checks if a request to the API is authenticated Gets API Token from HTTP Request and return Auth result @param HTTPRequest $request HTTP API request @return true|RESTfulAPIError True if token is valid OR RESTfulAPIError with details
entailment
private function validateAPIToken($token, $request) { //get owner with that token $SQL_token = Convert::raw2sql($token); $tokenColumn = $this->tokenConfig['DBColumn']; $tokenOwner = DataObject::get_one( $this->tokenConfig['owner'], "\"" . $this->tokenConfig['...
Validate the API token @param string $token Authentication token @param HTTPRequest $request HTTP API request @return true|RESTfulAPIError True if token is valid OR RESTfulAPIError with details
entailment
protected function jsonify($data) { // JSON_NUMERIC_CHECK removes leading zeros // which is an issue in cases like postcode e.g. 00160 // see https://bugs.php.net/bug.php?id=64695 $json = json_encode($data); //catch JSON parsing error $error = RESTfulAPIError::get_js...
Convert data into a JSON string @param mixed $data Data to convert @return string JSON data
entailment
public function serialize($data) { $json = ''; $formattedData = null; if ($data instanceof DataObject) { $formattedData = $this->formatDataObject($data); } elseif ($data instanceof DataList) { $formattedData = $this->formatDataList($data); } ...
Convert raw data (DataObject or DataList) to JSON ready to be consumed by the client API @param mixed $data Data to serialize @return string JSON representation of data
entailment
protected function formatDataObject(DataObject $dataObject) { // api access control if (!RESTfulAPI::api_access_control($dataObject, 'GET')) { return null; } if (method_exists($dataObject, 'onBeforeSerialize')) { $dataObject->onBeforeSerialize(); } ...
Format a DataObject keys and values ready to be turned into JSON @param DataObject $dataObject The data object to format @return array|null The formatted array map representation of the DataObject or null is permission denied
entailment
protected function formatDataList(DataList $dataList) { $formattedDataListMap = array(); foreach ($dataList as $dataObject) { $formattedDataObjectMap = $this->formatDataObject($dataObject); if ($formattedDataObjectMap) { array_push($formattedDataListMap, $for...
Format a DataList into a formatted array ready to be turned into JSON @param DataList $dataList The DataList to format @return array The formatted array representation of the DataList
entailment
protected function getEmbedData(DataObject $record, $relationName) { if ($record->hasMethod($relationName)) { $relationData = $record->$relationName(); if ($relationData instanceof RelationList) { return $this->formatDataList($relationData); } else { ...
Returns a DataObject relation's data formatted and ready to embed. @param DataObject $record The DataObject to get the data from @param string $relationName The name of the relation @return array|null Formatted DataObject or RelationList ready to embed or null if nothing to embed
entailment
protected function isEmbeddable($model, $relation) { if (array_key_exists($model, $this->embeddedRecords)) { return is_array($this->embeddedRecords[$model]) && in_array($relation, $this->embeddedRecords[$model]); } return false; }
Checks if a speicific model's relation should have its records embedded. @param string $model Model's classname @param string $relation Relation name @return boolean Trus if the relation should be embedded
entailment
protected function setQuery($query) { if (is_array($query)) { $query = http_build_query($query); } if (!$this->isValidQuery($query)) { throw new \InvalidArgumentException("Invalid query '$query'"); } $this->query = (string)$query; ...
Set the query @param string|array $query
entailment
public function register() { /** @noinspection PhpUndefinedFieldInspection */ $this->app->singleton('onesignal', function ($app) { /** @noinspection PhpUndefinedFunctionInspection */ /** @noinspection PhpUndefinedFunctionInspection */ /** @noinspection PhpUndefine...
Register the application services. @return void
entailment
public function getMethod() { if (!isset($this->method)) { $this->method = $this->determineMethod(); } return $this->method; }
Retrieves the HTTP method of the request. @return string Returns the request method.
entailment
protected function assertMethod($method) { if (!is_string($method)) { $type = (is_object($method) ? get_class($method) . ' ' : '') . gettype($method); throw new \InvalidArgumentException("Method should be a string, not a $type"); } if (preg_match('/[^a-z\-]/i...
Assert method is valid @param string $method @throws \InvalidArgumentException
entailment
public function withMethod($method) { $this->assertMethod($method); $request = $this->copy(); $request->method = $method; return $request; }
Return an instance with the provided HTTP method. @param string $method Case-sensitive method. @return static @throws \InvalidArgumentException for invalid HTTP methods.
entailment
protected function header($string, $replace = true, $http_response_code = null) { header($string, $replace, $http_response_code); }
Wrapper for `header` function @link http://php.net/manual/en/function.header.php @codeCoverageIgnore @param string $string @param boolean $replace @param int $http_response_code
entailment
protected function assertStatusCode($code) { if (!is_int($code) && !(is_string($code) && ctype_digit($code))) { throw new \InvalidArgumentException("Response code must be integer"); } if ($code < 100 || $code > 999) { throw new \InvalidArgumentException("Resp...
Assert that the status code is valid (100..999) @param string $code @throws \InvalidArgumentException
entailment
protected function setStatus($code, $reasonPhrase) { $this->assertStatusCode($code); $this->assertReasonPhrase($reasonPhrase); if (empty($reasonPhrase) && array_key_exists($code, $this->defaultStatuses)) { $reasonPhrase = $this->defaultStatuses[$code]; } ...
Set the specified status code and reason phrase. @param int $code @param string $reasonPhrase
entailment
public function withStatus($code, $reasonPhrase = '') { $status = clone $this; $status->setStatus($code, $reasonPhrase); return $status; }
Create a new response status object with the specified code and phrase. @param int $code @param string $reasonPhrase @return ResponseStatus
entailment
public function requireDefaultRecords() { // Readers $readersGroup = DataObject::get(Group::class)->filter(array( 'Code' => 'restfulapi-readers', )); if (!$readersGroup->count()) { $readerGroup = new Group(); $readerGroup->Code = 'restfulapi-reade...
Create the default Groups and add default admin to admin group
entailment
public function loadAssets($table) { if (TL_MODE !== 'BE' || !is_array($GLOBALS['TL_DCA'][$table]['fields'])) { return; } foreach ($GLOBALS['TL_DCA'][$table]['fields'] as $field) { if ($field['inputType'] === 'fineUploader') { FineUploaderWidget::incl...
Load the widget assets if they are needed. Load them here so the widget in subpalette can work as well. @param string $table
entailment
public function validateUpload() { $varInput = parent::validateUpload(); // Check image size if (($arrImageSize = @getimagesize(TL_ROOT . '/' . $varInput)) !== false) { // Image exceeds maximum image width if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['imageWidth']) ...
Validate the upload @return string
entailment
protected function validator($varInput) { $varReturn = parent::validator($varInput); $arrReturn = array_filter((array) $varReturn); $intCount = 0; foreach ($arrReturn as $varFile) { // Get the file model if (\Validator::isUuid($varFile)) { $ob...
Store the file information in the session @param mixed @return mixed
entailment
public function parse($arrAttributes=null) { if (!$this->blnValuesPrepared) { $arrSet = array(); $arrValues = array(); $arrUuids = array(); $arrTemp = array(); if (!empty($this->varValue)) { // Can be an array $this->varValue = (a...
Generate the widget and return it as string @param array @return string
entailment
protected function mapUriPartsFromServerParams(array $params) { $parts = []; $map = [ 'PHP_AUTH_USER' => 'user', 'PHP_AUTH_PWD' => 'password', 'HTTP_HOST' => 'host', 'SERVER_PORT' => 'port', 'REQUEST_URI' => 'path', 'QU...
Map server params for URI @param array $params @return array
entailment
protected function determineUri() { $params = $this->getServerParams(); $parts = $this->mapUriPartsFromServerParams($params); if ( isset($params['SERVER_PROTOCOL']) && \Jasny\str_starts_with(strtoupper($params['SERVER_PROTOCOL']), 'HTTP/') ) ...
Determine the URI base on the server parameters @return string
entailment
public function getUri() { if (!isset($this->uri)) { $this->uri = $this->determineUri(); } return $this->uri; }
Retrieves the URI instance. This method MUST return a UriInterface instance. @see http://tools.ietf.org/html/rfc3986#section-4.3 @return UriInterface Returns a UriInterface instance representing the URI of the request.
entailment
public function withUri(UriInterface $uri, $preserveHost = false) { $request = $this->copy(); $request->uri = $uri; if (!$preserveHost) { $request = $request->withHeader('Host', $request->uri->getHost()); } return $request; }
Returns an instance with the provided URI. @see http://tools.ietf.org/html/rfc3986#section-4.3 @param UriInterface $uri New request URI to use. @param boolean $preserveHost Preserve the original state of the Host header. @return static
entailment
public function getParser() { if (true === empty($this->parser)) { $typeParserClassName = sprintf('\ReadmeGen\Vcs\Type\%s', ucfirst($this->config['vcs'])); if (false === class_exists($typeParserClassName)) { throw new \InvalidArgumentException(sprintf('Class "%s" doe...
Returns the parser. @return Parser @throws \InvalidArgumentException When the VCS parser class does not exist.
entailment
public function extractMessages(array $log = null) { if (true === empty($log)) { return array(); } $this->extractor->setMessageGroups($this->config['message_groups']); return $this->extractor->setLog($log) ->extract(); }
Returns messages extracted from the log. @param array $log @return array
entailment
public function getDecoratedMessages(array $log = null) { if (true === empty($log)) { return array(); } return $this->decorator->setLog($log) ->setIssueTrackerUrlPattern($this->config['issue_tracker_pattern']) ->decorate(); }
Returns decorated log messages. @param array $log @return array|Output\Format\FormatInterface
entailment
public function get($path, array $sourceConfig = null) { $config = Yaml::parse($this->getFileContent($path)); if (false === empty($sourceConfig)) { return array_replace_recursive($sourceConfig, $config); } return $config; }
Returns the config as an array. @param string $path Path to the file. @param array $sourceConfig Config array the result should be merged with. @return array @throws \Symfony\Component\Yaml\Exception\ParseException When a parse error occurs.
entailment
protected function getFileContent($path) { if (false === file_exists($path)) { throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $path)); } return file_get_contents($path); }
Returns the file's contents. @param string $path Path to file. @return string @throws \InvalidArgumentException When the file does not exist.
entailment
protected function setUriParts(array $parts) { foreach ($parts as $key => $value) { if (!method_exists($this, "set$key")) { continue; } $this->{"set$key"}($value); } }
Set the URI parts @param array $parts
entailment
protected function buildUri(array $parts) { $uri = ($parts['scheme'] ? "{$parts['scheme']}:" : '') . ($parts['user'] || $parts['host'] ? '//' : '') . ($parts['user'] ? "{$parts['user']}" : '') . ($parts['user'] && $parts['pass'] ? ":{$parts['pass']}" : '')...
Build a uri from all the parts @param array $parts @return type
entailment
protected function determineRequestTarget() { $params = $this->getServerParams(); return isset($params['REQUEST_URI']) ? $params['REQUEST_URI'] : (isset($params['REQUEST_METHOD']) && $params['REQUEST_METHOD'] === 'OPTIONS' ? '*' : '/'); }
Determine the request target based on the server params @return string
entailment
public function getRequestTarget() { if (!isset($this->requestTarget)) { $this->requestTarget = $this->determineRequestTarget(); } return $this->requestTarget; }
Retrieves the message's request target. Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()). In most cases, this will be the origin-form of the composed URI, unless a value was provide...
entailment
protected function assertRequestTarget($requestTarget) { if (!is_string($requestTarget)) { $type = (is_object($requestTarget) ? get_class($requestTarget) . ' ' : '') . gettype($requestTarget); throw new \InvalidArgumentException("Request target should be a string, not a $type"); ...
Assert that the request target is a string @param string $requestTarget @throws \InvalidArgumentException
entailment
public function withRequestTarget($requestTarget) { $this->assertRequestTarget($requestTarget); $request = $this->copy(); $request->requestTarget = $requestTarget; return $request; }
Return an instance with the specific request-target. @see http://tools.ietf.org/html/rfc7230#section-5.3 (for the various request-target forms allowed in request messages) @param string $requestTarget @return static @throws \InvalidArgumentException if $requestTarget is not a string
entailment
protected function extractForFromForwardedHeader($forwarded) { $ips = []; $parts = array_map('trim', explode(',', $forwarded)); foreach ($parts as $part) { list($key, $value) = explode('=', $part, 2) + [1 => null]; if ($key === 'for') { ...
Extract the `for` part from the Forwarded header @param string $forwarded @return string
entailment
protected function getForwardedIp(ServerRequestInterface $request, $ip) { $ips = [$ip]; $forwardedFor = $this->splitIps($request->getHeaderLine('X-Forwarded-For')); $forwarded = $this->extractForFromForwardedHeader($request->getHeaderLine('Forwarded')); $clientIp = $this->sp...
Get the forwarded ip @param ServerRequestInterface $request @param string $ip Connected IP @return string|null
entailment
protected function getTrustedForwardedIp(array $ips) { if (is_string($this->trustedProxy)) { foreach ($ips as $ip) { if (\Jasny\ip_in_cidr($ip, $this->trustedProxy)) { continue; } return $ip; } } ...
Select an IP which is within the list of trusted ips @param array $ips @return string
entailment
protected static function _cache($type, $key, $value = false) { $key = '_' . $key; $type = '_' . $type; if ($value !== false) { self::$_cache[$type][$key] = $value; return $value; } if (!isset(self::$_cache[$type][$key])) { return false; ...
Cache inflected values, and return if already available @param string $type Inflection type @param string $key Original value @param string $value Inflected value @return string Inflected value, from cache
entailment
public static function rules($type, $rules, $reset = false) { $var = '_' . $type; switch ($type) { case 'transliteration': if ($reset) { self::$_transliteration = $rules; } else { self::$_transliteration = $rules + ...
Adds custom inflection $rules, of either 'plural', 'singular' or 'transliteration' $type. ### Usage: {{{ Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables')); Inflector::rules('plural', array( 'rules' => array('/^(inflect)ors$/i' => '\1ables'), 'uninflected' => array('dontinflectme'), 'irregular' => arr...
entailment
public static function pluralize($word) { if (isset(self::$_cache['pluralize'][$word])) { return self::$_cache['pluralize'][$word]; } if (!isset(self::$_plural['merged']['irregular'])) { self::$_plural['merged']['irregular'] = self::$_plural['irregular']; } ...
Return $word in plural form. @param string $word Word in singular @return string Word in plural @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::pluralize
entailment
public static function camelize($lowerCaseAndUnderscoredWord) { if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) { $result = str_replace(' ', '', Inflector::humanize($lowerCaseAndUnderscoredWord)); self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $re...
Returns the given lower_case_and_underscored_word as a CamelCased word. @param string $lowerCaseAndUnderscoredWord Word to camelize @return string Camelized word. LikeThis. @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::camelize
entailment
public static function underscore($camelCasedWord) { if (!($result = self::_cache(__FUNCTION__, $camelCasedWord))) { $result = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord)); self::_cache(__FUNCTION__, $camelCasedWord, $result); } return $resul...
Returns the given camelCasedWord as an underscored_word. @param string $camelCasedWord Camel-cased word to be "underscorized" @return string Underscore-syntaxed version of the $camelCasedWord @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::underscore
entailment
public static function humanize($lowerCaseAndUnderscoredWord) { if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) { $result = ucwords(str_replace('_', ' ', $lowerCaseAndUnderscoredWord)); self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result); ...
Returns the given underscored_word_group as a Human Readable Word Group. (Underscores are replaced by spaces and capitalized following words.) @param string $lowerCaseAndUnderscoredWord String to be made more readable @return string Human-readable string @link http://book.cakephp.org/2.0/en/core-utility-libraries/infl...
entailment
public static function tableize($className) { if (!($result = self::_cache(__FUNCTION__, $className))) { $result = Inflector::pluralize(Inflector::underscore($className)); self::_cache(__FUNCTION__, $className, $result); } return $result; }
Returns corresponding table name for given model $className. ("people" for the model class "Person"). @param string $className Name of class to get database table name for @return string Name of the database table for given class @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::tab...
entailment
public static function classify($tableName) { if (!($result = self::_cache(__FUNCTION__, $tableName))) { $result = Inflector::camelize(Inflector::singularize($tableName)); self::_cache(__FUNCTION__, $tableName, $result); } return $result; }
Returns Cake model class name ("Person" for the database table "people".) for given database table. @param string $tableName Name of database table to get class name for @return string Class name @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::classify
entailment
public static function variable($string) { if (!($result = self::_cache(__FUNCTION__, $string))) { $camelized = Inflector::camelize(Inflector::underscore($string)); $replace = strtolower(substr($camelized, 0, 1)); $result = preg_replace('/\\w/', $replace, $camelized, 1); ...
Returns camelBacked version of an underscored string. @param string $string @return string in variable form @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::variable
entailment
public static function slug($string, $replacement = '_') { $quotedReplacement = preg_quote($replacement, '/'); $merge = array( '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ', '/\\s+/' => $replacement, sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quoted...
Returns a string with all spaces converted to underscores (by default), accented characters converted to non-accented characters, and non word characters removed. @param string $string the string you want to slug @param string $replacement will replace keys in map @return string @link http://book.cakephp.org/2.0/en/co...
entailment
protected function isValidDomain($hostname) { return preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $hostname) && preg_match("/^.{1,253}$/", $hostname) && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $hostname) && !preg_match("/^\d{0,3}\.\d{0,3}\.\d{0...
Check if the hostname is valid a valid domain name according to RFC 3986 and RFC 1123 @param string $hostname @return boolean
entailment
protected function setHost($host) { $host = strtolower($host); if ($host !== '' && !$this->isValidDomain($host) && !$this->isValidIpv4($host) && !$this->isValidIpv6($host)) { throw new \InvalidArgumentException("Invalid hostname '$host'"); } $this->host ...
Set the host @param string $host
entailment
public function dispatchAjaxRequest($strAction, \DataContainer $dc) { switch ($strAction) { // Upload the file /** @noinspection PhpMissingBreakStatementInspection */ case 'fineuploader_upload': $arrData['strTable'] = $dc->table; $arrData['...
Dispatch an AJAX request @param string @param \DataContainer
entailment
public function executeAjaxActions($arrData) { \Input::setGet('no_ajax', 1); // Avoid circular reference switch (\Input::post('action')) { // Upload the file case 'fineuploader_upload': $arrData['name'] = \Input::post('name'); /** @var FormFi...
Execute AJAX actions in front end @param array
entailment