repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
evias/nem-php
src/Handlers/GuzzleRequestHandler.php
GuzzleRequestHandler.get
public function get($uri, $bodyJSON = null, array $options = [], $usePromises = false) { $headers = []; if (!empty($options["headers"])) $headers = $options["headers"]; // overwrite mandatory headers if (is_string($bodyJSON)){ $headers["Content-Length"] = strlen($bodyJSON); } // get generic headers $headers = $this->normalizeHeaders($headers); // prepare guzzle request options $options = array_merge($options, [ "body" => $bodyJSON ?: "", "headers" => $headers, ]); $client = new Client(["base_uri" => $this->getBaseUrl()]); $request = new Request("GET", $uri, $options); if (! $usePromises) // return the response object when the request is completed. // this behaviour handles the request synchronously. return $client->send($request); return $this->promiseResponse($client, $request, $options); }
php
public function get($uri, $bodyJSON = null, array $options = [], $usePromises = false) { $headers = []; if (!empty($options["headers"])) $headers = $options["headers"]; // overwrite mandatory headers if (is_string($bodyJSON)){ $headers["Content-Length"] = strlen($bodyJSON); } // get generic headers $headers = $this->normalizeHeaders($headers); // prepare guzzle request options $options = array_merge($options, [ "body" => $bodyJSON ?: "", "headers" => $headers, ]); $client = new Client(["base_uri" => $this->getBaseUrl()]); $request = new Request("GET", $uri, $options); if (! $usePromises) // return the response object when the request is completed. // this behaviour handles the request synchronously. return $client->send($request); return $this->promiseResponse($client, $request, $options); }
[ "public", "function", "get", "(", "$", "uri", ",", "$", "bodyJSON", "=", "null", ",", "array", "$", "options", "=", "[", "]", ",", "$", "usePromises", "=", "false", ")", "{", "$", "headers", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$"...
This method triggers a GET request to the given URI using the GuzzleHttp client. Default behaviour disables Promises Features. Promises Features - success callback can be configured with $options["onSuccess"], a ResponseInterface object will be passed to this callable when the Request Completes. - error callback can be configured with $options["onError"], a RequestException object will be passed to this callable when the Request encounters an error @see \NEM\Contracts\RequestHandler @param string $uri @param string $bodyJSON @param array $options can contain "headers" array, "onSuccess" callable, "onError" callable and any other GuzzleHTTP request options. @param boolean $usePromises @return [type]
[ "This", "method", "triggers", "a", "GET", "request", "to", "the", "given", "URI", "using", "the", "GuzzleHttp", "client", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Handlers/GuzzleRequestHandler.php#L178-L206
evias/nem-php
src/Handlers/GuzzleRequestHandler.php
GuzzleRequestHandler.post
public function post($uri, $bodyJSON, array $options = [], $usePromises = false) { $headers = []; if (!empty($options["headers"])) $headers = $options["headers"]; // overwrite mandatory headers if (is_string($bodyJSON)){ $headers["Content-Length"] = strlen($bodyJSON); } // get generic headers $headers = $this->normalizeHeaders($headers); // prepare guzzle request options $options = [ "headers" => $headers, "json" => $bodyJSON, ]; $client = new Client(["base_uri" => $this->getBaseUrl()]); if (! $usePromises) { // return the response object when the request is completed. // this behaviour handles the request synchronously. return $client->request('POST', $uri, $options); //XXX return $response->getBody()->getContents(); } return $this->promiseResponse($client, $request, $options); }
php
public function post($uri, $bodyJSON, array $options = [], $usePromises = false) { $headers = []; if (!empty($options["headers"])) $headers = $options["headers"]; // overwrite mandatory headers if (is_string($bodyJSON)){ $headers["Content-Length"] = strlen($bodyJSON); } // get generic headers $headers = $this->normalizeHeaders($headers); // prepare guzzle request options $options = [ "headers" => $headers, "json" => $bodyJSON, ]; $client = new Client(["base_uri" => $this->getBaseUrl()]); if (! $usePromises) { // return the response object when the request is completed. // this behaviour handles the request synchronously. return $client->request('POST', $uri, $options); //XXX return $response->getBody()->getContents(); } return $this->promiseResponse($client, $request, $options); }
[ "public", "function", "post", "(", "$", "uri", ",", "$", "bodyJSON", ",", "array", "$", "options", "=", "[", "]", ",", "$", "usePromises", "=", "false", ")", "{", "$", "headers", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "options", ...
This method triggers a POST request to the given URI using the GuzzleHttp client. @todo Implement POST Promises features @see \NEM\Contracts\RequestHandler @param string $uri @param string $bodyJSON @param array $options @param boolean $synchronous @return [type]
[ "This", "method", "triggers", "a", "POST", "request", "to", "the", "given", "URI", "using", "the", "GuzzleHttp", "client", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Handlers/GuzzleRequestHandler.php#L220-L250
evias/nem-php
src/Models/TimeWindow.php
TimeWindow.toNIS
public function toNIS() { if ($this->getAttribute("timeStamp")) { // from NIS timestamp $ts = $this->getAttribute("timeStamp"); if (! empty($ts)) return $ts; return $this->diff("now", static::$nemesis); } else { // from UTC timestamp $utc = $this->getAttribute("utc"); return $this->diff($utc, static::$nemesis); } }
php
public function toNIS() { if ($this->getAttribute("timeStamp")) { // from NIS timestamp $ts = $this->getAttribute("timeStamp"); if (! empty($ts)) return $ts; return $this->diff("now", static::$nemesis); } else { // from UTC timestamp $utc = $this->getAttribute("utc"); return $this->diff($utc, static::$nemesis); } }
[ "public", "function", "toNIS", "(", ")", "{", "if", "(", "$", "this", "->", "getAttribute", "(", "\"timeStamp\"", ")", ")", "{", "// from NIS timestamp", "$", "ts", "=", "$", "this", "->", "getAttribute", "(", "\"timeStamp\"", ")", ";", "if", "(", "!", ...
Returns timestamp since NEM Nemesis block. The calculated NEM Time is equal to the *Count of Seconds* between the `timeStamp` attribute and the NEM Genesis Block Time. @return int The NEM NIS compliant timestamp.
[ "Returns", "timestamp", "since", "NEM", "Nemesis", "block", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/TimeWindow.php#L89-L104
evias/nem-php
src/Models/TimeWindow.php
TimeWindow.toUTC
public function toUTC() { $ts = time(); if ($this->getAttribute("timeStamp")) { // from NIS to UTC $ts = (int) $this->getAttribute("timeStamp"); return self::$nemesis + (1000 * $ts); } else { // has UTC return $this->getAttribute("utc"); } }
php
public function toUTC() { $ts = time(); if ($this->getAttribute("timeStamp")) { // from NIS to UTC $ts = (int) $this->getAttribute("timeStamp"); return self::$nemesis + (1000 * $ts); } else { // has UTC return $this->getAttribute("utc"); } }
[ "public", "function", "toUTC", "(", ")", "{", "$", "ts", "=", "time", "(", ")", ";", "if", "(", "$", "this", "->", "getAttribute", "(", "\"timeStamp\"", ")", ")", "{", "// from NIS to UTC", "$", "ts", "=", "(", "int", ")", "$", "this", "->", "getAt...
Returns timestamp in UTC format. @return int The UTC format timestamp
[ "Returns", "timestamp", "in", "UTC", "format", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/TimeWindow.php#L111-L123
evias/nem-php
src/Models/TimeWindow.php
TimeWindow.diff
public function diff($a = "now", $b = null) { $start = $a ?: "now"; $until = $b ?: static::$nemesis; $startTime = is_numeric($start) ? $start : @strtotime($start); $endTime = is_numeric($until) ? $until : @strtotime($until); $dtStart = (new DateTime("@$startTime", new DateTimeZone("UTC")))->getTimestamp(); $dtUntil = (new DateTime("@$endTime", new DateTimeZone("UTC")))->getTimestamp(); // never return negative timestamps return $dtUntil > $dtStart ? $dtUntil - $dtStart : $dtStart - $dtUntil; }
php
public function diff($a = "now", $b = null) { $start = $a ?: "now"; $until = $b ?: static::$nemesis; $startTime = is_numeric($start) ? $start : @strtotime($start); $endTime = is_numeric($until) ? $until : @strtotime($until); $dtStart = (new DateTime("@$startTime", new DateTimeZone("UTC")))->getTimestamp(); $dtUntil = (new DateTime("@$endTime", new DateTimeZone("UTC")))->getTimestamp(); // never return negative timestamps return $dtUntil > $dtStart ? $dtUntil - $dtStart : $dtStart - $dtUntil; }
[ "public", "function", "diff", "(", "$", "a", "=", "\"now\"", ",", "$", "b", "=", "null", ")", "{", "$", "start", "=", "$", "a", "?", ":", "\"now\"", ";", "$", "until", "=", "$", "b", "?", ":", "static", "::", "$", "nemesis", ";", "$", "startT...
The diff() method lets you return the number of seconds difference between two timestamps. @param null|integer|string $a The (optional) lvalue (Default is "now"). @param null|integer|string $b The (optional) rvalue (Default is the UTC time of the NEM genesis block). @return integer Number of seconds between `a` and `b` timestamps.
[ "The", "diff", "()", "method", "lets", "you", "return", "the", "number", "of", "seconds", "difference", "between", "two", "timestamps", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/TimeWindow.php#L133-L147
evias/nem-php
src/Infrastructure/Service.php
Service.getPath
public function getPath($uri, array $params, $withQuery = true) { $cleanUrl = trim($this->getBaseUrl(), "/ "); $cleanUri = trim($uri, "/ "); if ($withQuery === false || empty($params)) return sprintf("%s/%s", $this->getBaseUrl(), $cleanUri); // build HTTP query for GET request $query = http_build_query($params); return sprintf("/%s/%s?%s", $cleanUrl, $cleanUri, $query); }
php
public function getPath($uri, array $params, $withQuery = true) { $cleanUrl = trim($this->getBaseUrl(), "/ "); $cleanUri = trim($uri, "/ "); if ($withQuery === false || empty($params)) return sprintf("%s/%s", $this->getBaseUrl(), $cleanUri); // build HTTP query for GET request $query = http_build_query($params); return sprintf("/%s/%s?%s", $cleanUrl, $cleanUri, $query); }
[ "public", "function", "getPath", "(", "$", "uri", ",", "array", "$", "params", ",", "$", "withQuery", "=", "true", ")", "{", "$", "cleanUrl", "=", "trim", "(", "$", "this", "->", "getBaseUrl", "(", ")", ",", "\"/ \"", ")", ";", "$", "cleanUri", "="...
Helper for creating HTTP request full paths. @param string $uri @param array $params @param boolean $withQuery @return string
[ "Helper", "for", "creating", "HTTP", "request", "full", "paths", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Infrastructure/Service.php#L93-L104
evias/nem-php
src/Mosaics/Registry.php
Registry.getDefinition
static public function getDefinition($mosaic) { // read the mosaic's fully qualified name if ($mosaic instanceof Mosaic) { $fqn = $mosaic->getFQN(); } elseif ($mosaic instanceof MosaicAttachment) { $fqn = $mosaic->mosaicId()->getFQN(); } elseif (is_string($mosaic)) { $fqn = $mosaic; } else { throw new InvalidArgumentException("Unrecognized `mosaic` parameter to \\NEM\\Models\\Mosaics\\Registry::getDefinition()."); } $preconfigClass = self::morphClass($fqn); if (false !== $preconfigClass && class_exists($preconfigClass)) { // Pre-Configured mosaic definition found return new $preconfigClass(); } // no pre-configured mosaic definition class found, use NIS // Web service to read mosaic definition. return false; }
php
static public function getDefinition($mosaic) { // read the mosaic's fully qualified name if ($mosaic instanceof Mosaic) { $fqn = $mosaic->getFQN(); } elseif ($mosaic instanceof MosaicAttachment) { $fqn = $mosaic->mosaicId()->getFQN(); } elseif (is_string($mosaic)) { $fqn = $mosaic; } else { throw new InvalidArgumentException("Unrecognized `mosaic` parameter to \\NEM\\Models\\Mosaics\\Registry::getDefinition()."); } $preconfigClass = self::morphClass($fqn); if (false !== $preconfigClass && class_exists($preconfigClass)) { // Pre-Configured mosaic definition found return new $preconfigClass(); } // no pre-configured mosaic definition class found, use NIS // Web service to read mosaic definition. return false; }
[ "static", "public", "function", "getDefinition", "(", "$", "mosaic", ")", "{", "// read the mosaic's fully qualified name", "if", "(", "$", "mosaic", "instanceof", "Mosaic", ")", "{", "$", "fqn", "=", "$", "mosaic", "->", "getFQN", "(", ")", ";", "}", "elsei...
Load a pre-configured mosaic definition or fetch it using the Infrastructure service for Mosaics. @param \NEM\Models\Mosaic|\NEM\Models\MosaicAttachment|string $mosaic The mosaic object or name for which to get the definition. @param string|integer $network Default is mainnet (104), testnet is -104 (0x98) and mijin is 96 (0x60) @return \NEM\Models\MosaicDefinition @throws \InvalidArgumentException On invalid `mosaic` parameter.
[ "Load", "a", "pre", "-", "configured", "mosaic", "definition", "or", "fetch", "it", "using", "the", "Infrastructure", "service", "for", "Mosaics", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Registry.php#L54-L80
evias/nem-php
src/Mosaics/Registry.php
Registry.morphClass
static public function morphClass($fqn) { $namespace = "\\NEM\\Mosaics"; $classPath = []; // each namespace/sub-namespace has its own folder if ((bool) preg_match("/([^:]+):([^:]+)$/", $fqn, $classPath)) { $nsParts = explode(".", $classPath[1]); // $1 is namespace (before semi-colon ':') $className = ucfirst($classPath[2]); // $2 is mosaic name (after semi-colon ':') // format class name by mosaic fully qualified name. /** * @example FQN is `evias.sdk:nem-php`, this will be * represented in a PSR-4 class scheme with the following path: * * \NEM\Mosaics\Evias\Sdk\NemPhp.php */ $transReg = "/[^a-zA-Z0-9]/"; // format class path $classPath = array_map(function($item) use ($transReg) { // transformer for PSR-4 vali^ class/namespace format. $norm = preg_replace($transReg, "_", $item); $upper = ucwords(str_replace("_", " ", strtolower($norm))); return str_replace(" ", "", $upper); }, array_merge($nsParts, [$className])); $preconfigured = $namespace . "\\" . implode("\\", $classPath); return $preconfigured; } return false; }
php
static public function morphClass($fqn) { $namespace = "\\NEM\\Mosaics"; $classPath = []; // each namespace/sub-namespace has its own folder if ((bool) preg_match("/([^:]+):([^:]+)$/", $fqn, $classPath)) { $nsParts = explode(".", $classPath[1]); // $1 is namespace (before semi-colon ':') $className = ucfirst($classPath[2]); // $2 is mosaic name (after semi-colon ':') // format class name by mosaic fully qualified name. /** * @example FQN is `evias.sdk:nem-php`, this will be * represented in a PSR-4 class scheme with the following path: * * \NEM\Mosaics\Evias\Sdk\NemPhp.php */ $transReg = "/[^a-zA-Z0-9]/"; // format class path $classPath = array_map(function($item) use ($transReg) { // transformer for PSR-4 vali^ class/namespace format. $norm = preg_replace($transReg, "_", $item); $upper = ucwords(str_replace("_", " ", strtolower($norm))); return str_replace(" ", "", $upper); }, array_merge($nsParts, [$className])); $preconfigured = $namespace . "\\" . implode("\\", $classPath); return $preconfigured; } return false; }
[ "static", "public", "function", "morphClass", "(", "$", "fqn", ")", "{", "$", "namespace", "=", "\"\\\\NEM\\\\Mosaics\"", ";", "$", "classPath", "=", "[", "]", ";", "// each namespace/sub-namespace has its own folder", "if", "(", "(", "bool", ")", "preg_match", ...
Helper to format a fully qualified mosaic name into a PHP class namespaced. Some of the mosaics present on the NEM network will be represented by pre-configured classes in the SDK as such to give an idea on how to pre-configure mosaic definition and also to allow reducing the amount of data that needs to be fetched over the network. @param string $fqn @return string @throws \InvalidArgumentException On invalid mosaic fully qualified name.
[ "Helper", "to", "format", "a", "fully", "qualified", "mosaic", "name", "into", "a", "PHP", "class", "namespaced", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Registry.php#L95-L130
evias/nem-php
src/Models/MosaicProperties.php
MosaicProperties.toDTO
public function toDTO() { // sort properties lexicographically (see toDTO() overload) $sorted = $this->sortBy("name"); $props = []; $names = [ "divisibility" => 0, "initialSupply" => 1, "supplyMutable" => 2, "transferable" => 3, ]; $ix = 0; foreach ($sorted->all() as $item) { // discover if (is_array($item)) { $item = new MosaicProperty($item); } $name = $item->name; $value = (string) $item->value; if (in_array($name, ["supplyMutable", "transferable"])) { $value = ($item->value !== "false" && (bool) $item->value) ? "true" : "false"; } // update mosaic property value. $ix = $names[$name]; $props[$ix] = [ "name" => $name, "value" => $value, ]; } return $props; }
php
public function toDTO() { // sort properties lexicographically (see toDTO() overload) $sorted = $this->sortBy("name"); $props = []; $names = [ "divisibility" => 0, "initialSupply" => 1, "supplyMutable" => 2, "transferable" => 3, ]; $ix = 0; foreach ($sorted->all() as $item) { // discover if (is_array($item)) { $item = new MosaicProperty($item); } $name = $item->name; $value = (string) $item->value; if (in_array($name, ["supplyMutable", "transferable"])) { $value = ($item->value !== "false" && (bool) $item->value) ? "true" : "false"; } // update mosaic property value. $ix = $names[$name]; $props[$ix] = [ "name" => $name, "value" => $value, ]; } return $props; }
[ "public", "function", "toDTO", "(", ")", "{", "// sort properties lexicographically (see toDTO() overload)", "$", "sorted", "=", "$", "this", "->", "sortBy", "(", "\"name\"", ")", ";", "$", "props", "=", "[", "]", ";", "$", "names", "=", "[", "\"divisibility\"...
Overload collection toDTO() to make sure to *always use the same sorting*. Mosaic Properties are ordered as described below: - divisibility - initialSupply - supplyMutable - transferable The order of properties is not important for NIS but gives us consistency in the way we can use mosaic properties. @see https://bob.nem.ninja/docs/#mosaicProperties NIS MosaicProperties Documentation @return array Array representation of the collection objects *compliable* with NIS definition.
[ "Overload", "collection", "toDTO", "()", "to", "make", "sure", "to", "*", "always", "use", "the", "same", "sorting", "*", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicProperties.php#L52-L88
evias/nem-php
src/Models/MosaicProperties.php
MosaicProperties.serialize
public function serialize($parameters = null) { $nisPropertiesData = $this->toDTO(); $cntProps = count($nisPropertiesData); // shortcuts $serializer = $this->getSerializer(); // serialize attachments // prepend size on 4 bytes $prependSize = $serializer->serializeInt($cntProps); // prepare objects $props = [ new MosaicProperty(["name" => "divisibility", "value" => $nisPropertiesData[0]["value"]]), new MosaicProperty(["name" => "initialSupply", "value" => $nisPropertiesData[1]["value"]]), new MosaicProperty(["name" => "supplyMutable", "value" => $nisPropertiesData[2]["value"]]), new MosaicProperty(["name" => "transferable", "value" => $nisPropertiesData[3]["value"]]), ]; // serialize properties in strict order $uint8_divisibility = $props[0]->serialize(); $uint8_supply = $props[1]->serialize(); $uint8_mutable = $props[2]->serialize(); $uint8_transfer = $props[3]->serialize(); // concatenate uint8 representation $output = array_merge( $prependSize, $uint8_divisibility, $uint8_supply, $uint8_mutable, $uint8_transfer ); // no need to use the aggregator, we dynamically aggregated // our collection data and prepended the size on 4 bytes. return $output; }
php
public function serialize($parameters = null) { $nisPropertiesData = $this->toDTO(); $cntProps = count($nisPropertiesData); // shortcuts $serializer = $this->getSerializer(); // serialize attachments // prepend size on 4 bytes $prependSize = $serializer->serializeInt($cntProps); // prepare objects $props = [ new MosaicProperty(["name" => "divisibility", "value" => $nisPropertiesData[0]["value"]]), new MosaicProperty(["name" => "initialSupply", "value" => $nisPropertiesData[1]["value"]]), new MosaicProperty(["name" => "supplyMutable", "value" => $nisPropertiesData[2]["value"]]), new MosaicProperty(["name" => "transferable", "value" => $nisPropertiesData[3]["value"]]), ]; // serialize properties in strict order $uint8_divisibility = $props[0]->serialize(); $uint8_supply = $props[1]->serialize(); $uint8_mutable = $props[2]->serialize(); $uint8_transfer = $props[3]->serialize(); // concatenate uint8 representation $output = array_merge( $prependSize, $uint8_divisibility, $uint8_supply, $uint8_mutable, $uint8_transfer ); // no need to use the aggregator, we dynamically aggregated // our collection data and prepended the size on 4 bytes. return $output; }
[ "public", "function", "serialize", "(", "$", "parameters", "=", "null", ")", "{", "$", "nisPropertiesData", "=", "$", "this", "->", "toDTO", "(", ")", ";", "$", "cntProps", "=", "count", "(", "$", "nisPropertiesData", ")", ";", "// shortcuts", "$", "seri...
Overload of the \NEM\Core\ModelCollection::serialize() method to provide with a specialization for *MosaicProperties Arrays* serialization. @see \NEM\Contracts\Serializable @param null|string $parameters non-null will return only the named sub-dtos. @return array Returns a byte-array with values in UInt8 representation.
[ "Overload", "of", "the", "\\", "NEM", "\\", "Core", "\\", "ModelCollection", "::", "serialize", "()", "method", "to", "provide", "with", "a", "specialization", "for", "*", "MosaicProperties", "Arrays", "*", "serialization", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicProperties.php#L98-L136
evias/nem-php
src/Models/MosaicProperties.php
MosaicProperties.getProperty
public function getProperty($name) { $propertiesNames = [ "divisibility" => 0, "initialSupply" => 1, "supplyMutable" => 2, "transferable" => 3, ]; if (! array_key_exists($name, $propertiesNames)) { throw new InvalidArgumentException("Mosaic property name '" . $name ."' is invalid. Must be one of 'divisibility', " . "'initialSupply', 'supplyMutable' or 'transferable'."); } // sort properties lexicographically (see toDTO() overload) $sorted = $this->sortBy("name"); $index = $propertiesNames[$name]; $prop = $sorted->get($index); if ($prop instanceof MosaicProperty) { return $prop->value; } return $prop["value"]; }
php
public function getProperty($name) { $propertiesNames = [ "divisibility" => 0, "initialSupply" => 1, "supplyMutable" => 2, "transferable" => 3, ]; if (! array_key_exists($name, $propertiesNames)) { throw new InvalidArgumentException("Mosaic property name '" . $name ."' is invalid. Must be one of 'divisibility', " . "'initialSupply', 'supplyMutable' or 'transferable'."); } // sort properties lexicographically (see toDTO() overload) $sorted = $this->sortBy("name"); $index = $propertiesNames[$name]; $prop = $sorted->get($index); if ($prop instanceof MosaicProperty) { return $prop->value; } return $prop["value"]; }
[ "public", "function", "getProperty", "(", "$", "name", ")", "{", "$", "propertiesNames", "=", "[", "\"divisibility\"", "=>", "0", ",", "\"initialSupply\"", "=>", "1", ",", "\"supplyMutable\"", "=>", "2", ",", "\"transferable\"", "=>", "3", ",", "]", ";", "...
Helper to read a given `name` mosaic property name. @param string $name Mosaic property name. @return integer|boolean
[ "Helper", "to", "read", "a", "given", "name", "mosaic", "property", "name", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicProperties.php#L144-L168
evias/nem-php
src/Models/ModelCollection.php
ModelCollection.toDTO
public function toDTO() { $dtos = []; foreach ($this->all() as $ix => $item) { if ($item instanceof DataTransferObject) array_push($dtos, $item->toDTO()); else array_push($dtos, $item); } return $dtos; }
php
public function toDTO() { $dtos = []; foreach ($this->all() as $ix => $item) { if ($item instanceof DataTransferObject) array_push($dtos, $item->toDTO()); else array_push($dtos, $item); } return $dtos; }
[ "public", "function", "toDTO", "(", ")", "{", "$", "dtos", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "all", "(", ")", "as", "$", "ix", "=>", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "DataTransferObject", ")", "arr...
Generic helper to convert a Collection instance to a Data Transfer Object (array). This will make it easy to bridge implemented models to NEM *NIS compliant* objects. @see http://bob.nem.ninja/docs/ NIS API Documentation @return array Array representation of the collection objects *compliable* with NIS definition.
[ "Generic", "helper", "to", "convert", "a", "Collection", "instance", "to", "a", "Data", "Transfer", "Object", "(", "array", ")", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/ModelCollection.php#L69-L80
evias/nem-php
src/Models/ModelCollection.php
ModelCollection.serialize
public function serialize($parameters = null) { $json = json_encode($this->toDTO()); return $this->getSerializer()->serializeString($json); }
php
public function serialize($parameters = null) { $json = json_encode($this->toDTO()); return $this->getSerializer()->serializeString($json); }
[ "public", "function", "serialize", "(", "$", "parameters", "=", "null", ")", "{", "$", "json", "=", "json_encode", "(", "$", "this", "->", "toDTO", "(", ")", ")", ";", "return", "$", "this", "->", "getSerializer", "(", ")", "->", "serializeString", "("...
This method should return a *byte-array* with UInt8 representation of bytes for the said collection of objects. @see \NEM\Contracts\Serializable @param null|string $parameters non-null will return only the named sub-dtos. @return array Returns a byte-array with values in UInt8 representation.
[ "This", "method", "should", "return", "a", "*", "byte", "-", "array", "*", "with", "UInt8", "representation", "of", "bytes", "for", "the", "said", "collection", "of", "objects", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/ModelCollection.php#L91-L95
evias/nem-php
src/Models/ModelCollection.php
ModelCollection.paginate
public function paginate(ServiceInterface $service, $method, array $arguments = [], $field = "id", $pageSize = 25) { if (! method_exists($service, $method)) { throw new BadMethodCallException("Invalid method name '" . $method . "'. Not implemented in Service '" . get_class($service) . "'."); } $hasValues = []; $objects = []; $cntResults = 0; do { // forward service method call $items = call_user_func_array([$service, $method], $arguments); $cntResults = count($objects); $lastObj = end($objects); $dotObj = ArrayHelper::dot((array) $lastObj); $lastValue = $dotObj[$field]; if (in_array($lastValue, $hasValues)) break; // done (looping) if ($cntResults < $pageSize) break; // done (retrieved less values than maximum possible) array_push($hasValues, $lastValue); $objects = $objects + $items; } while ($cntResults); return $objects; }
php
public function paginate(ServiceInterface $service, $method, array $arguments = [], $field = "id", $pageSize = 25) { if (! method_exists($service, $method)) { throw new BadMethodCallException("Invalid method name '" . $method . "'. Not implemented in Service '" . get_class($service) . "'."); } $hasValues = []; $objects = []; $cntResults = 0; do { // forward service method call $items = call_user_func_array([$service, $method], $arguments); $cntResults = count($objects); $lastObj = end($objects); $dotObj = ArrayHelper::dot((array) $lastObj); $lastValue = $dotObj[$field]; if (in_array($lastValue, $hasValues)) break; // done (looping) if ($cntResults < $pageSize) break; // done (retrieved less values than maximum possible) array_push($hasValues, $lastValue); $objects = $objects + $items; } while ($cntResults); return $objects; }
[ "public", "function", "paginate", "(", "ServiceInterface", "$", "service", ",", "$", "method", ",", "array", "$", "arguments", "=", "[", "]", ",", "$", "field", "=", "\"id\"", ",", "$", "pageSize", "=", "25", ")", "{", "if", "(", "!", "method_exists", ...
Helper to *paginate requests* to NIS. This will automatically re-call the Service method in case there is more results to process. This method can be used to return the *full list* of transactions rather than just a *pageSize* number of transactions. @param \NEM\Infrastructure\ServiceInterface $service The NEM Service helper. @param string $method The Service method name to replicate. @param array $arguments The (optional) arguments list for the forwarded method call. @param string $field The (optional) Array Dot Notation for retrieving the *counting* field. @param integer $pageSize The (optional) number of elements which NIS will return with the given Service method. @return \NEM\Models\ModelCollection @throws \BadMethodCallException On invalid service method.
[ "Helper", "to", "*", "paginate", "requests", "*", "to", "NIS", "." ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/ModelCollection.php#L114-L145
evias/nem-php
src/Models/MultisigInfo.php
MultisigInfo.toDTO
public function toDTO($filterByKey = null) { if (empty($this->cosignatoriesCount) || $this->cosignatoriesCount < 0) $this->cosignatoriesCount = 0; if (empty($this->minCosignatories) || $this->minCosignatories < 0) $this->minCosignatories = 0; return [ "cosignatoriesCount" => (int) $this->cosignatoriesCount, "minCosignatories" => (int) $this->minCosignatories, ]; }
php
public function toDTO($filterByKey = null) { if (empty($this->cosignatoriesCount) || $this->cosignatoriesCount < 0) $this->cosignatoriesCount = 0; if (empty($this->minCosignatories) || $this->minCosignatories < 0) $this->minCosignatories = 0; return [ "cosignatoriesCount" => (int) $this->cosignatoriesCount, "minCosignatories" => (int) $this->minCosignatories, ]; }
[ "public", "function", "toDTO", "(", "$", "filterByKey", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "cosignatoriesCount", ")", "||", "$", "this", "->", "cosignatoriesCount", "<", "0", ")", "$", "this", "->", "cosignatoriesCount", "...
MultisigModification DTO automatically builds a *NIS compliant* [MultisigCosignatoryModification](https://bob.nem.ninja/docs/#multisigCosignatoryModification) @return array Associative array with key `modificationType` integer and `cosignatoryAccount` public key.
[ "MultisigModification", "DTO", "automatically", "builds", "a", "*", "NIS", "compliant", "*", "[", "MultisigCosignatoryModification", "]", "(", "https", ":", "//", "bob", ".", "nem", ".", "ninja", "/", "docs", "/", "#multisigCosignatoryModification", ")" ]
train
https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MultisigInfo.php#L60-L72
php-enqueue/dsn
Dsn.php
Dsn.parse
public static function parse(string $dsn): array { if (false === strpos($dsn, ':')) { throw new \LogicException(sprintf('The DSN is invalid. It does not have scheme separator ":".')); } list($scheme, $dsnWithoutScheme) = explode(':', $dsn, 2); $scheme = strtolower($scheme); if (false == preg_match('/^[a-z\d+-.]*$/', $scheme)) { throw new \LogicException('The DSN is invalid. Scheme contains illegal symbols.'); } $schemeParts = explode('+', $scheme); $schemeProtocol = $schemeParts[0]; unset($schemeParts[0]); $schemeExtensions = array_values($schemeParts); $user = parse_url($dsn, PHP_URL_USER) ?: null; if (is_string($user)) { $user = rawurldecode($user); } $password = parse_url($dsn, PHP_URL_PASS) ?: null; if (is_string($password)) { $password = rawurldecode($password); } $path = parse_url($dsn, PHP_URL_PATH) ?: null; if ($path) { $path = rawurldecode($path); } $query = []; $queryString = parse_url($dsn, PHP_URL_QUERY) ?: null; if (is_string($queryString)) { $query = self::httpParseQuery($queryString, '&', PHP_QUERY_RFC3986); } $hostsPorts = ''; if (0 === strpos($dsnWithoutScheme, '//')) { $dsnWithoutScheme = substr($dsnWithoutScheme, 2); $dsnWithoutUserPassword = explode('@', $dsnWithoutScheme, 2); $dsnWithoutUserPassword = 2 === count($dsnWithoutUserPassword) ? $dsnWithoutUserPassword[1] : $dsnWithoutUserPassword[0] ; list($hostsPorts) = explode('#', $dsnWithoutUserPassword, 2); list($hostsPorts) = explode('?', $hostsPorts, 2); list($hostsPorts) = explode('/', $hostsPorts, 2); } if (empty($hostsPorts)) { return [ new self( $scheme, $schemeProtocol, $schemeExtensions, null, null, null, null, $path, $queryString, $query ), ]; } $dsns = []; $hostParts = explode(',', $hostsPorts); foreach ($hostParts as $key => $hostPart) { unset($hostParts[$key]); $parts = explode(':', $hostPart, 2); $host = $parts[0]; $port = null; if (isset($parts[1])) { $port = (int) $parts[1]; } $dsns[] = new self( $scheme, $schemeProtocol, $schemeExtensions, $user, $password, $host, $port, $path, $queryString, $query ); } return $dsns; }
php
public static function parse(string $dsn): array { if (false === strpos($dsn, ':')) { throw new \LogicException(sprintf('The DSN is invalid. It does not have scheme separator ":".')); } list($scheme, $dsnWithoutScheme) = explode(':', $dsn, 2); $scheme = strtolower($scheme); if (false == preg_match('/^[a-z\d+-.]*$/', $scheme)) { throw new \LogicException('The DSN is invalid. Scheme contains illegal symbols.'); } $schemeParts = explode('+', $scheme); $schemeProtocol = $schemeParts[0]; unset($schemeParts[0]); $schemeExtensions = array_values($schemeParts); $user = parse_url($dsn, PHP_URL_USER) ?: null; if (is_string($user)) { $user = rawurldecode($user); } $password = parse_url($dsn, PHP_URL_PASS) ?: null; if (is_string($password)) { $password = rawurldecode($password); } $path = parse_url($dsn, PHP_URL_PATH) ?: null; if ($path) { $path = rawurldecode($path); } $query = []; $queryString = parse_url($dsn, PHP_URL_QUERY) ?: null; if (is_string($queryString)) { $query = self::httpParseQuery($queryString, '&', PHP_QUERY_RFC3986); } $hostsPorts = ''; if (0 === strpos($dsnWithoutScheme, '//')) { $dsnWithoutScheme = substr($dsnWithoutScheme, 2); $dsnWithoutUserPassword = explode('@', $dsnWithoutScheme, 2); $dsnWithoutUserPassword = 2 === count($dsnWithoutUserPassword) ? $dsnWithoutUserPassword[1] : $dsnWithoutUserPassword[0] ; list($hostsPorts) = explode('#', $dsnWithoutUserPassword, 2); list($hostsPorts) = explode('?', $hostsPorts, 2); list($hostsPorts) = explode('/', $hostsPorts, 2); } if (empty($hostsPorts)) { return [ new self( $scheme, $schemeProtocol, $schemeExtensions, null, null, null, null, $path, $queryString, $query ), ]; } $dsns = []; $hostParts = explode(',', $hostsPorts); foreach ($hostParts as $key => $hostPart) { unset($hostParts[$key]); $parts = explode(':', $hostPart, 2); $host = $parts[0]; $port = null; if (isset($parts[1])) { $port = (int) $parts[1]; } $dsns[] = new self( $scheme, $schemeProtocol, $schemeExtensions, $user, $password, $host, $port, $path, $queryString, $query ); } return $dsns; }
[ "public", "static", "function", "parse", "(", "string", "$", "dsn", ")", ":", "array", "{", "if", "(", "false", "===", "strpos", "(", "$", "dsn", ",", "':'", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'The DSN is inval...
@param string $dsn @return Dsn[]
[ "@param", "string", "$dsn" ]
train
https://github.com/php-enqueue/dsn/blob/5d011c648395307c740d8c0e420f8a9faebce72f/Dsn.php#L199-L297
php-enqueue/dsn
Dsn.php
Dsn.httpParseQuery
private static function httpParseQuery(string $queryString, string $argSeparator = '&', int $decType = PHP_QUERY_RFC1738): array { $result = []; $parts = explode($argSeparator, $queryString); foreach ($parts as $part) { list($paramName, $paramValue) = explode('=', $part, 2); switch ($decType) { case PHP_QUERY_RFC3986: $paramName = rawurldecode($paramName); $paramValue = rawurldecode($paramValue); break; case PHP_QUERY_RFC1738: default: $paramName = urldecode($paramName); $paramValue = urldecode($paramValue); break; } if (preg_match_all('/\[([^\]]*)\]/m', $paramName, $matches)) { $paramName = substr($paramName, 0, strpos($paramName, '[')); $keys = array_merge([$paramName], $matches[1]); } else { $keys = [$paramName]; } $target = &$result; foreach ($keys as $index) { if ('' === $index) { if (is_array($target)) { $intKeys = array_filter(array_keys($target), 'is_int'); $index = count($intKeys) ? max($intKeys) + 1 : 0; } else { $target = [$target]; $index = 1; } } elseif (isset($target[$index]) && !is_array($target[$index])) { $target[$index] = [$target[$index]]; } $target = &$target[$index]; } if (is_array($target)) { $target[] = $paramValue; } else { $target = $paramValue; } } return $result; }
php
private static function httpParseQuery(string $queryString, string $argSeparator = '&', int $decType = PHP_QUERY_RFC1738): array { $result = []; $parts = explode($argSeparator, $queryString); foreach ($parts as $part) { list($paramName, $paramValue) = explode('=', $part, 2); switch ($decType) { case PHP_QUERY_RFC3986: $paramName = rawurldecode($paramName); $paramValue = rawurldecode($paramValue); break; case PHP_QUERY_RFC1738: default: $paramName = urldecode($paramName); $paramValue = urldecode($paramValue); break; } if (preg_match_all('/\[([^\]]*)\]/m', $paramName, $matches)) { $paramName = substr($paramName, 0, strpos($paramName, '[')); $keys = array_merge([$paramName], $matches[1]); } else { $keys = [$paramName]; } $target = &$result; foreach ($keys as $index) { if ('' === $index) { if (is_array($target)) { $intKeys = array_filter(array_keys($target), 'is_int'); $index = count($intKeys) ? max($intKeys) + 1 : 0; } else { $target = [$target]; $index = 1; } } elseif (isset($target[$index]) && !is_array($target[$index])) { $target[$index] = [$target[$index]]; } $target = &$target[$index]; } if (is_array($target)) { $target[] = $paramValue; } else { $target = $paramValue; } } return $result; }
[ "private", "static", "function", "httpParseQuery", "(", "string", "$", "queryString", ",", "string", "$", "argSeparator", "=", "'&'", ",", "int", "$", "decType", "=", "PHP_QUERY_RFC1738", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "$", "p...
based on http://php.net/manual/en/function.parse-str.php#119484 with some slight modifications.
[ "based", "on", "http", ":", "//", "php", ".", "net", "/", "manual", "/", "en", "/", "function", ".", "parse", "-", "str", ".", "php#119484", "with", "some", "slight", "modifications", "." ]
train
https://github.com/php-enqueue/dsn/blob/5d011c648395307c740d8c0e420f8a9faebce72f/Dsn.php#L302-L355
amphp/socket
src/BasicSocketPool.php
BasicSocketPool.normalizeUri
private function normalizeUri(string $uri): string { if (\stripos($uri, 'unix://') === 0) { return $uri; } try { $parts = Uri\parse($uri); } catch (\Exception $exception) { throw new SocketException("Could not parse URI", 0, $exception); } if ($parts['scheme'] === null) { throw new SocketException("Invalid URI for socket pool; no scheme given"); } $port = $parts['port'] ?? 0; if ($parts['host'] === null || $port === 0) { throw new SocketException("Invalid URI for socket pool; missing host or port"); } $scheme = \strtolower($parts['scheme']); $host = \strtolower($parts['host']); if (!\array_key_exists($scheme, self::ALLOWED_SCHEMES)) { throw new SocketException(\sprintf( "Invalid URI for socket pool; '%s' scheme not allowed - scheme must be one of %s", $scheme, \implode(', ', \array_keys(self::ALLOWED_SCHEMES)) )); } if ($parts['query'] !== null || $parts['fragment'] !== null) { throw new SocketException("Invalid URI for socket pool; query or fragment components not allowed"); } if ($parts['path'] !== '') { throw new SocketException("Invalid URI for socket pool; path component must be empty"); } if ($parts['user'] !== null) { throw new SocketException("Invalid URI for socket pool; user component not allowed"); } return $scheme . '://' . $host . ':' . $port; }
php
private function normalizeUri(string $uri): string { if (\stripos($uri, 'unix://') === 0) { return $uri; } try { $parts = Uri\parse($uri); } catch (\Exception $exception) { throw new SocketException("Could not parse URI", 0, $exception); } if ($parts['scheme'] === null) { throw new SocketException("Invalid URI for socket pool; no scheme given"); } $port = $parts['port'] ?? 0; if ($parts['host'] === null || $port === 0) { throw new SocketException("Invalid URI for socket pool; missing host or port"); } $scheme = \strtolower($parts['scheme']); $host = \strtolower($parts['host']); if (!\array_key_exists($scheme, self::ALLOWED_SCHEMES)) { throw new SocketException(\sprintf( "Invalid URI for socket pool; '%s' scheme not allowed - scheme must be one of %s", $scheme, \implode(', ', \array_keys(self::ALLOWED_SCHEMES)) )); } if ($parts['query'] !== null || $parts['fragment'] !== null) { throw new SocketException("Invalid URI for socket pool; query or fragment components not allowed"); } if ($parts['path'] !== '') { throw new SocketException("Invalid URI for socket pool; path component must be empty"); } if ($parts['user'] !== null) { throw new SocketException("Invalid URI for socket pool; user component not allowed"); } return $scheme . '://' . $host . ':' . $port; }
[ "private", "function", "normalizeUri", "(", "string", "$", "uri", ")", ":", "string", "{", "if", "(", "\\", "stripos", "(", "$", "uri", ",", "'unix://'", ")", "===", "0", ")", "{", "return", "$", "uri", ";", "}", "try", "{", "$", "parts", "=", "U...
@param string $uri @return string @throws SocketException
[ "@param", "string", "$uri" ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/BasicSocketPool.php#L44-L90
amphp/socket
src/ClientSocket.php
ClientSocket.enableCrypto
final public function enableCrypto(ClientTlsContext $tlsContext = null): Promise { if (($resource = $this->getResource()) === null) { return new Failure(new ClosedException("The socket has been closed")); } $tlsContext = $tlsContext ?? new ClientTlsContext; return Internal\enableCrypto($resource, $tlsContext->toStreamContextArray()); }
php
final public function enableCrypto(ClientTlsContext $tlsContext = null): Promise { if (($resource = $this->getResource()) === null) { return new Failure(new ClosedException("The socket has been closed")); } $tlsContext = $tlsContext ?? new ClientTlsContext; return Internal\enableCrypto($resource, $tlsContext->toStreamContextArray()); }
[ "final", "public", "function", "enableCrypto", "(", "ClientTlsContext", "$", "tlsContext", "=", "null", ")", ":", "Promise", "{", "if", "(", "(", "$", "resource", "=", "$", "this", "->", "getResource", "(", ")", ")", "===", "null", ")", "{", "return", ...
{@inheritdoc} @param ClientTlsContext|null $tlsContext
[ "{", "@inheritdoc", "}" ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ClientSocket.php#L16-L25
amphp/socket
src/ResourceSocket.php
ResourceSocket.disableCrypto
final public function disableCrypto(): Promise { if (($resource = $this->reader->getResource()) === null) { return new Failure(new ClosedException('The socket has been closed')); } return Internal\disableCrypto($resource); }
php
final public function disableCrypto(): Promise { if (($resource = $this->reader->getResource()) === null) { return new Failure(new ClosedException('The socket has been closed')); } return Internal\disableCrypto($resource); }
[ "final", "public", "function", "disableCrypto", "(", ")", ":", "Promise", "{", "if", "(", "(", "$", "resource", "=", "$", "this", "->", "reader", "->", "getResource", "(", ")", ")", "===", "null", ")", "{", "return", "new", "Failure", "(", "new", "Cl...
Disables encryption on this socket. @return Promise
[ "Disables", "encryption", "on", "this", "socket", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ResourceSocket.php#L45-L52
amphp/socket
src/Server.php
Server.accept
public function accept(): Promise { if ($this->acceptor) { throw new PendingAcceptError; } if (!$this->socket) { return new Success; // Resolve with null when server is closed. } // Error reporting suppressed since stream_socket_accept() emits E_WARNING on client accept failure. if ($client = @\stream_socket_accept($this->socket, 0)) { // Timeout of 0 to be non-blocking. return new Success(new ServerSocket($client, $this->chunkSize)); } $this->acceptor = new Deferred; Loop::enable($this->watcher); return $this->acceptor->promise(); }
php
public function accept(): Promise { if ($this->acceptor) { throw new PendingAcceptError; } if (!$this->socket) { return new Success; // Resolve with null when server is closed. } // Error reporting suppressed since stream_socket_accept() emits E_WARNING on client accept failure. if ($client = @\stream_socket_accept($this->socket, 0)) { // Timeout of 0 to be non-blocking. return new Success(new ServerSocket($client, $this->chunkSize)); } $this->acceptor = new Deferred; Loop::enable($this->watcher); return $this->acceptor->promise(); }
[ "public", "function", "accept", "(", ")", ":", "Promise", "{", "if", "(", "$", "this", "->", "acceptor", ")", "{", "throw", "new", "PendingAcceptError", ";", "}", "if", "(", "!", "$", "this", "->", "socket", ")", "{", "return", "new", "Success", ";",...
@return Promise<ServerSocket|null> @throws PendingAcceptError If another accept request is pending.
[ "@return", "Promise<ServerSocket|null", ">" ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/Server.php#L98-L117
amphp/socket
src/DatagramSocket.php
DatagramSocket.receive
public function receive(): Promise { if ($this->reader) { throw new PendingReceiveError; } if (!$this->socket) { return new Success; // Resolve with null when endpoint is closed. } $this->reader = new Deferred; Loop::enable($this->watcher); return $this->reader->promise(); }
php
public function receive(): Promise { if ($this->reader) { throw new PendingReceiveError; } if (!$this->socket) { return new Success; // Resolve with null when endpoint is closed. } $this->reader = new Deferred; Loop::enable($this->watcher); return $this->reader->promise(); }
[ "public", "function", "receive", "(", ")", ":", "Promise", "{", "if", "(", "$", "this", "->", "reader", ")", "{", "throw", "new", "PendingReceiveError", ";", "}", "if", "(", "!", "$", "this", "->", "socket", ")", "{", "return", "new", "Success", ";",...
@return Promise<[string $address, string $data]|null> Resolves with null if the socket is closed. @throws PendingReceiveError If a receive request is already pending.
[ "@return", "Promise<", "[", "string", "$address", "string", "$data", "]", "|null", ">", "Resolves", "with", "null", "if", "the", "socket", "is", "closed", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/DatagramSocket.php#L84-L98
amphp/socket
src/DatagramSocket.php
DatagramSocket.send
public function send(string $address, string $data): Promise { \assert($this->isAddressValid($address), "Invalid packet address"); if (!$this->socket) { return new Failure(new SocketException('The endpoint is not writable')); } $result = @\stream_socket_sendto($this->socket, $data, 0, $address); if ($result < 0 || $result === false) { $error = \error_get_last(); return new Failure(new SocketException('Could not send packet on endpoint: ' . $error['message'])); } return new Success($result); }
php
public function send(string $address, string $data): Promise { \assert($this->isAddressValid($address), "Invalid packet address"); if (!$this->socket) { return new Failure(new SocketException('The endpoint is not writable')); } $result = @\stream_socket_sendto($this->socket, $data, 0, $address); if ($result < 0 || $result === false) { $error = \error_get_last(); return new Failure(new SocketException('Could not send packet on endpoint: ' . $error['message'])); } return new Success($result); }
[ "public", "function", "send", "(", "string", "$", "address", ",", "string", "$", "data", ")", ":", "Promise", "{", "\\", "assert", "(", "$", "this", "->", "isAddressValid", "(", "$", "address", ")", ",", "\"Invalid packet address\"", ")", ";", "if", "(",...
@param string $address @param string $data @return Promise<int> Resolves with the number of bytes written to the socket. @throws SocketException If the UDP socket closes before the data can be sent.
[ "@param", "string", "$address", "@param", "string", "$data" ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/DatagramSocket.php#L108-L124
amphp/socket
src/DatagramSocket.php
DatagramSocket.isAddressValid
private function isAddressValid(string $address): bool { $position = \strrpos($address, ':'); if ($position === false) { return ($address[0] ?? '') === "\0"; // udg socket address. } $ip = \trim(\substr($address, 0, $position), '[]'); $port = (int) \substr($address, $position + 1); return \inet_pton($ip) !== false && $port > 0 && $port < 65536; }
php
private function isAddressValid(string $address): bool { $position = \strrpos($address, ':'); if ($position === false) { return ($address[0] ?? '') === "\0"; // udg socket address. } $ip = \trim(\substr($address, 0, $position), '[]'); $port = (int) \substr($address, $position + 1); return \inet_pton($ip) !== false && $port > 0 && $port < 65536; }
[ "private", "function", "isAddressValid", "(", "string", "$", "address", ")", ":", "bool", "{", "$", "position", "=", "\\", "strrpos", "(", "$", "address", ",", "':'", ")", ";", "if", "(", "$", "position", "===", "false", ")", "{", "return", "(", "$",...
Rough address validation to catch programming mistakes. @param string $address @return bool
[ "Rough", "address", "validation", "to", "catch", "programming", "mistakes", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/DatagramSocket.php#L195-L206
amphp/socket
src/ServerTlsContext.php
ServerTlsContext.withMinimumVersion
public function withMinimumVersion(int $version): self { if ($version !== self::TLSv1_0 && $version !== self::TLSv1_1 && $version !== self::TLSv1_2) { throw new \Error('Invalid minimum version, only TLSv1.0, TLSv1.1 or TLSv1.2 allowed'); } $clone = clone $this; $clone->minVersion = $version; return $clone; }
php
public function withMinimumVersion(int $version): self { if ($version !== self::TLSv1_0 && $version !== self::TLSv1_1 && $version !== self::TLSv1_2) { throw new \Error('Invalid minimum version, only TLSv1.0, TLSv1.1 or TLSv1.2 allowed'); } $clone = clone $this; $clone->minVersion = $version; return $clone; }
[ "public", "function", "withMinimumVersion", "(", "int", "$", "version", ")", ":", "self", "{", "if", "(", "$", "version", "!==", "self", "::", "TLSv1_0", "&&", "$", "version", "!==", "self", "::", "TLSv1_1", "&&", "$", "version", "!==", "self", "::", "...
Minimum TLS version to negotiate. Defaults to TLS 1.0. @param int $version `ServerTlsContext::TLSv1_0`, `ServerTlsContext::TLSv1_1`, or `ServerTlsContext::TLSv1_2`. @return self Cloned, modified instance. @throws \Error If an invalid minimum version is given.
[ "Minimum", "TLS", "version", "to", "negotiate", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ServerTlsContext.php#L44-L54
amphp/socket
src/ServerTlsContext.php
ServerTlsContext.withCertificates
public function withCertificates(array $certificates): self { foreach ($certificates as $key => $certificate) { if (!\is_string($key)) { throw new \TypeError('Expected an array mapping domain names to Certificate instances'); } if (!$certificate instanceof Certificate) { throw new \TypeError('Expected an array of Certificate instances'); } if (\PHP_VERSION_ID < 70200 && $certificate->getCertFile() !== $certificate->getKeyFile()) { throw new \Error( 'Different files for cert and key are not supported on this version of PHP. ' . 'Please upgrade to PHP 7.2 or later.' ); } } $clone = clone $this; $clone->certificates = $certificates; return $clone; }
php
public function withCertificates(array $certificates): self { foreach ($certificates as $key => $certificate) { if (!\is_string($key)) { throw new \TypeError('Expected an array mapping domain names to Certificate instances'); } if (!$certificate instanceof Certificate) { throw new \TypeError('Expected an array of Certificate instances'); } if (\PHP_VERSION_ID < 70200 && $certificate->getCertFile() !== $certificate->getKeyFile()) { throw new \Error( 'Different files for cert and key are not supported on this version of PHP. ' . 'Please upgrade to PHP 7.2 or later.' ); } } $clone = clone $this; $clone->certificates = $certificates; return $clone; }
[ "public", "function", "withCertificates", "(", "array", "$", "certificates", ")", ":", "self", "{", "foreach", "(", "$", "certificates", "as", "$", "key", "=>", "$", "certificate", ")", "{", "if", "(", "!", "\\", "is_string", "(", "$", "key", ")", ")",...
Certificates to use for the given host names. @param array $certificates Must be a associative array mapping hostnames to certificate instances. @return self Cloned, modified instance.
[ "Certificates", "to", "use", "for", "the", "given", "host", "names", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ServerTlsContext.php#L285-L308
amphp/socket
src/ServerTlsContext.php
ServerTlsContext.withSecurityLevel
public function withSecurityLevel(int $level): self { // See https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_security_level.html // Level 2 is not recommended, because of SHA-1 by that document, // but SHA-1 should be phased out now on general internet use. // We therefore default to level 2. if ($level < 0 || $level > 5) { throw new \Error("Invalid security level ({$level}), must be between 0 and 5."); } if (\OPENSSL_VERSION_NUMBER < 0x10100000) { throw new \Error("Can't set a security level, as PHP is compiled with OpenSSL < 1.1.0."); } $clone = clone $this; $clone->securityLevel = $level; return $clone; }
php
public function withSecurityLevel(int $level): self { // See https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_security_level.html // Level 2 is not recommended, because of SHA-1 by that document, // but SHA-1 should be phased out now on general internet use. // We therefore default to level 2. if ($level < 0 || $level > 5) { throw new \Error("Invalid security level ({$level}), must be between 0 and 5."); } if (\OPENSSL_VERSION_NUMBER < 0x10100000) { throw new \Error("Can't set a security level, as PHP is compiled with OpenSSL < 1.1.0."); } $clone = clone $this; $clone->securityLevel = $level; return $clone; }
[ "public", "function", "withSecurityLevel", "(", "int", "$", "level", ")", ":", "self", "{", "// See https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_security_level.html", "// Level 2 is not recommended, because of SHA-1 by that document,", "// but SHA-1 should be phased out now on g...
Security level to use. Requires OpenSSL 1.1.0 or higher. @param int $level Must be between 0 and 5. @return self Cloned, modified instance.
[ "Security", "level", "to", "use", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ServerTlsContext.php#L327-L346
amphp/socket
src/ServerTlsContext.php
ServerTlsContext.toStreamContextArray
public function toStreamContextArray(): array { $options = [ 'crypto_method' => $this->toStreamCryptoMethod(), 'peer_name' => $this->peerName, 'verify_peer' => $this->verifyPeer, 'verify_peer_name' => $this->verifyPeer, 'verify_depth' => $this->verifyDepth, 'ciphers' => $this->ciphers ?? \OPENSSL_DEFAULT_STREAM_CIPHERS, 'honor_cipher_order' => true, 'single_dh_use' => true, 'no_ticket' => true, 'capture_peer_cert' => $this->capturePeer, 'capture_peer_chain' => $this->capturePeer, ]; if ($this->defaultCertificate !== null) { $options['local_cert'] = $this->defaultCertificate->getCertFile(); if ($this->defaultCertificate->getCertFile() !== $this->defaultCertificate->getKeyFile()) { $options['local_pk'] = $this->defaultCertificate->getKeyFile(); } } if ($this->certificates) { $options['SNI_server_certs'] = \array_map(static function (Certificate $certificate) { if ($certificate->getCertFile() === $certificate->getKeyFile()) { return $certificate->getCertFile(); } return [ 'local_cert' => $certificate->getCertFile(), 'local_pk' => $certificate->getKeyFile(), ]; }, $this->certificates); } if ($this->caFile !== null) { $options['cafile'] = $this->caFile; } if ($this->caPath !== null) { $options['capath'] = $this->caPath; } if (\OPENSSL_VERSION_NUMBER >= 0x10100000) { $options['security_level'] = $this->securityLevel; } return ['ssl' => $options]; }
php
public function toStreamContextArray(): array { $options = [ 'crypto_method' => $this->toStreamCryptoMethod(), 'peer_name' => $this->peerName, 'verify_peer' => $this->verifyPeer, 'verify_peer_name' => $this->verifyPeer, 'verify_depth' => $this->verifyDepth, 'ciphers' => $this->ciphers ?? \OPENSSL_DEFAULT_STREAM_CIPHERS, 'honor_cipher_order' => true, 'single_dh_use' => true, 'no_ticket' => true, 'capture_peer_cert' => $this->capturePeer, 'capture_peer_chain' => $this->capturePeer, ]; if ($this->defaultCertificate !== null) { $options['local_cert'] = $this->defaultCertificate->getCertFile(); if ($this->defaultCertificate->getCertFile() !== $this->defaultCertificate->getKeyFile()) { $options['local_pk'] = $this->defaultCertificate->getKeyFile(); } } if ($this->certificates) { $options['SNI_server_certs'] = \array_map(static function (Certificate $certificate) { if ($certificate->getCertFile() === $certificate->getKeyFile()) { return $certificate->getCertFile(); } return [ 'local_cert' => $certificate->getCertFile(), 'local_pk' => $certificate->getKeyFile(), ]; }, $this->certificates); } if ($this->caFile !== null) { $options['cafile'] = $this->caFile; } if ($this->caPath !== null) { $options['capath'] = $this->caPath; } if (\OPENSSL_VERSION_NUMBER >= 0x10100000) { $options['security_level'] = $this->securityLevel; } return ['ssl' => $options]; }
[ "public", "function", "toStreamContextArray", "(", ")", ":", "array", "{", "$", "options", "=", "[", "'crypto_method'", "=>", "$", "this", "->", "toStreamCryptoMethod", "(", ")", ",", "'peer_name'", "=>", "$", "this", "->", "peerName", ",", "'verify_peer'", ...
Converts this TLS context into PHP's equivalent stream context array. @return array Stream context array compatible with PHP's streams.
[ "Converts", "this", "TLS", "context", "into", "PHP", "s", "equivalent", "stream", "context", "array", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ServerTlsContext.php#L366-L416
amphp/socket
src/ClientTlsContext.php
ClientTlsContext.toStreamContextArray
public function toStreamContextArray(): array { $options = [ 'crypto_method' => $this->toStreamCryptoMethod(), 'peer_name' => $this->peerName, 'verify_peer' => $this->verifyPeer, 'verify_peer_name' => $this->verifyPeer, 'verify_depth' => $this->verifyDepth, 'ciphers' => $this->ciphers ?? \OPENSSL_DEFAULT_STREAM_CIPHERS, 'capture_peer_cert' => $this->capturePeer, 'capture_peer_cert_chain' => $this->capturePeer, 'SNI_enabled' => $this->sniEnabled, ]; if ($this->certificate !== null) { $options['local_cert'] = $this->certificate->getCertFile(); if ($this->certificate->getCertFile() !== $this->certificate->getKeyFile()) { $options['local_pk'] = $this->certificate->getKeyFile(); } } if ($this->caFile !== null) { $options['cafile'] = $this->caFile; } if ($this->caPath !== null) { $options['capath'] = $this->caPath; } if (\OPENSSL_VERSION_NUMBER >= 0x10100000) { $options['security_level'] = $this->securityLevel; } return ['ssl' => $options]; }
php
public function toStreamContextArray(): array { $options = [ 'crypto_method' => $this->toStreamCryptoMethod(), 'peer_name' => $this->peerName, 'verify_peer' => $this->verifyPeer, 'verify_peer_name' => $this->verifyPeer, 'verify_depth' => $this->verifyDepth, 'ciphers' => $this->ciphers ?? \OPENSSL_DEFAULT_STREAM_CIPHERS, 'capture_peer_cert' => $this->capturePeer, 'capture_peer_cert_chain' => $this->capturePeer, 'SNI_enabled' => $this->sniEnabled, ]; if ($this->certificate !== null) { $options['local_cert'] = $this->certificate->getCertFile(); if ($this->certificate->getCertFile() !== $this->certificate->getKeyFile()) { $options['local_pk'] = $this->certificate->getKeyFile(); } } if ($this->caFile !== null) { $options['cafile'] = $this->caFile; } if ($this->caPath !== null) { $options['capath'] = $this->caPath; } if (\OPENSSL_VERSION_NUMBER >= 0x10100000) { $options['security_level'] = $this->securityLevel; } return ['ssl' => $options]; }
[ "public", "function", "toStreamContextArray", "(", ")", ":", "array", "{", "$", "options", "=", "[", "'crypto_method'", "=>", "$", "this", "->", "toStreamCryptoMethod", "(", ")", ",", "'peer_name'", "=>", "$", "this", "->", "peerName", ",", "'verify_peer'", ...
Converts this TLS context into PHP's equivalent stream context array. @return array Stream context array compatible with PHP's streams.
[ "Converts", "this", "TLS", "context", "into", "PHP", "s", "equivalent", "stream", "context", "array", "." ]
train
https://github.com/amphp/socket/blob/d759f2d516ad434e44d9ede8aecc1d1a8b1464bc/src/ClientTlsContext.php#L357-L392
neos/flow-development-collection
Neos.Flow/Classes/I18n/LocaleCollection.php
LocaleCollection.addLocale
public function addLocale(Locale $locale) { if (isset($this->localeCollection[(string)$locale])) { return false; } // We need to invalidate the parent's array as it could be inaccurate $this->localeParentCollection = []; $this->localeCollection[(string)$locale] = $locale; return true; }
php
public function addLocale(Locale $locale) { if (isset($this->localeCollection[(string)$locale])) { return false; } // We need to invalidate the parent's array as it could be inaccurate $this->localeParentCollection = []; $this->localeCollection[(string)$locale] = $locale; return true; }
[ "public", "function", "addLocale", "(", "Locale", "$", "locale", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "localeCollection", "[", "(", "string", ")", "$", "locale", "]", ")", ")", "{", "return", "false", ";", "}", "// We need to invalidate ...
Adds a locale to the collection. @param Locale $locale The Locale to be inserted @return boolean false when same locale was already inserted before
[ "Adds", "a", "locale", "to", "the", "collection", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/LocaleCollection.php#L53-L64
neos/flow-development-collection
Neos.Flow/Classes/I18n/LocaleCollection.php
LocaleCollection.getParentLocaleOf
public function getParentLocaleOf(Locale $locale) { $localeIdentifier = (string)$locale; if (!isset($this->localeCollection[$localeIdentifier])) { return null; } if (isset($this->localeParentCollection[$localeIdentifier])) { return $this->localeParentCollection[$localeIdentifier]; } $parentLocaleIdentifier = $localeIdentifier; do { // Remove the last (most specific) part of the locale tag $parentLocaleIdentifier = substr($parentLocaleIdentifier, 0, (int)strrpos($parentLocaleIdentifier, '_')); if (isset($this->localeCollection[$parentLocaleIdentifier])) { return $this->localeParentCollection[$localeIdentifier] = $this->localeCollection[$parentLocaleIdentifier]; } } while (strrpos($parentLocaleIdentifier, '_') !== false); return null; }
php
public function getParentLocaleOf(Locale $locale) { $localeIdentifier = (string)$locale; if (!isset($this->localeCollection[$localeIdentifier])) { return null; } if (isset($this->localeParentCollection[$localeIdentifier])) { return $this->localeParentCollection[$localeIdentifier]; } $parentLocaleIdentifier = $localeIdentifier; do { // Remove the last (most specific) part of the locale tag $parentLocaleIdentifier = substr($parentLocaleIdentifier, 0, (int)strrpos($parentLocaleIdentifier, '_')); if (isset($this->localeCollection[$parentLocaleIdentifier])) { return $this->localeParentCollection[$localeIdentifier] = $this->localeCollection[$parentLocaleIdentifier]; } } while (strrpos($parentLocaleIdentifier, '_') !== false); return null; }
[ "public", "function", "getParentLocaleOf", "(", "Locale", "$", "locale", ")", "{", "$", "localeIdentifier", "=", "(", "string", ")", "$", "locale", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "localeCollection", "[", "$", "localeIdentifier", "]",...
Returns a parent Locale object of the locale provided. The parent is a locale which is more generic than the one given as parameter. For example, the parent for locale en_GB will be locale en, of course if it exists in the locale tree of available locales. This method returns NULL when no parent locale is available, or when Locale object provided is not in the tree (ie it's not in a group of available locales). Note: to find a best-matching locale to one which doesn't exist in the system, please use findBestMatchingLocale() method of this class. @param Locale $locale The Locale to search parent for @return mixed Existing Locale instance or NULL on failure
[ "Returns", "a", "parent", "Locale", "object", "of", "the", "locale", "provided", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/LocaleCollection.php#L83-L106
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.createFromServer
public static function createFromServer(array $server) { $headerFields = []; if (isset($server['PHP_AUTH_USER']) && isset($server['PHP_AUTH_PW'])) { $headerFields['Authorization'] = 'Basic ' . base64_encode($server['PHP_AUTH_USER'] . ':' . $server['PHP_AUTH_PW']); } foreach ($server as $name => $value) { if (strpos($name, 'HTTP_') === 0) { $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); $headerFields[$name] = $value; } elseif ($name == 'REDIRECT_REMOTE_AUTHORIZATION' && !isset($headerFields['Authorization'])) { $headerFields['Authorization'] = $value; } elseif (in_array($name, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $name)))); $headerFields[$name] = $value; } } return new self($headerFields); }
php
public static function createFromServer(array $server) { $headerFields = []; if (isset($server['PHP_AUTH_USER']) && isset($server['PHP_AUTH_PW'])) { $headerFields['Authorization'] = 'Basic ' . base64_encode($server['PHP_AUTH_USER'] . ':' . $server['PHP_AUTH_PW']); } foreach ($server as $name => $value) { if (strpos($name, 'HTTP_') === 0) { $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); $headerFields[$name] = $value; } elseif ($name == 'REDIRECT_REMOTE_AUTHORIZATION' && !isset($headerFields['Authorization'])) { $headerFields['Authorization'] = $value; } elseif (in_array($name, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $name)))); $headerFields[$name] = $value; } } return new self($headerFields); }
[ "public", "static", "function", "createFromServer", "(", "array", "$", "server", ")", "{", "$", "headerFields", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "server", "[", "'PHP_AUTH_USER'", "]", ")", "&&", "isset", "(", "$", "server", "[", "'PHP_...
Creates a new Headers instance from the given $_SERVER-superglobal-like array. @param array $server An array similar or equal to $_SERVER, containing headers in the form of "HTTP_FOO_BAR" @return Headers
[ "Creates", "a", "new", "Headers", "instance", "from", "the", "given", "$_SERVER", "-", "superglobal", "-", "like", "array", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L66-L85
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.set
public function set($name, $values, $replaceExistingHeader = true) { if ($values instanceof \DateTimeInterface) { $date = clone $values; $date->setTimezone(new \DateTimeZone('GMT')); $values = [$date->format('D, d M Y H:i:s') . ' GMT']; } else { $values = (array) $values; } switch ($name) { case 'Host': if (count($values) > 1) { throw new \InvalidArgumentException('The "Host" header must be unique and thus only one field value may be specified.', 1478206019); } // Ensure Host is the first header. // See: http://tools.ietf.org/html/rfc7230#section-5.4 $this->fields = ['Host' => $values] + $this->fields; break; case 'Cache-Control': $this->setCacheControlDirectivesFromRawHeader(implode(', ', $values)); break; case 'Cookie': if (count($values) !== 1) { throw new \InvalidArgumentException('The "Cookie" header must be unique and thus only one field value may be specified.', 1345127727); } $this->setCookiesFromRawHeader(array_pop($values)); break; default: if ($replaceExistingHeader === true || !isset($this->fields[$name])) { $this->fields[$name] = $values; } else { $this->fields[$name] = array_merge($this->fields[$name], $values); } } }
php
public function set($name, $values, $replaceExistingHeader = true) { if ($values instanceof \DateTimeInterface) { $date = clone $values; $date->setTimezone(new \DateTimeZone('GMT')); $values = [$date->format('D, d M Y H:i:s') . ' GMT']; } else { $values = (array) $values; } switch ($name) { case 'Host': if (count($values) > 1) { throw new \InvalidArgumentException('The "Host" header must be unique and thus only one field value may be specified.', 1478206019); } // Ensure Host is the first header. // See: http://tools.ietf.org/html/rfc7230#section-5.4 $this->fields = ['Host' => $values] + $this->fields; break; case 'Cache-Control': $this->setCacheControlDirectivesFromRawHeader(implode(', ', $values)); break; case 'Cookie': if (count($values) !== 1) { throw new \InvalidArgumentException('The "Cookie" header must be unique and thus only one field value may be specified.', 1345127727); } $this->setCookiesFromRawHeader(array_pop($values)); break; default: if ($replaceExistingHeader === true || !isset($this->fields[$name])) { $this->fields[$name] = $values; } else { $this->fields[$name] = array_merge($this->fields[$name], $values); } } }
[ "public", "function", "set", "(", "$", "name", ",", "$", "values", ",", "$", "replaceExistingHeader", "=", "true", ")", "{", "if", "(", "$", "values", "instanceof", "\\", "DateTimeInterface", ")", "{", "$", "date", "=", "clone", "$", "values", ";", "$"...
Sets the specified HTTP header DateTime objects will be converted to a string representation internally but will be returned as DateTime objects on calling get(). Please note that dates are normalized to GMT internally, so that get() will return the same point in time, but not necessarily in the same timezone, if it was not GMT previously. GMT is used synonymously with UTC as per RFC 2616 3.3.1. @param string $name Name of the header, for example "Location", "Content-Description" etc. @param array|string|\DateTime $values An array of values or a single value for the specified header field @param boolean $replaceExistingHeader If a header with the same name should be replaced. Default is true. @return void @throws \InvalidArgumentException @api
[ "Sets", "the", "specified", "HTTP", "header" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L104-L139
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.getRaw
public function getRaw(string $name): array { if (strtolower($name) === 'cache-control') { return $this->getCacheControlDirectives(); } if (strtolower($name) === 'set-cookie') { $cookies = $this->fields['Set-Cookie'] ?? []; foreach ($this->cookies as $cookie) { $cookies[] = (string)$cookie; } return $cookies; } if (!isset($this->fields[$name])) { return []; } return $this->fields[$name]; }
php
public function getRaw(string $name): array { if (strtolower($name) === 'cache-control') { return $this->getCacheControlDirectives(); } if (strtolower($name) === 'set-cookie') { $cookies = $this->fields['Set-Cookie'] ?? []; foreach ($this->cookies as $cookie) { $cookies[] = (string)$cookie; } return $cookies; } if (!isset($this->fields[$name])) { return []; } return $this->fields[$name]; }
[ "public", "function", "getRaw", "(", "string", "$", "name", ")", ":", "array", "{", "if", "(", "strtolower", "(", "$", "name", ")", "===", "'cache-control'", ")", "{", "return", "$", "this", "->", "getCacheControlDirectives", "(", ")", ";", "}", "if", ...
Get raw header values @param string $name @return string[]
[ "Get", "raw", "header", "values" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L147-L166
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.get
public function get($name) { if (strtolower($name) === 'cache-control') { return $this->getCacheControlHeader(); } if (strtolower($name) === 'set-cookie') { $cookies = $this->fields['Set-Cookie'] ?? []; foreach ($this->cookies as $cookie) { $cookies[] = (string)$cookie; } return $cookies; } if (!isset($this->fields[$name])) { return null; } $convertedValues = []; foreach ($this->fields[$name] as $index => $value) { $convertedValues[$index] = \DateTime::createFromFormat(DATE_RFC2822, $value); if ($convertedValues[$index] === false) { $convertedValues[$index] = $value; } } return (count($convertedValues) > 1) ? $convertedValues : reset($convertedValues); }
php
public function get($name) { if (strtolower($name) === 'cache-control') { return $this->getCacheControlHeader(); } if (strtolower($name) === 'set-cookie') { $cookies = $this->fields['Set-Cookie'] ?? []; foreach ($this->cookies as $cookie) { $cookies[] = (string)$cookie; } return $cookies; } if (!isset($this->fields[$name])) { return null; } $convertedValues = []; foreach ($this->fields[$name] as $index => $value) { $convertedValues[$index] = \DateTime::createFromFormat(DATE_RFC2822, $value); if ($convertedValues[$index] === false) { $convertedValues[$index] = $value; } } return (count($convertedValues) > 1) ? $convertedValues : reset($convertedValues); }
[ "public", "function", "get", "(", "$", "name", ")", "{", "if", "(", "strtolower", "(", "$", "name", ")", "===", "'cache-control'", ")", "{", "return", "$", "this", "->", "getCacheControlHeader", "(", ")", ";", "}", "if", "(", "strtolower", "(", "$", ...
Returns the specified HTTP header Dates are returned as DateTime objects with the timezone set to GMT. @param string $name Name of the header, for example "Location", "Content-Description" etc. @return array|string An array of field values if multiple headers of that name exist, a string value if only one value exists and NULL if there is no such header. @api
[ "Returns", "the", "specified", "HTTP", "header" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L177-L205
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.getAll
public function getAll() { $fields = $this->fields; $cacheControlHeader = $this->getCacheControlHeader(); $fields['Cache-Control'] = [$cacheControlHeader]; if (empty($cacheControlHeader)) { unset($fields['Cache-Control']); } return $fields; }
php
public function getAll() { $fields = $this->fields; $cacheControlHeader = $this->getCacheControlHeader(); $fields['Cache-Control'] = [$cacheControlHeader]; if (empty($cacheControlHeader)) { unset($fields['Cache-Control']); } return $fields; }
[ "public", "function", "getAll", "(", ")", "{", "$", "fields", "=", "$", "this", "->", "fields", ";", "$", "cacheControlHeader", "=", "$", "this", "->", "getCacheControlHeader", "(", ")", ";", "$", "fields", "[", "'Cache-Control'", "]", "=", "[", "$", "...
Returns all header fields Note that even for those header fields which exist only one time, the value is returned as an array (with a single item). @return array @api
[ "Returns", "all", "header", "fields" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L216-L225
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.has
public function has($name) { if ($name === 'Cache-Control') { return ($this->getCacheControlHeader() !== null); } return isset($this->fields[$name]); }
php
public function has($name) { if ($name === 'Cache-Control') { return ($this->getCacheControlHeader() !== null); } return isset($this->fields[$name]); }
[ "public", "function", "has", "(", "$", "name", ")", "{", "if", "(", "$", "name", "===", "'Cache-Control'", ")", "{", "return", "(", "$", "this", "->", "getCacheControlHeader", "(", ")", "!==", "null", ")", ";", "}", "return", "isset", "(", "$", "this...
Checks if the specified HTTP header exists @param string $name Name of the header @return boolean @api
[ "Checks", "if", "the", "specified", "HTTP", "header", "exists" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L234-L240
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.setCacheControlDirective
public function setCacheControlDirective($name, $value = null) { switch ($name) { case 'public': $this->cacheDirectives['visibility'] = 'public'; break; case 'private': case 'no-cache': $this->cacheDirectives['visibility'] = $name . (!empty($value) ? '="' . $value . '"' : ''); break; case 'no-store': case 'no-transform': case 'must-revalidate': case 'proxy-revalidate': $this->cacheDirectives[$name] = $name; break; case 'max-age': case 's-maxage': $this->cacheDirectives[$name] = $name . '=' . $value; break; } }
php
public function setCacheControlDirective($name, $value = null) { switch ($name) { case 'public': $this->cacheDirectives['visibility'] = 'public'; break; case 'private': case 'no-cache': $this->cacheDirectives['visibility'] = $name . (!empty($value) ? '="' . $value . '"' : ''); break; case 'no-store': case 'no-transform': case 'must-revalidate': case 'proxy-revalidate': $this->cacheDirectives[$name] = $name; break; case 'max-age': case 's-maxage': $this->cacheDirectives[$name] = $name . '=' . $value; break; } }
[ "public", "function", "setCacheControlDirective", "(", "$", "name", ",", "$", "value", "=", "null", ")", "{", "switch", "(", "$", "name", ")", "{", "case", "'public'", ":", "$", "this", "->", "cacheDirectives", "[", "'visibility'", "]", "=", "'public'", ...
Sets a special directive for use in the Cache-Control header, according to RFC 2616 / 14.9 @param string $name Name of the directive, for example "max-age" @param string $value An optional value @return void @api
[ "Sets", "a", "special", "directive", "for", "use", "in", "the", "Cache", "-", "Control", "header", "according", "to", "RFC", "2616", "/", "14", ".", "9" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L339-L360
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.getCacheControlDirective
public function getCacheControlDirective($name) { $value = null; switch ($name) { case 'public': $value = ($this->cacheDirectives['visibility'] === 'public' ? true : null); break; case 'private': case 'no-cache': preg_match('/^(' . $name . ')(?:="([^"]+)")?$/', $this->cacheDirectives['visibility'], $matches); if (!isset($matches[1])) { $value = null; } else { $value = (isset($matches[2]) ? $matches[2] : true); } break; case 'no-store': case 'no-transform': case 'must-revalidate': case 'proxy-revalidate': $value = ($this->cacheDirectives[$name] !== '' ? true : null); break; case 'max-age': case 's-maxage': preg_match('/^(' . $name . ')=(.+)$/', $this->cacheDirectives[$name], $matches); if (!isset($matches[1])) { $value = null; } else { $value = (isset($matches[2]) ? intval($matches[2]) : true); } break; } return $value; }
php
public function getCacheControlDirective($name) { $value = null; switch ($name) { case 'public': $value = ($this->cacheDirectives['visibility'] === 'public' ? true : null); break; case 'private': case 'no-cache': preg_match('/^(' . $name . ')(?:="([^"]+)")?$/', $this->cacheDirectives['visibility'], $matches); if (!isset($matches[1])) { $value = null; } else { $value = (isset($matches[2]) ? $matches[2] : true); } break; case 'no-store': case 'no-transform': case 'must-revalidate': case 'proxy-revalidate': $value = ($this->cacheDirectives[$name] !== '' ? true : null); break; case 'max-age': case 's-maxage': preg_match('/^(' . $name . ')=(.+)$/', $this->cacheDirectives[$name], $matches); if (!isset($matches[1])) { $value = null; } else { $value = (isset($matches[2]) ? intval($matches[2]) : true); } break; } return $value; }
[ "public", "function", "getCacheControlDirective", "(", "$", "name", ")", "{", "$", "value", "=", "null", ";", "switch", "(", "$", "name", ")", "{", "case", "'public'", ":", "$", "value", "=", "(", "$", "this", "->", "cacheDirectives", "[", "'visibility'"...
Returns the value of the specified Cache-Control directive. If the cache directive is not present, NULL is returned. If the specified directive is present but contains no value, this method returns true. Finally, if the directive is present and does contain a value, the value is returned. @param string $name Name of the cache directive, for example "max-age" @return mixed @api
[ "Returns", "the", "value", "of", "the", "specified", "Cache", "-", "Control", "directive", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L398-L433
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.setCacheControlDirectivesFromRawHeader
protected function setCacheControlDirectivesFromRawHeader($rawFieldValue) { foreach (array_keys($this->cacheDirectives) as $key) { $this->cacheDirectives[$key] = ''; } preg_match_all('/([a-zA-Z][a-zA-Z_-]*)\s*(?:=\s*(?:"([^"]*)"|([^,;\s"]*)))?/', $rawFieldValue, $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (isset($match[2]) && $match[2] !== '') { $value = $match[2]; } elseif (isset($match[3]) && $match[3] !== '') { $value = $match[3]; } else { $value = null; } $this->setCacheControlDirective(strtolower($match[1]), $value); } }
php
protected function setCacheControlDirectivesFromRawHeader($rawFieldValue) { foreach (array_keys($this->cacheDirectives) as $key) { $this->cacheDirectives[$key] = ''; } preg_match_all('/([a-zA-Z][a-zA-Z_-]*)\s*(?:=\s*(?:"([^"]*)"|([^,;\s"]*)))?/', $rawFieldValue, $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (isset($match[2]) && $match[2] !== '') { $value = $match[2]; } elseif (isset($match[3]) && $match[3] !== '') { $value = $match[3]; } else { $value = null; } $this->setCacheControlDirective(strtolower($match[1]), $value); } }
[ "protected", "function", "setCacheControlDirectivesFromRawHeader", "(", "$", "rawFieldValue", ")", "{", "foreach", "(", "array_keys", "(", "$", "this", "->", "cacheDirectives", ")", "as", "$", "key", ")", "{", "$", "this", "->", "cacheDirectives", "[", "$", "k...
Internally sets the cache directives correctly by parsing the given Cache-Control field value. @param string $rawFieldValue The value of a specification compliant Cache-Control header @return void @see set()
[ "Internally", "sets", "the", "cache", "directives", "correctly", "by", "parsing", "the", "given", "Cache", "-", "Control", "field", "value", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L443-L459
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.getCacheControlHeader
protected function getCacheControlHeader() { $cacheControl = ''; foreach ($this->cacheDirectives as $cacheDirective) { $cacheControl .= ($cacheDirective !== '' ? $cacheDirective . ', ' : ''); } $cacheControl = trim($cacheControl, ' ,'); return ($cacheControl === '' ? null : $cacheControl); }
php
protected function getCacheControlHeader() { $cacheControl = ''; foreach ($this->cacheDirectives as $cacheDirective) { $cacheControl .= ($cacheDirective !== '' ? $cacheDirective . ', ' : ''); } $cacheControl = trim($cacheControl, ' ,'); return ($cacheControl === '' ? null : $cacheControl); }
[ "protected", "function", "getCacheControlHeader", "(", ")", "{", "$", "cacheControl", "=", "''", ";", "foreach", "(", "$", "this", "->", "cacheDirectives", "as", "$", "cacheDirective", ")", "{", "$", "cacheControl", ".=", "(", "$", "cacheDirective", "!==", "...
Renders and returns a Cache-Control header, based on the previously set cache control directives. @return string Either the value of the header or NULL if it shall be omitted @see get()
[ "Renders", "and", "returns", "a", "Cache", "-", "Control", "header", "based", "on", "the", "previously", "set", "cache", "control", "directives", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L476-L484
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.setCookiesFromRawHeader
protected function setCookiesFromRawHeader($rawFieldValue) { $cookiePairs = explode(';', $rawFieldValue); foreach ($cookiePairs as $cookiePair) { if (strpos($cookiePair, '=') === false) { continue; } list($name, $value) = explode('=', $cookiePair, 2); $trimmedName = trim($name); if ($trimmedName !== '' && preg_match(Cookie::PATTERN_TOKEN, $trimmedName) === 1) { $this->setCookie(new Cookie($trimmedName, urldecode(trim($value, "\t ;\"")))); } } }
php
protected function setCookiesFromRawHeader($rawFieldValue) { $cookiePairs = explode(';', $rawFieldValue); foreach ($cookiePairs as $cookiePair) { if (strpos($cookiePair, '=') === false) { continue; } list($name, $value) = explode('=', $cookiePair, 2); $trimmedName = trim($name); if ($trimmedName !== '' && preg_match(Cookie::PATTERN_TOKEN, $trimmedName) === 1) { $this->setCookie(new Cookie($trimmedName, urldecode(trim($value, "\t ;\"")))); } } }
[ "protected", "function", "setCookiesFromRawHeader", "(", "$", "rawFieldValue", ")", "{", "$", "cookiePairs", "=", "explode", "(", "';'", ",", "$", "rawFieldValue", ")", ";", "foreach", "(", "$", "cookiePairs", "as", "$", "cookiePair", ")", "{", "if", "(", ...
Internally sets cookie objects based on the Cookie header field value. @param string $rawFieldValue The value of a specification compliant Cookie header @return void @see set()
[ "Internally", "sets", "cookie", "objects", "based", "on", "the", "Cookie", "header", "field", "value", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L493-L507
neos/flow-development-collection
Neos.Flow/Classes/Http/Headers.php
Headers.getPreparedValues
public function getPreparedValues() { $preparedValues = []; foreach ($this->getAll() as $name => $values) { $preparedValues = array_merge($preparedValues, $this->prepareValues($name, $values)); } return $preparedValues; }
php
public function getPreparedValues() { $preparedValues = []; foreach ($this->getAll() as $name => $values) { $preparedValues = array_merge($preparedValues, $this->prepareValues($name, $values)); } return $preparedValues; }
[ "public", "function", "getPreparedValues", "(", ")", "{", "$", "preparedValues", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getAll", "(", ")", "as", "$", "name", "=>", "$", "values", ")", "{", "$", "preparedValues", "=", "array_merge", "("...
Get all header lines prepared as "name: value" strings. @return array
[ "Get", "all", "header", "lines", "prepared", "as", "name", ":", "value", "strings", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Headers.php#L514-L522
neos/flow-development-collection
Neos.Flow/Classes/I18n/FormatResolver.php
FormatResolver.resolvePlaceholders
public function resolvePlaceholders($textWithPlaceholders, array $arguments, Locale $locale = null) { if ($locale === null) { $locale = $this->localizationService->getConfiguration()->getDefaultLocale(); } $lastPlaceHolderAt = 0; while ($lastPlaceHolderAt < strlen($textWithPlaceholders) && ($startOfPlaceholder = strpos($textWithPlaceholders, '{', $lastPlaceHolderAt)) !== false) { $endOfPlaceholder = strpos($textWithPlaceholders, '}', $lastPlaceHolderAt); $startOfNextPlaceholder = strpos($textWithPlaceholders, '{', $startOfPlaceholder + 1); if ($endOfPlaceholder === false || ($startOfPlaceholder + 1) >= $endOfPlaceholder || ($startOfNextPlaceholder !== false && $startOfNextPlaceholder < $endOfPlaceholder)) { // There is no closing bracket, or it is placed before the opening bracket, or there is nothing between brackets throw new Exception\InvalidFormatPlaceholderException('Text provided contains incorrectly formatted placeholders. Please make sure you conform the placeholder\'s syntax.', 1278057790); } $contentBetweenBrackets = substr($textWithPlaceholders, $startOfPlaceholder + 1, $endOfPlaceholder - $startOfPlaceholder - 1); $placeholderElements = explode(',', str_replace(' ', '', $contentBetweenBrackets)); $valueIndex = $placeholderElements[0]; if (!array_key_exists($valueIndex, $arguments)) { throw new Exception\IndexOutOfBoundsException('Placeholder "' . $valueIndex . '" was not provided, make sure you provide values for every placeholder.', 1278057791); } if (isset($placeholderElements[1])) { $formatterName = $placeholderElements[1]; $formatter = $this->getFormatter($formatterName); $formattedPlaceholder = $formatter->format($arguments[$valueIndex], $locale, array_slice($placeholderElements, 2)); } else { // No formatter defined, just string-cast the value $formattedPlaceholder = (string)($arguments[$valueIndex]); } $textWithPlaceholders = str_replace('{' . $contentBetweenBrackets . '}', $formattedPlaceholder, $textWithPlaceholders); $lastPlaceHolderAt = $startOfPlaceholder + strlen($formattedPlaceholder); } return $textWithPlaceholders; }
php
public function resolvePlaceholders($textWithPlaceholders, array $arguments, Locale $locale = null) { if ($locale === null) { $locale = $this->localizationService->getConfiguration()->getDefaultLocale(); } $lastPlaceHolderAt = 0; while ($lastPlaceHolderAt < strlen($textWithPlaceholders) && ($startOfPlaceholder = strpos($textWithPlaceholders, '{', $lastPlaceHolderAt)) !== false) { $endOfPlaceholder = strpos($textWithPlaceholders, '}', $lastPlaceHolderAt); $startOfNextPlaceholder = strpos($textWithPlaceholders, '{', $startOfPlaceholder + 1); if ($endOfPlaceholder === false || ($startOfPlaceholder + 1) >= $endOfPlaceholder || ($startOfNextPlaceholder !== false && $startOfNextPlaceholder < $endOfPlaceholder)) { // There is no closing bracket, or it is placed before the opening bracket, or there is nothing between brackets throw new Exception\InvalidFormatPlaceholderException('Text provided contains incorrectly formatted placeholders. Please make sure you conform the placeholder\'s syntax.', 1278057790); } $contentBetweenBrackets = substr($textWithPlaceholders, $startOfPlaceholder + 1, $endOfPlaceholder - $startOfPlaceholder - 1); $placeholderElements = explode(',', str_replace(' ', '', $contentBetweenBrackets)); $valueIndex = $placeholderElements[0]; if (!array_key_exists($valueIndex, $arguments)) { throw new Exception\IndexOutOfBoundsException('Placeholder "' . $valueIndex . '" was not provided, make sure you provide values for every placeholder.', 1278057791); } if (isset($placeholderElements[1])) { $formatterName = $placeholderElements[1]; $formatter = $this->getFormatter($formatterName); $formattedPlaceholder = $formatter->format($arguments[$valueIndex], $locale, array_slice($placeholderElements, 2)); } else { // No formatter defined, just string-cast the value $formattedPlaceholder = (string)($arguments[$valueIndex]); } $textWithPlaceholders = str_replace('{' . $contentBetweenBrackets . '}', $formattedPlaceholder, $textWithPlaceholders); $lastPlaceHolderAt = $startOfPlaceholder + strlen($formattedPlaceholder); } return $textWithPlaceholders; }
[ "public", "function", "resolvePlaceholders", "(", "$", "textWithPlaceholders", ",", "array", "$", "arguments", ",", "Locale", "$", "locale", "=", "null", ")", "{", "if", "(", "$", "locale", "===", "null", ")", "{", "$", "locale", "=", "$", "this", "->", ...
Replaces all placeholders in text with corresponding values. A placeholder is a group of elements separated with comma. First element is required and defines index of value to insert (numeration starts from 0, and is directly used to access element from $values array). Second element is a name of formatter to use. It's optional, and if not given, value will be simply string-casted. Remaining elements are formatter- specific and they are directly passed to the formatter class. @param string $textWithPlaceholders String message with placeholder(s) @param array $arguments An array of values to replace placeholders with @param Locale $locale Locale to use (NULL for default one) @return string The $text with placeholders resolved @throws Exception\InvalidFormatPlaceholderException When encountered incorrectly formatted placeholder @throws Exception\IndexOutOfBoundsException When trying to format nonexistent value @api
[ "Replaces", "all", "placeholders", "in", "text", "with", "corresponding", "values", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/FormatResolver.php#L101-L139
neos/flow-development-collection
Neos.Flow/Classes/I18n/FormatResolver.php
FormatResolver.getFormatter
protected function getFormatter($formatterType) { $foundFormatter = false; $formatterType = ltrim($formatterType, '\\'); if (isset($this->formatters[$formatterType])) { $foundFormatter = $this->formatters[$formatterType]; } if ($foundFormatter === false) { if ($this->objectManager->isRegistered($formatterType)) { $possibleClassName = $formatterType; } else { $possibleClassName = sprintf('Neos\Flow\I18n\Formatter\%sFormatter', ucfirst($formatterType)); if (!$this->objectManager->isRegistered($possibleClassName)) { throw new Exception\UnknownFormatterException('Could not find formatter for "' . $formatterType . '".', 1278057791); } } if (!$this->reflectionService->isClassImplementationOf($possibleClassName, Formatter\FormatterInterface::class)) { throw new Exception\InvalidFormatterException(sprintf('The resolved internationalization formatter class name "%s" does not implement "%s" as required.', $possibleClassName, FormatterInterface::class), 1358162557); } $foundFormatter = $this->objectManager->get($possibleClassName); } $this->formatters[$formatterType] = $foundFormatter; return $foundFormatter; }
php
protected function getFormatter($formatterType) { $foundFormatter = false; $formatterType = ltrim($formatterType, '\\'); if (isset($this->formatters[$formatterType])) { $foundFormatter = $this->formatters[$formatterType]; } if ($foundFormatter === false) { if ($this->objectManager->isRegistered($formatterType)) { $possibleClassName = $formatterType; } else { $possibleClassName = sprintf('Neos\Flow\I18n\Formatter\%sFormatter', ucfirst($formatterType)); if (!$this->objectManager->isRegistered($possibleClassName)) { throw new Exception\UnknownFormatterException('Could not find formatter for "' . $formatterType . '".', 1278057791); } } if (!$this->reflectionService->isClassImplementationOf($possibleClassName, Formatter\FormatterInterface::class)) { throw new Exception\InvalidFormatterException(sprintf('The resolved internationalization formatter class name "%s" does not implement "%s" as required.', $possibleClassName, FormatterInterface::class), 1358162557); } $foundFormatter = $this->objectManager->get($possibleClassName); } $this->formatters[$formatterType] = $foundFormatter; return $foundFormatter; }
[ "protected", "function", "getFormatter", "(", "$", "formatterType", ")", "{", "$", "foundFormatter", "=", "false", ";", "$", "formatterType", "=", "ltrim", "(", "$", "formatterType", ",", "'\\\\'", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "f...
Returns instance of concrete formatter. The type provided has to be either a name of existing class placed in I18n\Formatter namespace or a fully qualified class name; in both cases implementing this' package's FormatterInterface. For example, when $formatterName is 'number', the I18n\Formatter\NumberFormatter class has to exist; when $formatterName is 'Acme\Foobar\I18nFormatter\SampleFormatter', this class must exist and implement I18n\Formatter\FormatterInterface. Throws exception if there is no formatter for name given or one could be retrieved but does not satisfy the FormatterInterface. @param string $formatterType Either one of the built-in formatters or fully qualified formatter class name @return Formatter\FormatterInterface The concrete formatter class @throws Exception\UnknownFormatterException When formatter for a name given does not exist @throws Exception\InvalidFormatterException When formatter for a name given does not exist
[ "Returns", "instance", "of", "concrete", "formatter", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/FormatResolver.php#L160-L186
neos/flow-development-collection
Neos.Flow/Classes/Security/Authentication/Provider/FileBasedSimpleKeyProvider.php
FileBasedSimpleKeyProvider.authenticate
public function authenticate(TokenInterface $authenticationToken) { if (!($authenticationToken instanceof PasswordToken)) { throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840); } $credentials = $authenticationToken->getCredentials(); if (is_array($credentials) && isset($credentials['password'])) { $this->validateCredentials($authenticationToken, $credentials); return; } if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } }
php
public function authenticate(TokenInterface $authenticationToken) { if (!($authenticationToken instanceof PasswordToken)) { throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840); } $credentials = $authenticationToken->getCredentials(); if (is_array($credentials) && isset($credentials['password'])) { $this->validateCredentials($authenticationToken, $credentials); return; } if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } }
[ "public", "function", "authenticate", "(", "TokenInterface", "$", "authenticationToken", ")", "{", "if", "(", "!", "(", "$", "authenticationToken", "instanceof", "PasswordToken", ")", ")", "{", "throw", "new", "UnsupportedAuthenticationTokenException", "(", "'This pro...
Sets isAuthenticated to true for all tokens. @param TokenInterface $authenticationToken The token to be authenticated @return void @throws UnsupportedAuthenticationTokenException @throws \Neos\Flow\Security\Exception @throws \Neos\Flow\Security\Exception\InvalidAuthenticationStatusException
[ "Sets", "isAuthenticated", "to", "true", "for", "all", "tokens", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Security/Authentication/Provider/FileBasedSimpleKeyProvider.php#L85-L100
neos/flow-development-collection
Neos.Flow/Classes/Command/SessionCommandController.php
SessionCommandController.destroyAllCommand
public function destroyAllCommand() { $this->cacheManager->getCache('Flow_Session_Storage')->flush(); $this->cacheManager->getCache('Flow_Session_MetaData')->flush(); $this->outputLine('Destroyed all sessions.'); $this->sendAndExit(0); }
php
public function destroyAllCommand() { $this->cacheManager->getCache('Flow_Session_Storage')->flush(); $this->cacheManager->getCache('Flow_Session_MetaData')->flush(); $this->outputLine('Destroyed all sessions.'); $this->sendAndExit(0); }
[ "public", "function", "destroyAllCommand", "(", ")", "{", "$", "this", "->", "cacheManager", "->", "getCache", "(", "'Flow_Session_Storage'", ")", "->", "flush", "(", ")", ";", "$", "this", "->", "cacheManager", "->", "getCache", "(", "'Flow_Session_MetaData'", ...
Destroys all sessions. This special command is needed, because sessions are kept in persistent storage and are not flushed with other caches by default. This is functionally equivalent to `./flow flow:cache:flushOne Flow_Session_Storage && ./flow flow:cache:flushOne Flow_Session_MetaData` @return void @since 5.2
[ "Destroys", "all", "sessions", ".", "This", "special", "command", "is", "needed", "because", "sessions", "are", "kept", "in", "persistent", "storage", "and", "are", "not", "flushed", "with", "other", "caches", "by", "default", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Command/SessionCommandController.php#L52-L58
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.initializeObject
public function initializeObject() { if ($this->cache->has('typeConverterMap')) { $this->typeConverters = $this->cache->get('typeConverterMap'); return; } $this->typeConverters = $this->prepareTypeConverterMap(); $this->cache->set('typeConverterMap', $this->typeConverters); }
php
public function initializeObject() { if ($this->cache->has('typeConverterMap')) { $this->typeConverters = $this->cache->get('typeConverterMap'); return; } $this->typeConverters = $this->prepareTypeConverterMap(); $this->cache->set('typeConverterMap', $this->typeConverters); }
[ "public", "function", "initializeObject", "(", ")", "{", "if", "(", "$", "this", "->", "cache", "->", "has", "(", "'typeConverterMap'", ")", ")", "{", "$", "this", "->", "typeConverters", "=", "$", "this", "->", "cache", "->", "get", "(", "'typeConverter...
Lifecycle method, called after all dependencies have been injected. Here, the typeConverter array gets initialized. @return void
[ "Lifecycle", "method", "called", "after", "all", "dependencies", "have", "been", "injected", ".", "Here", "the", "typeConverter", "array", "gets", "initialized", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L73-L82
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.convert
public function convert($source, $targetType, PropertyMappingConfigurationInterface $configuration = null) { if ($configuration === null) { $configuration = $this->buildPropertyMappingConfiguration(); } $currentPropertyPath = []; $this->messages = new Result(); try { $result = $this->doMapping($source, $targetType, $configuration, $currentPropertyPath); if ($result instanceof Error) { return null; } return $result; } catch (SecurityException $exception) { throw $exception; } catch (\Exception $exception) { throw new PropertyException('Could not convert target type "' . $targetType . '"' . (count($currentPropertyPath) > 0 ? ', at property path "' . implode('.', $currentPropertyPath) . '"' : '') . ': ' . $exception->getMessage(), 1297759968, $exception); } }
php
public function convert($source, $targetType, PropertyMappingConfigurationInterface $configuration = null) { if ($configuration === null) { $configuration = $this->buildPropertyMappingConfiguration(); } $currentPropertyPath = []; $this->messages = new Result(); try { $result = $this->doMapping($source, $targetType, $configuration, $currentPropertyPath); if ($result instanceof Error) { return null; } return $result; } catch (SecurityException $exception) { throw $exception; } catch (\Exception $exception) { throw new PropertyException('Could not convert target type "' . $targetType . '"' . (count($currentPropertyPath) > 0 ? ', at property path "' . implode('.', $currentPropertyPath) . '"' : '') . ': ' . $exception->getMessage(), 1297759968, $exception); } }
[ "public", "function", "convert", "(", "$", "source", ",", "$", "targetType", ",", "PropertyMappingConfigurationInterface", "$", "configuration", "=", "null", ")", "{", "if", "(", "$", "configuration", "===", "null", ")", "{", "$", "configuration", "=", "$", ...
Map $source to $targetType, and return the result. If $source is an object and already is of type $targetType, we do return the unmodified object. @param mixed $source the source data to map. MUST be a simple type, NO object allowed! @param string $targetType The type of the target; can be either a class name or a simple type. @param PropertyMappingConfigurationInterface $configuration Configuration for the property mapping. If NULL, the PropertyMappingConfigurationBuilder will create a default configuration. @return mixed an instance of $targetType @throws Exception @throws SecurityException @api
[ "Map", "$source", "to", "$targetType", "and", "return", "the", "result", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L111-L131
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.doMapping
protected function doMapping($source, $targetType, PropertyMappingConfigurationInterface $configuration, &$currentPropertyPath) { $targetTypeWithoutNull = TypeHandling::stripNullableType($targetType); $isNullableType = $targetType !== $targetTypeWithoutNull; if ($source === null && $isNullableType) { return null; } $targetType = $targetTypeWithoutNull; if (is_object($source)) { $targetClass = TypeHandling::truncateElementType($targetType); if ($source instanceof $targetClass) { return $source; } } if ($source === null) { $source = ''; } $typeConverter = $this->findTypeConverter($source, $targetType, $configuration); $targetType = $typeConverter->getTargetTypeForSource($source, $targetType, $configuration); if (!is_object($typeConverter) || !($typeConverter instanceof TypeConverterInterface)) { throw new Exception\TypeConverterException('Type converter for "' . $source . '" -> "' . $targetType . '" not found.'); } $convertedChildProperties = []; foreach ($typeConverter->getSourceChildPropertiesToBeConverted($source) as $sourcePropertyName => $sourcePropertyValue) { $targetPropertyName = $configuration->getTargetPropertyName($sourcePropertyName); if ($configuration->shouldSkip($targetPropertyName)) { continue; } if (!$configuration->shouldMap($targetPropertyName)) { if ($configuration->shouldSkipUnknownProperties()) { continue; } throw new Exception\InvalidPropertyMappingConfigurationException('It is not allowed to map property "' . $targetPropertyName . '". You need to use $propertyMappingConfiguration->allowProperties(\'' . $targetPropertyName . '\') to enable mapping of this property.', 1335969887); } $targetPropertyType = $typeConverter->getTypeOfChildProperty($targetType, $targetPropertyName, $configuration); if ($targetPropertyType === null) { continue; } $subConfiguration = $configuration->getConfigurationFor($targetPropertyName); $currentPropertyPath[] = $targetPropertyName; $targetPropertyValue = $this->doMapping($sourcePropertyValue, $targetPropertyType, $subConfiguration, $currentPropertyPath); array_pop($currentPropertyPath); if (!($targetPropertyValue instanceof Error)) { $convertedChildProperties[$targetPropertyName] = $targetPropertyValue; } } $result = $typeConverter->convertFrom($source, $targetType, $convertedChildProperties, $configuration); if ($result instanceof Error) { $this->messages->forProperty(implode('.', $currentPropertyPath))->addError($result); } return $result; }
php
protected function doMapping($source, $targetType, PropertyMappingConfigurationInterface $configuration, &$currentPropertyPath) { $targetTypeWithoutNull = TypeHandling::stripNullableType($targetType); $isNullableType = $targetType !== $targetTypeWithoutNull; if ($source === null && $isNullableType) { return null; } $targetType = $targetTypeWithoutNull; if (is_object($source)) { $targetClass = TypeHandling::truncateElementType($targetType); if ($source instanceof $targetClass) { return $source; } } if ($source === null) { $source = ''; } $typeConverter = $this->findTypeConverter($source, $targetType, $configuration); $targetType = $typeConverter->getTargetTypeForSource($source, $targetType, $configuration); if (!is_object($typeConverter) || !($typeConverter instanceof TypeConverterInterface)) { throw new Exception\TypeConverterException('Type converter for "' . $source . '" -> "' . $targetType . '" not found.'); } $convertedChildProperties = []; foreach ($typeConverter->getSourceChildPropertiesToBeConverted($source) as $sourcePropertyName => $sourcePropertyValue) { $targetPropertyName = $configuration->getTargetPropertyName($sourcePropertyName); if ($configuration->shouldSkip($targetPropertyName)) { continue; } if (!$configuration->shouldMap($targetPropertyName)) { if ($configuration->shouldSkipUnknownProperties()) { continue; } throw new Exception\InvalidPropertyMappingConfigurationException('It is not allowed to map property "' . $targetPropertyName . '". You need to use $propertyMappingConfiguration->allowProperties(\'' . $targetPropertyName . '\') to enable mapping of this property.', 1335969887); } $targetPropertyType = $typeConverter->getTypeOfChildProperty($targetType, $targetPropertyName, $configuration); if ($targetPropertyType === null) { continue; } $subConfiguration = $configuration->getConfigurationFor($targetPropertyName); $currentPropertyPath[] = $targetPropertyName; $targetPropertyValue = $this->doMapping($sourcePropertyValue, $targetPropertyType, $subConfiguration, $currentPropertyPath); array_pop($currentPropertyPath); if (!($targetPropertyValue instanceof Error)) { $convertedChildProperties[$targetPropertyName] = $targetPropertyValue; } } $result = $typeConverter->convertFrom($source, $targetType, $convertedChildProperties, $configuration); if ($result instanceof Error) { $this->messages->forProperty(implode('.', $currentPropertyPath))->addError($result); } return $result; }
[ "protected", "function", "doMapping", "(", "$", "source", ",", "$", "targetType", ",", "PropertyMappingConfigurationInterface", "$", "configuration", ",", "&", "$", "currentPropertyPath", ")", "{", "$", "targetTypeWithoutNull", "=", "TypeHandling", "::", "stripNullabl...
Internal function which actually does the property mapping. @param mixed $source the source data to map. MUST be a simple type, NO object allowed! @param string $targetType The type of the target; can be either a class name or a simple type. @param PropertyMappingConfigurationInterface $configuration Configuration for the property mapping. @param array $currentPropertyPath The property path currently being mapped; used for knowing the context in case an exception is thrown. @return mixed an instance of $targetType @throws Exception\TypeConverterException @throws Exception\InvalidPropertyMappingConfigurationException
[ "Internal", "function", "which", "actually", "does", "the", "property", "mapping", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L155-L217
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.findTypeConverter
protected function findTypeConverter($source, $targetType, PropertyMappingConfigurationInterface $configuration) { if ($configuration->getTypeConverter() !== null) { return $configuration->getTypeConverter(); } if (!is_string($targetType)) { throw new Exception\InvalidTargetException('The target type was no string, but of type "' . gettype($targetType) . '"', 1297941727); } $normalizedTargetType = TypeHandling::normalizeType($targetType); $truncatedTargetType = TypeHandling::truncateElementType($normalizedTargetType); $converter = null; $normalizedSourceTypes = $this->determineSourceTypes($source); foreach ($normalizedSourceTypes as $sourceType) { if (TypeHandling::isSimpleType($truncatedTargetType)) { if (isset($this->typeConverters[$sourceType][$truncatedTargetType])) { $converter = $this->findEligibleConverterWithHighestPriority($this->typeConverters[$sourceType][$truncatedTargetType], $source, $normalizedTargetType); } } else { $converter = $this->findFirstEligibleTypeConverterInObjectHierarchy($source, $sourceType, $normalizedTargetType); } if ($converter !== null) { return $converter; } } throw new Exception\TypeConverterException('No converter found which can be used to convert from "' . implode('" or "', $normalizedSourceTypes) . '" to "' . $normalizedTargetType . '".'); }
php
protected function findTypeConverter($source, $targetType, PropertyMappingConfigurationInterface $configuration) { if ($configuration->getTypeConverter() !== null) { return $configuration->getTypeConverter(); } if (!is_string($targetType)) { throw new Exception\InvalidTargetException('The target type was no string, but of type "' . gettype($targetType) . '"', 1297941727); } $normalizedTargetType = TypeHandling::normalizeType($targetType); $truncatedTargetType = TypeHandling::truncateElementType($normalizedTargetType); $converter = null; $normalizedSourceTypes = $this->determineSourceTypes($source); foreach ($normalizedSourceTypes as $sourceType) { if (TypeHandling::isSimpleType($truncatedTargetType)) { if (isset($this->typeConverters[$sourceType][$truncatedTargetType])) { $converter = $this->findEligibleConverterWithHighestPriority($this->typeConverters[$sourceType][$truncatedTargetType], $source, $normalizedTargetType); } } else { $converter = $this->findFirstEligibleTypeConverterInObjectHierarchy($source, $sourceType, $normalizedTargetType); } if ($converter !== null) { return $converter; } } throw new Exception\TypeConverterException('No converter found which can be used to convert from "' . implode('" or "', $normalizedSourceTypes) . '" to "' . $normalizedTargetType . '".'); }
[ "protected", "function", "findTypeConverter", "(", "$", "source", ",", "$", "targetType", ",", "PropertyMappingConfigurationInterface", "$", "configuration", ")", "{", "if", "(", "$", "configuration", "->", "getTypeConverter", "(", ")", "!==", "null", ")", "{", ...
Determine the type converter to be used. If no converter has been found, an exception is raised. @param mixed $source @param string $targetType @param PropertyMappingConfigurationInterface $configuration @return TypeConverterInterface Type Converter which should be used to convert between $source and $targetType. @throws Exception\TypeConverterException @throws Exception\InvalidTargetException
[ "Determine", "the", "type", "converter", "to", "be", "used", ".", "If", "no", "converter", "has", "been", "found", "an", "exception", "is", "raised", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L229-L258
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.findFirstEligibleTypeConverterInObjectHierarchy
protected function findFirstEligibleTypeConverterInObjectHierarchy($source, $sourceType, $targetType) { $targetClass = TypeHandling::truncateElementType($targetType); if (!class_exists($targetClass) && !interface_exists($targetClass)) { throw new Exception\InvalidTargetException(sprintf('Could not find a suitable type converter for "%s" because the class / interface "%s" does not exist.', $targetType, $targetClass), 1297948764); } if (!isset($this->typeConverters[$sourceType])) { return null; } $convertersForSource = $this->typeConverters[$sourceType]; if (isset($convertersForSource[$targetClass])) { $converter = $this->findEligibleConverterWithHighestPriority($convertersForSource[$targetClass], $source, $targetType); if ($converter !== null) { return $converter; } } foreach (class_parents($targetClass) as $parentClass) { if (!isset($convertersForSource[$parentClass])) { continue; } $converter = $this->findEligibleConverterWithHighestPriority($convertersForSource[$parentClass], $source, $targetType); if ($converter !== null) { return $converter; } } $converters = $this->getConvertersForInterfaces($convertersForSource, class_implements($targetClass)); $converter = $this->findEligibleConverterWithHighestPriority($converters, $source, $targetType); if ($converter !== null) { return $converter; } if (isset($convertersForSource['object'])) { return $this->findEligibleConverterWithHighestPriority($convertersForSource['object'], $source, $targetType); } else { return null; } }
php
protected function findFirstEligibleTypeConverterInObjectHierarchy($source, $sourceType, $targetType) { $targetClass = TypeHandling::truncateElementType($targetType); if (!class_exists($targetClass) && !interface_exists($targetClass)) { throw new Exception\InvalidTargetException(sprintf('Could not find a suitable type converter for "%s" because the class / interface "%s" does not exist.', $targetType, $targetClass), 1297948764); } if (!isset($this->typeConverters[$sourceType])) { return null; } $convertersForSource = $this->typeConverters[$sourceType]; if (isset($convertersForSource[$targetClass])) { $converter = $this->findEligibleConverterWithHighestPriority($convertersForSource[$targetClass], $source, $targetType); if ($converter !== null) { return $converter; } } foreach (class_parents($targetClass) as $parentClass) { if (!isset($convertersForSource[$parentClass])) { continue; } $converter = $this->findEligibleConverterWithHighestPriority($convertersForSource[$parentClass], $source, $targetType); if ($converter !== null) { return $converter; } } $converters = $this->getConvertersForInterfaces($convertersForSource, class_implements($targetClass)); $converter = $this->findEligibleConverterWithHighestPriority($converters, $source, $targetType); if ($converter !== null) { return $converter; } if (isset($convertersForSource['object'])) { return $this->findEligibleConverterWithHighestPriority($convertersForSource['object'], $source, $targetType); } else { return null; } }
[ "protected", "function", "findFirstEligibleTypeConverterInObjectHierarchy", "(", "$", "source", ",", "$", "sourceType", ",", "$", "targetType", ")", "{", "$", "targetClass", "=", "TypeHandling", "::", "truncateElementType", "(", "$", "targetType", ")", ";", "if", ...
Tries to find a suitable type converter for the given source and target type. @param string $source The actual source value @param string $sourceType Type of the source to convert from @param string $targetType Name of the target type to find a type converter for @return mixed Either the matching object converter or NULL @throws Exception\InvalidTargetException
[ "Tries", "to", "find", "a", "suitable", "type", "converter", "for", "the", "given", "source", "and", "target", "type", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L269-L310
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.determineSourceTypes
protected function determineSourceTypes($source) { if (is_string($source)) { return ['string']; } elseif (is_array($source)) { return ['array']; } elseif (is_float($source)) { return ['float']; } elseif (is_integer($source)) { return ['integer']; } elseif (is_bool($source)) { return ['boolean']; } elseif (is_object($source)) { $class = get_class($source); $parentClasses = class_parents($class); $interfaces = class_implements($class); return array_merge([$class], $parentClasses, $interfaces, ['object']); } else { throw new Exception\InvalidSourceException('The source is not of type string, array, float, integer, boolean or object, but of type "' . gettype($source) . '"', 1297773150); } }
php
protected function determineSourceTypes($source) { if (is_string($source)) { return ['string']; } elseif (is_array($source)) { return ['array']; } elseif (is_float($source)) { return ['float']; } elseif (is_integer($source)) { return ['integer']; } elseif (is_bool($source)) { return ['boolean']; } elseif (is_object($source)) { $class = get_class($source); $parentClasses = class_parents($class); $interfaces = class_implements($class); return array_merge([$class], $parentClasses, $interfaces, ['object']); } else { throw new Exception\InvalidSourceException('The source is not of type string, array, float, integer, boolean or object, but of type "' . gettype($source) . '"', 1297773150); } }
[ "protected", "function", "determineSourceTypes", "(", "$", "source", ")", "{", "if", "(", "is_string", "(", "$", "source", ")", ")", "{", "return", "[", "'string'", "]", ";", "}", "elseif", "(", "is_array", "(", "$", "source", ")", ")", "{", "return", ...
Determine the type of the source data, or throw an exception if source was an unsupported format. @param mixed $source @return array Possible source types (single value for simple typed source, multiple values for object source) @throws Exception\InvalidSourceException
[ "Determine", "the", "type", "of", "the", "source", "data", "or", "throw", "an", "exception", "if", "source", "was", "an", "unsupported", "format", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L373-L394
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.prepareTypeConverterMap
protected function prepareTypeConverterMap() { $typeConverterMap = []; $typeConverterClassNames = static::getTypeConverterImplementationClassNames($this->objectManager); foreach ($typeConverterClassNames as $typeConverterClassName) { /** @var TypeConverterInterface $typeConverter */ $typeConverter = $this->objectManager->get($typeConverterClassName); foreach ($typeConverter->getSupportedSourceTypes() as $supportedSourceType) { $normalizedSourceType = TypeHandling::normalizeType($supportedSourceType); $normalizedTargetType = TypeHandling::normalizeType($typeConverter->getSupportedTargetType()); if (isset($typeConverterMap[$normalizedSourceType][$normalizedTargetType][$typeConverter->getPriority()])) { throw new Exception\DuplicateTypeConverterException('There exist at least two converters which handle the conversion from "' . $supportedSourceType . '" to "' . $normalizedTargetType . '" with priority "' . $typeConverter->getPriority() . '": ' . $typeConverterMap[$supportedSourceType][$normalizedTargetType][$typeConverter->getPriority()] . ' and ' . get_class($typeConverter), 1297951378); } $typeConverterMap[$normalizedSourceType][$normalizedTargetType][$typeConverter->getPriority()] = $typeConverterClassName; } } return $typeConverterMap; }
php
protected function prepareTypeConverterMap() { $typeConverterMap = []; $typeConverterClassNames = static::getTypeConverterImplementationClassNames($this->objectManager); foreach ($typeConverterClassNames as $typeConverterClassName) { /** @var TypeConverterInterface $typeConverter */ $typeConverter = $this->objectManager->get($typeConverterClassName); foreach ($typeConverter->getSupportedSourceTypes() as $supportedSourceType) { $normalizedSourceType = TypeHandling::normalizeType($supportedSourceType); $normalizedTargetType = TypeHandling::normalizeType($typeConverter->getSupportedTargetType()); if (isset($typeConverterMap[$normalizedSourceType][$normalizedTargetType][$typeConverter->getPriority()])) { throw new Exception\DuplicateTypeConverterException('There exist at least two converters which handle the conversion from "' . $supportedSourceType . '" to "' . $normalizedTargetType . '" with priority "' . $typeConverter->getPriority() . '": ' . $typeConverterMap[$supportedSourceType][$normalizedTargetType][$typeConverter->getPriority()] . ' and ' . get_class($typeConverter), 1297951378); } $typeConverterMap[$normalizedSourceType][$normalizedTargetType][$typeConverter->getPriority()] = $typeConverterClassName; } } return $typeConverterMap; }
[ "protected", "function", "prepareTypeConverterMap", "(", ")", "{", "$", "typeConverterMap", "=", "[", "]", ";", "$", "typeConverterClassNames", "=", "static", "::", "getTypeConverterImplementationClassNames", "(", "$", "this", "->", "objectManager", ")", ";", "forea...
Collects all TypeConverter implementations in a multi-dimensional array with source and target types. @return array @throws Exception\DuplicateTypeConverterException @see getTypeConverters
[ "Collects", "all", "TypeConverter", "implementations", "in", "a", "multi", "-", "dimensional", "array", "with", "source", "and", "target", "types", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L403-L421
neos/flow-development-collection
Neos.Flow/Classes/Property/PropertyMapper.php
PropertyMapper.buildPropertyMappingConfiguration
public function buildPropertyMappingConfiguration($type = PropertyMappingConfiguration::class) { /** @var PropertyMappingConfiguration $configuration */ $configuration = new $type(); $configuration->setTypeConverterOptions(TypeConverter\PersistentObjectConverter::class, [ TypeConverter\PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED => true, TypeConverter\PersistentObjectConverter::CONFIGURATION_MODIFICATION_ALLOWED => true ]); $configuration->allowAllProperties(); return $configuration; }
php
public function buildPropertyMappingConfiguration($type = PropertyMappingConfiguration::class) { /** @var PropertyMappingConfiguration $configuration */ $configuration = new $type(); $configuration->setTypeConverterOptions(TypeConverter\PersistentObjectConverter::class, [ TypeConverter\PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED => true, TypeConverter\PersistentObjectConverter::CONFIGURATION_MODIFICATION_ALLOWED => true ]); $configuration->allowAllProperties(); return $configuration; }
[ "public", "function", "buildPropertyMappingConfiguration", "(", "$", "type", "=", "PropertyMappingConfiguration", "::", "class", ")", "{", "/** @var PropertyMappingConfiguration $configuration */", "$", "configuration", "=", "new", "$", "type", "(", ")", ";", "$", "conf...
Builds the default property mapping configuration. @param string $type the implementation class name of the PropertyMappingConfiguration to instantiate; must be a subclass of Neos\Flow\Property\PropertyMappingConfiguration @return PropertyMappingConfiguration
[ "Builds", "the", "default", "property", "mapping", "configuration", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/PropertyMapper.php#L446-L458
neos/flow-development-collection
Neos.Cache/Classes/Backend/RequireOnceFromValueTrait.php
RequireOnceFromValueTrait.requireOnce
public function requireOnce(string $entryIdentifier) { $value = trim($this->get($entryIdentifier)); if ($value === '') { return false; } if (isset($this->_requiredEntryIdentifiers[$entryIdentifier])) { return false; } $this->_requiredEntryIdentifiers[$entryIdentifier] = true; return include('data:text/plain;base64,' . base64_encode($value)); }
php
public function requireOnce(string $entryIdentifier) { $value = trim($this->get($entryIdentifier)); if ($value === '') { return false; } if (isset($this->_requiredEntryIdentifiers[$entryIdentifier])) { return false; } $this->_requiredEntryIdentifiers[$entryIdentifier] = true; return include('data:text/plain;base64,' . base64_encode($value)); }
[ "public", "function", "requireOnce", "(", "string", "$", "entryIdentifier", ")", "{", "$", "value", "=", "trim", "(", "$", "this", "->", "get", "(", "$", "entryIdentifier", ")", ")", ";", "if", "(", "$", "value", "===", "''", ")", "{", "return", "fal...
Loads PHP code from the cache and require_onces it right away. @param string $entryIdentifier An identifier which describes the cache entry to load @return mixed Potential return value from the include operation @api
[ "Loads", "PHP", "code", "from", "the", "cache", "and", "require_onces", "it", "right", "away", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Cache/Classes/Backend/RequireOnceFromValueTrait.php#L31-L42
neos/flow-development-collection
Neos.Flow/Classes/Property/TypeConverter/ScalarTypeToObjectConverter.php
ScalarTypeToObjectConverter.canConvertFrom
public function canConvertFrom($source, $targetType) { if (( $this->reflectionService->isClassAnnotatedWith($targetType, Flow\Entity::class) || $this->reflectionService->isClassAnnotatedWith($targetType, Flow\ValueObject::class) || $this->reflectionService->isClassAnnotatedWith($targetType, Entity::class) ) === true) { return false; } $methodParameters = $this->reflectionService->getMethodParameters($targetType, '__construct'); if (count($methodParameters) !== 1) { return false; } $methodParameter = array_shift($methodParameters); return TypeHandling::normalizeType($methodParameter['type']) === gettype($source); }
php
public function canConvertFrom($source, $targetType) { if (( $this->reflectionService->isClassAnnotatedWith($targetType, Flow\Entity::class) || $this->reflectionService->isClassAnnotatedWith($targetType, Flow\ValueObject::class) || $this->reflectionService->isClassAnnotatedWith($targetType, Entity::class) ) === true) { return false; } $methodParameters = $this->reflectionService->getMethodParameters($targetType, '__construct'); if (count($methodParameters) !== 1) { return false; } $methodParameter = array_shift($methodParameters); return TypeHandling::normalizeType($methodParameter['type']) === gettype($source); }
[ "public", "function", "canConvertFrom", "(", "$", "source", ",", "$", "targetType", ")", "{", "if", "(", "(", "$", "this", "->", "reflectionService", "->", "isClassAnnotatedWith", "(", "$", "targetType", ",", "Flow", "\\", "Entity", "::", "class", ")", "||...
Only convert if the given target class has a constructor with one argument being of type given type @param string $source @param string $targetType @return bool
[ "Only", "convert", "if", "the", "given", "target", "class", "has", "a", "constructor", "with", "one", "argument", "being", "of", "type", "given", "type" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Property/TypeConverter/ScalarTypeToObjectConverter.php#L59-L75
neos/flow-development-collection
Neos.Flow/Classes/Cli/CommandController.php
CommandController.processRequest
public function processRequest(RequestInterface $request, ResponseInterface $response) { if (!$request instanceof Request) { throw new UnsupportedRequestTypeException(sprintf('%s only supports command line requests – requests of type "%s" given.', get_class($this), get_class($request)), 1300787096); } $this->request = $request; $this->request->setDispatched(true); $this->response = $response; $this->commandMethodName = $this->resolveCommandMethodName(); $this->initializeCommandMethodArguments(); $this->mapRequestArgumentsToControllerArguments(); $this->callCommandMethod(); }
php
public function processRequest(RequestInterface $request, ResponseInterface $response) { if (!$request instanceof Request) { throw new UnsupportedRequestTypeException(sprintf('%s only supports command line requests – requests of type "%s" given.', get_class($this), get_class($request)), 1300787096); } $this->request = $request; $this->request->setDispatched(true); $this->response = $response; $this->commandMethodName = $this->resolveCommandMethodName(); $this->initializeCommandMethodArguments(); $this->mapRequestArgumentsToControllerArguments(); $this->callCommandMethod(); }
[ "public", "function", "processRequest", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "if", "(", "!", "$", "request", "instanceof", "Request", ")", "{", "throw", "new", "UnsupportedRequestTypeException", "(", "sprint...
Processes a command line request. @param RequestInterface $request The request object @param ResponseInterface $response The response, modified by this handler @return void @throws UnsupportedRequestTypeException if the controller doesn't support the current request type @api
[ "Processes", "a", "command", "line", "request", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/CommandController.php#L115-L129
neos/flow-development-collection
Neos.Flow/Classes/Cli/CommandController.php
CommandController.initializeCommandMethodArguments
protected function initializeCommandMethodArguments() { $this->arguments->removeAll(); $methodParameters = $this->commandManager->getCommandMethodParameters(get_class($this), $this->commandMethodName); foreach ($methodParameters as $parameterName => $parameterInfo) { $dataType = null; if (isset($parameterInfo['type'])) { $dataType = $parameterInfo['type']; } elseif ($parameterInfo['array']) { $dataType = 'array'; } if ($dataType === null) { throw new InvalidArgumentTypeException(sprintf('The argument type for parameter $%s of method %s->%s() could not be detected.', $parameterName, get_class($this), $this->commandMethodName), 1306755296); } $defaultValue = (isset($parameterInfo['defaultValue']) ? $parameterInfo['defaultValue'] : null); $this->arguments->addNewArgument($parameterName, $dataType, ($parameterInfo['optional'] === false), $defaultValue); } }
php
protected function initializeCommandMethodArguments() { $this->arguments->removeAll(); $methodParameters = $this->commandManager->getCommandMethodParameters(get_class($this), $this->commandMethodName); foreach ($methodParameters as $parameterName => $parameterInfo) { $dataType = null; if (isset($parameterInfo['type'])) { $dataType = $parameterInfo['type']; } elseif ($parameterInfo['array']) { $dataType = 'array'; } if ($dataType === null) { throw new InvalidArgumentTypeException(sprintf('The argument type for parameter $%s of method %s->%s() could not be detected.', $parameterName, get_class($this), $this->commandMethodName), 1306755296); } $defaultValue = (isset($parameterInfo['defaultValue']) ? $parameterInfo['defaultValue'] : null); $this->arguments->addNewArgument($parameterName, $dataType, ($parameterInfo['optional'] === false), $defaultValue); } }
[ "protected", "function", "initializeCommandMethodArguments", "(", ")", "{", "$", "this", "->", "arguments", "->", "removeAll", "(", ")", ";", "$", "methodParameters", "=", "$", "this", "->", "commandManager", "->", "getCommandMethodParameters", "(", "get_class", "...
Initializes the arguments array of this controller by creating an empty argument object for each of the method arguments found in the designated command method. @return void @throws InvalidArgumentTypeException
[ "Initializes", "the", "arguments", "array", "of", "this", "controller", "by", "creating", "an", "empty", "argument", "object", "for", "each", "of", "the", "method", "arguments", "found", "in", "the", "designated", "command", "method", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/CommandController.php#L156-L174
neos/flow-development-collection
Neos.Flow/Classes/Cli/CommandController.php
CommandController.mapRequestArgumentsToControllerArguments
protected function mapRequestArgumentsToControllerArguments() { /** @var Argument $argument */ foreach ($this->arguments as $argument) { $argumentName = $argument->getName(); if ($this->request->hasArgument($argumentName)) { $argument->setValue($this->request->getArgument($argumentName)); continue; } if (!$argument->isRequired()) { continue; } $argumentValue = null; while ($argumentValue === null) { $argumentValue = $this->output->ask(sprintf('<comment>Please specify the required argument "%s":</comment> ', $argumentName)); } if ($argumentValue === null) { $exception = new CommandException(sprintf('Required argument "%s" is not set.', $argumentName), 1306755520); $this->forward('error', HelpCommandController::class, ['exception' => $exception]); } $argument->setValue($argumentValue); } }
php
protected function mapRequestArgumentsToControllerArguments() { /** @var Argument $argument */ foreach ($this->arguments as $argument) { $argumentName = $argument->getName(); if ($this->request->hasArgument($argumentName)) { $argument->setValue($this->request->getArgument($argumentName)); continue; } if (!$argument->isRequired()) { continue; } $argumentValue = null; while ($argumentValue === null) { $argumentValue = $this->output->ask(sprintf('<comment>Please specify the required argument "%s":</comment> ', $argumentName)); } if ($argumentValue === null) { $exception = new CommandException(sprintf('Required argument "%s" is not set.', $argumentName), 1306755520); $this->forward('error', HelpCommandController::class, ['exception' => $exception]); } $argument->setValue($argumentValue); } }
[ "protected", "function", "mapRequestArgumentsToControllerArguments", "(", ")", "{", "/** @var Argument $argument */", "foreach", "(", "$", "this", "->", "arguments", "as", "$", "argument", ")", "{", "$", "argumentName", "=", "$", "argument", "->", "getName", "(", ...
Maps arguments delivered by the request object to the local controller arguments. @return void
[ "Maps", "arguments", "delivered", "by", "the", "request", "object", "to", "the", "local", "controller", "arguments", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/CommandController.php#L181-L205
neos/flow-development-collection
Neos.Flow/Classes/Cli/CommandController.php
CommandController.forward
protected function forward(string $commandName, string $controllerObjectName = null, array $arguments = []) { $this->request->setDispatched(false); $this->request->setControllerCommandName($commandName); if ($controllerObjectName !== null) { $this->request->setControllerObjectName($controllerObjectName); } $this->request->setArguments($arguments); $this->arguments->removeAll(); throw new StopActionException(); }
php
protected function forward(string $commandName, string $controllerObjectName = null, array $arguments = []) { $this->request->setDispatched(false); $this->request->setControllerCommandName($commandName); if ($controllerObjectName !== null) { $this->request->setControllerObjectName($controllerObjectName); } $this->request->setArguments($arguments); $this->arguments->removeAll(); throw new StopActionException(); }
[ "protected", "function", "forward", "(", "string", "$", "commandName", ",", "string", "$", "controllerObjectName", "=", "null", ",", "array", "$", "arguments", "=", "[", "]", ")", "{", "$", "this", "->", "request", "->", "setDispatched", "(", "false", ")",...
Forwards the request to another command and / or CommandController. Request is directly transferred to the other command / controller without the need for a new request. @param string $commandName @param string $controllerObjectName @param array $arguments @return void @throws StopActionException
[ "Forwards", "the", "request", "to", "another", "command", "and", "/", "or", "CommandController", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/CommandController.php#L219-L230
neos/flow-development-collection
Neos.Flow/Classes/Cli/CommandController.php
CommandController.callCommandMethod
protected function callCommandMethod() { $preparedArguments = []; /** @var Argument $argument */ foreach ($this->arguments as $argument) { $preparedArguments[] = $argument->getValue(); } $command = new Command(get_class($this), $this->request->getControllerCommandName()); if ($command->isDeprecated()) { $suggestedCommandMessage = ''; $relatedCommandIdentifiers = $command->getRelatedCommandIdentifiers(); if ($relatedCommandIdentifiers !== []) { $suggestedCommandMessage = sprintf( ', use the following command%s instead: %s', count($relatedCommandIdentifiers) > 1 ? 's' : '', implode(', ', $relatedCommandIdentifiers) ); } $this->outputLine('<b>Warning:</b> This command is <b>DEPRECATED</b>%s%s', [$suggestedCommandMessage, PHP_EOL]); } $commandResult = call_user_func_array([$this, $this->commandMethodName], $preparedArguments); if (is_string($commandResult) && strlen($commandResult) > 0) { $this->response->appendContent($commandResult); } elseif (is_object($commandResult) && method_exists($commandResult, '__toString')) { $this->response->appendContent((string)$commandResult); } }
php
protected function callCommandMethod() { $preparedArguments = []; /** @var Argument $argument */ foreach ($this->arguments as $argument) { $preparedArguments[] = $argument->getValue(); } $command = new Command(get_class($this), $this->request->getControllerCommandName()); if ($command->isDeprecated()) { $suggestedCommandMessage = ''; $relatedCommandIdentifiers = $command->getRelatedCommandIdentifiers(); if ($relatedCommandIdentifiers !== []) { $suggestedCommandMessage = sprintf( ', use the following command%s instead: %s', count($relatedCommandIdentifiers) > 1 ? 's' : '', implode(', ', $relatedCommandIdentifiers) ); } $this->outputLine('<b>Warning:</b> This command is <b>DEPRECATED</b>%s%s', [$suggestedCommandMessage, PHP_EOL]); } $commandResult = call_user_func_array([$this, $this->commandMethodName], $preparedArguments); if (is_string($commandResult) && strlen($commandResult) > 0) { $this->response->appendContent($commandResult); } elseif (is_object($commandResult) && method_exists($commandResult, '__toString')) { $this->response->appendContent((string)$commandResult); } }
[ "protected", "function", "callCommandMethod", "(", ")", "{", "$", "preparedArguments", "=", "[", "]", ";", "/** @var Argument $argument */", "foreach", "(", "$", "this", "->", "arguments", "as", "$", "argument", ")", "{", "$", "preparedArguments", "[", "]", "=...
Calls the specified command method and passes the arguments. If the command returns a string, it is appended to the content in the response object. If the command doesn't return anything and a valid view exists, the view is rendered automatically. @return void
[ "Calls", "the", "specified", "command", "method", "and", "passes", "the", "arguments", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Cli/CommandController.php#L241-L271
neos/flow-development-collection
Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php
NumberFormatter.format
public function format($value, Locale $locale, array $styleProperties = []) { if (isset($styleProperties[0])) { $formatType = $styleProperties[0]; NumbersReader::validateFormatType($formatType); } else { $formatType = NumbersReader::FORMAT_TYPE_DECIMAL; } switch ($formatType) { case NumbersReader::FORMAT_TYPE_PERCENT: return $this->formatPercentNumber($value, $locale, NumbersReader::FORMAT_LENGTH_DEFAULT); default: return $this->formatDecimalNumber($value, $locale, NumbersReader::FORMAT_LENGTH_DEFAULT); } }
php
public function format($value, Locale $locale, array $styleProperties = []) { if (isset($styleProperties[0])) { $formatType = $styleProperties[0]; NumbersReader::validateFormatType($formatType); } else { $formatType = NumbersReader::FORMAT_TYPE_DECIMAL; } switch ($formatType) { case NumbersReader::FORMAT_TYPE_PERCENT: return $this->formatPercentNumber($value, $locale, NumbersReader::FORMAT_LENGTH_DEFAULT); default: return $this->formatDecimalNumber($value, $locale, NumbersReader::FORMAT_LENGTH_DEFAULT); } }
[ "public", "function", "format", "(", "$", "value", ",", "Locale", "$", "locale", ",", "array", "$", "styleProperties", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "styleProperties", "[", "0", "]", ")", ")", "{", "$", "formatType", "=", "...
Formats provided value using optional style properties @param mixed $value Formatter-specific variable to format (can be integer, \DateTime, etc) @param Locale $locale Locale to use @param array $styleProperties Integer-indexed array of formatter-specific style properties (can be empty) @return string String representation of $value provided, or (string)$value @api
[ "Formats", "provided", "value", "using", "optional", "style", "properties" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php#L65-L80
neos/flow-development-collection
Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php
NumberFormatter.formatNumberWithCustomPattern
public function formatNumberWithCustomPattern($number, $format, Locale $locale) { return $this->doFormattingWithParsedFormat($number, $this->numbersReader->parseCustomFormat($format), $this->numbersReader->getLocalizedSymbolsForLocale($locale)); }
php
public function formatNumberWithCustomPattern($number, $format, Locale $locale) { return $this->doFormattingWithParsedFormat($number, $this->numbersReader->parseCustomFormat($format), $this->numbersReader->getLocalizedSymbolsForLocale($locale)); }
[ "public", "function", "formatNumberWithCustomPattern", "(", "$", "number", ",", "$", "format", ",", "Locale", "$", "locale", ")", "{", "return", "$", "this", "->", "doFormattingWithParsedFormat", "(", "$", "number", ",", "$", "this", "->", "numbersReader", "->...
Returns number formatted by custom format, string provided in parameter. Format must obey syntax defined in CLDR specification, excluding unimplemented features (see documentation for this class). Format is remembered in this classes cache and won't be parsed again for some time. @param mixed $number Float or int, can be negative, can be NaN or infinite @param string $format Format string @param Locale $locale A locale used for finding symbols array @return string Formatted number. Will return string-casted version of $number if pattern is not valid / supported @api
[ "Returns", "number", "formatted", "by", "custom", "format", "string", "provided", "in", "parameter", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php#L97-L100
neos/flow-development-collection
Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php
NumberFormatter.formatDecimalNumber
public function formatDecimalNumber($number, Locale $locale, $formatLength = NumbersReader::FORMAT_LENGTH_DEFAULT) { NumbersReader::validateFormatLength($formatLength); return $this->doFormattingWithParsedFormat($number, $this->numbersReader->parseFormatFromCldr($locale, NumbersReader::FORMAT_TYPE_DECIMAL, $formatLength), $this->numbersReader->getLocalizedSymbolsForLocale($locale)); }
php
public function formatDecimalNumber($number, Locale $locale, $formatLength = NumbersReader::FORMAT_LENGTH_DEFAULT) { NumbersReader::validateFormatLength($formatLength); return $this->doFormattingWithParsedFormat($number, $this->numbersReader->parseFormatFromCldr($locale, NumbersReader::FORMAT_TYPE_DECIMAL, $formatLength), $this->numbersReader->getLocalizedSymbolsForLocale($locale)); }
[ "public", "function", "formatDecimalNumber", "(", "$", "number", ",", "Locale", "$", "locale", ",", "$", "formatLength", "=", "NumbersReader", "::", "FORMAT_LENGTH_DEFAULT", ")", "{", "NumbersReader", "::", "validateFormatLength", "(", "$", "formatLength", ")", ";...
Formats number with format string for decimal numbers defined in CLDR for particular locale. Note: currently length is not used in decimalFormats from CLDR. But it's defined in the specification, so we support it here. @param mixed $number Float or int, can be negative, can be NaN or infinite @param Locale $locale @param string $formatLength One of NumbersReader FORMAT_LENGTH constants @return string Formatted number. Will return string-casted version of $number if there is no pattern for given $locale / $formatLength @api
[ "Formats", "number", "with", "format", "string", "for", "decimal", "numbers", "defined", "in", "CLDR", "for", "particular", "locale", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php#L115-L119
neos/flow-development-collection
Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php
NumberFormatter.formatPercentNumber
public function formatPercentNumber($number, Locale $locale, $formatLength = NumbersReader::FORMAT_LENGTH_DEFAULT) { NumbersReader::validateFormatLength($formatLength); return $this->doFormattingWithParsedFormat($number, $this->numbersReader->parseFormatFromCldr($locale, NumbersReader::FORMAT_TYPE_PERCENT, $formatLength), $this->numbersReader->getLocalizedSymbolsForLocale($locale)); }
php
public function formatPercentNumber($number, Locale $locale, $formatLength = NumbersReader::FORMAT_LENGTH_DEFAULT) { NumbersReader::validateFormatLength($formatLength); return $this->doFormattingWithParsedFormat($number, $this->numbersReader->parseFormatFromCldr($locale, NumbersReader::FORMAT_TYPE_PERCENT, $formatLength), $this->numbersReader->getLocalizedSymbolsForLocale($locale)); }
[ "public", "function", "formatPercentNumber", "(", "$", "number", ",", "Locale", "$", "locale", ",", "$", "formatLength", "=", "NumbersReader", "::", "FORMAT_LENGTH_DEFAULT", ")", "{", "NumbersReader", "::", "validateFormatLength", "(", "$", "formatLength", ")", ";...
Formats number with format string for percentage defined in CLDR for particular locale. Note: currently length is not used in percentFormats from CLDR. But it's defined in the specification, so we support it here. @param mixed $number Float or int, can be negative, can be NaN or infinite @param Locale $locale @param string $formatLength One of NumbersReader FORMAT_LENGTH constants @return string Formatted number. Will return string-casted version of $number if there is no pattern for given $locale / $formatLength @api
[ "Formats", "number", "with", "format", "string", "for", "percentage", "defined", "in", "CLDR", "for", "particular", "locale", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php#L134-L138
neos/flow-development-collection
Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php
NumberFormatter.formatCurrencyNumber
public function formatCurrencyNumber($number, Locale $locale, $currency, $formatLength = NumbersReader::FORMAT_LENGTH_DEFAULT, $currencyCode = null) { NumbersReader::validateFormatLength($formatLength); $parsedFormat = $this->numbersReader->parseFormatFromCldr($locale, NumbersReader::FORMAT_TYPE_CURRENCY, $formatLength); if ($currencyCode !== null) { // When currencyCode is set, maxDecimalDigits and rounding is overridden with CLDR data $currencyFraction = $this->currencyReader->getFraction($currencyCode); $parsedFormat['rounding'] = $currencyFraction['rounding']; $parsedFormat['maxDecimalDigits'] = $currencyFraction['digits']; $parsedFormat['minDecimalDigits'] = min($parsedFormat['minDecimalDigits'], $parsedFormat['maxDecimalDigits']); } return $this->doFormattingWithParsedFormat($number, $parsedFormat, $this->numbersReader->getLocalizedSymbolsForLocale($locale), $currency); }
php
public function formatCurrencyNumber($number, Locale $locale, $currency, $formatLength = NumbersReader::FORMAT_LENGTH_DEFAULT, $currencyCode = null) { NumbersReader::validateFormatLength($formatLength); $parsedFormat = $this->numbersReader->parseFormatFromCldr($locale, NumbersReader::FORMAT_TYPE_CURRENCY, $formatLength); if ($currencyCode !== null) { // When currencyCode is set, maxDecimalDigits and rounding is overridden with CLDR data $currencyFraction = $this->currencyReader->getFraction($currencyCode); $parsedFormat['rounding'] = $currencyFraction['rounding']; $parsedFormat['maxDecimalDigits'] = $currencyFraction['digits']; $parsedFormat['minDecimalDigits'] = min($parsedFormat['minDecimalDigits'], $parsedFormat['maxDecimalDigits']); } return $this->doFormattingWithParsedFormat($number, $parsedFormat, $this->numbersReader->getLocalizedSymbolsForLocale($locale), $currency); }
[ "public", "function", "formatCurrencyNumber", "(", "$", "number", ",", "Locale", "$", "locale", ",", "$", "currency", ",", "$", "formatLength", "=", "NumbersReader", "::", "FORMAT_LENGTH_DEFAULT", ",", "$", "currencyCode", "=", "null", ")", "{", "NumbersReader",...
Formats number with format string for currency defined in CLDR for particular locale. Currency symbol provided will be inserted into formatted number string. Note: currently length is not used in currencyFormats from CLDR. But it's defined in the specification, so we support it here. @param mixed $number Float or int, can be negative, can be NaN or infinite @param Locale $locale @param string $currency Currency symbol (or name) @param string $formatLength One of NumbersReader FORMAT_LENGTH constants @param string $currencyCode The ISO 4217 currency code of the currency to format. Used to set decimal places and rounding. @return string Formatted number. Will return string-casted version of $number if there is no pattern for given $locale / $formatLength @api
[ "Formats", "number", "with", "format", "string", "for", "currency", "defined", "in", "CLDR", "for", "particular", "locale", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php#L157-L171
neos/flow-development-collection
Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php
NumberFormatter.doFormattingWithParsedFormat
protected function doFormattingWithParsedFormat($number, array $parsedFormat, array $symbols, $currency = null) { if ($parsedFormat === false) { return (string)$number; } if (is_nan($number)) { return $symbols['nan']; } if (is_infinite($number)) { if ($number < 0) { return $parsedFormat['negativePrefix'] . $symbols['infinity'] . $parsedFormat['negativeSuffix']; } else { return $parsedFormat['positivePrefix'] . $symbols['infinity'] . $parsedFormat['positiveSuffix']; } } $isNegative = $number < 0; $number = abs($number * $parsedFormat['multiplier']); if ($parsedFormat['rounding'] > 0) { $number = round($number / $parsedFormat['rounding'], 0, \PHP_ROUND_HALF_EVEN) * $parsedFormat['rounding']; } if ($parsedFormat['maxDecimalDigits'] >= 0) { $number = round($number, $parsedFormat['maxDecimalDigits']); } $number = (string)$number; if (($positionOfDecimalSeparator = strpos($number, '.')) !== false) { $integerPart = substr($number, 0, $positionOfDecimalSeparator); $decimalPart = substr($number, $positionOfDecimalSeparator + 1); } else { $integerPart = $number; $decimalPart = ''; } if ($parsedFormat['minDecimalDigits'] > strlen($decimalPart)) { $decimalPart = str_pad($decimalPart, $parsedFormat['minDecimalDigits'], '0'); } $integerPart = str_pad($integerPart, $parsedFormat['minIntegerDigits'], '0', STR_PAD_LEFT); if ($parsedFormat['primaryGroupingSize'] > 0 && strlen($integerPart) > $parsedFormat['primaryGroupingSize']) { $primaryGroupOfIntegerPart = substr($integerPart, - $parsedFormat['primaryGroupingSize']); $restOfIntegerPart = substr($integerPart, 0, - $parsedFormat['primaryGroupingSize']); // Pad the numbers with spaces from the left, so the length of the string is a multiply of secondaryGroupingSize (and str_split() can split on equal parts) $padLengthToGetEvenSize = (int)((strlen($restOfIntegerPart) + $parsedFormat['secondaryGroupingSize'] - 1) / $parsedFormat['secondaryGroupingSize']) * $parsedFormat['secondaryGroupingSize']; $restOfIntegerPart = str_pad($restOfIntegerPart, $padLengthToGetEvenSize, ' ', STR_PAD_LEFT); // Insert localized group separators between every secondary groups and primary group (using str_split() and implode()) $secondaryGroupsOfIntegerPart = str_split($restOfIntegerPart, $parsedFormat['secondaryGroupingSize']); $integerPart = ltrim(implode($symbols['group'], $secondaryGroupsOfIntegerPart)) . $symbols['group'] . $primaryGroupOfIntegerPart; } if (strlen($decimalPart) > 0) { $decimalPart = $symbols['decimal'] . $decimalPart; } if ($isNegative) { $number = $parsedFormat['negativePrefix'] . $integerPart . $decimalPart . $parsedFormat['negativeSuffix']; } else { $number = $parsedFormat['positivePrefix'] . $integerPart . $decimalPart . $parsedFormat['positiveSuffix']; } $number = str_replace(['%', '‰', '-'], [$symbols['percentSign'], $symbols['perMille'], $symbols['minusSign']], $number); if ($currency !== null) { $number = str_replace('¤', $currency, $number); } return $number; }
php
protected function doFormattingWithParsedFormat($number, array $parsedFormat, array $symbols, $currency = null) { if ($parsedFormat === false) { return (string)$number; } if (is_nan($number)) { return $symbols['nan']; } if (is_infinite($number)) { if ($number < 0) { return $parsedFormat['negativePrefix'] . $symbols['infinity'] . $parsedFormat['negativeSuffix']; } else { return $parsedFormat['positivePrefix'] . $symbols['infinity'] . $parsedFormat['positiveSuffix']; } } $isNegative = $number < 0; $number = abs($number * $parsedFormat['multiplier']); if ($parsedFormat['rounding'] > 0) { $number = round($number / $parsedFormat['rounding'], 0, \PHP_ROUND_HALF_EVEN) * $parsedFormat['rounding']; } if ($parsedFormat['maxDecimalDigits'] >= 0) { $number = round($number, $parsedFormat['maxDecimalDigits']); } $number = (string)$number; if (($positionOfDecimalSeparator = strpos($number, '.')) !== false) { $integerPart = substr($number, 0, $positionOfDecimalSeparator); $decimalPart = substr($number, $positionOfDecimalSeparator + 1); } else { $integerPart = $number; $decimalPart = ''; } if ($parsedFormat['minDecimalDigits'] > strlen($decimalPart)) { $decimalPart = str_pad($decimalPart, $parsedFormat['minDecimalDigits'], '0'); } $integerPart = str_pad($integerPart, $parsedFormat['minIntegerDigits'], '0', STR_PAD_LEFT); if ($parsedFormat['primaryGroupingSize'] > 0 && strlen($integerPart) > $parsedFormat['primaryGroupingSize']) { $primaryGroupOfIntegerPart = substr($integerPart, - $parsedFormat['primaryGroupingSize']); $restOfIntegerPart = substr($integerPart, 0, - $parsedFormat['primaryGroupingSize']); // Pad the numbers with spaces from the left, so the length of the string is a multiply of secondaryGroupingSize (and str_split() can split on equal parts) $padLengthToGetEvenSize = (int)((strlen($restOfIntegerPart) + $parsedFormat['secondaryGroupingSize'] - 1) / $parsedFormat['secondaryGroupingSize']) * $parsedFormat['secondaryGroupingSize']; $restOfIntegerPart = str_pad($restOfIntegerPart, $padLengthToGetEvenSize, ' ', STR_PAD_LEFT); // Insert localized group separators between every secondary groups and primary group (using str_split() and implode()) $secondaryGroupsOfIntegerPart = str_split($restOfIntegerPart, $parsedFormat['secondaryGroupingSize']); $integerPart = ltrim(implode($symbols['group'], $secondaryGroupsOfIntegerPart)) . $symbols['group'] . $primaryGroupOfIntegerPart; } if (strlen($decimalPart) > 0) { $decimalPart = $symbols['decimal'] . $decimalPart; } if ($isNegative) { $number = $parsedFormat['negativePrefix'] . $integerPart . $decimalPart . $parsedFormat['negativeSuffix']; } else { $number = $parsedFormat['positivePrefix'] . $integerPart . $decimalPart . $parsedFormat['positiveSuffix']; } $number = str_replace(['%', '‰', '-'], [$symbols['percentSign'], $symbols['perMille'], $symbols['minusSign']], $number); if ($currency !== null) { $number = str_replace('¤', $currency, $number); } return $number; }
[ "protected", "function", "doFormattingWithParsedFormat", "(", "$", "number", ",", "array", "$", "parsedFormat", ",", "array", "$", "symbols", ",", "$", "currency", "=", "null", ")", "{", "if", "(", "$", "parsedFormat", "===", "false", ")", "{", "return", "...
Formats provided float or integer. Format rules defined in $parsedFormat array are used. Localizable symbols are replaced with elements from $symbols array, and currency placeholder is replaced with the value of $currency, if not NULL. If $number is NaN or infinite, proper localized symbol will be returned, as defined in CLDR specification. @param mixed $number Float or int, can be negative, can be NaN or infinite @param array $parsedFormat An array describing format (as in $parsedFormats property) @param array $symbols An array with symbols to use (as in $localeSymbols property) @param string $currency Currency symbol to be inserted into formatted number (if applicable) @return string Formatted number. Will return string-casted version of $number if pattern is false
[ "Formats", "provided", "float", "or", "integer", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Formatter/NumberFormatter.php#L189-L263
neos/flow-development-collection
Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php
RequestInformationHelper.getScriptRequestPathAndFilename
public static function getScriptRequestPathAndFilename(ServerRequestInterface $request): string { $server = $request->getServerParams(); if (isset($server['SCRIPT_NAME'])) { return $server['SCRIPT_NAME']; } if (isset($server['ORIG_SCRIPT_NAME'])) { return $server['ORIG_SCRIPT_NAME']; } return ''; }
php
public static function getScriptRequestPathAndFilename(ServerRequestInterface $request): string { $server = $request->getServerParams(); if (isset($server['SCRIPT_NAME'])) { return $server['SCRIPT_NAME']; } if (isset($server['ORIG_SCRIPT_NAME'])) { return $server['ORIG_SCRIPT_NAME']; } return ''; }
[ "public", "static", "function", "getScriptRequestPathAndFilename", "(", "ServerRequestInterface", "$", "request", ")", ":", "string", "{", "$", "server", "=", "$", "request", "->", "getServerParams", "(", ")", ";", "if", "(", "isset", "(", "$", "server", "[", ...
Returns the relative path (i.e. relative to the web root) and name of the script as it was accessed through the web server. @param ServerRequestInterface $request The request in question @return string Relative path and name of the PHP script as accessed through the web @api
[ "Returns", "the", "relative", "path", "(", "i", ".", "e", ".", "relative", "to", "the", "web", "root", ")", "and", "name", "of", "the", "script", "as", "it", "was", "accessed", "through", "the", "web", "server", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php#L32-L43
neos/flow-development-collection
Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php
RequestInformationHelper.getScriptRequestPath
public static function getScriptRequestPath(ServerRequestInterface $request): string { // FIXME: Shouldn't this be a simple dirname on getScriptRequestPathAndFilename $requestPathSegments = explode('/', self::getScriptRequestPathAndFilename($request)); array_pop($requestPathSegments); return implode('/', $requestPathSegments) . '/'; }
php
public static function getScriptRequestPath(ServerRequestInterface $request): string { // FIXME: Shouldn't this be a simple dirname on getScriptRequestPathAndFilename $requestPathSegments = explode('/', self::getScriptRequestPathAndFilename($request)); array_pop($requestPathSegments); return implode('/', $requestPathSegments) . '/'; }
[ "public", "static", "function", "getScriptRequestPath", "(", "ServerRequestInterface", "$", "request", ")", ":", "string", "{", "// FIXME: Shouldn't this be a simple dirname on getScriptRequestPathAndFilename", "$", "requestPathSegments", "=", "explode", "(", "'/'", ",", "sel...
Returns the relative path (i.e. relative to the web root) to the script as it was accessed through the web server. @param ServerRequestInterface $request The request in question @return string Relative path to the PHP script as accessed through the web @api
[ "Returns", "the", "relative", "path", "(", "i", ".", "e", ".", "relative", "to", "the", "web", "root", ")", "to", "the", "script", "as", "it", "was", "accessed", "through", "the", "web", "server", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php#L53-L59
neos/flow-development-collection
Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php
RequestInformationHelper.generateBaseUri
public static function generateBaseUri(ServerRequestInterface $request): UriInterface { $baseUri = clone $request->getUri(); $baseUri = $baseUri->withQuery(''); $baseUri = $baseUri->withFragment(''); $baseUri = $baseUri->withPath(self::getScriptRequestPath($request)); return $baseUri; }
php
public static function generateBaseUri(ServerRequestInterface $request): UriInterface { $baseUri = clone $request->getUri(); $baseUri = $baseUri->withQuery(''); $baseUri = $baseUri->withFragment(''); $baseUri = $baseUri->withPath(self::getScriptRequestPath($request)); return $baseUri; }
[ "public", "static", "function", "generateBaseUri", "(", "ServerRequestInterface", "$", "request", ")", ":", "UriInterface", "{", "$", "baseUri", "=", "clone", "$", "request", "->", "getUri", "(", ")", ";", "$", "baseUri", "=", "$", "baseUri", "->", "withQuer...
Tries to detect the base URI of request. @param ServerRequestInterface $request @return UriInterface
[ "Tries", "to", "detect", "the", "base", "URI", "of", "request", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php#L67-L75
neos/flow-development-collection
Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php
RequestInformationHelper.generateRequestLine
public static function generateRequestLine(RequestInterface $request): string { return sprintf("%s %s HTTP/%s\r\n", $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion()); }
php
public static function generateRequestLine(RequestInterface $request): string { return sprintf("%s %s HTTP/%s\r\n", $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion()); }
[ "public", "static", "function", "generateRequestLine", "(", "RequestInterface", "$", "request", ")", ":", "string", "{", "return", "sprintf", "(", "\"%s %s HTTP/%s\\r\\n\"", ",", "$", "request", "->", "getMethod", "(", ")", ",", "$", "request", "->", "getRequest...
Return the Request-Line of this Request Message, consisting of the method, the URI and the HTTP version Would be, for example, "GET /foo?bar=baz HTTP/1.1" Note that the URI part is, at the moment, only possible in the form "abs_path" since the actual requestUri of the Request cannot be determined during the creation of the Request. @param RequestInterface $request @return string @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1
[ "Return", "the", "Request", "-", "Line", "of", "this", "Request", "Message", "consisting", "of", "the", "method", "the", "URI", "and", "the", "HTTP", "version", "Would", "be", "for", "example", "GET", "/", "foo?bar", "=", "baz", "HTTP", "/", "1", ".", ...
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php#L87-L90
neos/flow-development-collection
Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php
RequestInformationHelper.renderRequestHeaders
public static function renderRequestHeaders(RequestInterface $request): string { $renderedHeaders = ''; $headers = $request->getHeaders(); if ($headers instanceof Headers) { $renderedHeaders .= $headers->__toString(); } else { foreach (array_keys($headers) as $name) { $renderedHeaders .= $request->getHeaderLine($name); } } return $renderedHeaders; }
php
public static function renderRequestHeaders(RequestInterface $request): string { $renderedHeaders = ''; $headers = $request->getHeaders(); if ($headers instanceof Headers) { $renderedHeaders .= $headers->__toString(); } else { foreach (array_keys($headers) as $name) { $renderedHeaders .= $request->getHeaderLine($name); } } return $renderedHeaders; }
[ "public", "static", "function", "renderRequestHeaders", "(", "RequestInterface", "$", "request", ")", ":", "string", "{", "$", "renderedHeaders", "=", "''", ";", "$", "headers", "=", "$", "request", "->", "getHeaders", "(", ")", ";", "if", "(", "$", "heade...
Renders the HTTP headers - EXCLUDING the status header - of the given request @param RequestInterface $request @return string
[ "Renders", "the", "HTTP", "headers", "-", "EXCLUDING", "the", "status", "header", "-", "of", "the", "given", "request" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php#L98-L111
neos/flow-development-collection
Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php
RequestInformationHelper.getContentCharset
public static function getContentCharset(RequestInterface $request): string { $contentType = $request->getHeaderLine('Content-Type'); if (preg_match('/[^;]+; ?charset=(?P<charset>[^;]+);?.*/', $contentType, $matches)) { return $matches['charset']; } return ''; }
php
public static function getContentCharset(RequestInterface $request): string { $contentType = $request->getHeaderLine('Content-Type'); if (preg_match('/[^;]+; ?charset=(?P<charset>[^;]+);?.*/', $contentType, $matches)) { return $matches['charset']; } return ''; }
[ "public", "static", "function", "getContentCharset", "(", "RequestInterface", "$", "request", ")", ":", "string", "{", "$", "contentType", "=", "$", "request", "->", "getHeaderLine", "(", "'Content-Type'", ")", ";", "if", "(", "preg_match", "(", "'/[^;]+; ?chars...
Extract the charset from the content type header if available @param RequestInterface $request @return string the found charset or empty string if none
[ "Extract", "the", "charset", "from", "the", "content", "type", "header", "if", "available" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Http/Helper/RequestInformationHelper.php#L119-L127
neos/flow-development-collection
Neos.Flow/Classes/Utility/Algorithms.php
Algorithms.generateRandomString
public static function generateRandomString($count, $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') { $characterCount = \Neos\Utility\Unicode\Functions::strlen($characters); $string = ''; for ($i = 0; $i < $count; $i++) { $string .= \Neos\Utility\Unicode\Functions::substr($characters, random_int(0, ($characterCount - 1)), 1); } return $string; }
php
public static function generateRandomString($count, $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') { $characterCount = \Neos\Utility\Unicode\Functions::strlen($characters); $string = ''; for ($i = 0; $i < $count; $i++) { $string .= \Neos\Utility\Unicode\Functions::substr($characters, random_int(0, ($characterCount - 1)), 1); } return $string; }
[ "public", "static", "function", "generateRandomString", "(", "$", "count", ",", "$", "characters", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'", ")", "{", "$", "characterCount", "=", "\\", "Neos", "\\", "Utility", "\\", "Unicode", "\\", "Fun...
Returns a random string with alpha-numeric characters. @param integer $count Number of characters to generate @param string $characters Allowed characters, defaults to alpha-numeric (a-zA-Z0-9) @return string A random string
[ "Returns", "a", "random", "string", "with", "alpha", "-", "numeric", "characters", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Utility/Algorithms.php#L71-L80
neos/flow-development-collection
Neos.Flow/Classes/I18n/Xliff/V12/XliffParser.php
XliffParser.doParsingFromRoot
protected function doParsingFromRoot(\SimpleXMLElement $root): array { $parsedData = []; foreach ($root->children() as $file) { $parsedData[] = $this->getFileData($file); } return $parsedData; }
php
protected function doParsingFromRoot(\SimpleXMLElement $root): array { $parsedData = []; foreach ($root->children() as $file) { $parsedData[] = $this->getFileData($file); } return $parsedData; }
[ "protected", "function", "doParsingFromRoot", "(", "\\", "SimpleXMLElement", "$", "root", ")", ":", "array", "{", "$", "parsedData", "=", "[", "]", ";", "foreach", "(", "$", "root", "->", "children", "(", ")", "as", "$", "file", ")", "{", "$", "parsedD...
Returns array representation of XLIFF data, starting from a root node. @param \SimpleXMLElement $root A root node @return array An array representing parsed XLIFF @throws InvalidXliffDataException @todo Support "approved" attribute
[ "Returns", "array", "representation", "of", "XLIFF", "data", "starting", "from", "a", "root", "node", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/I18n/Xliff/V12/XliffParser.php#L44-L53
neos/flow-development-collection
Neos.Utility.Lock/Classes/FlockLockStrategy.php
FlockLockStrategy.configureLockDirectory
protected function configureLockDirectory(string $lockDirectory) { Utility\Files::createDirectoryRecursively($lockDirectory); $this->temporaryDirectory = $lockDirectory; }
php
protected function configureLockDirectory(string $lockDirectory) { Utility\Files::createDirectoryRecursively($lockDirectory); $this->temporaryDirectory = $lockDirectory; }
[ "protected", "function", "configureLockDirectory", "(", "string", "$", "lockDirectory", ")", "{", "Utility", "\\", "Files", "::", "createDirectoryRecursively", "(", "$", "lockDirectory", ")", ";", "$", "this", "->", "temporaryDirectory", "=", "$", "lockDirectory", ...
Sets the temporaryDirectory as static variable for the lock class. @param string $lockDirectory @throws LockNotAcquiredException return void
[ "Sets", "the", "temporaryDirectory", "as", "static", "variable", "for", "the", "lock", "class", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Utility.Lock/Classes/FlockLockStrategy.php#L91-L95
neos/flow-development-collection
Neos.Utility.Lock/Classes/FlockLockStrategy.php
FlockLockStrategy.tryToAcquireLock
protected function tryToAcquireLock(bool $exclusiveLock): bool { $this->filePointer = @fopen($this->lockFileName, 'w'); if ($this->filePointer === false) { throw new LockNotAcquiredException(sprintf('Lock file "%s" could not be opened', $this->lockFileName), 1386520596); } $this->applyFlock($exclusiveLock); $fstat = fstat($this->filePointer); $stat = @stat($this->lockFileName); // Make sure that the file did not get unlinked between the fopen and the actual flock // This will always be true on windows, because 'ino' stat will always be 0, but unlink is not possible on opened files anyway if ($stat !== false && $stat['ino'] === $fstat['ino']) { return true; } flock($this->filePointer, LOCK_UN); fclose($this->filePointer); $this->filePointer = null; usleep(100 + rand(0, 100)); return false; }
php
protected function tryToAcquireLock(bool $exclusiveLock): bool { $this->filePointer = @fopen($this->lockFileName, 'w'); if ($this->filePointer === false) { throw new LockNotAcquiredException(sprintf('Lock file "%s" could not be opened', $this->lockFileName), 1386520596); } $this->applyFlock($exclusiveLock); $fstat = fstat($this->filePointer); $stat = @stat($this->lockFileName); // Make sure that the file did not get unlinked between the fopen and the actual flock // This will always be true on windows, because 'ino' stat will always be 0, but unlink is not possible on opened files anyway if ($stat !== false && $stat['ino'] === $fstat['ino']) { return true; } flock($this->filePointer, LOCK_UN); fclose($this->filePointer); $this->filePointer = null; usleep(100 + rand(0, 100)); return false; }
[ "protected", "function", "tryToAcquireLock", "(", "bool", "$", "exclusiveLock", ")", ":", "bool", "{", "$", "this", "->", "filePointer", "=", "@", "fopen", "(", "$", "this", "->", "lockFileName", ",", "'w'", ")", ";", "if", "(", "$", "this", "->", "fil...
Tries to open a lock file and apply the lock to it. @param boolean $exclusiveLock @return boolean Was a lock aquired? @throws LockNotAcquiredException
[ "Tries", "to", "open", "a", "lock", "file", "and", "apply", "the", "lock", "to", "it", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Utility.Lock/Classes/FlockLockStrategy.php#L104-L127
neos/flow-development-collection
Neos.Utility.Lock/Classes/FlockLockStrategy.php
FlockLockStrategy.applyFlock
protected function applyFlock(bool $exclusiveLock) { $lockOption = $exclusiveLock === true ? LOCK_EX : LOCK_SH; if (flock($this->filePointer, $lockOption) !== true) { throw new LockNotAcquiredException(sprintf('Could not lock file "%s"', $this->lockFileName), 1386520597); } }
php
protected function applyFlock(bool $exclusiveLock) { $lockOption = $exclusiveLock === true ? LOCK_EX : LOCK_SH; if (flock($this->filePointer, $lockOption) !== true) { throw new LockNotAcquiredException(sprintf('Could not lock file "%s"', $this->lockFileName), 1386520597); } }
[ "protected", "function", "applyFlock", "(", "bool", "$", "exclusiveLock", ")", "{", "$", "lockOption", "=", "$", "exclusiveLock", "===", "true", "?", "LOCK_EX", ":", "LOCK_SH", ";", "if", "(", "flock", "(", "$", "this", "->", "filePointer", ",", "$", "lo...
apply flock to the opened lock file. @param boolean $exclusiveLock @throws LockNotAcquiredException
[ "apply", "flock", "to", "the", "opened", "lock", "file", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Utility.Lock/Classes/FlockLockStrategy.php#L135-L142
neos/flow-development-collection
Neos.Utility.Lock/Classes/FlockLockStrategy.php
FlockLockStrategy.release
public function release(): bool { $success = true; if (is_resource($this->filePointer)) { // FIXME: The lockfile should be unlocked at this point but this will again lead to race conditions, // so we need to find out how to do this in a safe way. Keeping the lock files is very inode intensive // and should therefore change ASAP. if (flock($this->filePointer, LOCK_UN) === false) { $success = false; } fclose($this->filePointer); } return $success; }
php
public function release(): bool { $success = true; if (is_resource($this->filePointer)) { // FIXME: The lockfile should be unlocked at this point but this will again lead to race conditions, // so we need to find out how to do this in a safe way. Keeping the lock files is very inode intensive // and should therefore change ASAP. if (flock($this->filePointer, LOCK_UN) === false) { $success = false; } fclose($this->filePointer); } return $success; }
[ "public", "function", "release", "(", ")", ":", "bool", "{", "$", "success", "=", "true", ";", "if", "(", "is_resource", "(", "$", "this", "->", "filePointer", ")", ")", "{", "// FIXME: The lockfile should be unlocked at this point but this will again lead to race con...
Releases the lock @return boolean true on success, false otherwise
[ "Releases", "the", "lock" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Utility.Lock/Classes/FlockLockStrategy.php#L149-L163
neos/flow-development-collection
Neos.Eel/Classes/Utility.php
Utility.getDefaultContextVariables
public static function getDefaultContextVariables(array $configuration) { $defaultContextVariables = []; foreach ($configuration as $variableName => $objectType) { $currentPathBase = & $defaultContextVariables; $variablePathNames = explode('.', $variableName); foreach ($variablePathNames as $pathName) { if (!isset($currentPathBase[$pathName])) { $currentPathBase[$pathName] = []; } $currentPathBase = & $currentPathBase[$pathName]; } $currentPathBase = new $objectType(); } return $defaultContextVariables; }
php
public static function getDefaultContextVariables(array $configuration) { $defaultContextVariables = []; foreach ($configuration as $variableName => $objectType) { $currentPathBase = & $defaultContextVariables; $variablePathNames = explode('.', $variableName); foreach ($variablePathNames as $pathName) { if (!isset($currentPathBase[$pathName])) { $currentPathBase[$pathName] = []; } $currentPathBase = & $currentPathBase[$pathName]; } $currentPathBase = new $objectType(); } return $defaultContextVariables; }
[ "public", "static", "function", "getDefaultContextVariables", "(", "array", "$", "configuration", ")", "{", "$", "defaultContextVariables", "=", "[", "]", ";", "foreach", "(", "$", "configuration", "as", "$", "variableName", "=>", "$", "objectType", ")", "{", ...
Get variables from configuration that should be set in the context by default. For example Eel helpers are made available by this. @param array $configuration An one dimensional associative array of context variable paths mapping to object names @return array Array with default context variable objects.
[ "Get", "variables", "from", "configuration", "that", "should", "be", "set", "in", "the", "context", "by", "default", ".", "For", "example", "Eel", "helpers", "are", "made", "available", "by", "this", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Eel/Classes/Utility.php#L27-L43
neos/flow-development-collection
Neos.Eel/Classes/Utility.php
Utility.evaluateEelExpression
public static function evaluateEelExpression($expression, EelEvaluatorInterface $eelEvaluator, array $contextVariables, array $defaultContextConfiguration = []) { $matches = null; if (!preg_match(Package::EelExpressionRecognizer, $expression, $matches)) { throw new Exception('The EEL expression "' . $expression . '" was not a valid EEL expression. Perhaps you forgot to wrap it in ${...}?', 1410441849); } $defaultContextVariables = self::getDefaultContextVariables($defaultContextConfiguration); $contextVariables = array_merge($defaultContextVariables, $contextVariables); if (isset($contextVariables['q'])) { throw new Exception('Context variable "q" not allowed, as it is already reserved for FlowQuery use.', 1410441819); } $contextVariables['q'] = function ($element) { return new FlowQuery\FlowQuery(is_array($element) || $element instanceof \Traversable ? $element : [$element]); }; $context = new ProtectedContext($contextVariables); $context->whitelist('q'); return $eelEvaluator->evaluate($matches['exp'], $context); }
php
public static function evaluateEelExpression($expression, EelEvaluatorInterface $eelEvaluator, array $contextVariables, array $defaultContextConfiguration = []) { $matches = null; if (!preg_match(Package::EelExpressionRecognizer, $expression, $matches)) { throw new Exception('The EEL expression "' . $expression . '" was not a valid EEL expression. Perhaps you forgot to wrap it in ${...}?', 1410441849); } $defaultContextVariables = self::getDefaultContextVariables($defaultContextConfiguration); $contextVariables = array_merge($defaultContextVariables, $contextVariables); if (isset($contextVariables['q'])) { throw new Exception('Context variable "q" not allowed, as it is already reserved for FlowQuery use.', 1410441819); } $contextVariables['q'] = function ($element) { return new FlowQuery\FlowQuery(is_array($element) || $element instanceof \Traversable ? $element : [$element]); }; $context = new ProtectedContext($contextVariables); $context->whitelist('q'); return $eelEvaluator->evaluate($matches['exp'], $context); }
[ "public", "static", "function", "evaluateEelExpression", "(", "$", "expression", ",", "EelEvaluatorInterface", "$", "eelEvaluator", ",", "array", "$", "contextVariables", ",", "array", "$", "defaultContextConfiguration", "=", "[", "]", ")", "{", "$", "matches", "=...
Evaluate an Eel expression. @param string $expression @param EelEvaluatorInterface $eelEvaluator @param array $contextVariables @param array $defaultContextConfiguration @return mixed @throws Exception
[ "Evaluate", "an", "Eel", "expression", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Eel/Classes/Utility.php#L55-L77
neos/flow-development-collection
Neos.FluidAdaptor/Classes/ViewHelpers/Format/UrlencodeViewHelper.php
UrlencodeViewHelper.renderStatic
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) { $value = $arguments['value']; if ($value === null) { $value = $renderChildrenClosure(); } if (!is_string($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new ViewHelper\Exception(sprintf('This ViewHelper works with values that are of type string or objects that implement a __toString method. You provided "%s"', is_object($value) ? get_class($value) : gettype($value)), 1359389241); } return rawurlencode($value); }
php
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) { $value = $arguments['value']; if ($value === null) { $value = $renderChildrenClosure(); } if (!is_string($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new ViewHelper\Exception(sprintf('This ViewHelper works with values that are of type string or objects that implement a __toString method. You provided "%s"', is_object($value) ? get_class($value) : gettype($value)), 1359389241); } return rawurlencode($value); }
[ "public", "static", "function", "renderStatic", "(", "array", "$", "arguments", ",", "\\", "Closure", "$", "renderChildrenClosure", ",", "RenderingContextInterface", "$", "renderingContext", ")", "{", "$", "value", "=", "$", "arguments", "[", "'value'", "]", ";"...
Applies rawurlencode() on the specified value. @param array $arguments @param \Closure $renderChildrenClosure @param RenderingContextInterface $renderingContext @return string @throws \Neos\FluidAdaptor\Core\ViewHelper\Exception
[ "Applies", "rawurlencode", "()", "on", "the", "specified", "value", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.FluidAdaptor/Classes/ViewHelpers/Format/UrlencodeViewHelper.php#L81-L93
neos/flow-development-collection
Neos.Flow/Classes/Validation/Validator/NumberValidator.php
NumberValidator.isValid
protected function isValid($value) { if (!isset($this->options['locale'])) { $locale = $this->localizationService->getConfiguration()->getDefaultLocale(); } elseif (is_string($this->options['locale'])) { $locale = new I18n\Locale($this->options['locale']); } elseif ($this->options['locale'] instanceof I18n\Locale) { $locale = $this->options['locale']; } else { $this->addError('The "locale" option can be only set to string identifier, or Locale object.', 1281286579); return; } $strictMode = $this->options['strictMode']; $formatLength = $this->options['formatLength']; NumbersReader::validateFormatLength($formatLength); $formatType = $this->options['formatType']; NumbersReader::validateFormatType($formatType); if ($formatType === NumbersReader::FORMAT_TYPE_PERCENT) { if ($this->numberParser->parsePercentNumber($value, $locale, $formatLength, $strictMode) === false) { $this->addError('A valid percent number is expected.', 1281452093); } return; } else { if ($this->numberParser->parseDecimalNumber($value, $locale, $formatLength, $strictMode) === false) { $this->addError('A valid decimal number is expected.', 1281452094); } } }
php
protected function isValid($value) { if (!isset($this->options['locale'])) { $locale = $this->localizationService->getConfiguration()->getDefaultLocale(); } elseif (is_string($this->options['locale'])) { $locale = new I18n\Locale($this->options['locale']); } elseif ($this->options['locale'] instanceof I18n\Locale) { $locale = $this->options['locale']; } else { $this->addError('The "locale" option can be only set to string identifier, or Locale object.', 1281286579); return; } $strictMode = $this->options['strictMode']; $formatLength = $this->options['formatLength']; NumbersReader::validateFormatLength($formatLength); $formatType = $this->options['formatType']; NumbersReader::validateFormatType($formatType); if ($formatType === NumbersReader::FORMAT_TYPE_PERCENT) { if ($this->numberParser->parsePercentNumber($value, $locale, $formatLength, $strictMode) === false) { $this->addError('A valid percent number is expected.', 1281452093); } return; } else { if ($this->numberParser->parseDecimalNumber($value, $locale, $formatLength, $strictMode) === false) { $this->addError('A valid decimal number is expected.', 1281452094); } } }
[ "protected", "function", "isValid", "(", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'locale'", "]", ")", ")", "{", "$", "locale", "=", "$", "this", "->", "localizationService", "->", "getConfiguration", "(...
Checks if the given value is a valid number. @param mixed $value The value that should be validated @return void @api @todo Currency support should be added when it will be supported by NumberParser
[ "Checks", "if", "the", "given", "value", "is", "a", "valid", "number", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Validation/Validator/NumberValidator.php#L55-L86
neos/flow-development-collection
Neos.Flow/Classes/Session/Http/SessionRequestComponent.php
SessionRequestComponent.prepareCookie
protected function prepareCookie(string $name, string $value) { return new Cookie( $name, $value, 0, $this->sessionSettings['cookie']['lifetime'], $this->sessionSettings['cookie']['domain'], $this->sessionSettings['cookie']['path'], $this->sessionSettings['cookie']['secure'], $this->sessionSettings['cookie']['httponly'] ); }
php
protected function prepareCookie(string $name, string $value) { return new Cookie( $name, $value, 0, $this->sessionSettings['cookie']['lifetime'], $this->sessionSettings['cookie']['domain'], $this->sessionSettings['cookie']['path'], $this->sessionSettings['cookie']['secure'], $this->sessionSettings['cookie']['httponly'] ); }
[ "protected", "function", "prepareCookie", "(", "string", "$", "name", ",", "string", "$", "value", ")", "{", "return", "new", "Cookie", "(", "$", "name", ",", "$", "value", ",", "0", ",", "$", "this", "->", "sessionSettings", "[", "'cookie'", "]", "[",...
Prepares a cookie object for the session. @param string $name @param string $value @return Cookie
[ "Prepares", "a", "cookie", "object", "for", "the", "session", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Session/Http/SessionRequestComponent.php#L73-L85
neos/flow-development-collection
Neos.Flow/Classes/Mvc/DispatchComponent.php
DispatchComponent.handle
public function handle(ComponentContext $componentContext) { $componentContext = $this->prepareActionRequest($componentContext); $actionRequest = $componentContext->getParameter(DispatchComponent::class, 'actionRequest'); $this->setDefaultControllerAndActionNameIfNoneSpecified($actionRequest); $actionResponse = $this->prepareActionResponse($componentContext->getHttpResponse()); $this->dispatcher->dispatch($actionRequest, $actionResponse); // TODO: This should change in next major when the action response is no longer a HTTP response for backward compatibility. $componentContext->replaceHttpResponse($actionResponse); }
php
public function handle(ComponentContext $componentContext) { $componentContext = $this->prepareActionRequest($componentContext); $actionRequest = $componentContext->getParameter(DispatchComponent::class, 'actionRequest'); $this->setDefaultControllerAndActionNameIfNoneSpecified($actionRequest); $actionResponse = $this->prepareActionResponse($componentContext->getHttpResponse()); $this->dispatcher->dispatch($actionRequest, $actionResponse); // TODO: This should change in next major when the action response is no longer a HTTP response for backward compatibility. $componentContext->replaceHttpResponse($actionResponse); }
[ "public", "function", "handle", "(", "ComponentContext", "$", "componentContext", ")", "{", "$", "componentContext", "=", "$", "this", "->", "prepareActionRequest", "(", "$", "componentContext", ")", ";", "$", "actionRequest", "=", "$", "componentContext", "->", ...
Create an action request from stored route match values and dispatch to that @param ComponentContext $componentContext @return void
[ "Create", "an", "action", "request", "from", "stored", "route", "match", "values", "and", "dispatch", "to", "that" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Mvc/DispatchComponent.php#L76-L85
neos/flow-development-collection
Neos.Flow/Classes/Mvc/DispatchComponent.php
DispatchComponent.prepareActionRequest
protected function prepareActionRequest(ComponentContext $componentContext) { $httpRequest = $componentContext->getHttpRequest(); $arguments = $httpRequest->getArguments(); $parsedBody = $this->parseRequestBody($httpRequest); if ($parsedBody !== []) { $arguments = Arrays::arrayMergeRecursiveOverrule($arguments, $parsedBody); $httpRequest = $httpRequest->withParsedBody($parsedBody); } $routingMatchResults = $componentContext->getParameter(Routing\RoutingComponent::class, 'matchResults'); if ($routingMatchResults !== null) { $arguments = Arrays::arrayMergeRecursiveOverrule($arguments, $routingMatchResults); } /** @var $actionRequest ActionRequest */ $actionRequest = $this->objectManager->get(ActionRequest::class, $httpRequest); $actionRequest->setArguments($arguments); $this->securityContext->setRequest($actionRequest); $componentContext->replaceHttpRequest($httpRequest); $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest); return $componentContext; }
php
protected function prepareActionRequest(ComponentContext $componentContext) { $httpRequest = $componentContext->getHttpRequest(); $arguments = $httpRequest->getArguments(); $parsedBody = $this->parseRequestBody($httpRequest); if ($parsedBody !== []) { $arguments = Arrays::arrayMergeRecursiveOverrule($arguments, $parsedBody); $httpRequest = $httpRequest->withParsedBody($parsedBody); } $routingMatchResults = $componentContext->getParameter(Routing\RoutingComponent::class, 'matchResults'); if ($routingMatchResults !== null) { $arguments = Arrays::arrayMergeRecursiveOverrule($arguments, $routingMatchResults); } /** @var $actionRequest ActionRequest */ $actionRequest = $this->objectManager->get(ActionRequest::class, $httpRequest); $actionRequest->setArguments($arguments); $this->securityContext->setRequest($actionRequest); $componentContext->replaceHttpRequest($httpRequest); $componentContext->setParameter(DispatchComponent::class, 'actionRequest', $actionRequest); return $componentContext; }
[ "protected", "function", "prepareActionRequest", "(", "ComponentContext", "$", "componentContext", ")", "{", "$", "httpRequest", "=", "$", "componentContext", "->", "getHttpRequest", "(", ")", ";", "$", "arguments", "=", "$", "httpRequest", "->", "getArguments", "...
Create ActionRequest with arguments from body and routing merged and add it to the component context. TODO: This could be a separate HTTP component (ActionRequestFactoryComponent) that sits in the chain before the DispatchComponent. @param ComponentContext $componentContext @return ComponentContext
[ "Create", "ActionRequest", "with", "arguments", "from", "body", "and", "routing", "merged", "and", "add", "it", "to", "the", "component", "context", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Mvc/DispatchComponent.php#L95-L122
neos/flow-development-collection
Neos.Flow/Classes/Mvc/DispatchComponent.php
DispatchComponent.parseRequestBody
protected function parseRequestBody(HttpRequest $httpRequest) { $requestBody = $httpRequest->getContent(); if ($requestBody === null || $requestBody === '') { return []; } $mediaTypeConverter = $this->objectManager->get(MediaTypeConverterInterface::class); $propertyMappingConfiguration = new PropertyMappingConfiguration(); $propertyMappingConfiguration->setTypeConverter($mediaTypeConverter); $propertyMappingConfiguration->setTypeConverterOption(MediaTypeConverterInterface::class, MediaTypeConverterInterface::CONFIGURATION_MEDIA_TYPE, $httpRequest->getHeader('Content-Type')); $arguments = $this->propertyMapper->convert($requestBody, 'array', $propertyMappingConfiguration); return $arguments; }
php
protected function parseRequestBody(HttpRequest $httpRequest) { $requestBody = $httpRequest->getContent(); if ($requestBody === null || $requestBody === '') { return []; } $mediaTypeConverter = $this->objectManager->get(MediaTypeConverterInterface::class); $propertyMappingConfiguration = new PropertyMappingConfiguration(); $propertyMappingConfiguration->setTypeConverter($mediaTypeConverter); $propertyMappingConfiguration->setTypeConverterOption(MediaTypeConverterInterface::class, MediaTypeConverterInterface::CONFIGURATION_MEDIA_TYPE, $httpRequest->getHeader('Content-Type')); $arguments = $this->propertyMapper->convert($requestBody, 'array', $propertyMappingConfiguration); return $arguments; }
[ "protected", "function", "parseRequestBody", "(", "HttpRequest", "$", "httpRequest", ")", "{", "$", "requestBody", "=", "$", "httpRequest", "->", "getContent", "(", ")", ";", "if", "(", "$", "requestBody", "===", "null", "||", "$", "requestBody", "===", "''"...
Parses the request body according to the media type. @param HttpRequest $httpRequest @return array
[ "Parses", "the", "request", "body", "according", "to", "the", "media", "type", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Mvc/DispatchComponent.php#L130-L144
neos/flow-development-collection
Neos.Flow/Classes/Mvc/DispatchComponent.php
DispatchComponent.setDefaultControllerAndActionNameIfNoneSpecified
protected function setDefaultControllerAndActionNameIfNoneSpecified(ActionRequest $actionRequest) { if ($actionRequest->getControllerName() === null) { $actionRequest->setControllerName('Standard'); } if ($actionRequest->getControllerActionName() === null) { $actionRequest->setControllerActionName('index'); } }
php
protected function setDefaultControllerAndActionNameIfNoneSpecified(ActionRequest $actionRequest) { if ($actionRequest->getControllerName() === null) { $actionRequest->setControllerName('Standard'); } if ($actionRequest->getControllerActionName() === null) { $actionRequest->setControllerActionName('index'); } }
[ "protected", "function", "setDefaultControllerAndActionNameIfNoneSpecified", "(", "ActionRequest", "$", "actionRequest", ")", "{", "if", "(", "$", "actionRequest", "->", "getControllerName", "(", ")", "===", "null", ")", "{", "$", "actionRequest", "->", "setController...
Set the default controller and action names if none has been specified. @param ActionRequest $actionRequest @return void
[ "Set", "the", "default", "controller", "and", "action", "names", "if", "none", "has", "been", "specified", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Mvc/DispatchComponent.php#L152-L160
neos/flow-development-collection
Neos.Flow/Classes/Mvc/DispatchComponent.php
DispatchComponent.prepareActionResponse
protected function prepareActionResponse(\Psr\Http\Message\ResponseInterface $httpResponse): ActionResponse { $rawResponse = implode("\r\n", ResponseInformationHelper::prepareHeaders($httpResponse)); $rawResponse .= "\r\n\r\n"; $rawResponse .= $httpResponse->getBody()->getContents(); return ActionResponse::createFromRaw($rawResponse); }
php
protected function prepareActionResponse(\Psr\Http\Message\ResponseInterface $httpResponse): ActionResponse { $rawResponse = implode("\r\n", ResponseInformationHelper::prepareHeaders($httpResponse)); $rawResponse .= "\r\n\r\n"; $rawResponse .= $httpResponse->getBody()->getContents(); return ActionResponse::createFromRaw($rawResponse); }
[ "protected", "function", "prepareActionResponse", "(", "\\", "Psr", "\\", "Http", "\\", "Message", "\\", "ResponseInterface", "$", "httpResponse", ")", ":", "ActionResponse", "{", "$", "rawResponse", "=", "implode", "(", "\"\\r\\n\"", ",", "ResponseInformationHelper...
Prepares the ActionResponse to be dispatched TODO: Needs to be adapted for next major when we only deliver an action response inside the dispatch. @param \Psr\Http\Message\ResponseInterface $httpResponse @return ActionResponse|\Psr\Http\Message\ResponseInterface
[ "Prepares", "the", "ActionResponse", "to", "be", "dispatched" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Mvc/DispatchComponent.php#L170-L177
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeClassLoader
public static function initializeClassLoader(Bootstrap $bootstrap) { $proxyClassLoader = new ProxyClassLoader($bootstrap->getContext()); spl_autoload_register([$proxyClassLoader, 'loadClass'], true, true); $bootstrap->setEarlyInstance(ProxyClassLoader::class, $proxyClassLoader); if (!self::useClassLoader($bootstrap)) { return; } $initialClassLoaderMappings = [ [ 'namespace' => 'Neos\\Flow\\', 'classPath' => FLOW_PATH_FLOW . 'Classes/', 'mappingType' => ClassLoader::MAPPING_TYPE_PSR4 ] ]; if ($bootstrap->getContext()->isTesting()) { $initialClassLoaderMappings[] = [ 'namespace' => 'Neos\\Flow\\Tests\\', 'classPath' => FLOW_PATH_FLOW . 'Tests/', 'mappingType' => ClassLoader::MAPPING_TYPE_PSR4 ]; } $classLoader = new ClassLoader($initialClassLoaderMappings); spl_autoload_register([$classLoader, 'loadClass'], true); $bootstrap->setEarlyInstance(ClassLoader::class, $classLoader); if ($bootstrap->getContext()->isTesting()) { $classLoader->setConsiderTestsNamespace(true); } }
php
public static function initializeClassLoader(Bootstrap $bootstrap) { $proxyClassLoader = new ProxyClassLoader($bootstrap->getContext()); spl_autoload_register([$proxyClassLoader, 'loadClass'], true, true); $bootstrap->setEarlyInstance(ProxyClassLoader::class, $proxyClassLoader); if (!self::useClassLoader($bootstrap)) { return; } $initialClassLoaderMappings = [ [ 'namespace' => 'Neos\\Flow\\', 'classPath' => FLOW_PATH_FLOW . 'Classes/', 'mappingType' => ClassLoader::MAPPING_TYPE_PSR4 ] ]; if ($bootstrap->getContext()->isTesting()) { $initialClassLoaderMappings[] = [ 'namespace' => 'Neos\\Flow\\Tests\\', 'classPath' => FLOW_PATH_FLOW . 'Tests/', 'mappingType' => ClassLoader::MAPPING_TYPE_PSR4 ]; } $classLoader = new ClassLoader($initialClassLoaderMappings); spl_autoload_register([$classLoader, 'loadClass'], true); $bootstrap->setEarlyInstance(ClassLoader::class, $classLoader); if ($bootstrap->getContext()->isTesting()) { $classLoader->setConsiderTestsNamespace(true); } }
[ "public", "static", "function", "initializeClassLoader", "(", "Bootstrap", "$", "bootstrap", ")", "{", "$", "proxyClassLoader", "=", "new", "ProxyClassLoader", "(", "$", "bootstrap", "->", "getContext", "(", ")", ")", ";", "spl_autoload_register", "(", "[", "$",...
Initializes the Class Loader @param Bootstrap $bootstrap @return void
[ "Initializes", "the", "Class", "Loader" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L69-L101
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.registerClassLoaderInAnnotationRegistry
public static function registerClassLoaderInAnnotationRegistry(Bootstrap $bootstrap) { AnnotationRegistry::registerLoader([$bootstrap->getEarlyInstance(\Composer\Autoload\ClassLoader::class), 'loadClass']); if (self::useClassLoader($bootstrap)) { AnnotationRegistry::registerLoader([$bootstrap->getEarlyInstance(ClassLoader::class), 'loadClass']); } }
php
public static function registerClassLoaderInAnnotationRegistry(Bootstrap $bootstrap) { AnnotationRegistry::registerLoader([$bootstrap->getEarlyInstance(\Composer\Autoload\ClassLoader::class), 'loadClass']); if (self::useClassLoader($bootstrap)) { AnnotationRegistry::registerLoader([$bootstrap->getEarlyInstance(ClassLoader::class), 'loadClass']); } }
[ "public", "static", "function", "registerClassLoaderInAnnotationRegistry", "(", "Bootstrap", "$", "bootstrap", ")", "{", "AnnotationRegistry", "::", "registerLoader", "(", "[", "$", "bootstrap", "->", "getEarlyInstance", "(", "\\", "Composer", "\\", "Autoload", "\\", ...
Register the class loader into the Doctrine AnnotationRegistry so the DocParser is able to load annation classes from packages. @param Bootstrap $bootstrap @return void
[ "Register", "the", "class", "loader", "into", "the", "Doctrine", "AnnotationRegistry", "so", "the", "DocParser", "is", "able", "to", "load", "annation", "classes", "from", "packages", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L110-L116
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeClassLoaderClassesCache
public static function initializeClassLoaderClassesCache(Bootstrap $bootstrap) { $classesCache = $bootstrap->getEarlyInstance(CacheManager::class)->getCache('Flow_Object_Classes'); $bootstrap->getEarlyInstance(ProxyClassLoader::class)->injectClassesCache($classesCache); }
php
public static function initializeClassLoaderClassesCache(Bootstrap $bootstrap) { $classesCache = $bootstrap->getEarlyInstance(CacheManager::class)->getCache('Flow_Object_Classes'); $bootstrap->getEarlyInstance(ProxyClassLoader::class)->injectClassesCache($classesCache); }
[ "public", "static", "function", "initializeClassLoaderClassesCache", "(", "Bootstrap", "$", "bootstrap", ")", "{", "$", "classesCache", "=", "$", "bootstrap", "->", "getEarlyInstance", "(", "CacheManager", "::", "class", ")", "->", "getCache", "(", "'Flow_Object_Cla...
Injects the classes cache to the already initialized class loader @param Bootstrap $bootstrap @return void
[ "Injects", "the", "classes", "cache", "to", "the", "already", "initialized", "class", "loader" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L124-L128
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.forceFlushCachesIfNecessary
public static function forceFlushCachesIfNecessary(Bootstrap $bootstrap) { if (!isset($_SERVER['argv']) || !isset($_SERVER['argv'][1]) || !isset($_SERVER['argv'][2]) || !in_array($_SERVER['argv'][1], ['neos.flow:cache:flush', 'flow:cache:flush']) || !in_array($_SERVER['argv'][2], ['--force', '-f'])) { return; } $bootstrap->getEarlyInstance(CacheManager::class)->flushCaches(); $environment = $bootstrap->getEarlyInstance(Environment::class); Files::emptyDirectoryRecursively($environment->getPathToTemporaryDirectory()); echo 'Force-flushed caches for "' . $bootstrap->getContext() . '" context.' . PHP_EOL; // In production the site will be locked as this is a compiletime request so we need to take care to remove that lock again. if ($bootstrap->getContext()->isProduction()) { $bootstrap->getEarlyInstance(CoreLockManager::class)->unlockSite(); } exit(0); }
php
public static function forceFlushCachesIfNecessary(Bootstrap $bootstrap) { if (!isset($_SERVER['argv']) || !isset($_SERVER['argv'][1]) || !isset($_SERVER['argv'][2]) || !in_array($_SERVER['argv'][1], ['neos.flow:cache:flush', 'flow:cache:flush']) || !in_array($_SERVER['argv'][2], ['--force', '-f'])) { return; } $bootstrap->getEarlyInstance(CacheManager::class)->flushCaches(); $environment = $bootstrap->getEarlyInstance(Environment::class); Files::emptyDirectoryRecursively($environment->getPathToTemporaryDirectory()); echo 'Force-flushed caches for "' . $bootstrap->getContext() . '" context.' . PHP_EOL; // In production the site will be locked as this is a compiletime request so we need to take care to remove that lock again. if ($bootstrap->getContext()->isProduction()) { $bootstrap->getEarlyInstance(CoreLockManager::class)->unlockSite(); } exit(0); }
[ "public", "static", "function", "forceFlushCachesIfNecessary", "(", "Bootstrap", "$", "bootstrap", ")", "{", "if", "(", "!", "isset", "(", "$", "_SERVER", "[", "'argv'", "]", ")", "||", "!", "isset", "(", "$", "_SERVER", "[", "'argv'", "]", "[", "1", "...
Does some emergency, forced, low level flush caches if the user told to do so through the command line. @param Bootstrap $bootstrap @return void
[ "Does", "some", "emergency", "forced", "low", "level", "flush", "caches", "if", "the", "user", "told", "to", "do", "so", "through", "the", "command", "line", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L137-L157
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializePackageManagement
public static function initializePackageManagement(Bootstrap $bootstrap) { $packageManager = new PackageManager(PackageManager::DEFAULT_PACKAGE_INFORMATION_CACHE_FILEPATH, FLOW_PATH_PACKAGES); $bootstrap->setEarlyInstance(PackageManagerInterface::class, $packageManager); $bootstrap->setEarlyInstance(PackageManager::class, $packageManager); // The package:rescan must happen as early as possible, compiletime alone is not enough. if (isset($_SERVER['argv'][1]) && in_array($_SERVER['argv'][1], ['neos.flow:package:rescan', 'flow:package:rescan'])) { $packageManager->rescanPackages(); } $packageManager->initialize($bootstrap); if (self::useClassLoader($bootstrap)) { $bootstrap->getEarlyInstance(ClassLoader::class)->setPackages($packageManager->getAvailablePackages()); } }
php
public static function initializePackageManagement(Bootstrap $bootstrap) { $packageManager = new PackageManager(PackageManager::DEFAULT_PACKAGE_INFORMATION_CACHE_FILEPATH, FLOW_PATH_PACKAGES); $bootstrap->setEarlyInstance(PackageManagerInterface::class, $packageManager); $bootstrap->setEarlyInstance(PackageManager::class, $packageManager); // The package:rescan must happen as early as possible, compiletime alone is not enough. if (isset($_SERVER['argv'][1]) && in_array($_SERVER['argv'][1], ['neos.flow:package:rescan', 'flow:package:rescan'])) { $packageManager->rescanPackages(); } $packageManager->initialize($bootstrap); if (self::useClassLoader($bootstrap)) { $bootstrap->getEarlyInstance(ClassLoader::class)->setPackages($packageManager->getAvailablePackages()); } }
[ "public", "static", "function", "initializePackageManagement", "(", "Bootstrap", "$", "bootstrap", ")", "{", "$", "packageManager", "=", "new", "PackageManager", "(", "PackageManager", "::", "DEFAULT_PACKAGE_INFORMATION_CACHE_FILEPATH", ",", "FLOW_PATH_PACKAGES", ")", ";"...
Initializes the package system and loads the package configuration and settings provided by the packages. @param Bootstrap $bootstrap @return void
[ "Initializes", "the", "package", "system", "and", "loads", "the", "package", "configuration", "and", "settings", "provided", "by", "the", "packages", "." ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L177-L192
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeConfiguration
public static function initializeConfiguration(Bootstrap $bootstrap) { $context = $bootstrap->getContext(); $environment = new Environment($context); $environment->setTemporaryDirectoryBase(FLOW_PATH_TEMPORARY_BASE); $bootstrap->setEarlyInstance(Environment::class, $environment); /** @var PackageManager $packageManager */ $packageManager = $bootstrap->getEarlyInstance(PackageManager::class); $configurationManager = new ConfigurationManager($context); $configurationManager->setTemporaryDirectoryPath($environment->getPathToTemporaryDirectory()); $configurationManager->injectConfigurationSource(new YamlSource()); $configurationManager->setPackages($packageManager->getFlowPackages()); if ($configurationManager->loadConfigurationCache() === false) { $configurationManager->refreshConfiguration(); } $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $lockManager = new LockManager($settings['utility']['lockStrategyClassName'], ['lockDirectory' => Files::concatenatePaths([ $environment->getPathToTemporaryDirectory(), 'Lock' ])]); Lock::setLockManager($lockManager); $packageManager->injectSettings($settings); $bootstrap->getSignalSlotDispatcher()->dispatch(ConfigurationManager::class, 'configurationManagerReady', [$configurationManager]); $bootstrap->setEarlyInstance(ConfigurationManager::class, $configurationManager); }
php
public static function initializeConfiguration(Bootstrap $bootstrap) { $context = $bootstrap->getContext(); $environment = new Environment($context); $environment->setTemporaryDirectoryBase(FLOW_PATH_TEMPORARY_BASE); $bootstrap->setEarlyInstance(Environment::class, $environment); /** @var PackageManager $packageManager */ $packageManager = $bootstrap->getEarlyInstance(PackageManager::class); $configurationManager = new ConfigurationManager($context); $configurationManager->setTemporaryDirectoryPath($environment->getPathToTemporaryDirectory()); $configurationManager->injectConfigurationSource(new YamlSource()); $configurationManager->setPackages($packageManager->getFlowPackages()); if ($configurationManager->loadConfigurationCache() === false) { $configurationManager->refreshConfiguration(); } $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $lockManager = new LockManager($settings['utility']['lockStrategyClassName'], ['lockDirectory' => Files::concatenatePaths([ $environment->getPathToTemporaryDirectory(), 'Lock' ])]); Lock::setLockManager($lockManager); $packageManager->injectSettings($settings); $bootstrap->getSignalSlotDispatcher()->dispatch(ConfigurationManager::class, 'configurationManagerReady', [$configurationManager]); $bootstrap->setEarlyInstance(ConfigurationManager::class, $configurationManager); }
[ "public", "static", "function", "initializeConfiguration", "(", "Bootstrap", "$", "bootstrap", ")", "{", "$", "context", "=", "$", "bootstrap", "->", "getContext", "(", ")", ";", "$", "environment", "=", "new", "Environment", "(", "$", "context", ")", ";", ...
Initializes the Configuration Manager, the Flow settings and the Environment service @param Bootstrap $bootstrap @return void @throws FlowException
[ "Initializes", "the", "Configuration", "Manager", "the", "Flow", "settings", "and", "the", "Environment", "service" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L201-L230
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeSystemLogger
public static function initializeSystemLogger(Bootstrap $bootstrap) { $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $throwableStorage = self::initializeExceptionStorage($bootstrap); $bootstrap->setEarlyInstance(ThrowableStorageInterface::class, $throwableStorage); /** @var PsrLoggerFactoryInterface $psrLoggerFactoryName */ $psrLoggerFactoryName = $settings['log']['psr3']['loggerFactory']; $psrLogConfigurations = $settings['log']['psr3'][$psrLoggerFactoryName] ?? []; if ($psrLoggerFactoryName === 'legacy') { $psrLoggerFactoryName = PsrLoggerFactory::class; $psrLogConfigurations = (new LoggerBackendConfigurationHelper($settings['log']))->getNormalizedLegacyConfiguration(); } $psrLogFactory = $psrLoggerFactoryName::create($psrLogConfigurations); // This is all deprecated and can be removed with the removal of respective interfaces and classes. $loggerFactory = new LoggerFactory($psrLogFactory, $throwableStorage); $bootstrap->setEarlyInstance($psrLoggerFactoryName, $psrLogFactory); $bootstrap->setEarlyInstance(PsrLoggerFactoryInterface::class, $psrLogFactory); $bootstrap->setEarlyInstance(LoggerFactory::class, $loggerFactory); $deprecatedLogger = $settings['log']['systemLogger']['logger'] ?? Logger::class; $deprecatedLoggerBackend = $settings['log']['systemLogger']['backend'] ?? ''; $deprecatedLoggerBackendOptions = $settings['log']['systemLogger']['backendOptions'] ?? []; $systemLogger = $loggerFactory->create('SystemLogger', $deprecatedLogger, $deprecatedLoggerBackend, $deprecatedLoggerBackendOptions); $bootstrap->setEarlyInstance(SystemLoggerInterface::class, $systemLogger); }
php
public static function initializeSystemLogger(Bootstrap $bootstrap) { $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $throwableStorage = self::initializeExceptionStorage($bootstrap); $bootstrap->setEarlyInstance(ThrowableStorageInterface::class, $throwableStorage); /** @var PsrLoggerFactoryInterface $psrLoggerFactoryName */ $psrLoggerFactoryName = $settings['log']['psr3']['loggerFactory']; $psrLogConfigurations = $settings['log']['psr3'][$psrLoggerFactoryName] ?? []; if ($psrLoggerFactoryName === 'legacy') { $psrLoggerFactoryName = PsrLoggerFactory::class; $psrLogConfigurations = (new LoggerBackendConfigurationHelper($settings['log']))->getNormalizedLegacyConfiguration(); } $psrLogFactory = $psrLoggerFactoryName::create($psrLogConfigurations); // This is all deprecated and can be removed with the removal of respective interfaces and classes. $loggerFactory = new LoggerFactory($psrLogFactory, $throwableStorage); $bootstrap->setEarlyInstance($psrLoggerFactoryName, $psrLogFactory); $bootstrap->setEarlyInstance(PsrLoggerFactoryInterface::class, $psrLogFactory); $bootstrap->setEarlyInstance(LoggerFactory::class, $loggerFactory); $deprecatedLogger = $settings['log']['systemLogger']['logger'] ?? Logger::class; $deprecatedLoggerBackend = $settings['log']['systemLogger']['backend'] ?? ''; $deprecatedLoggerBackendOptions = $settings['log']['systemLogger']['backendOptions'] ?? []; $systemLogger = $loggerFactory->create('SystemLogger', $deprecatedLogger, $deprecatedLoggerBackend, $deprecatedLoggerBackendOptions); $bootstrap->setEarlyInstance(SystemLoggerInterface::class, $systemLogger); }
[ "public", "static", "function", "initializeSystemLogger", "(", "Bootstrap", "$", "bootstrap", ")", "{", "$", "configurationManager", "=", "$", "bootstrap", "->", "getEarlyInstance", "(", "ConfigurationManager", "::", "class", ")", ";", "$", "settings", "=", "$", ...
Initializes the System Logger @param Bootstrap $bootstrap @return void
[ "Initializes", "the", "System", "Logger" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L238-L265
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeExceptionStorage
protected static function initializeExceptionStorage(Bootstrap $bootstrap): ThrowableStorageInterface { $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $storageClassName = $settings['log']['throwables']['storageClass'] ?? FileStorage::class; $storageOptions = $settings['log']['throwables']['optionsByImplementation'][$storageClassName] ?? []; if (!in_array(ThrowableStorageInterface::class, class_implements($storageClassName, true))) { throw new \Exception( sprintf('The class "%s" configured as throwable storage does not implement the ThrowableStorageInterface', $storageClassName), 1540583485 ); } /** @var ThrowableStorageInterface $throwableStorage */ $throwableStorage = $storageClassName::createWithOptions($storageOptions); $throwableStorage->setBacktraceRenderer(function ($backtrace) { return Debugger::getBacktraceCode($backtrace, false, true); }); $throwableStorage->setRequestInformationRenderer(function () { $output = ''; if (!(Bootstrap::$staticObjectManager instanceof ObjectManagerInterface)) { return $output; } $bootstrap = Bootstrap::$staticObjectManager->get(Bootstrap::class); /* @var Bootstrap $bootstrap */ $requestHandler = $bootstrap->getActiveRequestHandler(); if (!$requestHandler instanceof HttpRequestHandlerInterface) { return $output; } $request = $requestHandler->getHttpRequest(); $response = $requestHandler->getHttpResponse(); $output .= PHP_EOL . 'HTTP REQUEST:' . PHP_EOL . ($request == '' ? '[request was empty]' : $request) . PHP_EOL; $output .= PHP_EOL . 'HTTP RESPONSE:' . PHP_EOL . ($response == '' ? '[response was empty]' : $response) . PHP_EOL; $output .= PHP_EOL . 'PHP PROCESS:' . PHP_EOL . 'Inode: ' . getmyinode() . PHP_EOL . 'PID: ' . getmypid() . PHP_EOL . 'UID: ' . getmyuid() . PHP_EOL . 'GID: ' . getmygid() . PHP_EOL . 'User: ' . get_current_user() . PHP_EOL; return $output; }); return $throwableStorage; }
php
protected static function initializeExceptionStorage(Bootstrap $bootstrap): ThrowableStorageInterface { $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $storageClassName = $settings['log']['throwables']['storageClass'] ?? FileStorage::class; $storageOptions = $settings['log']['throwables']['optionsByImplementation'][$storageClassName] ?? []; if (!in_array(ThrowableStorageInterface::class, class_implements($storageClassName, true))) { throw new \Exception( sprintf('The class "%s" configured as throwable storage does not implement the ThrowableStorageInterface', $storageClassName), 1540583485 ); } /** @var ThrowableStorageInterface $throwableStorage */ $throwableStorage = $storageClassName::createWithOptions($storageOptions); $throwableStorage->setBacktraceRenderer(function ($backtrace) { return Debugger::getBacktraceCode($backtrace, false, true); }); $throwableStorage->setRequestInformationRenderer(function () { $output = ''; if (!(Bootstrap::$staticObjectManager instanceof ObjectManagerInterface)) { return $output; } $bootstrap = Bootstrap::$staticObjectManager->get(Bootstrap::class); /* @var Bootstrap $bootstrap */ $requestHandler = $bootstrap->getActiveRequestHandler(); if (!$requestHandler instanceof HttpRequestHandlerInterface) { return $output; } $request = $requestHandler->getHttpRequest(); $response = $requestHandler->getHttpResponse(); $output .= PHP_EOL . 'HTTP REQUEST:' . PHP_EOL . ($request == '' ? '[request was empty]' : $request) . PHP_EOL; $output .= PHP_EOL . 'HTTP RESPONSE:' . PHP_EOL . ($response == '' ? '[response was empty]' : $response) . PHP_EOL; $output .= PHP_EOL . 'PHP PROCESS:' . PHP_EOL . 'Inode: ' . getmyinode() . PHP_EOL . 'PID: ' . getmypid() . PHP_EOL . 'UID: ' . getmyuid() . PHP_EOL . 'GID: ' . getmygid() . PHP_EOL . 'User: ' . get_current_user() . PHP_EOL; return $output; }); return $throwableStorage; }
[ "protected", "static", "function", "initializeExceptionStorage", "(", "Bootstrap", "$", "bootstrap", ")", ":", "ThrowableStorageInterface", "{", "$", "configurationManager", "=", "$", "bootstrap", "->", "getEarlyInstance", "(", "ConfigurationManager", "::", "class", ")"...
Initialize the exception storage @param Bootstrap $bootstrap @return ThrowableStorageInterface @throws FlowException @throws \Neos\Flow\Configuration\Exception\InvalidConfigurationTypeException
[ "Initialize", "the", "exception", "storage" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L275-L321
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeErrorHandling
public static function initializeErrorHandling(Bootstrap $bootstrap) { $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $errorHandler = new ErrorHandler(); $errorHandler->setExceptionalErrors($settings['error']['errorHandler']['exceptionalErrors']); $exceptionHandler = class_exists($settings['error']['exceptionHandler']['className']) ? new $settings['error']['exceptionHandler']['className'] : new ProductionExceptionHandler(); if (is_callable([$exceptionHandler, 'injectSystemLogger'])) { $exceptionHandler->injectSystemLogger($bootstrap->getEarlyInstance(SystemLoggerInterface::class)); } if (is_callable([$exceptionHandler, 'injectLogger'])) { $exceptionHandler->injectLogger($bootstrap->getEarlyInstance(PsrLoggerFactoryInterface::class)->get('systemLogger')); } if (is_callable([$exceptionHandler, 'injectThrowableStorage'])) { $exceptionHandler->injectThrowableStorage($bootstrap->getEarlyInstance(ThrowableStorageInterface::class)); } $exceptionHandler->setOptions($settings['error']['exceptionHandler']); }
php
public static function initializeErrorHandling(Bootstrap $bootstrap) { $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $settings = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow'); $errorHandler = new ErrorHandler(); $errorHandler->setExceptionalErrors($settings['error']['errorHandler']['exceptionalErrors']); $exceptionHandler = class_exists($settings['error']['exceptionHandler']['className']) ? new $settings['error']['exceptionHandler']['className'] : new ProductionExceptionHandler(); if (is_callable([$exceptionHandler, 'injectSystemLogger'])) { $exceptionHandler->injectSystemLogger($bootstrap->getEarlyInstance(SystemLoggerInterface::class)); } if (is_callable([$exceptionHandler, 'injectLogger'])) { $exceptionHandler->injectLogger($bootstrap->getEarlyInstance(PsrLoggerFactoryInterface::class)->get('systemLogger')); } if (is_callable([$exceptionHandler, 'injectThrowableStorage'])) { $exceptionHandler->injectThrowableStorage($bootstrap->getEarlyInstance(ThrowableStorageInterface::class)); } $exceptionHandler->setOptions($settings['error']['exceptionHandler']); }
[ "public", "static", "function", "initializeErrorHandling", "(", "Bootstrap", "$", "bootstrap", ")", "{", "$", "configurationManager", "=", "$", "bootstrap", "->", "getEarlyInstance", "(", "ConfigurationManager", "::", "class", ")", ";", "$", "settings", "=", "$", ...
Initializes the error handling @param Bootstrap $bootstrap @return void
[ "Initializes", "the", "error", "handling" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L329-L350
neos/flow-development-collection
Neos.Flow/Classes/Core/Booting/Scripts.php
Scripts.initializeCacheManagement
public static function initializeCacheManagement(Bootstrap $bootstrap) { /** @var ConfigurationManager $configurationManager */ $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $environment = $bootstrap->getEarlyInstance(Environment::class); $cacheFactoryObjectConfiguration = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_OBJECTS, CacheFactoryInterface::class); $cacheFactoryClass = isset($cacheFactoryObjectConfiguration['className']) ? $cacheFactoryObjectConfiguration['className'] : CacheFactory::class; /** @var CacheFactory $cacheFactory */ $cacheFactory = new $cacheFactoryClass($bootstrap->getContext(), $environment, $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow.cache.applicationIdentifier')); $cacheManager = new CacheManager(); $cacheManager->setCacheConfigurations($configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_CACHES)); $cacheManager->injectConfigurationManager($configurationManager); $cacheManager->injectLogger($bootstrap->getEarlyInstance(PsrLoggerFactoryInterface::class)->get('systemLogger')); $cacheManager->injectEnvironment($environment); $cacheManager->injectCacheFactory($cacheFactory); $cacheFactory->injectCacheManager($cacheManager); $bootstrap->setEarlyInstance(CacheManager::class, $cacheManager); $bootstrap->setEarlyInstance(CacheFactory::class, $cacheFactory); }
php
public static function initializeCacheManagement(Bootstrap $bootstrap) { /** @var ConfigurationManager $configurationManager */ $configurationManager = $bootstrap->getEarlyInstance(ConfigurationManager::class); $environment = $bootstrap->getEarlyInstance(Environment::class); $cacheFactoryObjectConfiguration = $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_OBJECTS, CacheFactoryInterface::class); $cacheFactoryClass = isset($cacheFactoryObjectConfiguration['className']) ? $cacheFactoryObjectConfiguration['className'] : CacheFactory::class; /** @var CacheFactory $cacheFactory */ $cacheFactory = new $cacheFactoryClass($bootstrap->getContext(), $environment, $configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow.cache.applicationIdentifier')); $cacheManager = new CacheManager(); $cacheManager->setCacheConfigurations($configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_CACHES)); $cacheManager->injectConfigurationManager($configurationManager); $cacheManager->injectLogger($bootstrap->getEarlyInstance(PsrLoggerFactoryInterface::class)->get('systemLogger')); $cacheManager->injectEnvironment($environment); $cacheManager->injectCacheFactory($cacheFactory); $cacheFactory->injectCacheManager($cacheManager); $bootstrap->setEarlyInstance(CacheManager::class, $cacheManager); $bootstrap->setEarlyInstance(CacheFactory::class, $cacheFactory); }
[ "public", "static", "function", "initializeCacheManagement", "(", "Bootstrap", "$", "bootstrap", ")", "{", "/** @var ConfigurationManager $configurationManager */", "$", "configurationManager", "=", "$", "bootstrap", "->", "getEarlyInstance", "(", "ConfigurationManager", "::"...
Initializes the cache framework @param Bootstrap $bootstrap @return void
[ "Initializes", "the", "cache", "framework" ]
train
https://github.com/neos/flow-development-collection/blob/a4484ef2a57e050dc9bd87c8481eeb250c7a36fa/Neos.Flow/Classes/Core/Booting/Scripts.php#L358-L381