sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected static function _determineUniversalImplClass(int $tag): string { if (!array_key_exists($tag, self::MAP_TAG_TO_CLASS)) { throw new \UnexpectedValueException( "Universal tag $tag not implemented."); } return self::MAP_TAG_TO_CLASS[$tag]; }
Determine the class that implements an universal type of the given tag. @param int $tag @throws \UnexpectedValueException @return string Class name
entailment
protected function _typeDescriptorString(): string { if ($this->typeClass() == Identifier::CLASS_UNIVERSAL) { return self::tagToName($this->_typeTag); } return sprintf("%s TAG %d", Identifier::classToName($this->typeClass()), $this->_typeTag); }
Get textual description of the type for debugging purposes. @return string
entailment
public static function tagToName(int $tag): string { if (!array_key_exists($tag, self::MAP_TYPE_TO_NAME)) { return "TAG $tag"; } return self::MAP_TYPE_TO_NAME[$tag]; }
Get human readable name for an universal tag. @param int $tag @return string
entailment
public function check($phone, $id = null) { $params = array('phone' => $phone, 'id' => $id); return $this->master->call('phones/check', $params); }
Checking phone in to HLR @param string $phone @param string $id Query ID returned if the processing takes longer than 60 seconds @return object @option string "phone" @option string "status" @option int "imsi" @option string "network" @option bool "ported" @option string "network_ported"
entailment
public function sendRequest($data) { return $this->httpClient->request( $this->getHttpMethod(), $this->getEndpoint(), [ 'Accept' => 'application/json', 'Authorization' => $this->getServiceKey(), 'Content-Type' => 'application/json', ], json_encode($data) ); }
Make the actual request to WorldPay @param mixed $data The data to encode and send to the API endpoint @return \Psr\Http\Message\ResponseInterface HTTP response object
entailment
public function sendData($data) { $httpResponse = $this->sendRequest($data); $responseClass = $this->getResponseClassName(); return $this->response = new $responseClass($this, $httpResponse); }
Send the request to the API then build the response object @param mixed $data The data to encode and send to the API endpoint @return JsonResponse
entailment
public function handle() { $args = [ 'name' => $this->argumentName(), '--type' => strtolower($this->type), // settings type '--plain' => $this->optionPlain(), // if plain stub '--force' => $this->optionForce(), // force override '--stub' => $this->optionStub(), // custom stub name '--name' => $this->optionName(), // custom name for file ]; // extra custom option if ($this->extraOption) { $args["--{$this->extraOption}"] = $this->optionExtra(); } $this->call('generate:file', $args); }
Execute the console command. @return void
entailment
protected function getArgumentNameOnly() { $name = $this->argumentName(); if (str_contains($name, '/')) { $name = str_replace('/', '.', $name); } if (str_contains($name, '\\')) { $name = str_replace('\\', '.', $name); } if (str_contains($name, '.')) { return substr($name, strrpos($name, '.') + 1); } return $name; }
Only return the name of the file Ignore the path / namespace of the file @return array|mixed|string
entailment
protected function getArgumentPath($withName = false) { $name = $this->argumentName(); if (str_contains($name, '.')) { $name = str_replace('.', '/', $name); } if (str_contains($name, '\\')) { $name = str_replace('\\', '/', $name); } // ucfirst char, for correct namespace $name = implode('/', array_map('ucfirst', explode('/', $name))); // if we need to keep lowercase if ($this->settingsDirectoryFormat() === 'strtolower') { $name = implode('/', array_map('strtolower', explode('/', $name))); } // if we want the path with name if ($withName) { return $name . '/'; } if (str_contains($name, '/')) { return substr($name, 0, strripos($name, '/') + 1); } return ''; }
Return the path of the file @param bool $withName @return array|mixed|string
entailment
protected function getResourceName($name, $format = true) { // we assume its already formatted to resource name if ($name && $format === false) { return $name; } $name = isset($name) ? $name : $this->resource; $this->resource = lcfirst(str_singular(class_basename($name))); $this->resourceLowerCase = strtolower($name); return $this->resource; }
Get the resource name @param $name @param bool $format @return string
entailment
protected function getModelName($name = null) { $name = isset($name) ? $name : $this->resource; //return ucwords(camel_case($this->getResourceName($name))); return str_singular(ucwords(camel_case(class_basename($name)))); }
Get the name for the model @param null $name @return string
entailment
protected function getSeedName($name = null) { return ucwords(camel_case(str_replace($this->settings['postfix'], '', $this->getResourceName($name)))); }
Get the name for the seed @param null $name @return string
entailment
protected function getCollectionUpperName($name = null) { $name = str_plural($this->getResourceName($name)); $pieces = explode('_', $name); $name = ""; foreach ($pieces as $k => $str) { $name .= ucfirst($str); } return $name; }
Get the plural uppercase name of the resouce @param null $name @return null|string
entailment
protected function getContractName($name = null) { $name = isset($name) ? $name : $this->resource; $name = str_singular(ucwords(camel_case(class_basename($name)))); return $name . config('generators.settings.contract.postfix'); }
Get the name of the contract @param null $name @return string
entailment
protected function getContractNamespace($withApp = true) { // get path from settings $path = config('generators.settings.contract.namespace') . '\\'; // dont add the default namespace if specified not to in config $path .= str_replace('/', '\\', $this->getArgumentPath()); $pieces = array_map('ucfirst', explode('/', $path)); $namespace = ($withApp === true ? $this->getAppNamespace() : '') . implode('\\', $pieces); $namespace = rtrim(ltrim(str_replace('\\\\', '\\', $namespace), '\\'), '\\'); return $namespace; }
Get the namespace of where contract was created @param bool $withApp @return string
entailment
protected function getViewPath($name) { $pieces = explode('/', $name); // dont plural if reserve word foreach ($pieces as $k => $value) { if (!in_array($value, config('generators.reserve_words'))) { $pieces[$k] = str_plural(snake_case($pieces[$k])); } } $name = implode('.', $pieces); //$name = implode('.', array_map('str_plural', explode('/', $name))); return strtolower(rtrim(ltrim($name, '.'), '.')); }
Get the path to the view file @param $name @return string
entailment
protected function getViewPathFormatted($name) { $path = $this->getViewPath($name); if (strpos($path, 'admin.') === 0) { $path = substr($path, 6); } if (strpos($path, 'admins.') === 0) { $path = substr($path, 7); } if (strpos($path, 'website.') === 0) { $path = substr($path, 8); } if (strpos($path, 'websites.') === 0) { $path = substr($path, 9); } return $path; }
Remove 'admin' and 'webiste' if first in path The Base Controller has it as a 'prefix path' @param $name @return string
entailment
protected function getStub() { $key = $this->getOptionStubKey(); // get the stub path $stub = config('generators.' . $key); if (is_null($stub)) { $this->error('The stub does not exist in the config file - "' . $key . '"'); exit; } return $stub; }
Get the stub file for the generator. @return string
entailment
protected function getOptionStubKey() { $plain = $this->option('plain'); $stub = $this->option('stub') . ($plain ? '_plain' : '') . '_stub'; // if no stub, we assume its the same as the type if (is_null($this->option('stub'))) { $stub = $this->option('type') . ($plain ? '_plain' : '') . '_stub'; } return $stub; }
Get the key where the stub is located @return string
entailment
public function isSuccessful() { $isHttpSuccess = parent::isSuccessful(); $isPurchaseSuccess = false; if (isset($this->data['paymentStatus']) && $this->data['paymentStatus'] == $this->successfulPaymentStatus) { $isPurchaseSuccess = true; } return ($isHttpSuccess && $isPurchaseSuccess); }
Is the response successful? @return bool
entailment
public function getMessage() { // check for HTTP failure response first $httpMessage = parent::getMessage(); if ($httpMessage !== null) { return $httpMessage; } // check if descriptive failure reason is available if (!$this->isSuccessful() && isset($this->data['paymentStatusReason'])) { return $this->data['paymentStatusReason']; } // check if general payment status is available if (isset($this->data['paymentStatus'])) { return $this->data['paymentStatus']; } }
What is the relevant description of the transaction response? @todo Sometimes the 'description' field is more user-friendly (see simulated eror) - how do we decide which one? @return string|null
entailment
public function sortedSet(): self { $obj = clone $this; usort($obj->_elements, function (Element $a, Element $b) { if ($a->typeClass() != $b->typeClass()) { return $a->typeClass() < $b->typeClass() ? -1 : 1; } if ($a->tag() == $b->tag()) { return 0; } return $a->tag() < $b->tag() ? -1 : 1; }); return $obj; }
Sort by canonical ascending order. Used for DER encoding of SET type. @return self
entailment
public function sortedSetOf(): self { $obj = clone $this; usort($obj->_elements, function (Element $a, Element $b) { $a_der = $a->toDER(); $b_der = $b->toDER(); return strcmp($a_der, $b_der); }); return $obj; }
Sort by encoding ascending order. Used for DER encoding of SET OF type. @return self
entailment
public function getStatus($ticket) { try { return $this->getStatusInternal($ticket); } catch (\SoapFault $e) { $result = new StatusResult(); $result->setError($this->getErrorFromFault($e)); return $result; } }
@param string $ticket @return StatusResult
entailment
protected static function _explodeDottedOID(string $oid): array { $subids = []; if (strlen($oid)) { foreach (explode(".", $oid) as $subid) { $n = @gmp_init($subid, 10); if (false === $n) { throw new \UnexpectedValueException( "'$subid' is not a number."); } $subids[] = $n; } } return $subids; }
Explode dotted OID to an array of sub ID's. @param string $oid OID in dotted format @return \GMP[] Array of GMP numbers
entailment
protected static function _implodeSubIDs(\GMP ...$subids): string { return implode(".", array_map(function ($num) { return gmp_strval($num, 10); }, $subids)); }
Implode an array of sub IDs to dotted OID format. @param \GMP ...$subids @return string
entailment
protected static function _encodeSubIDs(\GMP ...$subids): string { $data = ""; foreach ($subids as $subid) { // if number fits to one base 128 byte if ($subid < 128) { $data .= chr(intval($subid)); } else { // encode to multiple bytes $bytes = []; do { array_unshift($bytes, 0x7f & gmp_intval($subid)); $subid >>= 7; } while ($subid > 0); // all bytes except last must have bit 8 set to one foreach (array_splice($bytes, 0, -1) as $byte) { $data .= chr(0x80 | $byte); } $data .= chr(reset($bytes)); } } return $data; }
Encode sub ID's to DER. @param \GMP ...$subids @return string
entailment
protected static function _decodeSubIDs(string $data): array { $subids = []; $idx = 0; $end = strlen($data); while ($idx < $end) { $num = gmp_init("0", 10); while (true) { if ($idx >= $end) { throw new DecodeException("Unexpected end of data."); } $byte = ord($data[$idx++]); $num |= $byte & 0x7f; // bit 8 of the last octet is zero if (!($byte & 0x80)) { break; } $num <<= 7; } $subids[] = $num; } return $subids; }
Decode sub ID's from DER data. @param string $data @throws DecodeException @return \GMP[] Array of GMP numbers
entailment
public function validateImageSize($attribute, $value, $parameters) { $image = $this->getImagePath($value); // Get the image dimension info, or fail. $image_size = @getimagesize($image); if ($image_size === false) { return false; } // If only one dimension rule is passed, assume it applies to both height and width. if (!isset($parameters[1])) { $parameters[1] = $parameters[0]; } // Parse the parameters. Options are: // // "300" or "=300" - dimension must be exactly 300 pixels // "<300" - dimension must be less than 300 pixels // "<=300" - dimension must be less than or equal to 300 pixels // ">300" - dimension must be greater than 300 pixels // ">=300" - dimension must be greater than or equal to 300 pixels $width_check = $this->checkDimension($parameters[0], $image_size[0]); $height_check = $this->checkDimension($parameters[1], $image_size[1]); return $width_check['pass'] && $height_check['pass']; }
Usage: image_size:width[,height] @param $attribute string @param $value string|array @param $parameters array @return boolean
entailment
public function replaceImageSize($message, $attribute, $rule, $parameters) { $width = $height = $this->checkDimension($parameters[0]); if (isset($parameters[1])) { $height = $this->checkDimension($parameters[1]); } return str_replace( [':width', ':height'], [$width['message'], $height['message']], $message ); }
Build the error message for validation failures. @param string $message @param string $attribute @param string $rule @param array $parameters @return string
entailment
public function validateImageAspect($attribute, $value, $parameters) { $image = $this->getImagePath($value); // Get the image dimension info, or fail. $image_size = @getimagesize($image); if ($image_size === false) { return false; } $image_width = $image_size[0]; $image_height = $image_size[1]; // Parse the parameter(s). Options are: // // "0.75" - one param: a decimal ratio (width/height) // "3,4" - two params: width, height // // If the first value is prefixed with "~", the orientation doesn't matter, i.e.: // // "~3,4" - would accept either "3:4" or "4:3" images $both_orientations = false; if (substr($parameters[0], 0, 1) === '~') { $parameters[0] = substr($parameters[0], 1); $both_orientations = true; } if (count($parameters) === 1) { $aspect_width = $parameters[0]; $aspect_height = 1; } else { $aspect_width = (int) $parameters[0]; $aspect_height = (int) $parameters[1]; } if ($aspect_width === 0 || $aspect_height === 0) { throw new RuntimeException('Aspect is zero or infinite: ' . $parameters[0]); } $check = ($image_width * $aspect_height) / $aspect_width; if ((int) round($check) === $image_height) { return true; } if ($both_orientations) { $check = ($image_width * $aspect_width) / $aspect_height; if ((int) round($check) === $image_height) { return true; } } return false; }
Usage: image_aspect:ratio @param $attribute string @param $value string|array @param $parameters array @return boolean @throws \RuntimeException
entailment
protected function checkDimension($rule, $dimension = 0) { $dimension = (int) $dimension; if ($rule === '*') { $message = $this->translator->trans('image-validator::validation.anysize'); $pass = true; } else if (preg_match('/^(\d+)\-(\d+)$/', $rule, $matches)) { $size1 = (int) $matches[1]; $size2 = (int) $matches[2]; $message = $this->translator->trans('image-validator::validation.between', compact('size1', 'size2')); $pass = ($dimension >= $size1) && ($dimension <= $size2); } else if (preg_match('/^([<=>]*)(\d+)$/', $rule, $matches)) { $size = (int) $matches[2]; switch ($matches[1]) { case '>': $message = $this->translator->trans('image-validator::validation.greaterthan', compact('size')); $pass = $dimension > $size; break; case '>=': $message = $this->translator->trans('image-validator::validation.greaterthanorequal', compact('size')); $pass = $dimension >= $size; break; case '<': $message = $this->translator->trans('image-validator::validation.lessthan', compact('size')); $pass = $dimension < $size; break; case '<=': $message = $this->translator->trans('image-validator::validation.lessthanorequal', compact('size')); $pass = $dimension <= $size; break; case '=': case '': $message = $this->translator->trans('image-validator::validation.equal', compact('size')); $pass = $dimension == $size; break; default: throw new RuntimeException('Unknown image size validation rule: ' . $rule); } } else { throw new RuntimeException('Unknown image size validation rule: ' . $rule); } return compact('message', 'pass'); }
Parse the dimension rule and check if the dimension passes the rule. @param string $rule @param integer $dimension @return array @throws \RuntimeException
entailment
public static function fromString(string $time, string $tz = null): self { try { if (!isset($tz)) { $tz = date_default_timezone_get(); } return new static( new \DateTimeImmutable($time, self::_createTimeZone($tz))); } catch (\Exception $e) { throw new \RuntimeException( "Failed to create DateTime: " . self::_getLastDateTimeImmutableErrorsStr(), 0, $e); } }
Initialize from datetime string. @link http://php.net/manual/en/datetime.formats.php @param string $time Time string @param string|null $tz Timezone, if null use default. @throws \RuntimeException @return self
entailment
private static function _decimalToNR3(string $str): string { // if number is in exponent form /** @var $match string[] */ if (preg_match(self::PHP_EXPONENT_DNUM, $str, $match)) { $parts = explode(".", $match[1]); $m = ltrim($parts[0], "0"); $e = intval($match[2]); // if mantissa had decimals if (count($parts) == 2) { $d = rtrim($parts[1], "0"); $e -= strlen($d); $m .= $d; } } else { // explode from decimal $parts = explode(".", $str); $m = ltrim($parts[0], "0"); // if number had decimals if (count($parts) == 2) { // exponent is negative number of the decimals $e = -strlen($parts[1]); // append decimals to the mantissa $m .= $parts[1]; } else { $e = 0; } // shift trailing zeroes from the mantissa to the exponent while (substr($m, -1) === "0") { $e++; $m = substr($m, 0, -1); } } /* if exponent is zero, it must be prefixed with a "+" sign (X.690 07-2002, section 11.3.2.6) */ if (0 == $e) { $es = "+"; } else { $es = $e < 0 ? "-" : ""; } return sprintf("%s.E%s%d", $m, $es, abs($e)); }
Convert decimal number string to NR3 form. @param string $str @return string
entailment
private static function _nr3ToDecimal(string $str): float { /** @var $match string[] */ if (!preg_match(self::NR3_REGEX, $str, $match)) { throw new \UnexpectedValueException( "'$str' is not a valid NR3 form real."); } $m = $match[2]; // if number started with minus sign $inv = $match[1] == "-"; $e = intval($match[3]); // positive exponent if ($e > 0) { // pad with trailing zeroes $num = $m . str_repeat("0", $e); } else if ($e < 0) { // pad with leading zeroes if (strlen($m) < abs($e)) { $m = str_repeat("0", abs($e) - strlen($m)) . $m; } // insert decimal point $num = substr($m, 0, $e) . "." . substr($m, $e); } else { $num = empty($m) ? "0" : $m; } // if number is negative if ($inv) { $num = "-$num"; } return floatval($num); }
Convert NR3 form number to decimal. @param string $str @throws \UnexpectedValueException @return float
entailment
public function unix2DosTime($unixtime = 0) { $timearray = (0 == $unixtime) ? getdate() : getdate($unixtime); if ($timearray['year'] < 1980) { $timearray['year'] = 1980; $timearray['mon'] = 1; $timearray['mday'] = 1; $timearray['hours'] = 0; $timearray['minutes'] = 0; $timearray['seconds'] = 0; } // end if return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1); }
Converts an Unix timestamp to a four byte DOS date and time format (date in high two bytes, time in low two bytes allowing magnitude comparison). @param int $unixtime the current Unix timestamp @return int the current date in a four byte DOS format
entailment
public function addFile($data, $name, $time = 0) { $name = str_replace('\\', '/', $name); $hexdtime = pack('V', $this->unix2DosTime($time)); $frd = "\x50\x4b\x03\x04"; $frd .= "\x14\x00"; // ver needed to extract $frd .= "\x00\x00"; // gen purpose bit flag $frd .= "\x08\x00"; // compression method $frd .= $hexdtime; // last mod time and date // "local file header" segment list($zdata, $part) = $this->getPartsFromData($data, $name); $frd .= $part.$name; // "file data" segment $frd .= $zdata; // echo this entry on the fly, ... $this->datasec[] = $frd; // now add to central directory record $cdrec = "\x50\x4b\x01\x02"; $cdrec .= "\x00\x00"; // version made by $cdrec .= "\x14\x00"; // version needed to extract $cdrec .= "\x00\x00"; // gen purpose bit flag $cdrec .= "\x08\x00"; // compression method $cdrec .= $hexdtime; // last mod time & date $cdrec .= $part; // file comment length, disk number start, internal file attributes $cdrec .= str_repeat(pack('v', 0), 3); $cdrec .= pack('V', 32); // external file attributes // - 'archive' bit set $cdrec .= pack('V', $this->old_offset); // relative offset of local header $this->old_offset += strlen($frd); $cdrec .= $name; // optional extra field, file comment goes here // save to central directory $this->ctrl_dir[] = $cdrec; }
Adds "file" to archive. @param string $data file contents @param string $name name of the file in the archive (may contains the path) @param int $time the current timestamp
entailment
public function compress($filename, $content) { $this->addFile($content, $filename); $zip = $this->file(); $this->clear(); return $zip; }
Comprime el contenido del archivo con el nombre especifico y retorna el contenido del zip. @param string $filename @param string $content @return string
entailment
public function decompress($content, callable $filter = null) { $start = 0; $result = []; while (true) { $dat = substr($content, $start, 30); if (empty($dat)) { break; } $head = unpack(self::UNZIP_FORMAT, $dat); $filename = substr(substr($content, $start), 30, $head['namelen']); if (empty($filename)) { break; } $count = 30 + $head['namelen'] + $head['exlen']; if (!$filter || $filter($filename)) { $result[] = [ 'filename' => $filename, 'content' => gzinflate(substr($content, $start + $count, $head['csize'])), ]; } $start += $count + $head['csize']; } return $result; }
Extract files. @param string $content @param callable|null $filter @return array
entailment
public function send($filename, $content) { $client = $this->getClient(); $result = new SummaryResult(); try { $zipContent = $this->compress($filename.'.xml', $content); $params = [ 'fileName' => $filename.'.zip', 'contentFile' => $zipContent, ]; $response = $client->call('sendSummary', ['parameters' => $params]); $result ->setTicket($response->ticket) ->setSuccess(true); } catch (\SoapFault $e) { $result->setError($this->getErrorFromFault($e)); } return $result; }
@param string $filename @param string $content @return BaseResult
entailment
public function handle() { $name = $this->parseName($this->getNameInput()); $path = $this->getPath($name); if ($this->files->exists($path) && $this->optionForce() === false) { return $this->error($this->type . ' already exists!'); } // if we need to append the parent models $modelOne = $this->getModelName($this->argument('tableOne')); $modelTwo = $this->getModelName($this->argument('tableTwo')); if ($this->confirm("Add Many To Many Relationship in '{$modelOne}' and '{$modelTwo}' Models? [yes|no]")) { $this->addRelationshipsInParents(); } $this->makeDirectory($path); $this->files->put($path, $this->buildClass($name)); $this->info($this->type . ' created successfully.'); $this->info('- ' . $path); }
Execute the console command. @return mixed
entailment
protected function parseName($name) { $tables = array_map('str_singular', $this->getSortedTableNames()); $name = implode('', array_map('ucwords', $tables)); $pieces = explode('_', $name); $name = implode('', array_map('ucwords', $pieces)); return "Create{$name}PivotTable"; }
Parse the name and format. @param string $name @return string
entailment
protected function replaceSchema(&$stub) { $tables = $this->getSortedTableNames(); $stub = str_replace(['{{columnOne}}', '{{columnTwo}}'], array_merge(array_map('str_singular', $tables), $tables), $stub); $stub = str_replace(['{{tableOne}}', '{{tableTwo}}'], array_merge(array_map('str_plural', $tables), $tables), $stub); return $this; }
Apply the correct schema to the stub. @param string $stub @return $this
entailment
protected function getSortedTableNames() { $tables = [ strtolower($this->argument('tableOne')), strtolower($this->argument('tableTwo')) ]; sort($tables); return $tables; }
Sort the two tables in alphabetical order. @return array
entailment
public function addRelationshipsInParents() { $options = config('generators.settings'); if (!$options['model']) { $this->info('Model files not found.'); return; } $modelSettings = $options['model']; // model names $modelOne = $this->getModelName($this->argument('tableOne')); $modelTwo = $this->getModelName($this->argument('tableTwo')); // model path $modelOnePath = $modelSettings['path'] . $modelOne . '.php'; $modelTwoPath = $modelSettings['path'] . $modelTwo . '.php'; $this->addRelationshipInModel($modelOnePath, $modelTwo, $this->argument('tableTwo')); $this->addRelationshipInModel($modelTwoPath, $modelOne, $this->argument('tableOne')); }
Append Many to Many Relationships in Parent Models
entailment
private function addRelationshipInModel($modelPath, $relationshipModel, $tableName) { // load model $model = $this->files->get($modelPath); // get the position where to insert into file $index = strlen($model) - strpos(strrev($model), '}') - 1; // load many to many stub $stub = $this->files->get(config('generators.' . 'many_many_relationship_stub')); $stub = str_replace('{{model}}', $relationshipModel, $stub); $stub = str_replace('{{relationship}}', camel_case($tableName), $stub); //$stub = str_replace('{{relationship}}', strtolower(str_plural($relationshipModel)), $stub); // insert many many stub in model $model = substr_replace($model, $stub, $index, 0); // save model file $this->files->put($modelPath, $model); $this->info("{$relationshipModel} many to many Relationship added in {$modelPath}"); }
Insert the many to many relationship in model @param $modelPath @param $relationshipModel @param $tableName
entailment
public function humanReadable(bool $short_form = true): string { if ($short_form) { return inet_ntop($this->binary()); } $octets = explode('.', inet_ntop($this->binary())); return sprintf('%03d.%03d.%03d.%03d', ...$octets); }
{@inheritdoc}
entailment
public static function toNumeric($requestorType) { if (!is_string($requestorType)) { throw new \InvalidArgumentException('The requestor type "' . $requestorType . '" is not a string.'); } return static::defines(strtoupper($requestorType), true); }
@param string $requestorType @return string
entailment
public static function cleanFields($fields) { $fields = parent::cleanFields($fields); if (('*' !== array_get($fields, 0)) && !in_array('private', $fields)) { $fields[] = 'private'; } return $fields; }
Removes unwanted fields from field list if supplied. @param mixed $fields @return array
entailment
public function attributesToArray() { $attributes = parent::attributesToArray(); if (array_get_bool($attributes, 'private') && !is_null(array_get($attributes, 'value'))) { $attributes['value'] = $this->protectionMask; } return $attributes; }
{@inheritdoc}
entailment
public function setAttribute($key, $value) { // if mask, no need to do anything else. if (('value' === $key) && ($value === $this->protectionMask)) { return $this; } return parent::setAttribute($key, $value); }
{@inheritdoc}
entailment
public static function toString($numericLevel = self::SWAGGER_JSON) { if (!is_numeric($numericLevel)) { throw new \InvalidArgumentException('The format type "' . $numericLevel . '" is not numeric.'); } return static::nameOf($numericLevel); }
@param int $numericLevel @throws NotImplementedException @throws \InvalidArgumentException @return string
entailment
public function addPlugin(Plugin $plugin, $key = null) { if ($key) { $this->plugins[$key] = $plugin; } else { $this->plugins[] = $plugin; } $plugin->configure($this); return $this; }
Add a plugin @param Plugin $plugin the instanciated plugin @param string $key a key to quickly find the plugin with getPlugin() @return TcTable
entailment
public function removePlugin($key) { if (!isset($this->plugins[$key])) { return $this; } if (method_exists($this->plugins[$key], 'unconfigure')) { $this->plugins[$key]->unconfigure($this); } unset($this->plugins[$key]); return $this; }
Remove a plugin and its events by the key @param string $key the key used in TcTable::addPlugin() @return TcTable
entailment
public function getPlugin($key) { return isset($this->plugins[$key]) ? $this->plugins[$key] : null; }
Get a plugin @param mixed $key plugin index (0, 1, 2, etc) or string @return Plugin
entailment
public function on($event, callable $fn) { if (!isset($this->events[$event])) { $this->events[$event] = []; } $this->events[$event][] = $fn; return $this; }
Set an action to do on the specified event @param int $event event code @param callable $fn function to call when the event is triggered @return TcTable
entailment
public function un($event, callable $fn = null) { if (isset($this->events[$event])) { if ($fn) { foreach ($this->events[$event] as $k => $ev) { if ($ev === $fn) { unset($this->events[$event][$k]); break; } } } else { unset($this->events[$event]); } } return $this; }
Remove an action setted for the specified event @param int $event event code @param callable|null $fn function to call when the event was triggered @return TcTable
entailment
public function trigger($event, array $args = [], $acceptReturn = false) { if (isset($this->events[$event])) { array_unshift($args, $this); foreach ($this->events[$event] as $fn) { $data = call_user_func_array($fn, $args); if ($acceptReturn) { if ($data !== null) { return $data; } } elseif ($data === false) { return false; } } } }
Browse registered actions for this event @param int $event event code @param array $args arra of arguments to pass to the event function @param bool $acceptReturn TRUE so a non-null function return can be used by TcTable @return mixed desired content or null
entailment
public function addColumn($column, array $definition) { // set new column with default definitions. Note that [ln] is always // set to FALSE. When addBody(), TRUE will be setted for the last // column. $this->columnDefinition[$column] = array_merge([ 'isMultiLine' => false, 'isMultiLineHeader' => false, 'isImage' => false, 'renderer' => null, 'headerRenderer' => null, 'header' => '', 'drawFn' => null, 'drawHeaderFn' => null, // cell 'width' => 10, 'height' => null, 'border' => 0, 'ln' => false, 'align' => 'L', 'fill' => false, 'link' => '', 'stretch' => 0, 'ignoreHeight' => false, 'calign' => 'T', 'valign' => 'M', // multiCell 'x' => '', 'y' => '', 'reseth' => true, 'isHtml' => false, 'maxh' => null, 'autoPadding' => true, 'fitcell' => false, // getNumLines 'cellPadding' => '' ], $this->defaultColumnDefinition, $definition); if ($this->columnDefinition[$column]['height'] === null) { $this->columnDefinition[$column]['height'] = $this->getColumnHeight(); } $this->trigger(self::EV_COLUMN_ADDED, [ $column, $this->columnDefinition[$column] ]); return $this; }
Define a column. Config array is mostly what we find in \TCPDF Cell and MultiCell. Frequently used Cell and MultiCell options: <ul> <li><i>callable</i> <b>renderer</b>: renderer function for datas. Recieve (TcTable $table, $data, $row, $column, $height). The last parameter is TRUE when called during height calculation. This method is called twice, one time for cell height calculation and one time for data drawing.</li> <li><i>callable</i> <b>headerRenderer</b>: renderer function for headers. Recieve (TcTable $table, $data, $row, $column)</li> <li><i>string</i> <b>header</b>: column header text</li> <li><i>float</i> <b>width</b>: column width</li> <li><i>string</i> <b>border</b>: cell border (LTBR)</li> <li><i>string</i> <b>align</b>: text horizontal align (LCR)</li> <li><i>string</i> <b>valign</b>: text vertical align (TCB)</li> <li><i>float</i> <b>height</b>: min height for cell (default to {@link setColumnHeight()}</li> </ul> MultiCell options: <ul> <li><i>bool</i> <b>isMultiLine</b>: true tell this is a multiline column</li> <li><i>bool</i> <b>isMultiLineHeader</b>: true tell this is a header multiline</li> <li><i>bool</i> <b>isHtml</b>: true to tell that this is HTML content</li> </ul> All other options available: <ul> <li><i>callable</i> <b>drawFn</b>: a callable function that will draw the cell/multicell/image or anything else. The func receive as args (TcTable $table, mixed $data, array $columnDefinition, string $column, array|object $row)</li> <li><i>callable</i> <b>drawHeaderFn</b>: a callable function that will draw the cell/multicell/image or anything else. The func receive as args (TcTable $table, mixed $data, array $columnDefinition, string $column, array|object $row)</li> <li><i>bool</i> <b>ln</b>: managed by TcTable. This option is ignored.</li> <li><i>bool</i> <b>fill</b>: see doc {@link \TCPDF::Cell}</li> <li><i>string</i> <b>link</b>: see doc {@link \TCPDF::Cell}</li> <li><i>int</i> <b>stretch</b>: see doc {@link \TCPDF::Cell}</li> <li><i>bool</i> <b>ignoreHeight</b>: see doc {@link \TCPDF::Cell}</li> <li><i>string</i> <b>calign</b>: see doc {@link \TCPDF::Cell}</li> <li><i>mixed</i> <b>x</b>: see doc {@link \TCPDF::MultiCell}</li> <li><i>mixed</i> <b>y</b>: see doc {@link \TCPDF::MultiCell}</li> <li><i>bool</i> <b>reseth</b>: see doc {@link \TCPDF::MultiCell}</li> <li><i>float</i> <b>maxh</b>: see doc {@link \TCPDF::MultiCell}</li> <li><i>bool</i> <b>autoPadding</b>: see doc {@link \TCPDF::MultiCell}</li> <li><i>bool</i> <b>fitcell</b>: see doc {@link \TCPDF::MultiCell}</li> <li><i>string</i> <b>cellPadding</b>: see doc {@link \TCPDF::getNumLines}</li> </ul> @param string $column @param array $definition @return TcTable
entailment
public function setColumns(array $columns, $add = false) { if (!$add) { $this->columnDefinition = []; } foreach ($columns as $key => $def) { $this->addColumn($key, $def); } return $this; }
Add many columns in one shot @see addColumn @param array $columns @param bool $add true to add these columns to existing columns @return \mangetasoupe\pdf\TcTable
entailment
public function setColumnDefinition($column, $definition, $value) { $this->columnDefinition[$column][$definition] = $value; return $this; }
Set a specific definition for a column, like the value of border, calign and so on @param string $column column string index @param string $definition definition name (border, calign, etc.) @param mixed $value definition value ('LTBR', 'T', etc.) @return TcTable
entailment
public function getColumnWidthBetween($columnA, $columnB) { $width = 0; $check = false; foreach ($this->columnDefinition as $key => $def) { // begin sum either from start, or from column A if ($key == $columnA || !$columnA) { $check = true; } // stop sum if we want width from start to column B if (!$columnA && $key == $columnB) { break; } if ($check) { $width += $def['width']; } if ($key == $columnB) { break; } } return $width; }
Get width between two columns. Widths of these columns are included in the sum. Example: $table->getColumnWidthBetween('B', 'D'); <pre> | A | B | C | D | E | | |-> | ->| ->| | </pre> If column A is empty, behave like {@link TcTable::getColumnWidthUntil()}. If column B is empty, behave like {@link TcTable::getColumnWidthFrom()}. @param string $columnA start column @param string $columnB last column @return float
entailment
public function setRowDefinition($column, $definition, $value) { if ($column === null) { foreach ($this->columnDefinition as $key => $v) { $this->rowDefinition[$key][$definition] = $value; } } else { $this->rowDefinition[$column][$definition] = $value; } return $this; }
Set a custom configuration for one specific cell in the current row. @param string|null $column column string index. If null, the definition will be set for all columns @param string $definition specific configuration (border, etc.) @param mixed $value value ('LBR' for border, etc.) @return TcTable
entailment
public function getCurrentRowHeight($row) { // get the max height for this row $h = $this->getColumnHeight(); $this->setRowHeight($h); if (!isset($this->rowDefinition['_content'])) { $this->rowDefinition['_content'] = []; } foreach ($this->columnDefinition as $key => $def) { $h = $def['height']; if ($h > $this->getRowHeight()) { $this->setRowHeight($h); } $this->rowDefinition['_content'][$key] = $h; if ((!isset($row[$key]) && !is_callable($def['renderer']) && !is_callable($def['drawFn'])) || !$def['isMultiLine']) { continue; } $data = $this->fetchDataByUserFunc($def, isset($row[$key]) ? $row[$key] : '', $key, $row, false, true); $hd = $this->trigger(self::EV_CELL_HEIGHT_GET, [$key, $data, $row], true); if ($hd === null) { $data_to_check = $data; if ($def['isHtml']) { // getNumLines doesn't care about HTML. To simulate carriage return, // we replace <br> with \n. Any better idea? Transactions? $data = str_replace(["\n", "\r"], '', $data); $data_to_check = strip_tags(str_replace(['<br>', '<br/>', '<br />'], PHP_EOL, $data)); } $nb = $this->pdf->getNumLines($data_to_check, $def['width'], $def['reseth'], $def['autoPadding'], $def['cellPadding'], $def['border']); $hd = $nb * $h; $this->rowDefinition['_content'][$key] = $hd; } if ($hd > $this->getRowHeight()) { $this->setRowHeight($hd); } } return $this->getRowHeight(); }
Browse all cells for this row to find which content has the max height. Then we can adapt the height of all the other cells of this line. @param array|object $row @return float
entailment
public function addHeader() { $height = $this->getRowHeight(); $definition = $this->rowDefinition; $this->copyDefaultColumnDefinitions(null); if ($this->trigger(self::EV_HEADER_ADD) !== false) { foreach ($this->columnDefinition as $key => $def) { $this->addCell($key, $def['header'], $this->columnDefinition, true); } $this->trigger(self::EV_HEADER_ADDED); } // reset row definition, because headers also copy their own column // definition and override the data row definition already done before // this method is called $this->setRowHeight($height); $this->rowDefinition = $definition; return $this; }
Add table headers @return TcTable
entailment
public function addBody($rows, callable $fn = null) { // last column will have TRUE for the TCPDF [ln] property end($this->columnDefinition); $this->columnDefinition[key($this->columnDefinition)]['ln'] = true; $auto_pb = $this->pdf->getAutoPageBreak(); $bmargin = $this->pdf->getMargins()['bottom']; $this->pdf->SetAutoPageBreak(false, $this->bottomMargin); if ($this->trigger(self::EV_BODY_ADD, [$rows, $fn]) === false) { $this->trigger(self::EV_BODY_SKIPPED, [$rows]); $this->endBody($auto_pb, $bmargin); return $this; } if ($this->showHeader) { $this->addHeader(); } foreach ($rows as $index => $row) { $data = $fn ? $fn($this, $row, $index, false) : $row; // draw row only if it's an array. It gives the possibility to skip // some rows with the user func if (is_array($data) || is_object($data)) { $this->addRow($data, $index); } else { $this->trigger(self::EV_ROW_SKIPPED, [$row, $index]); } } $this->trigger(self::EV_BODY_ADDED, [$rows]); $this->endBody($auto_pb, $bmargin); return $this; }
Add content to the table. It launches events at start and end, if we need to add some custom stuff. The callable function structure is as follow: <ul> <li><i>TcTable</i> <b>$table</b> the TcTable object</li> <li><i>array|object</i> <b>$row</b> current row</li> <li><i>int</i> <b>$index</b> current row index</li> <li><i>bool</i> <b>$widow</b> TRUE if this method is called when parsing widows (from plugin plugin\Widows)</li> </ul> <ul> <li>Return <i>array</i> formatted data, where keys are the one configured in the column definition</li> </ul> @param array|Traversable $rows the complete set of data @param callable|null $fn data layout function @return TcTable
entailment
private function addRow($row, $index = null) { $this->copyDefaultColumnDefinitions($row, $index); if ($this->trigger(self::EV_ROW_ADD, [$row, $index]) === false) { return $this; } $h = $this->getRowHeight(); $page_break_trigger = $this->pdf->getPageHeight() - $this->pdf->getBreakMargin(); if ($this->pdf->GetY() + $h >= $page_break_trigger) { if ($this->trigger(self::EV_PAGE_ADD, [$row, $index, false]) !== false) { $this->pdf->AddPage(); $this->trigger(self::EV_PAGE_ADDED, [$row, $index, false]); } } foreach ($this->columnDefinition as $key => $value) { if (isset($this->rowDefinition[$key])) { $this->addCell($key, isset($row[$key]) ? $row[$key] : '', $row); } } $this->trigger(self::EV_ROW_ADDED, [$row, $index]); return $this; }
Add a row @param array|object $row row data @param int $index row index @return TcTable
entailment
private function addCell($column, $data, $row, $header = false) { $c = $this->rowDefinition[$column]; $data = $this->fetchDataByUserFunc($c, $data, $column, $row, $header, false); if ($this->trigger(self::EV_CELL_ADD, [$column, $data, $c, $row, $header]) === false) { $data = ''; } if ($this->drawByUserFunc($data, $column, $row, $header) === false) { $h = $this->getRowHeight(); if ((!$header && $c['isMultiLine']) || ($header && $c['isMultiLineHeader'])) { // for multicell, if maxh = null, set it to cell's height, so // vertical alignment can work $y = $this->pdf->GetY(); if ($c['valign'] === 'M' && $c['isHtml'] && $this->rowDefinition['_content'][$column] < $h) { // try to center vertically the best way we can the cell // when it's html content $pos = $y + (($h - $this->rowDefinition['_content'][$column]) / 2); $h = $this->rowDefinition['_content'][$column]; $c['x'] = $this->pdf->GetX(); $c['y'] = $pos; } $this->pdf->MultiCell($c['width'], $h, $data, $c['border'], $c['align'], $c['fill'], $c['ln'], $c['x'], $c['y'], $c['reseth'], $c['stretch'], $c['isHtml'], $c['autoPadding'], $c['maxh'] === null ? $h : $c['maxh'], $c['valign'], $c['fitcell']); if ($c['isHtml']) { // reset position after drawing the multicell html content $x = $this->pdf->GetX(); $this->pdf->SetY($y); $this->pdf->SetX($x); } } else { $this->pdf->Cell($c['width'], $h, $data, $c['border'], $c['ln'], $c['align'], $c['fill'], $c['link'], $c['stretch'], $c['ignoreHeight'], $c['calign'], $c['valign']); } } $this->trigger(self::EV_CELL_ADDED, [$column, $data, $c, $row, $header]); return $this; }
Draw a cell @param string $column column string index @param mixed $data data to draw inside the cell @param array|object $row all datas for this line @param bool $header true if we draw header cell @return TcTable
entailment
private function fetchDataByUserFunc($c, $data, $column, $row, $header, $heightc) { if (!$header && is_callable($c['renderer'])) { $data = $c['renderer']($this, $data, $row, $column, $heightc); } elseif ($header && is_callable($c['headerRenderer'])) { $data = $c['headerRenderer']($this, $data, $row, $column, $heightc); } return $data; }
Get data by user function, if it exists @param array $c the column definition @param mixed $data data to draw inside the cell @param string $column column string index @param array|object $row all datas for this line @param bool $header true if we draw header cell @param bool $heightc determine if we are in height calculation or not @return mixed
entailment
private function drawByUserFunc($data, $column, $row, $header) { $c = $this->rowDefinition[$column]; $result = false; if (!$header && is_callable($c['drawFn'])) { $result = $c['drawFn']($this, $data, $c, $column, $row); } elseif ($header && is_callable($c['drawHeaderFn'])) { $result = $c['drawHeaderFn']($this, $data, $c, $column, $row); } return $result; }
Draw cell/image or anything else by user function, if it exists @param mixed $data data to draw inside the cell @param string $column column string index @param array|object $row all datas for this line @param bool $header true if we draw header cell @return bool false to execute normal cell drawing
entailment
private function copyDefaultColumnDefinitions($columns = null, $rowIndex = null) { $this->rowDefinition = $this->columnDefinition; $h = $this->trigger(self::EV_ROW_HEIGHT_GET, [$columns, $rowIndex], true); if ($h === null) { $h = $columns !== null ? $this->getCurrentRowHeight($columns) : $this->getColumnHeight(); } $this->setRowHeight($h); }
Copy column definition inside a new property. It allows us to customize it only for this row. For the next row, column definition will again be the default one. Usefull for plugins that need to temporarily, for one precise row, to change column information (like background color, border, etc) @param array|object $columns row datas (for each cell) @param int $rowIndex row index @return void
entailment
public function up() { $driver = Schema::getConnection()->getDriverName(); // Even though we take care of this scenario in the code, // SQL Server does not allow potential cascading loops, // so set the default no action and clear out created/modified by another user when deleting a user. $onDelete = (('sqlsrv' === $driver) ? 'no action' : 'set null'); if (!Schema::hasTable('lookup')) { // make sure this isn't a clean install Schema::create('lookup', function (Blueprint $t) use ($onDelete) { $t->increments('id'); $t->integer('app_id')->unsigned()->nullable(); $t->foreign('app_id')->references('id')->on('app')->onDelete('cascade'); $t->integer('role_id')->unsigned()->nullable(); $t->foreign('role_id')->references('id')->on('role')->onDelete('cascade'); $t->integer('user_id')->unsigned()->nullable(); $t->foreign('user_id')->references('id')->on('user')->onDelete('cascade'); $t->string('name'); $t->text('value')->nullable(); $t->boolean('private')->default(0); $t->text('description')->nullable(); $t->timestamp('created_date')->nullable(); $t->timestamp('last_modified_date')->useCurrent(); $t->integer('created_by_id')->unsigned()->nullable(); $t->foreign('created_by_id')->references('id')->on('user')->onDelete($onDelete); $t->integer('last_modified_by_id')->unsigned()->nullable(); $t->foreign('last_modified_by_id')->references('id')->on('user')->onDelete($onDelete); }); $lookups = []; if (Schema::hasTable('app_lookup')) { $lookups = array_merge($lookups, DB::table('app_lookup')->get()->toArray()); } if (Schema::hasTable('role_lookup')) { $lookups = array_merge($lookups, DB::table('role_lookup')->get()->toArray()); } if (Schema::hasTable('user_lookup')) { $lookups = array_merge($lookups, DB::table('user_lookup')->get()->toArray()); } if (Schema::hasTable('system_lookup')) { $lookups = array_merge($lookups, DB::table('system_lookup')->get()->toArray()); } foreach ($lookups as $lookup) { $lookup = array_except((array)$lookup, 'id'); try { DB::table('lookup')->insert($lookup); Log::debug('Migrating Lookup: ' . array_get($lookup, 'name')); } catch (\Exception $ex) { Log::error('Migrating Lookup Failed for ' . array_get($lookup, 'name') . ': ' . $ex->getMessage()); } } } }
Run the migrations. @return void
entailment
public function up() { if (Schema::hasTable('service_type')) { Schema::table('service', function (Blueprint $t){ $t->dropForeign('service_type_foreign'); }); } if (Schema::hasTable('script_type')) { Schema::table('script_config', function (Blueprint $t){ $t->dropForeign('script_config_type_foreign'); }); Schema::table('event_script', function (Blueprint $t){ $t->dropForeign('event_script_type_foreign'); }); } }
Run the migrations. @return void
entailment
public function down() { if (Schema::hasTable('service_type')) { Schema::table('service', function (Blueprint $t){ $t->foreign('type')->references('name')->on('service_type')->onDelete('cascade'); }); } if (Schema::hasTable('script_type')) { Schema::table('script_config', function (Blueprint $t){ $t->foreign('type')->references('name')->on('script_type')->onDelete('cascade'); }); Schema::table('event_script', function (Blueprint $t){ $t->foreign('type')->references('name')->on('script_type')->onDelete('cascade'); }); } }
Reverse the migrations. @return void
entailment
public function setApiVersion($version = null) { if (empty($version)) { $version = \Config::get('df.api_version'); } $version = strval($version); // if numbers are passed in if (substr(strtolower($version), 0, 1) === 'v') { $version = substr($version, 1); } if (strpos($version, '.') === false) { $version = $version . '.0'; } $this->apiVersion = $version; }
{@inheritdoc}
entailment
public static function fromColumnSchema(ColumnSchema $column) { $type = $column->type; $format = ''; switch ($type) { case DbSimpleTypes::TYPE_ID: case DbSimpleTypes::TYPE_REF: case DbSimpleTypes::TYPE_USER_ID: case DbSimpleTypes::TYPE_USER_ID_ON_CREATE: case DbSimpleTypes::TYPE_USER_ID_ON_UPDATE: $type = 'integer'; $format = 'int32'; break; case DbSimpleTypes::TYPE_FLOAT: case DbSimpleTypes::TYPE_DOUBLE: $format = $type; $type = 'number'; break; case DbSimpleTypes::TYPE_DECIMAL: $type = 'number'; break; case DbSimpleTypes::TYPE_BINARY: case DbSimpleTypes::TYPE_DATE: $format = $type; $type = 'string'; break; case DbSimpleTypes::TYPE_DATETIME: case DbSimpleTypes::TYPE_TIMESTAMP: case DbSimpleTypes::TYPE_TIMESTAMP_ON_CREATE: case DbSimpleTypes::TYPE_TIMESTAMP_ON_UPDATE: $format = 'date-time'; $type = 'string'; break; case DbSimpleTypes::TYPE_TIME: case DbSimpleTypes::TYPE_TEXT: case DbSimpleTypes::TYPE_BIG_INT: case DbSimpleTypes::TYPE_MONEY: $type = 'string'; break; } return [ 'type' => $type, 'format' => $format, 'description' => strval($column->comment), ]; }
@param ColumnSchema $column @return array
entailment
public static function fromTableSchema(TableSchema $schema) { $properties = []; $required = []; foreach ($schema->getColumns() as $column) { if ($column->getRequired()) { $required[] = $column->getName(); } $properties[$column->getName()] = static::fromColumnSchema($column); } return [ 'type' => 'object', 'required' => $required, 'properties' => $properties ]; }
@param TableSchema $schema @return array
entailment
public function handleRequest(ServiceRequestInterface $request, $resource = null) { $this->setRequest($request); $this->setAction($request->getMethod()); $this->setResourceMembers($resource); $this->response = null; $resources = $this->getResourceHandlers(); if (!empty($resources) && !empty($this->resource)) { try { if (false === $this->response = $this->handleResource($resources)) { $message = ucfirst($this->action) . " requests for resource '{$this->resourcePath}' are not currently supported by the '{$this->name}' service."; throw new BadRequestException($message); } if (!($this->response instanceof ServiceResponseInterface || $this->response instanceof RedirectResponse || $this->response instanceof StreamedResponse ) ) { $this->response = ResponseFactory::create($this->response); } } catch (\Exception $e) { $this->response = static::exceptionToServiceResponse($e); } return $this->response; } try { // Perform any pre-processing $this->preProcess(); // pre-process can now create a response along with throw exceptions to circumvent the processRequest if (null === $this->response) { if (false === $this->response = $this->processRequest()) { $message = ucfirst($this->action) . " requests without a resource are not currently supported by the '{$this->name}' service."; throw new BadRequestException($message); } } if (!($this->response instanceof ServiceResponseInterface || $this->response instanceof RedirectResponse || $this->response instanceof StreamedResponse ) ) { $this->response = ResponseFactory::create($this->response); } } catch (\Exception $e) { $this->response = static::exceptionToServiceResponse($e); } // Perform any post-processing try { $this->postProcess(); } catch (\Exception $e) { // override the actual response with the exception $this->response = static::exceptionToServiceResponse($e); } // Perform any response processing return $this->respond(); }
@param ServiceRequestInterface $request @param string|null $resource @return \DreamFactory\Core\Contracts\ServiceResponseInterface
entailment
protected function handleResource(array $resources) { $found = array_by_key_value($resources, 'name', $this->resource); if (!isset($found, $found['class_name'])) { throw new NotFoundException("Resource '{$this->resource}' not found for service '{$this->name}'."); } $className = $found['class_name']; if (!class_exists($className)) { throw new InternalServerErrorException('Service configuration class name lookup failed for resource ' . $this->resourcePath); } /** @var ResourceInterface $resource */ $resource = $this->instantiateResource($className, $found); $newPath = $this->resourceArray; array_shift($newPath); $newPath = implode('/', $newPath); return $resource->handleRequest($this->request, $newPath); }
@param array $resources @return bool|mixed @throws InternalServerErrorException @throws NotFoundException
entailment
protected function firePreProcessEvent($name = null, $resource = null) { if (empty($name)) { $name = $this->getEventName(); } if (empty($resource)) { $resource = $this->getEventResource(); } $event = new PreProcessApiEvent($name, $this->request, $this->response, $resource); /** @noinspection PhpUnusedLocalVariableInspection */ $results = \Event::fire($event); $this->response = $event->response; }
Fires pre process event @param string|null $name Optional override for name @param string|null $resource Optional override for resource
entailment
protected function firePostProcessEvent($name = null, $resource = null) { if (empty($name)) { $name = $this->getEventName(); } if (empty($resource)) { $resource = $this->getEventResource(); } /** @noinspection PhpUnusedLocalVariableInspection */ $results = \Event::fire(new PostProcessApiEvent($name, $this->request, $this->response, $resource)); }
Fires post process event @param string|null $name Optional name to append @param string|null $resource Optional override for resource
entailment
protected function fireFinalEvent($name = null, $resource = null) { if (empty($name)) { $name = $this->getEventName(); } if (empty($resource)) { $resource = $this->getEventResource(); } /** @noinspection PhpUnusedLocalVariableInspection */ $results = \Event::fire(new ApiEvent($name, $this->request, $this->response, $resource)); }
Fires last event before responding @param string|null $name Optional name to append @param string|null $resource Optional override for resource
entailment
protected function setAction($action) { $this->action = trim(strtoupper($action)); // Check verb aliases, set correct action allowing for closures if (null !== ($alias = array_get($this->verbAliases, $this->action))) { // A closure? if (in_array($alias, Verbs::getDefinedConstants()) || !is_callable($alias)) { // Set original and work with alias $this->originalAction = $this->action; $this->action = $alias; } } return $this; }
Sets the HTTP Action verb @param $action string @return $this
entailment
protected function setResourceMembers($resourcePath = null) { // remove trailing slash here, override this function if you need it $this->resourcePath = rtrim($resourcePath, '/'); $this->resourceArray = (!empty($this->resourcePath)) ? explode('/', $this->resourcePath) : []; if (!empty($this->resourceArray)) { $resource = array_get($this->resourceArray, 0); if (!is_null($resource) && ('' !== $resource)) { $this->resource = $resource; } $id = array_get($this->resourceArray, 1); if (!is_null($id) && ('' !== $id)) { $this->resourceId = $id; } } return $this; }
Apply the commonly used REST path members to the class. @param string $resourcePath @return $this
entailment
protected function getPayloadData($key = null, $default = null) { $data = $this->request->getPayloadData($key, $default); return $data; }
@param null $key @param null $default @return mixed
entailment
protected function handleGET() { $resources = $this->getResources(); if (is_array($resources)) { $includeAccess = $this->request->getParameterAsBool(ApiOptions::INCLUDE_ACCESS); $asList = $this->request->getParameterAsBool(ApiOptions::AS_LIST); $idField = $this->request->getParameter(ApiOptions::ID_FIELD, static::getResourceIdentifier()); $fields = $this->request->getParameter(ApiOptions::FIELDS); if (!$asList && $includeAccess) { foreach ($resources as &$resource) { if (is_array($resource)) { $name = array_get($resource, $idField); $resource['access'] = VerbsMask::maskToArray($this->getPermissions($name)); } } } return ResourcesWrapper::cleanResources($resources, $asList, $idField, $fields); } return $resources; }
Handles GET action @return mixed @throws BadRequestException
entailment
public function humanReadable(bool $short_form = true): string { if ($short_form) { return inet_ntop($this->binary()); } $hex = str_pad($this->numeric(16), 32, '0', STR_PAD_LEFT); return implode(':', str_split($hex, 4)); }
{@inheritdoc}
entailment
public function reversePointer(): string { $ip = str_replace(':', '', $this->humanReadable(false)); $ip = strrev($ip); $ip = implode('.', str_split($ip)); $ip .= '.ip6.arpa.'; return $ip; }
{@inheritdoc}
entailment
public function subscribe($events) { $events->listen( [ ApiEvent::class, ], static::class . '@handleApiEvent' ); $events->listen( [ ServiceModifiedEvent::class, ServiceDeletedEvent::class, ], static::class . '@handleServiceChangeEvent' ); if (config('df.db.query_log_enabled')) { $events->listen( [ QueryExecuted::class, ], static::class . '@handleQueryExecutedEvent' ); } }
Register the listeners for the subscriber. @param Dispatcher $events
entailment
public function handleApiEvent($event) { $eventName = str_replace('.queued', null, $event->name); $ckey = 'event:' . $eventName; $records = Cache::remember($ckey, Config::get('df.default_cache_ttl'), function () use ($eventName) { return ServiceEventMap::whereEvent($eventName)->get()->all(); }); if (empty($records)) { // Look for wildcard events by service (example: user.*) $serviceName = substr($eventName, 0, strpos($eventName, '.')); $wildcardEvent = $serviceName . '.*'; $ckey = 'event:' . $wildcardEvent; $records = Cache::remember($ckey, Config::get('df.default_cache_ttl'), function () use ($wildcardEvent) { return ServiceEventMap::whereEvent($wildcardEvent)->get()->all(); }); } /** @var BaseModel $record */ foreach ($records as $record) { Log::debug('Service event handled: ' . $eventName); /** @var BaseRestService $service */ $service = \ServiceManager::getServiceById($record->service_id); Event::fire(new ServiceAssignedEvent($service, $event, $record->toArray())); } }
Handle API events. @param ApiEvent $event
entailment
public static function cleanResources( $resources, $as_list = false, $identifier = null, $fields = null, $force_wrap = false ) { // avoid single resources or already wrapped resources if ($resources instanceof Collection) { $resources = $resources->toArray(); } if (!Arr::isAssoc($resources)) { // may already be a simple list if (is_array(array_get($resources, 0))) { if (is_string($identifier)) { $identifier = array_map('trim', explode(',', trim($identifier, ','))); } elseif (!is_array($identifier)) { $identifier = []; } $identifier = array_values($identifier); if ($as_list) { if (1 == count($identifier)) { $resources = array_column($resources, $identifier[0]); } else { foreach ($resources as &$resource) { $out = ''; foreach ($identifier as $idField) { if (!empty($out)) { $out .= ','; } $out .= array_get($resource, $idField, ''); } $resource = '(' . $out . ')'; } } } elseif (empty($fields)) { if (is_array($identifier) && !empty($identifier)) { $identifier = array_flip($identifier); foreach ($resources as &$resource) { $resource = array_intersect_key($resource, $identifier); } } } elseif (ApiOptions::FIELDS_ALL !== $fields) { if (is_string($fields)) { $fields = array_map('trim', explode(',', trim($fields, ','))); } elseif (!is_array($fields)) { $fields = []; } $fields = array_flip(array_values($fields)); foreach ($resources as &$resource) { $resource = array_intersect_key($resource, $fields); } } } return static::wrapResources($resources, $force_wrap); } return ($force_wrap ? static::wrapResources($resources, true) : $resources); }
@param array $resources @param boolean $as_list @param string|array|null $identifier @param string|array|null $fields @param boolean $force_wrap @return array
entailment
public static function getDefinedConstants($flipped = false, $class = null, $listData = false) { $_key = static::introspect($class, [], false, $flipped ? 'flipped' : null); $_constants = false === $flipped ? static::$_constants[$_key] : array_flip(static::$_constants[$_key]); if (false === $listData) { return $_constants; } $_temp = []; foreach (static::$_constants[$_key] as $_constant => $_value) { $_temp[$_value] = static::display(static::neutralize($_constant)); unset($_value, $_constant); } return $_temp; }
Returns a hash of the called class's constants ( CONSTANT_NAME => value ). Caches for speed (class cache hash, say that ten times fast!). @param bool $flipped If true, the array is flipped before return ( value => CONSTANT_NAME ) @param string $class Used internally to cache constants @param bool $listData If true, the constant names themselves are cleaned up for display purposes. @return array
entailment
public static function toConstant($value) { if (false !== ($_index = array_search($value, static::getDefinedConstants()))) { return $_index; } throw new \InvalidArgumentException('The value "' . $value . '" has no associated constant.'); }
Given a VALUE, return the associated CONSTANT @param string $value @return string
entailment
public static function toValue($constant) { if (false !== ($_index = array_search($constant, static::getDefinedConstants(true)))) { return $_index; } throw new \InvalidArgumentException('The constant "' . $constant . '" has no associated value.'); }
Given a CONSTANT, return the associated VALUE @param mixed $constant @return string
entailment
public static function resolve($item) { try { return static::toConstant($item); } catch (\Exception $_ex) { // Ignored... } try { return static::toValue($item); } catch (\Exception $_ex) { // Ignored... } // Sorry charlie... throw new \InvalidArgumentException('The item "' . $item . '" can not be resolved.'); }
Given a CONSTANT or VALUE, return the VALUE @param string|int $item @return mixed
entailment
public static function contains($value, $returnConstant = false) { try { $_key = static::toConstant($value); return $returnConstant ? $_key : true; } catch (\Exception $_ex) { return false; } }
Returns constant name or true/false if class contains a specific constant value. Use for validity checks: if ( false === VeryCoolShit::contains( $evenCoolerShit ) ) { throw new \InvalidArgumentException( 'Sorry, your selection of "' . $evenCoolerShit . '" is invalid.' ); } @param mixed $value @param bool $returnConstant @return bool|mixed
entailment
public static function defines($constant, $returnValue = false) { try { $_value = static::toValue($constant); return $returnValue ? $_value : true; } catch (\InvalidArgumentException $_ex) { if ($returnValue) { throw $_ex; } } return false; }
Returns true or false if this class defines a specific constant. Optionally returns the value of the constant, but throws an exception if not found. Use for validity checks: if ( false === VeryCoolShit::contains( $evenCoolerShit ) ) { throw new \InvalidArgumentException( 'Sorry, your selection of "' . $evenCoolerShit . '" is invalid.' ); } @param string $constant @param bool $returnValue If true, returns the value of the constant if found, but throws an exception if not @throws \InvalidArgumentException @return bool|mixed
entailment
public static function nameOf($constant, $flipped = true, $pretty = true) { try { $_name = $flipped ? static::toValue($constant) : static::toConstant($constant); } catch (\InvalidArgumentException $_ex) { throw new \InvalidArgumentException('A constant with the value of "' . $constant . '" does not exist.'); } return !$flipped && $pretty ? static::display(static::neutralize($_name)) : $_name; }
Returns the constant name as a string @param string|int $constant The CONSTANT's value that you want the name of @param bool $flipped If false, $constant should be the CONSTANT's name. The CONSTANT's value will be returned instead. @param bool $pretty If true, returned value is prettified (acme.before_event becomes "Acme Before Event") @throws \InvalidArgumentException @return string|int
entailment
public static function prettyList($quote = null, $tags = false, $numbers = false, $lastOr = true) { $quote != '\'' && $quote != '"' && $quote = null; $_values = array_values($tags ? static::$tags : static::getDefinedConstants(true)); // Remove unwanted items... for ($_i = 0, $_max = count($_values); $_i < $_max; $_i++) { if ('_' == $_values[$_i][0]) { array_forget($_values, $_i); continue; } } // Find the last item for "or" placement end($_values); $_last = key($_values); $_list = null; for ($_i = 0, $_max = count($_values); $_i < $_max; $_i++) { // No comma on first guy... $_i != 0 && $_list .= ', '; // Add "or" on the last $lastOr && ($_i == $_last) && $_list .= 'or '; // Format the item if ($numbers) { $_item = $quote . static::toValue($_values[$_i]) . $quote . ' (' . strtolower($_values[$_i]) . ')'; } else { $_item = $quote . strtolower($_values[$_i]) . $quote; } $_list .= $_item; } return $_list; }
Returns a list of the constants in a comma-separated display manner @param string|null $quote An optional quote to enrobe the value (' or " only) @param bool $tags If true, $tags will be used instead of the constants themselves @param bool $numbers If true, the numeric value of the constant will be printed @param bool $lastOr If true, the word "or" will be placed before the last item in the list @return string
entailment
public static function neutralizeObject($object, $strip = null) { $_variables = is_array($object) ? $object : get_object_vars($object); if (!empty($_variables)) { foreach ($_variables as $_key => $_value) { $_originalKey = $_key; if ($strip) { $_key = str_replace($strip, null, $_key); } $_variables[static::neutralize(ltrim($_key, '_'))] = $_value; unset($_variables[$_originalKey]); } } return $_variables; }
Given an object, returns an array containing the variables of the object and their values. The keys for the object have been neutralized for your protection @param object $object @param string $strip If provided, it's value is removed from item before it's neutralized. Example: "REQUEST_URI" would be "URI" with $strip = "REQUEST_" @return string
entailment