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 |
|---|---|---|---|---|---|---|---|---|---|---|
cartalyst/stripe | src/Api/Invoices.php | Invoices.upcomingInvoice | public function upcomingInvoice($customerId, $subscriptionId = null, array $parameters = [])
{
$parameters = array_merge($parameters, [
'customer' => $customerId,
'subscription' => $subscriptionId,
]);
return $this->_get('invoices/upcoming', $parameters);
} | php | public function upcomingInvoice($customerId, $subscriptionId = null, array $parameters = [])
{
$parameters = array_merge($parameters, [
'customer' => $customerId,
'subscription' => $subscriptionId,
]);
return $this->_get('invoices/upcoming', $parameters);
} | [
"public",
"function",
"upcomingInvoice",
"(",
"$",
"customerId",
",",
"$",
"subscriptionId",
"=",
"null",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"array_merge",
"(",
"$",
"parameters",
",",
"[",
"'customer'",
"=>",... | Retrieves the given customer upcoming invoices.
@param string $customerId
@param string $subscriptionId
@param array $parameters
@return array | [
"Retrieves",
"the",
"given",
"customer",
"upcoming",
"invoices",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Api/Invoices.php#L72-L80 |
cartalyst/stripe | src/Api/Refunds.php | Refunds.create | public function create($chargeId, $amount = null, array $parameters = [])
{
$parameters = array_merge($parameters, array_filter(compact('amount')));
return $this->_post("charges/{$chargeId}/refunds", $parameters);
} | php | public function create($chargeId, $amount = null, array $parameters = [])
{
$parameters = array_merge($parameters, array_filter(compact('amount')));
return $this->_post("charges/{$chargeId}/refunds", $parameters);
} | [
"public",
"function",
"create",
"(",
"$",
"chargeId",
",",
"$",
"amount",
"=",
"null",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"array_merge",
"(",
"$",
"parameters",
",",
"array_filter",
"(",
"compact",
"(",
"'... | Creates a new refund for the given charge.
@param string $chargeId
@param int $amount
@param array $parameters
@return array | [
"Creates",
"a",
"new",
"refund",
"for",
"the",
"given",
"charge",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Api/Refunds.php#L33-L38 |
cartalyst/stripe | src/Api/Refunds.php | Refunds.all | public function all($chargeId = null, array $parameters = [])
{
if (! $chargeId) {
return $this->_get('refunds', $parameters);
}
return $this->_get("charges/{$chargeId}/refunds", $parameters);
} | php | public function all($chargeId = null, array $parameters = [])
{
if (! $chargeId) {
return $this->_get('refunds', $parameters);
}
return $this->_get("charges/{$chargeId}/refunds", $parameters);
} | [
"public",
"function",
"all",
"(",
"$",
"chargeId",
"=",
"null",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"chargeId",
")",
"{",
"return",
"$",
"this",
"->",
"_get",
"(",
"'refunds'",
",",
"$",
"parameters",
")",... | Lists all the refunds of the current Stripe account
or lists all the refunds for the given charge.
@param string|null $chargeId
@param array $parameters
@return array | [
"Lists",
"all",
"the",
"refunds",
"of",
"the",
"current",
"Stripe",
"account",
"or",
"lists",
"all",
"the",
"refunds",
"for",
"the",
"given",
"charge",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Api/Refunds.php#L77-L84 |
cartalyst/stripe | src/AmountConverter.php | AmountConverter.convert | public static function convert($number)
{
$number = preg_replace('/\,/i', '', $number);
$number = preg_replace('/([^0-9\.\-])/i', '', $number);
if (! is_numeric($number)) {
return '0.00';
}
$isCents = (bool) preg_match('/^0.\d+$/', $number);
return ($isCents ? '0' : null).number_format($number * 100., 0, '.', '');
} | php | public static function convert($number)
{
$number = preg_replace('/\,/i', '', $number);
$number = preg_replace('/([^0-9\.\-])/i', '', $number);
if (! is_numeric($number)) {
return '0.00';
}
$isCents = (bool) preg_match('/^0.\d+$/', $number);
return ($isCents ? '0' : null).number_format($number * 100., 0, '.', '');
} | [
"public",
"static",
"function",
"convert",
"(",
"$",
"number",
")",
"{",
"$",
"number",
"=",
"preg_replace",
"(",
"'/\\,/i'",
",",
"''",
",",
"$",
"number",
")",
";",
"$",
"number",
"=",
"preg_replace",
"(",
"'/([^0-9\\.\\-])/i'",
",",
"''",
",",
"$",
... | Converts the given number into cents.
@param mixed $number
@return string | [
"Converts",
"the",
"given",
"number",
"into",
"cents",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/AmountConverter.php#L31-L44 |
cartalyst/stripe | src/Exception/Handler.php | Handler.handleException | protected function handleException($message, $statusCode, $errorType, $errorCode, $missingParameter, $rawOutput)
{
if ($statusCode === 400 && $errorCode === 'rate_limit') {
$class = 'ApiLimitExceeded';
} elseif ($statusCode === 400 && $errorType === 'invalid_request_error') {
$class = 'MissingParameter';
} elseif (array_key_exists($errorType, $this->exceptionsByErrorType)) {
$class = $this->exceptionsByErrorType[$errorType];
} elseif (array_key_exists($statusCode, $this->exceptionsByStatusCode)) {
$class = $this->exceptionsByStatusCode[$statusCode];
} else {
$class = 'Stripe';
}
$class = "\\Cartalyst\\Stripe\\Exception\\{$class}Exception";
$instance = new $class($message, $statusCode);
$instance->setErrorCode($errorCode);
$instance->setErrorType($errorType);
$instance->setMissingParameter($missingParameter);
$instance->setRawOutput($rawOutput);
throw $instance;
} | php | protected function handleException($message, $statusCode, $errorType, $errorCode, $missingParameter, $rawOutput)
{
if ($statusCode === 400 && $errorCode === 'rate_limit') {
$class = 'ApiLimitExceeded';
} elseif ($statusCode === 400 && $errorType === 'invalid_request_error') {
$class = 'MissingParameter';
} elseif (array_key_exists($errorType, $this->exceptionsByErrorType)) {
$class = $this->exceptionsByErrorType[$errorType];
} elseif (array_key_exists($statusCode, $this->exceptionsByStatusCode)) {
$class = $this->exceptionsByStatusCode[$statusCode];
} else {
$class = 'Stripe';
}
$class = "\\Cartalyst\\Stripe\\Exception\\{$class}Exception";
$instance = new $class($message, $statusCode);
$instance->setErrorCode($errorCode);
$instance->setErrorType($errorType);
$instance->setMissingParameter($missingParameter);
$instance->setRawOutput($rawOutput);
throw $instance;
} | [
"protected",
"function",
"handleException",
"(",
"$",
"message",
",",
"$",
"statusCode",
",",
"$",
"errorType",
",",
"$",
"errorCode",
",",
"$",
"missingParameter",
",",
"$",
"rawOutput",
")",
"{",
"if",
"(",
"$",
"statusCode",
"===",
"400",
"&&",
"$",
"... | Guesses the FQN of the exception to be thrown.
@param string $message
@param int $statusCode
@param string $errorType
@param string $errorCode
@param string $missingParameter
@return void
@throws \Cartalyst\Stripe\Exception\StripeException | [
"Guesses",
"the",
"FQN",
"of",
"the",
"exception",
"to",
"be",
"thrown",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Exception/Handler.php#L107-L131 |
cartalyst/stripe | src/Stripe.php | Stripe.getApiInstance | protected function getApiInstance($method)
{
$class = "\\Cartalyst\\Stripe\\Api\\".ucwords($method);
if (class_exists($class) && ! (new ReflectionClass($class))->isAbstract()) {
return new $class($this->config);
}
throw new \BadMethodCallException("Undefined method [{$method}] called.");
} | php | protected function getApiInstance($method)
{
$class = "\\Cartalyst\\Stripe\\Api\\".ucwords($method);
if (class_exists($class) && ! (new ReflectionClass($class))->isAbstract()) {
return new $class($this->config);
}
throw new \BadMethodCallException("Undefined method [{$method}] called.");
} | [
"protected",
"function",
"getApiInstance",
"(",
"$",
"method",
")",
"{",
"$",
"class",
"=",
"\"\\\\Cartalyst\\\\Stripe\\\\Api\\\\\"",
".",
"ucwords",
"(",
"$",
"method",
")",
";",
"if",
"(",
"class_exists",
"(",
"$",
"class",
")",
"&&",
"!",
"(",
"new",
"R... | Returns the Api class instance for the given method.
@param string $method
@return \Cartalyst\Stripe\Api\ApiInterface
@throws \BadMethodCallException | [
"Returns",
"the",
"Api",
"class",
"instance",
"for",
"the",
"given",
"method",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Stripe.php#L265-L274 |
cartalyst/stripe | src/Api/BankAccounts.php | BankAccounts.create | public function create($customerId, $parameters = [])
{
if (is_array($parameters) && isset($parameters['source'])) {
$parameters['source']['object'] = 'bank_account';
} elseif (is_string($parameters)) {
$parameters = ['source' => $parameters];
}
return $this->_post("customers/{$customerId}/sources", $parameters);
} | php | public function create($customerId, $parameters = [])
{
if (is_array($parameters) && isset($parameters['source'])) {
$parameters['source']['object'] = 'bank_account';
} elseif (is_string($parameters)) {
$parameters = ['source' => $parameters];
}
return $this->_post("customers/{$customerId}/sources", $parameters);
} | [
"public",
"function",
"create",
"(",
"$",
"customerId",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"parameters",
")",
"&&",
"isset",
"(",
"$",
"parameters",
"[",
"'source'",
"]",
")",
")",
"{",
"$",
"parameters"... | Creates a new source on the given customer.
@param string $customerId
@param string|array $parameters
@return array | [
"Creates",
"a",
"new",
"source",
"on",
"the",
"given",
"customer",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Api/BankAccounts.php#L32-L41 |
cartalyst/stripe | src/Api/BankAccounts.php | BankAccounts.verify | public function verify($customerId, $bankAccountId, array $amounts, $verificationMethod = null)
{
return $this->_post("customers/{$customerId}/sources/{$bankAccountId}/verify", [
'amounts' => $amounts, 'verification_method' => $verificationMethod,
]);
} | php | public function verify($customerId, $bankAccountId, array $amounts, $verificationMethod = null)
{
return $this->_post("customers/{$customerId}/sources/{$bankAccountId}/verify", [
'amounts' => $amounts, 'verification_method' => $verificationMethod,
]);
} | [
"public",
"function",
"verify",
"(",
"$",
"customerId",
",",
"$",
"bankAccountId",
",",
"array",
"$",
"amounts",
",",
"$",
"verificationMethod",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"_post",
"(",
"\"customers/{$customerId}/sources/{$bankAccountId}/v... | Verifies the given bank account.
@param string $customerId
@param string $bankAccountId
@param array $amounts
@param string $verificationMethod
@return array | [
"Verifies",
"the",
"given",
"bank",
"account",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Api/BankAccounts.php#L103-L108 |
cartalyst/stripe | src/Api/FileLinks.php | FileLinks.create | public function create($fileId, array $attributes = [])
{
$attributes = array_merge($attributes, [
'file' => $fileId,
]);
return $this->_post("file_links", $attributes);
} | php | public function create($fileId, array $attributes = [])
{
$attributes = array_merge($attributes, [
'file' => $fileId,
]);
return $this->_post("file_links", $attributes);
} | [
"public",
"function",
"create",
"(",
"$",
"fileId",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"$",
"attributes",
"=",
"array_merge",
"(",
"$",
"attributes",
",",
"[",
"'file'",
"=>",
"$",
"fileId",
",",
"]",
")",
";",
"return",
"$",
... | Creates a new file link.
@param string $fileId
@param array $attributes
@return array | [
"Creates",
"a",
"new",
"file",
"link",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Api/FileLinks.php#L32-L39 |
cartalyst/stripe | src/Pager.php | Pager.fetch | public function fetch(array $parameters = [])
{
$this->api->setPerPage(100);
$results = $this->processRequest($parameters);
while ($this->nextToken) {
$results = array_merge($results, $this->processRequest($parameters));
}
return $results;
} | php | public function fetch(array $parameters = [])
{
$this->api->setPerPage(100);
$results = $this->processRequest($parameters);
while ($this->nextToken) {
$results = array_merge($results, $this->processRequest($parameters));
}
return $results;
} | [
"public",
"function",
"fetch",
"(",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"api",
"->",
"setPerPage",
"(",
"100",
")",
";",
"$",
"results",
"=",
"$",
"this",
"->",
"processRequest",
"(",
"$",
"parameters",
")",
";",
... | Fetches all the objects of the given api.
@param array $parameters
@return array | [
"Fetches",
"all",
"the",
"objects",
"of",
"the",
"given",
"api",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Pager.php#L58-L69 |
cartalyst/stripe | src/Pager.php | Pager.processRequest | protected function processRequest(array $parameters = [])
{
if ($this->nextToken) {
$parameters['starting_after'] = $this->nextToken;
}
if (isset($parameters[0])) {
$id = $parameters[0];
unset($parameters[0]);
if (isset($parameters[1])) {
$parameters = $parameters[1];
unset($parameters[1]);
}
$parameters = [ $id, $parameters ];
} else {
$parameters = [ $parameters ];
}
$result = call_user_func_array([ $this->api, 'all' ], $parameters);
$this->nextToken = $result['has_more'] ? end($result['data'])['id'] : false;
return $result['data'];
} | php | protected function processRequest(array $parameters = [])
{
if ($this->nextToken) {
$parameters['starting_after'] = $this->nextToken;
}
if (isset($parameters[0])) {
$id = $parameters[0];
unset($parameters[0]);
if (isset($parameters[1])) {
$parameters = $parameters[1];
unset($parameters[1]);
}
$parameters = [ $id, $parameters ];
} else {
$parameters = [ $parameters ];
}
$result = call_user_func_array([ $this->api, 'all' ], $parameters);
$this->nextToken = $result['has_more'] ? end($result['data'])['id'] : false;
return $result['data'];
} | [
"protected",
"function",
"processRequest",
"(",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"nextToken",
")",
"{",
"$",
"parameters",
"[",
"'starting_after'",
"]",
"=",
"$",
"this",
"->",
"nextToken",
";",
"}",
"i... | Processes the api request.
@param array $parameters
@return array | [
"Processes",
"the",
"api",
"request",
"."
] | train | https://github.com/cartalyst/stripe/blob/be3a233d3123fe01600c50fb47b8dc5bcdbc482b/src/Pager.php#L77-L104 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.setKeepAlive | public function setKeepAlive($b)
{
$this->_keepAlive = (boolean)$b;
if (!$this->_keepAlive && $this->_sock) {
fclose($this->_sock);
}
} | php | public function setKeepAlive($b)
{
$this->_keepAlive = (boolean)$b;
if (!$this->_keepAlive && $this->_sock) {
fclose($this->_sock);
}
} | [
"public",
"function",
"setKeepAlive",
"(",
"$",
"b",
")",
"{",
"$",
"this",
"->",
"_keepAlive",
"=",
"(",
"boolean",
")",
"$",
"b",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"_keepAlive",
"&&",
"$",
"this",
"->",
"_sock",
")",
"{",
"fclose",
"(",
"... | Define whether or not the FastCGI application should keep the connection
alive at the end of a request
@param Boolean $b true if the connection should stay alive, false otherwise | [
"Define",
"whether",
"or",
"not",
"the",
"FastCGI",
"application",
"should",
"keep",
"the",
"connection",
"alive",
"at",
"the",
"end",
"of",
"a",
"request"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L147-L153 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.setPersistentSocket | public function setPersistentSocket($b)
{
$was_persistent = ($this->_sock && $this->_persistentSocket);
$this->_persistentSocket = (boolean)$b;
if (!$this->_persistentSocket && $was_persistent) {
fclose($this->_sock);
}
} | php | public function setPersistentSocket($b)
{
$was_persistent = ($this->_sock && $this->_persistentSocket);
$this->_persistentSocket = (boolean)$b;
if (!$this->_persistentSocket && $was_persistent) {
fclose($this->_sock);
}
} | [
"public",
"function",
"setPersistentSocket",
"(",
"$",
"b",
")",
"{",
"$",
"was_persistent",
"=",
"(",
"$",
"this",
"->",
"_sock",
"&&",
"$",
"this",
"->",
"_persistentSocket",
")",
";",
"$",
"this",
"->",
"_persistentSocket",
"=",
"(",
"boolean",
")",
"... | Define whether or not PHP should attempt to re-use sockets opened by previous
request for efficiency
@param Boolean $b true if persistent socket should be used, false otherwise | [
"Define",
"whether",
"or",
"not",
"PHP",
"should",
"attempt",
"to",
"re",
"-",
"use",
"sockets",
"opened",
"by",
"previous",
"request",
"for",
"efficiency"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L171-L178 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.set_ms_timeout | private function set_ms_timeout($timeoutMs) {
if (!$this->_sock) {
return false;
}
return stream_set_timeout($this->_sock, floor($timeoutMs / 1000), ($timeoutMs % 1000) * 1000);
} | php | private function set_ms_timeout($timeoutMs) {
if (!$this->_sock) {
return false;
}
return stream_set_timeout($this->_sock, floor($timeoutMs / 1000), ($timeoutMs % 1000) * 1000);
} | [
"private",
"function",
"set_ms_timeout",
"(",
"$",
"timeoutMs",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_sock",
")",
"{",
"return",
"false",
";",
"}",
"return",
"stream_set_timeout",
"(",
"$",
"this",
"->",
"_sock",
",",
"floor",
"(",
"$",
"timeo... | Helper to avoid duplicating milliseconds to secs/usecs in a few places
@param Integer millisecond timeout
@return Boolean | [
"Helper",
"to",
"avoid",
"duplicating",
"milliseconds",
"to",
"secs",
"/",
"usecs",
"in",
"a",
"few",
"places"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L238-L243 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.connect | private function connect()
{
if (!$this->_sock) {
if ($this->_persistentSocket) {
$this->_sock = pfsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
} else {
$this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
}
if (!$this->_sock) {
throw new \Exception('Unable to connect to FastCGI application: ' . $errstr);
}
if (!$this->set_ms_timeout($this->_readWriteTimeout)) {
throw new \Exception('Unable to set timeout on socket');
}
}
} | php | private function connect()
{
if (!$this->_sock) {
if ($this->_persistentSocket) {
$this->_sock = pfsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
} else {
$this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
}
if (!$this->_sock) {
throw new \Exception('Unable to connect to FastCGI application: ' . $errstr);
}
if (!$this->set_ms_timeout($this->_readWriteTimeout)) {
throw new \Exception('Unable to set timeout on socket');
}
}
} | [
"private",
"function",
"connect",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_sock",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_persistentSocket",
")",
"{",
"$",
"this",
"->",
"_sock",
"=",
"pfsockopen",
"(",
"$",
"this",
"->",
"_host",
",",... | Create a connection to the FastCGI application | [
"Create",
"a",
"connection",
"to",
"the",
"FastCGI",
"application"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L249-L266 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.buildPacket | private function buildPacket($type, $content, $requestId = 1)
{
$clen = strlen($content);
return chr(self::VERSION_1) /* version */
. chr($type) /* type */
. chr(($requestId >> 8) & 0xFF) /* requestIdB1 */
. chr($requestId & 0xFF) /* requestIdB0 */
. chr(($clen >> 8 ) & 0xFF) /* contentLengthB1 */
. chr($clen & 0xFF) /* contentLengthB0 */
. chr(0) /* paddingLength */
. chr(0) /* reserved */
. $content; /* content */
} | php | private function buildPacket($type, $content, $requestId = 1)
{
$clen = strlen($content);
return chr(self::VERSION_1) /* version */
. chr($type) /* type */
. chr(($requestId >> 8) & 0xFF) /* requestIdB1 */
. chr($requestId & 0xFF) /* requestIdB0 */
. chr(($clen >> 8 ) & 0xFF) /* contentLengthB1 */
. chr($clen & 0xFF) /* contentLengthB0 */
. chr(0) /* paddingLength */
. chr(0) /* reserved */
. $content; /* content */
} | [
"private",
"function",
"buildPacket",
"(",
"$",
"type",
",",
"$",
"content",
",",
"$",
"requestId",
"=",
"1",
")",
"{",
"$",
"clen",
"=",
"strlen",
"(",
"$",
"content",
")",
";",
"return",
"chr",
"(",
"self",
"::",
"VERSION_1",
")",
"/* version */",
... | Build a FastCGI packet
@param Integer $type Type of the packet
@param String $content Content of the packet
@param Integer $requestId RequestId | [
"Build",
"a",
"FastCGI",
"packet"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L275-L287 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.readNvpair | private function readNvpair($data, $length = null)
{
$array = array();
if ($length === null) {
$length = strlen($data);
}
$p = 0;
while ($p != $length) {
$nlen = ord($data{$p++});
if ($nlen >= 128) {
$nlen = ($nlen & 0x7F << 24);
$nlen |= (ord($data{$p++}) << 16);
$nlen |= (ord($data{$p++}) << 8);
$nlen |= (ord($data{$p++}));
}
$vlen = ord($data{$p++});
if ($vlen >= 128) {
$vlen = ($nlen & 0x7F << 24);
$vlen |= (ord($data{$p++}) << 16);
$vlen |= (ord($data{$p++}) << 8);
$vlen |= (ord($data{$p++}));
}
$array[substr($data, $p, $nlen)] = substr($data, $p+$nlen, $vlen);
$p += ($nlen + $vlen);
}
return $array;
} | php | private function readNvpair($data, $length = null)
{
$array = array();
if ($length === null) {
$length = strlen($data);
}
$p = 0;
while ($p != $length) {
$nlen = ord($data{$p++});
if ($nlen >= 128) {
$nlen = ($nlen & 0x7F << 24);
$nlen |= (ord($data{$p++}) << 16);
$nlen |= (ord($data{$p++}) << 8);
$nlen |= (ord($data{$p++}));
}
$vlen = ord($data{$p++});
if ($vlen >= 128) {
$vlen = ($nlen & 0x7F << 24);
$vlen |= (ord($data{$p++}) << 16);
$vlen |= (ord($data{$p++}) << 8);
$vlen |= (ord($data{$p++}));
}
$array[substr($data, $p, $nlen)] = substr($data, $p+$nlen, $vlen);
$p += ($nlen + $vlen);
}
return $array;
} | [
"private",
"function",
"readNvpair",
"(",
"$",
"data",
",",
"$",
"length",
"=",
"null",
")",
"{",
"$",
"array",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"length",
"===",
"null",
")",
"{",
"$",
"length",
"=",
"strlen",
"(",
"$",
"data",
")",
... | Read a set of FastCGI Name value pairs
@param String $data Data containing the set of FastCGI NVPair
@return array of NVPair | [
"Read",
"a",
"set",
"of",
"FastCGI",
"Name",
"value",
"pairs"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L324-L355 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.decodePacketHeader | private function decodePacketHeader($data)
{
$ret = array();
$ret['version'] = ord($data{0});
$ret['type'] = ord($data{1});
$ret['requestId'] = (ord($data{2}) << 8) + ord($data{3});
$ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5});
$ret['paddingLength'] = ord($data{6});
$ret['reserved'] = ord($data{7});
return $ret;
} | php | private function decodePacketHeader($data)
{
$ret = array();
$ret['version'] = ord($data{0});
$ret['type'] = ord($data{1});
$ret['requestId'] = (ord($data{2}) << 8) + ord($data{3});
$ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5});
$ret['paddingLength'] = ord($data{6});
$ret['reserved'] = ord($data{7});
return $ret;
} | [
"private",
"function",
"decodePacketHeader",
"(",
"$",
"data",
")",
"{",
"$",
"ret",
"=",
"array",
"(",
")",
";",
"$",
"ret",
"[",
"'version'",
"]",
"=",
"ord",
"(",
"$",
"data",
"{",
"0",
"}",
")",
";",
"$",
"ret",
"[",
"'type'",
"]",
"=",
"or... | Decode a FastCGI Packet
@param String $data String containing all the packet
@return array | [
"Decode",
"a",
"FastCGI",
"Packet"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L363-L373 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.readPacket | private function readPacket()
{
if ($packet = fread($this->_sock, self::HEADER_LEN)) {
$resp = $this->decodePacketHeader($packet);
$resp['content'] = '';
if ($resp['contentLength']) {
$len = $resp['contentLength'];
while ($len && ($buf=fread($this->_sock, $len)) !== false) {
$len -= strlen($buf);
$resp['content'] .= $buf;
}
}
if ($resp['paddingLength']) {
$buf = fread($this->_sock, $resp['paddingLength']);
}
return $resp;
} else {
return false;
}
} | php | private function readPacket()
{
if ($packet = fread($this->_sock, self::HEADER_LEN)) {
$resp = $this->decodePacketHeader($packet);
$resp['content'] = '';
if ($resp['contentLength']) {
$len = $resp['contentLength'];
while ($len && ($buf=fread($this->_sock, $len)) !== false) {
$len -= strlen($buf);
$resp['content'] .= $buf;
}
}
if ($resp['paddingLength']) {
$buf = fread($this->_sock, $resp['paddingLength']);
}
return $resp;
} else {
return false;
}
} | [
"private",
"function",
"readPacket",
"(",
")",
"{",
"if",
"(",
"$",
"packet",
"=",
"fread",
"(",
"$",
"this",
"->",
"_sock",
",",
"self",
"::",
"HEADER_LEN",
")",
")",
"{",
"$",
"resp",
"=",
"$",
"this",
"->",
"decodePacketHeader",
"(",
"$",
"packet"... | Read a FastCGI Packet
@return array | [
"Read",
"a",
"FastCGI",
"Packet"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L380-L399 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.getValues | public function getValues(array $requestedInfo)
{
$this->connect();
$request = '';
foreach ($requestedInfo as $info) {
$request .= $this->buildNvpair($info, '');
}
fwrite($this->_sock, $this->buildPacket(self::GET_VALUES, $request, 0));
$resp = $this->readPacket();
if ($resp['type'] == self::GET_VALUES_RESULT) {
return $this->readNvpair($resp['content'], $resp['length']);
} else {
throw new \Exception('Unexpected response type, expecting GET_VALUES_RESULT');
}
} | php | public function getValues(array $requestedInfo)
{
$this->connect();
$request = '';
foreach ($requestedInfo as $info) {
$request .= $this->buildNvpair($info, '');
}
fwrite($this->_sock, $this->buildPacket(self::GET_VALUES, $request, 0));
$resp = $this->readPacket();
if ($resp['type'] == self::GET_VALUES_RESULT) {
return $this->readNvpair($resp['content'], $resp['length']);
} else {
throw new \Exception('Unexpected response type, expecting GET_VALUES_RESULT');
}
} | [
"public",
"function",
"getValues",
"(",
"array",
"$",
"requestedInfo",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"$",
"request",
"=",
"''",
";",
"foreach",
"(",
"$",
"requestedInfo",
"as",
"$",
"info",
")",
"{",
"$",
"request",
".=",
"$"... | Get Informations on the FastCGI application
@param array $requestedInfo information to retrieve
@return array | [
"Get",
"Informations",
"on",
"the",
"FastCGI",
"application"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L407-L423 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.request | public function request(array $params, $stdin)
{
$id = $this->async_request($params, $stdin);
return $this->wait_for_response($id);
} | php | public function request(array $params, $stdin)
{
$id = $this->async_request($params, $stdin);
return $this->wait_for_response($id);
} | [
"public",
"function",
"request",
"(",
"array",
"$",
"params",
",",
"$",
"stdin",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"async_request",
"(",
"$",
"params",
",",
"$",
"stdin",
")",
";",
"return",
"$",
"this",
"->",
"wait_for_response",
"(",
"$"... | Execute a request to the FastCGI application
@param array $params Array of parameters
@param String $stdin Content
@return String | [
"Execute",
"a",
"request",
"to",
"the",
"FastCGI",
"application"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L432-L436 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.async_request | public function async_request(array $params, $stdin)
{
$this->connect();
// Pick random number between 1 and max 16 bit unsigned int 65535
$id = mt_rand(1, (1 << 16) - 1);
// Using persistent sockets implies you want them keept alive by server!
$keepAlive = intval($this->_keepAlive || $this->_persistentSocket);
$request = $this->buildPacket(self::BEGIN_REQUEST
,chr(0) . chr(self::RESPONDER) . chr($keepAlive) . str_repeat(chr(0), 5)
,$id
);
$paramsRequest = '';
foreach ($params as $key => $value) {
$paramsRequest .= $this->buildNvpair($key, $value, $id);
}
if ($paramsRequest) {
$request .= $this->buildPacket(self::PARAMS, $paramsRequest, $id);
}
$request .= $this->buildPacket(self::PARAMS, '', $id);
if ($stdin) {
$request .= $this->buildPacket(self::STDIN, $stdin, $id);
}
$request .= $this->buildPacket(self::STDIN, '', $id);
if (fwrite($this->_sock, $request) === false || fflush($this->_sock) === false) {
$info = stream_get_meta_data($this->_sock);
if ($info['timed_out']) {
throw new TimedOutException('Write timed out');
}
// Broken pipe, tear down so future requests might succeed
fclose($this->_sock);
throw new \Exception('Failed to write request to socket');
}
$this->_requests[$id] = array(
'state' => self::REQ_STATE_WRITTEN,
'response' => null
);
return $id;
} | php | public function async_request(array $params, $stdin)
{
$this->connect();
// Pick random number between 1 and max 16 bit unsigned int 65535
$id = mt_rand(1, (1 << 16) - 1);
// Using persistent sockets implies you want them keept alive by server!
$keepAlive = intval($this->_keepAlive || $this->_persistentSocket);
$request = $this->buildPacket(self::BEGIN_REQUEST
,chr(0) . chr(self::RESPONDER) . chr($keepAlive) . str_repeat(chr(0), 5)
,$id
);
$paramsRequest = '';
foreach ($params as $key => $value) {
$paramsRequest .= $this->buildNvpair($key, $value, $id);
}
if ($paramsRequest) {
$request .= $this->buildPacket(self::PARAMS, $paramsRequest, $id);
}
$request .= $this->buildPacket(self::PARAMS, '', $id);
if ($stdin) {
$request .= $this->buildPacket(self::STDIN, $stdin, $id);
}
$request .= $this->buildPacket(self::STDIN, '', $id);
if (fwrite($this->_sock, $request) === false || fflush($this->_sock) === false) {
$info = stream_get_meta_data($this->_sock);
if ($info['timed_out']) {
throw new TimedOutException('Write timed out');
}
// Broken pipe, tear down so future requests might succeed
fclose($this->_sock);
throw new \Exception('Failed to write request to socket');
}
$this->_requests[$id] = array(
'state' => self::REQ_STATE_WRITTEN,
'response' => null
);
return $id;
} | [
"public",
"function",
"async_request",
"(",
"array",
"$",
"params",
",",
"$",
"stdin",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"// Pick random number between 1 and max 16 bit unsigned int 65535",
"$",
"id",
"=",
"mt_rand",
"(",
"1",
",",
"(",
"1... | Execute a request to the FastCGI application asyncronously
This sends request to application and returns the assigned ID for that request.
You should keep this id for later use with wait_for_response(). Ids are chosen randomly
rather than seqentially to guard against false-positives when using persistent sockets.
In that case it is possible that a delayed response to a request made by a previous script
invocation comes back on this socket and is mistaken for response to request made with same ID
during this request.
@param array $params Array of parameters
@param String $stdin Content
@return Integer | [
"Execute",
"a",
"request",
"to",
"the",
"FastCGI",
"application",
"asyncronously"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L453-L501 |
adoy/PHP-FastCGI-Client | src/Adoy/FastCGI/Client.php | Client.wait_for_response | public function wait_for_response($requestId, $timeoutMs = 0) {
if (!isset($this->_requests[$requestId])) {
throw new \Exception('Invalid request id given');
}
// If we already read the response during an earlier call for different id, just return it
if ($this->_requests[$requestId]['state'] == self::REQ_STATE_OK
|| $this->_requests[$requestId]['state'] == self::REQ_STATE_ERR
) {
return $this->_requests[$requestId]['response'];
}
if ($timeoutMs > 0) {
// Reset timeout on socket for now
$this->set_ms_timeout($timeoutMs);
} else {
$timeoutMs = $this->_readWriteTimeout;
}
// Need to manually check since we might do several reads none of which timeout themselves
// but still not get the response requested
$startTime = microtime(true);
do {
$resp = $this->readPacket();
if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
if ($resp['type'] == self::STDERR) {
$this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_ERR;
}
$this->_requests[$resp['requestId']]['response'] .= $resp['content'];
}
if ($resp['type'] == self::END_REQUEST) {
$this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_OK;
if ($resp['requestId'] == $requestId) {
break;
}
}
if (microtime(true) - $startTime >= ($timeoutMs * 1000)) {
// Reset
$this->set_ms_timeout($this->_readWriteTimeout);
throw new \Exception('Timed out');
}
} while ($resp);
if (!is_array($resp)) {
$info = stream_get_meta_data($this->_sock);
// We must reset timeout but it must be AFTER we get info
$this->set_ms_timeout($this->_readWriteTimeout);
if ($info['timed_out']) {
throw new TimedOutException('Read timed out');
}
if ($info['unread_bytes'] == 0
&& $info['blocked']
&& $info['eof']) {
throw new ForbiddenException('Not in white list. Check listen.allowed_clients.');
}
throw new \Exception('Read failed');
}
// Reset timeout
$this->set_ms_timeout($this->_readWriteTimeout);
switch (ord($resp['content']{4})) {
case self::CANT_MPX_CONN:
throw new \Exception('This app can\'t multiplex [CANT_MPX_CONN]');
break;
case self::OVERLOADED:
throw new \Exception('New request rejected; too busy [OVERLOADED]');
break;
case self::UNKNOWN_ROLE:
throw new \Exception('Role value not known [UNKNOWN_ROLE]');
break;
case self::REQUEST_COMPLETE:
return $this->_requests[$requestId]['response'];
}
} | php | public function wait_for_response($requestId, $timeoutMs = 0) {
if (!isset($this->_requests[$requestId])) {
throw new \Exception('Invalid request id given');
}
// If we already read the response during an earlier call for different id, just return it
if ($this->_requests[$requestId]['state'] == self::REQ_STATE_OK
|| $this->_requests[$requestId]['state'] == self::REQ_STATE_ERR
) {
return $this->_requests[$requestId]['response'];
}
if ($timeoutMs > 0) {
// Reset timeout on socket for now
$this->set_ms_timeout($timeoutMs);
} else {
$timeoutMs = $this->_readWriteTimeout;
}
// Need to manually check since we might do several reads none of which timeout themselves
// but still not get the response requested
$startTime = microtime(true);
do {
$resp = $this->readPacket();
if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
if ($resp['type'] == self::STDERR) {
$this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_ERR;
}
$this->_requests[$resp['requestId']]['response'] .= $resp['content'];
}
if ($resp['type'] == self::END_REQUEST) {
$this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_OK;
if ($resp['requestId'] == $requestId) {
break;
}
}
if (microtime(true) - $startTime >= ($timeoutMs * 1000)) {
// Reset
$this->set_ms_timeout($this->_readWriteTimeout);
throw new \Exception('Timed out');
}
} while ($resp);
if (!is_array($resp)) {
$info = stream_get_meta_data($this->_sock);
// We must reset timeout but it must be AFTER we get info
$this->set_ms_timeout($this->_readWriteTimeout);
if ($info['timed_out']) {
throw new TimedOutException('Read timed out');
}
if ($info['unread_bytes'] == 0
&& $info['blocked']
&& $info['eof']) {
throw new ForbiddenException('Not in white list. Check listen.allowed_clients.');
}
throw new \Exception('Read failed');
}
// Reset timeout
$this->set_ms_timeout($this->_readWriteTimeout);
switch (ord($resp['content']{4})) {
case self::CANT_MPX_CONN:
throw new \Exception('This app can\'t multiplex [CANT_MPX_CONN]');
break;
case self::OVERLOADED:
throw new \Exception('New request rejected; too busy [OVERLOADED]');
break;
case self::UNKNOWN_ROLE:
throw new \Exception('Role value not known [UNKNOWN_ROLE]');
break;
case self::REQUEST_COMPLETE:
return $this->_requests[$requestId]['response'];
}
} | [
"public",
"function",
"wait_for_response",
"(",
"$",
"requestId",
",",
"$",
"timeoutMs",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_requests",
"[",
"$",
"requestId",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"... | Blocking call that waits for response to specific request
@param Integer $requestId
@param Integer $timeoutMs [optional] the number of milliseconds to wait. Defaults to the ReadWriteTimeout value set.
@return string response body | [
"Blocking",
"call",
"that",
"waits",
"for",
"response",
"to",
"specific",
"request"
] | train | https://github.com/adoy/PHP-FastCGI-Client/blob/2554226463b886a4e044fe40b81062975a49b5bd/src/Adoy/FastCGI/Client.php#L510-L591 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/DateTime/PreciseFormatter.php | PreciseFormatter.formatDifference | public function formatDifference(PreciseDifference $difference, $locale = 'en')
{
$diff = [];
foreach ($difference->getCompoundResults() as $result) {
$diff[] = $this->translator->transChoice(
'compound.'.$result->getUnit()->getName(),
$result->getQuantity(),
['%count%' => $result->getQuantity()],
'difference',
$locale
);
}
return $this->translator->trans(
'compound.'.($difference->isPast() ? 'past' : 'future'),
['%value%' => \implode(', ', $diff)],
'difference',
$locale
);
} | php | public function formatDifference(PreciseDifference $difference, $locale = 'en')
{
$diff = [];
foreach ($difference->getCompoundResults() as $result) {
$diff[] = $this->translator->transChoice(
'compound.'.$result->getUnit()->getName(),
$result->getQuantity(),
['%count%' => $result->getQuantity()],
'difference',
$locale
);
}
return $this->translator->trans(
'compound.'.($difference->isPast() ? 'past' : 'future'),
['%value%' => \implode(', ', $diff)],
'difference',
$locale
);
} | [
"public",
"function",
"formatDifference",
"(",
"PreciseDifference",
"$",
"difference",
",",
"$",
"locale",
"=",
"'en'",
")",
"{",
"$",
"diff",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"difference",
"->",
"getCompoundResults",
"(",
")",
"as",
"$",
"result",... | @param PreciseDifference $difference
@param string $locale
@return string | [
"@param",
"PreciseDifference",
"$difference",
"@param",
"string",
"$locale"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/DateTime/PreciseFormatter.php#L37-L57 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/String/HtmlTruncate.php | HtmlTruncate.truncateHtml | private function truncateHtml($string, $charactersCount)
{
$limit = $charactersCount;
$offset = 0;
$tags = [];
// Handle special characters.
\preg_match_all('/&[a-z]+;/i', \strip_tags($string), $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach ($matches as $match) {
if ($match[0][1] >= $limit) {
break;
}
$limit += (\mb_strlen($match[0][0]) - 1);
}
// Handle all the html tags.
\preg_match_all('/<[^>]+>([^<]*)/', $string, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach ($matches as $match) {
if ($match[0][1] - $offset >= $limit) {
break;
}
$tag = \mb_substr(\strtok($match[0][0], " \t\n\r\0\x0B>"), 1);
if ($tag[0] != '/') {
$tags[] = $tag;
} elseif (\end($tags) == \mb_substr($tag, 1)) {
\array_pop($tags);
}
$offset += $match[1][1] - $match[0][1];
}
$newString = \mb_substr($string, 0, $limit = \min(\mb_strlen($string), $this->breakpoint->calculatePosition($string, $limit + $offset)));
$newString .= (\mb_strlen($string) > $limit ? $this->append : '');
$newString .= (\count($tags = \array_reverse($tags)) ? '</'.\implode('></', $tags).'>' : '');
return $newString;
} | php | private function truncateHtml($string, $charactersCount)
{
$limit = $charactersCount;
$offset = 0;
$tags = [];
// Handle special characters.
\preg_match_all('/&[a-z]+;/i', \strip_tags($string), $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach ($matches as $match) {
if ($match[0][1] >= $limit) {
break;
}
$limit += (\mb_strlen($match[0][0]) - 1);
}
// Handle all the html tags.
\preg_match_all('/<[^>]+>([^<]*)/', $string, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach ($matches as $match) {
if ($match[0][1] - $offset >= $limit) {
break;
}
$tag = \mb_substr(\strtok($match[0][0], " \t\n\r\0\x0B>"), 1);
if ($tag[0] != '/') {
$tags[] = $tag;
} elseif (\end($tags) == \mb_substr($tag, 1)) {
\array_pop($tags);
}
$offset += $match[1][1] - $match[0][1];
}
$newString = \mb_substr($string, 0, $limit = \min(\mb_strlen($string), $this->breakpoint->calculatePosition($string, $limit + $offset)));
$newString .= (\mb_strlen($string) > $limit ? $this->append : '');
$newString .= (\count($tags = \array_reverse($tags)) ? '</'.\implode('></', $tags).'>' : '');
return $newString;
} | [
"private",
"function",
"truncateHtml",
"(",
"$",
"string",
",",
"$",
"charactersCount",
")",
"{",
"$",
"limit",
"=",
"$",
"charactersCount",
";",
"$",
"offset",
"=",
"0",
";",
"$",
"tags",
"=",
"[",
"]",
";",
"// Handle special characters.",
"\\",
"preg_ma... | Truncates a string to the given length. It will optionally preserve
HTML tags if $is_html is set to true.
Adapted from FuelPHP Str::truncate (https://github.com/fuelphp/common/blob/master/src/Str.php)
@param string $string
@param int $charactersCount
@return string the truncated string | [
"Truncates",
"a",
"string",
"to",
"the",
"given",
"length",
".",
"It",
"will",
"optionally",
"preserve",
"HTML",
"tags",
"if",
"$is_html",
"is",
"set",
"to",
"true",
"."
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/String/HtmlTruncate.php#L64-L101 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Number/Ordinal/Builder.php | Builder.build | public static function build($locale)
{
// $locale should be xx or xx_YY
if (!\preg_match('/^([a-z]{2})(_([A-Z]{2}))?$/', $locale, $m)) {
throw new \RuntimeException("Invalid locale specified: '$locale'.");
}
$strategy = \ucfirst($m[1]);
if (!empty($m[3])) {
$strategy .= "_$m[3]";
}
$strategy = "\\Coduo\\PHPHumanizer\\Resources\\Ordinal\\{$strategy}Strategy";
if (\class_exists($strategy)) {
return new $strategy();
}
// Debatable: should we fallback to English?
// return self::build('en');
throw new \RuntimeException("Strategy for locale $locale not found.");
} | php | public static function build($locale)
{
// $locale should be xx or xx_YY
if (!\preg_match('/^([a-z]{2})(_([A-Z]{2}))?$/', $locale, $m)) {
throw new \RuntimeException("Invalid locale specified: '$locale'.");
}
$strategy = \ucfirst($m[1]);
if (!empty($m[3])) {
$strategy .= "_$m[3]";
}
$strategy = "\\Coduo\\PHPHumanizer\\Resources\\Ordinal\\{$strategy}Strategy";
if (\class_exists($strategy)) {
return new $strategy();
}
// Debatable: should we fallback to English?
// return self::build('en');
throw new \RuntimeException("Strategy for locale $locale not found.");
} | [
"public",
"static",
"function",
"build",
"(",
"$",
"locale",
")",
"{",
"// $locale should be xx or xx_YY",
"if",
"(",
"!",
"\\",
"preg_match",
"(",
"'/^([a-z]{2})(_([A-Z]{2}))?$/'",
",",
"$",
"locale",
",",
"$",
"m",
")",
")",
"{",
"throw",
"new",
"\\",
"Run... | @param string $locale
@return StrategyInterface
@throws \RuntimeException | [
"@param",
"string",
"$locale"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Number/Ordinal/Builder.php#L26-L47 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/DateTime/Formatter.php | Formatter.formatDifference | public function formatDifference(Difference $difference, $locale = 'en')
{
$translationKey = \sprintf('%s.%s', $difference->getUnit()->getName(), $difference->isPast() ? 'past' : 'future');
return $this->translator->transChoice(
$translationKey,
$difference->getQuantity(),
['%count%' => $difference->getQuantity()],
'difference',
$locale
);
} | php | public function formatDifference(Difference $difference, $locale = 'en')
{
$translationKey = \sprintf('%s.%s', $difference->getUnit()->getName(), $difference->isPast() ? 'past' : 'future');
return $this->translator->transChoice(
$translationKey,
$difference->getQuantity(),
['%count%' => $difference->getQuantity()],
'difference',
$locale
);
} | [
"public",
"function",
"formatDifference",
"(",
"Difference",
"$",
"difference",
",",
"$",
"locale",
"=",
"'en'",
")",
"{",
"$",
"translationKey",
"=",
"\\",
"sprintf",
"(",
"'%s.%s'",
",",
"$",
"difference",
"->",
"getUnit",
"(",
")",
"->",
"getName",
"(",... | @param Difference $difference
@param string $locale
@return string | [
"@param",
"Difference",
"$difference",
"@param",
"string",
"$locale"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/DateTime/Formatter.php#L37-L48 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/String/ShortcodeProcessor.php | ShortcodeProcessor.removeShortcodeTags | public function removeShortcodeTags($text)
{
$contentHandler = function (ShortcodeInterface $s) {
return $s->getContent();
};
return $this->createShortcodeProcessor($contentHandler)->process($text);
} | php | public function removeShortcodeTags($text)
{
$contentHandler = function (ShortcodeInterface $s) {
return $s->getContent();
};
return $this->createShortcodeProcessor($contentHandler)->process($text);
} | [
"public",
"function",
"removeShortcodeTags",
"(",
"$",
"text",
")",
"{",
"$",
"contentHandler",
"=",
"function",
"(",
"ShortcodeInterface",
"$",
"s",
")",
"{",
"return",
"$",
"s",
"->",
"getContent",
"(",
")",
";",
"}",
";",
"return",
"$",
"this",
"->",
... | Removes only shortcode tags from given text (leaves their content as it is).
@param string $text
@return string | [
"Removes",
"only",
"shortcode",
"tags",
"from",
"given",
"text",
"(",
"leaves",
"their",
"content",
"as",
"it",
"is",
")",
"."
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/String/ShortcodeProcessor.php#L44-L51 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/StringHumanizer.php | StringHumanizer.humanize | public static function humanize($text, $capitalize = true, $separator = '_', array $forbiddenWords = [])
{
return (string) new Humanize($text, $capitalize, $separator, $forbiddenWords);
} | php | public static function humanize($text, $capitalize = true, $separator = '_', array $forbiddenWords = [])
{
return (string) new Humanize($text, $capitalize, $separator, $forbiddenWords);
} | [
"public",
"static",
"function",
"humanize",
"(",
"$",
"text",
",",
"$",
"capitalize",
"=",
"true",
",",
"$",
"separator",
"=",
"'_'",
",",
"array",
"$",
"forbiddenWords",
"=",
"[",
"]",
")",
"{",
"return",
"(",
"string",
")",
"new",
"Humanize",
"(",
... | @param $text
@param bool|true $capitalize
@param string $separator
@param array $forbiddenWords
@return string | [
"@param",
"$text",
"@param",
"bool|true",
"$capitalize",
"@param",
"string",
"$separator",
"@param",
"array",
"$forbiddenWords"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/StringHumanizer.php#L30-L33 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/StringHumanizer.php | StringHumanizer.truncate | public static function truncate($text, $charactersCount, $append = '')
{
$truncate = new TextTruncate(new WordBreakpoint(), $append);
return $truncate->truncate($text, $charactersCount);
} | php | public static function truncate($text, $charactersCount, $append = '')
{
$truncate = new TextTruncate(new WordBreakpoint(), $append);
return $truncate->truncate($text, $charactersCount);
} | [
"public",
"static",
"function",
"truncate",
"(",
"$",
"text",
",",
"$",
"charactersCount",
",",
"$",
"append",
"=",
"''",
")",
"{",
"$",
"truncate",
"=",
"new",
"TextTruncate",
"(",
"new",
"WordBreakpoint",
"(",
")",
",",
"$",
"append",
")",
";",
"retu... | @param $text
@param $charactersCount
@param string $append
@return string | [
"@param",
"$text",
"@param",
"$charactersCount",
"@param",
"string",
"$append"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/StringHumanizer.php#L42-L47 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/StringHumanizer.php | StringHumanizer.truncateHtml | public static function truncateHtml($text, $charactersCount, $allowedTags = '', $append = '')
{
$truncate = new HtmlTruncate(new WordBreakpoint(), $allowedTags, $append);
return $truncate->truncate($text, $charactersCount);
} | php | public static function truncateHtml($text, $charactersCount, $allowedTags = '', $append = '')
{
$truncate = new HtmlTruncate(new WordBreakpoint(), $allowedTags, $append);
return $truncate->truncate($text, $charactersCount);
} | [
"public",
"static",
"function",
"truncateHtml",
"(",
"$",
"text",
",",
"$",
"charactersCount",
",",
"$",
"allowedTags",
"=",
"''",
",",
"$",
"append",
"=",
"''",
")",
"{",
"$",
"truncate",
"=",
"new",
"HtmlTruncate",
"(",
"new",
"WordBreakpoint",
"(",
")... | @param $text
@param $charactersCount
@param string $allowedTags
@param string $append
@return string | [
"@param",
"$text",
"@param",
"$charactersCount",
"@param",
"string",
"$allowedTags",
"@param",
"string",
"$append"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/StringHumanizer.php#L57-L62 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Resources/Ordinal/EnStrategy.php | EnStrategy.ordinalIndicator | public function ordinalIndicator($number)
{
$absNumber = \abs((integer) $number);
if (\in_array(($absNumber % 100), [11, 12, 13], true)) {
return 'th';
}
switch ($absNumber % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
} | php | public function ordinalIndicator($number)
{
$absNumber = \abs((integer) $number);
if (\in_array(($absNumber % 100), [11, 12, 13], true)) {
return 'th';
}
switch ($absNumber % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
} | [
"public",
"function",
"ordinalIndicator",
"(",
"$",
"number",
")",
"{",
"$",
"absNumber",
"=",
"\\",
"abs",
"(",
"(",
"integer",
")",
"$",
"number",
")",
";",
"if",
"(",
"\\",
"in_array",
"(",
"(",
"$",
"absNumber",
"%",
"100",
")",
",",
"[",
"11",... | {@inheritdoc} | [
"{"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Resources/Ordinal/EnStrategy.php#L29-L43 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/String/TextTruncate.php | TextTruncate.truncate | public function truncate($text, $charactersCount)
{
if ($charactersCount < 0 || \mb_strlen($text) <= $charactersCount) {
return $text;
}
$truncatedText = \rtrim(\mb_substr($text, 0, $this->breakpoint->calculatePosition($text, $charactersCount)));
return ($truncatedText === $text) ? $truncatedText : $truncatedText.$this->append;
} | php | public function truncate($text, $charactersCount)
{
if ($charactersCount < 0 || \mb_strlen($text) <= $charactersCount) {
return $text;
}
$truncatedText = \rtrim(\mb_substr($text, 0, $this->breakpoint->calculatePosition($text, $charactersCount)));
return ($truncatedText === $text) ? $truncatedText : $truncatedText.$this->append;
} | [
"public",
"function",
"truncate",
"(",
"$",
"text",
",",
"$",
"charactersCount",
")",
"{",
"if",
"(",
"$",
"charactersCount",
"<",
"0",
"||",
"\\",
"mb_strlen",
"(",
"$",
"text",
")",
"<=",
"$",
"charactersCount",
")",
"{",
"return",
"$",
"text",
";",
... | @param string $text
@param int $charactersCount
@return string | [
"@param",
"string",
"$text",
"@param",
"int",
"$charactersCount"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/String/TextTruncate.php#L42-L51 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/String/BinarySuffix.php | BinarySuffix.setSpecificPrecisionFormat | protected function setSpecificPrecisionFormat($precision)
{
if ($precision < 0) {
throw new \InvalidArgumentException('Precision must be positive');
}
if ($precision > 3) {
throw new \InvalidArgumentException('Invalid precision. Binary suffix converter can only represent values in '.
'up to three decimal places');
}
$icuFormat = '#';
if ($precision > 0) {
$icuFormat .= \str_pad('#.', (2 + $precision), '0');
}
foreach ($this->binaryPrefixes as $size => $unitPattern) {
if ($size >= 1024) {
$symbol = \substr($unitPattern, \strpos($unitPattern, ' '));
$this->binaryPrefixes[$size] = $icuFormat.$symbol;
}
}
} | php | protected function setSpecificPrecisionFormat($precision)
{
if ($precision < 0) {
throw new \InvalidArgumentException('Precision must be positive');
}
if ($precision > 3) {
throw new \InvalidArgumentException('Invalid precision. Binary suffix converter can only represent values in '.
'up to three decimal places');
}
$icuFormat = '#';
if ($precision > 0) {
$icuFormat .= \str_pad('#.', (2 + $precision), '0');
}
foreach ($this->binaryPrefixes as $size => $unitPattern) {
if ($size >= 1024) {
$symbol = \substr($unitPattern, \strpos($unitPattern, ' '));
$this->binaryPrefixes[$size] = $icuFormat.$symbol;
}
}
} | [
"protected",
"function",
"setSpecificPrecisionFormat",
"(",
"$",
"precision",
")",
"{",
"if",
"(",
"$",
"precision",
"<",
"0",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Precision must be positive'",
")",
";",
"}",
"if",
"(",
"$",
"prec... | Replaces the default ICU 56.1 decimal formats defined in $binaryPrefixes with ones that provide the same symbols
but the provided number of decimal places.
@param int $precision
@throws \InvalidArgumentException | [
"Replaces",
"the",
"default",
"ICU",
"56",
".",
"1",
"decimal",
"formats",
"defined",
"in",
"$binaryPrefixes",
"with",
"ones",
"that",
"provide",
"the",
"same",
"symbols",
"but",
"the",
"provided",
"number",
"of",
"decimal",
"places",
"."
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/String/BinarySuffix.php#L98-L119 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Collection/Formatter.php | Formatter.formatCommaSeparatedWithLimit | private function formatCommaSeparatedWithLimit($collection, $limit, $count)
{
$display = \array_map(function ($element) {
return (string) $element;
}, \array_slice($collection, 0, $limit));
$moreCount = $count - \count($display);
return $this->translator->transChoice('comma_separated_with_limit', $moreCount, [
'%list%' => \implode(', ', $display),
'%count%' => $moreCount,
], $this->catalogue);
} | php | private function formatCommaSeparatedWithLimit($collection, $limit, $count)
{
$display = \array_map(function ($element) {
return (string) $element;
}, \array_slice($collection, 0, $limit));
$moreCount = $count - \count($display);
return $this->translator->transChoice('comma_separated_with_limit', $moreCount, [
'%list%' => \implode(', ', $display),
'%count%' => $moreCount,
], $this->catalogue);
} | [
"private",
"function",
"formatCommaSeparatedWithLimit",
"(",
"$",
"collection",
",",
"$",
"limit",
",",
"$",
"count",
")",
"{",
"$",
"display",
"=",
"\\",
"array_map",
"(",
"function",
"(",
"$",
"element",
")",
"{",
"return",
"(",
"string",
")",
"$",
"el... | @param $collection
@param $limit
@param $count
@return string | [
"@param",
"$collection",
"@param",
"$limit",
"@param",
"$count"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Collection/Formatter.php#L67-L79 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Collection/Formatter.php | Formatter.formatCommaSeparated | private function formatCommaSeparated($collection, $count)
{
$display = \array_map(function ($element) {
return (string) $element;
}, \array_slice($collection, 0, $count - 1));
return $this->translator->trans('comma_separated', [
'%list%' => \implode(', ', $display),
'%last%' => (string) \end($collection),
], $this->catalogue);
} | php | private function formatCommaSeparated($collection, $count)
{
$display = \array_map(function ($element) {
return (string) $element;
}, \array_slice($collection, 0, $count - 1));
return $this->translator->trans('comma_separated', [
'%list%' => \implode(', ', $display),
'%last%' => (string) \end($collection),
], $this->catalogue);
} | [
"private",
"function",
"formatCommaSeparated",
"(",
"$",
"collection",
",",
"$",
"count",
")",
"{",
"$",
"display",
"=",
"\\",
"array_map",
"(",
"function",
"(",
"$",
"element",
")",
"{",
"return",
"(",
"string",
")",
"$",
"element",
";",
"}",
",",
"\\... | @param $collection
@param $count
@return string | [
"@param",
"$collection",
"@param",
"$count"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Collection/Formatter.php#L87-L97 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Collection/Formatter.php | Formatter.formatOnlyTwo | private function formatOnlyTwo($collection)
{
return $this->translator->trans('only_two', [
'%first%' => (string) $collection[0],
'%second%' => (string) $collection[1],
], $this->catalogue);
} | php | private function formatOnlyTwo($collection)
{
return $this->translator->trans('only_two', [
'%first%' => (string) $collection[0],
'%second%' => (string) $collection[1],
], $this->catalogue);
} | [
"private",
"function",
"formatOnlyTwo",
"(",
"$",
"collection",
")",
"{",
"return",
"$",
"this",
"->",
"translator",
"->",
"trans",
"(",
"'only_two'",
",",
"[",
"'%first%'",
"=>",
"(",
"string",
")",
"$",
"collection",
"[",
"0",
"]",
",",
"'%second%'",
"... | @param $collection
@return string | [
"@param",
"$collection"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Collection/Formatter.php#L104-L110 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Number/RomanNumeral.php | RomanNumeral.toRoman | public function toRoman($number)
{
if (($number < self::MIN_VALUE) || ($number > self::MAX_VALUE)) {
throw new \InvalidArgumentException();
}
$romanString = '';
while ($number > 0) {
foreach ($this->map as $key => $value) {
if ($number >= $value) {
$romanString .= $key;
$number -= $value;
break;
}
}
}
return $romanString;
} | php | public function toRoman($number)
{
if (($number < self::MIN_VALUE) || ($number > self::MAX_VALUE)) {
throw new \InvalidArgumentException();
}
$romanString = '';
while ($number > 0) {
foreach ($this->map as $key => $value) {
if ($number >= $value) {
$romanString .= $key;
$number -= $value;
break;
}
}
}
return $romanString;
} | [
"public",
"function",
"toRoman",
"(",
"$",
"number",
")",
"{",
"if",
"(",
"(",
"$",
"number",
"<",
"self",
"::",
"MIN_VALUE",
")",
"||",
"(",
"$",
"number",
">",
"self",
"::",
"MAX_VALUE",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException"... | @param $number
@return string
@throws \InvalidArgumentException | [
"@param",
"$number"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Number/RomanNumeral.php#L43-L62 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/Number/RomanNumeral.php | RomanNumeral.fromRoman | public function fromRoman($string)
{
if (\mb_strlen((string) $string) === 0 || 0 === \preg_match(self::ROMAN_STRING_MATCHER, (string) $string)) {
throw new \InvalidArgumentException();
}
$total = 0;
$i = \mb_strlen($string);
while ($i > 0) {
$digit = $this->map[$string{--$i}];
if ($i > 0) {
$previousDigit = $this->map[$string{$i - 1}];
if ($previousDigit < $digit) {
$digit -= $previousDigit;
--$i;
}
}
$total += $digit;
}
return $total;
} | php | public function fromRoman($string)
{
if (\mb_strlen((string) $string) === 0 || 0 === \preg_match(self::ROMAN_STRING_MATCHER, (string) $string)) {
throw new \InvalidArgumentException();
}
$total = 0;
$i = \mb_strlen($string);
while ($i > 0) {
$digit = $this->map[$string{--$i}];
if ($i > 0) {
$previousDigit = $this->map[$string{$i - 1}];
if ($previousDigit < $digit) {
$digit -= $previousDigit;
--$i;
}
}
$total += $digit;
}
return $total;
} | [
"public",
"function",
"fromRoman",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"\\",
"mb_strlen",
"(",
"(",
"string",
")",
"$",
"string",
")",
"===",
"0",
"||",
"0",
"===",
"\\",
"preg_match",
"(",
"self",
"::",
"ROMAN_STRING_MATCHER",
",",
"(",
"string",... | @param $string
@return int
@throws \InvalidArgumentException | [
"@param",
"$string"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/Number/RomanNumeral.php#L71-L96 |
coduo/php-humanizer | src/Coduo/PHPHumanizer/NumberHumanizer.php | NumberHumanizer.ordinalize | public static function ordinalize($number, $locale = 'en')
{
$ordinal = new Ordinal($number, $locale);
return (string) ($ordinal->isPrefix()) ? $ordinal.$number : $number.$ordinal;
} | php | public static function ordinalize($number, $locale = 'en')
{
$ordinal = new Ordinal($number, $locale);
return (string) ($ordinal->isPrefix()) ? $ordinal.$number : $number.$ordinal;
} | [
"public",
"static",
"function",
"ordinalize",
"(",
"$",
"number",
",",
"$",
"locale",
"=",
"'en'",
")",
"{",
"$",
"ordinal",
"=",
"new",
"Ordinal",
"(",
"$",
"number",
",",
"$",
"locale",
")",
";",
"return",
"(",
"string",
")",
"(",
"$",
"ordinal",
... | @param int|float $number
@param string $locale
@return string | [
"@param",
"int|float",
"$number",
"@param",
"string",
"$locale"
] | train | https://github.com/coduo/php-humanizer/blob/6255e022c0ff8767cae6cdb4552d13f5f0df0d65/src/Coduo/PHPHumanizer/NumberHumanizer.php#L27-L32 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.create | public function create($file, $path, $filename, $sizes)
{
$this->file = $file;
if (is_array($sizes)) {
$resized = array();
foreach ($sizes as $size) {
$this->new_width = $size[0]; //$new_width;
$this->new_height = $size[1]; //$new_height;
$this->option = $size[2]; //crop type
//ensure that the directory path exists
if (!is_dir($size[3])) {
mkdir($size[3]);
}
$resized[] = $this->do_resize($path.$filename, $size[3].$filename, $size[4]);
}
}
return $resized;
} | php | public function create($file, $path, $filename, $sizes)
{
$this->file = $file;
if (is_array($sizes)) {
$resized = array();
foreach ($sizes as $size) {
$this->new_width = $size[0]; //$new_width;
$this->new_height = $size[1]; //$new_height;
$this->option = $size[2]; //crop type
//ensure that the directory path exists
if (!is_dir($size[3])) {
mkdir($size[3]);
}
$resized[] = $this->do_resize($path.$filename, $size[3].$filename, $size[4]);
}
}
return $resized;
} | [
"public",
"function",
"create",
"(",
"$",
"file",
",",
"$",
"path",
",",
"$",
"filename",
",",
"$",
"sizes",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"if",
"(",
"is_array",
"(",
"$",
"sizes",
")",
")",
"{",
"$",
"resized",
"=... | /*
Create multiple thumbs/resizes of an image
Path to the original
sizes
width, height, crop type, path, quality | [
"/",
"*",
"Create",
"multiple",
"thumbs",
"/",
"resizes",
"of",
"an",
"image",
"Path",
"to",
"the",
"original",
"sizes",
"width",
"height",
"crop",
"type",
"path",
"quality"
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L63-L85 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.do_resize | private function do_resize($image, $save_path, $image_quality)
{
$image = $this->open_image($image);
$this->width = imagesx($image);
$this->height = imagesy($image);
// Get optimal width and height - based on $option.
$option_array = $this->get_dimensions($this->new_width, $this->new_height, $this->option);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
// Resample - create image canvas of x, y size.
$this->image_resized = imagecreatetruecolor($optimal_width, $optimal_height);
// Retain transparency for PNG and GIF files.
imagecolortransparent($this->image_resized, imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127));
imagealphablending($this->image_resized, false);
imagesavealpha($this->image_resized, true);
// Create the new image.
imagecopyresampled($this->image_resized, $image, 0, 0, 0, 0, $optimal_width, $optimal_height, $this->width, $this->height);
// if option is 'crop' or 'fit', then crop too
if ($this->option == 'crop' || $this->option == 'fit') {
$this->crop($optimal_width, $optimal_height, $this->new_width, $this->new_height);
}
// Get extension of the output file
$extension = strtolower(File::extension($save_path));
// Create and save an image based on it's extension
switch ($extension) {
case 'jpg':
case 'jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->image_resized, $save_path, $image_quality);
}
break;
case 'gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->image_resized, $save_path);
}
break;
case 'png':
// Scale quality from 0-100 to 0-9
$scale_quality = round(($image_quality / 100) * 9);
// Invert quality setting as 0 is best, not 9
$invert_scale_quality = 9 - $scale_quality;
if (imagetypes() & IMG_PNG) {
imagepng($this->image_resized, $save_path, $invert_scale_quality);
}
break;
default:
return false;
break;
}
// Remove the resource for the resized image
imagedestroy($this->image_resized);
return true;
} | php | private function do_resize($image, $save_path, $image_quality)
{
$image = $this->open_image($image);
$this->width = imagesx($image);
$this->height = imagesy($image);
// Get optimal width and height - based on $option.
$option_array = $this->get_dimensions($this->new_width, $this->new_height, $this->option);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
// Resample - create image canvas of x, y size.
$this->image_resized = imagecreatetruecolor($optimal_width, $optimal_height);
// Retain transparency for PNG and GIF files.
imagecolortransparent($this->image_resized, imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127));
imagealphablending($this->image_resized, false);
imagesavealpha($this->image_resized, true);
// Create the new image.
imagecopyresampled($this->image_resized, $image, 0, 0, 0, 0, $optimal_width, $optimal_height, $this->width, $this->height);
// if option is 'crop' or 'fit', then crop too
if ($this->option == 'crop' || $this->option == 'fit') {
$this->crop($optimal_width, $optimal_height, $this->new_width, $this->new_height);
}
// Get extension of the output file
$extension = strtolower(File::extension($save_path));
// Create and save an image based on it's extension
switch ($extension) {
case 'jpg':
case 'jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->image_resized, $save_path, $image_quality);
}
break;
case 'gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->image_resized, $save_path);
}
break;
case 'png':
// Scale quality from 0-100 to 0-9
$scale_quality = round(($image_quality / 100) * 9);
// Invert quality setting as 0 is best, not 9
$invert_scale_quality = 9 - $scale_quality;
if (imagetypes() & IMG_PNG) {
imagepng($this->image_resized, $save_path, $invert_scale_quality);
}
break;
default:
return false;
break;
}
// Remove the resource for the resized image
imagedestroy($this->image_resized);
return true;
} | [
"private",
"function",
"do_resize",
"(",
"$",
"image",
",",
"$",
"save_path",
",",
"$",
"image_quality",
")",
"{",
"$",
"image",
"=",
"$",
"this",
"->",
"open_image",
"(",
"$",
"image",
")",
";",
"$",
"this",
"->",
"width",
"=",
"imagesx",
"(",
"$",
... | Resizes and/or crops an image.
@param mixed $image resource or filepath
@param strung $save_path where to save the resized image
@param int (0-100) $quality
@return bool | [
"Resizes",
"and",
"/",
"or",
"crops",
"an",
"image",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L96-L164 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.get_dimensions | private function get_dimensions($new_width, $new_height, $option)
{
switch ($option) {
case 'exact':
$optimal_width = $new_width;
$optimal_height = $new_height;
break;
case 'portrait':
$optimal_width = $this->get_size_by_fixed_height($new_height);
$optimal_height = $new_height;
break;
case 'landscape':
$optimal_width = $new_width;
$optimal_height = $this->get_size_by_fixed_width($new_width);
break;
case 'auto':
$option_array = $this->get_size_by_auto($new_width, $new_height);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
break;
case 'fit':
$option_array = $this->get_size_by_fit($new_width, $new_height);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
break;
case 'crop':
$option_array = $this->get_optimal_crop($new_width, $new_height);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
break;
}
return array(
'optimal_width' => $optimal_width,
'optimal_height' => $optimal_height,
);
} | php | private function get_dimensions($new_width, $new_height, $option)
{
switch ($option) {
case 'exact':
$optimal_width = $new_width;
$optimal_height = $new_height;
break;
case 'portrait':
$optimal_width = $this->get_size_by_fixed_height($new_height);
$optimal_height = $new_height;
break;
case 'landscape':
$optimal_width = $new_width;
$optimal_height = $this->get_size_by_fixed_width($new_width);
break;
case 'auto':
$option_array = $this->get_size_by_auto($new_width, $new_height);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
break;
case 'fit':
$option_array = $this->get_size_by_fit($new_width, $new_height);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
break;
case 'crop':
$option_array = $this->get_optimal_crop($new_width, $new_height);
$optimal_width = $option_array['optimal_width'];
$optimal_height = $option_array['optimal_height'];
break;
}
return array(
'optimal_width' => $optimal_width,
'optimal_height' => $optimal_height,
);
} | [
"private",
"function",
"get_dimensions",
"(",
"$",
"new_width",
",",
"$",
"new_height",
",",
"$",
"option",
")",
"{",
"switch",
"(",
"$",
"option",
")",
"{",
"case",
"'exact'",
":",
"$",
"optimal_width",
"=",
"$",
"new_width",
";",
"$",
"optimal_height",
... | Return the image dimentions based on the option that was chosen.
@param int $new_width The width of the image
@param int $new_height The height of the image
@param string $option Either exact, portrait, landscape, auto or crop.
@return array | [
"Return",
"the",
"image",
"dimentions",
"based",
"on",
"the",
"option",
"that",
"was",
"chosen",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L208-L244 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.get_size_by_fixed_height | private function get_size_by_fixed_height($new_height)
{
$ratio = $this->width / $this->height;
$new_width = $new_height * $ratio;
return $new_width;
} | php | private function get_size_by_fixed_height($new_height)
{
$ratio = $this->width / $this->height;
$new_width = $new_height * $ratio;
return $new_width;
} | [
"private",
"function",
"get_size_by_fixed_height",
"(",
"$",
"new_height",
")",
"{",
"$",
"ratio",
"=",
"$",
"this",
"->",
"width",
"/",
"$",
"this",
"->",
"height",
";",
"$",
"new_width",
"=",
"$",
"new_height",
"*",
"$",
"ratio",
";",
"return",
"$",
... | Returns the width based on the image height.
@param int $new_height The height of the image
@return int | [
"Returns",
"the",
"width",
"based",
"on",
"the",
"image",
"height",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L253-L259 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.get_size_by_fixed_width | private function get_size_by_fixed_width($new_width)
{
$ratio = $this->height / $this->width;
$new_height = $new_width * $ratio;
return $new_height;
} | php | private function get_size_by_fixed_width($new_width)
{
$ratio = $this->height / $this->width;
$new_height = $new_width * $ratio;
return $new_height;
} | [
"private",
"function",
"get_size_by_fixed_width",
"(",
"$",
"new_width",
")",
"{",
"$",
"ratio",
"=",
"$",
"this",
"->",
"height",
"/",
"$",
"this",
"->",
"width",
";",
"$",
"new_height",
"=",
"$",
"new_width",
"*",
"$",
"ratio",
";",
"return",
"$",
"n... | Returns the height based on the image width.
@param int $new_width The width of the image
@return int | [
"Returns",
"the",
"height",
"based",
"on",
"the",
"image",
"width",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L268-L274 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.get_size_by_auto | private function get_size_by_auto($new_width, $new_height)
{
// Image to be resized is wider (landscape)
if ($this->height < $this->width) {
$optimal_width = $new_width;
$optimal_height = $this->get_size_by_fixed_width($new_width);
}
// Image to be resized is taller (portrait)
elseif ($this->height > $this->width) {
$optimal_width = $this->get_size_by_fixed_height($new_height);
$optimal_height = $new_height;
}
// Image to be resizerd is a square
else {
if ($new_height < $new_width) {
$optimal_width = $new_width;
$optimal_height = $this->get_size_by_fixed_width($new_width);
} elseif ($new_height > $new_width) {
$optimal_width = $this->get_size_by_fixed_height($new_height);
$optimal_height = $new_height;
} else {
// Sqaure being resized to a square
$optimal_width = $new_width;
$optimal_height = $new_height;
}
}
return array(
'optimal_width' => $optimal_width,
'optimal_height' => $optimal_height,
);
} | php | private function get_size_by_auto($new_width, $new_height)
{
// Image to be resized is wider (landscape)
if ($this->height < $this->width) {
$optimal_width = $new_width;
$optimal_height = $this->get_size_by_fixed_width($new_width);
}
// Image to be resized is taller (portrait)
elseif ($this->height > $this->width) {
$optimal_width = $this->get_size_by_fixed_height($new_height);
$optimal_height = $new_height;
}
// Image to be resizerd is a square
else {
if ($new_height < $new_width) {
$optimal_width = $new_width;
$optimal_height = $this->get_size_by_fixed_width($new_width);
} elseif ($new_height > $new_width) {
$optimal_width = $this->get_size_by_fixed_height($new_height);
$optimal_height = $new_height;
} else {
// Sqaure being resized to a square
$optimal_width = $new_width;
$optimal_height = $new_height;
}
}
return array(
'optimal_width' => $optimal_width,
'optimal_height' => $optimal_height,
);
} | [
"private",
"function",
"get_size_by_auto",
"(",
"$",
"new_width",
",",
"$",
"new_height",
")",
"{",
"// Image to be resized is wider (landscape)",
"if",
"(",
"$",
"this",
"->",
"height",
"<",
"$",
"this",
"->",
"width",
")",
"{",
"$",
"optimal_width",
"=",
"$"... | Checks to see if an image is portrait or landscape and resizes accordingly.
@param int $new_width The width of the image
@param int $new_height The height of the image
@return array | [
"Checks",
"to",
"see",
"if",
"an",
"image",
"is",
"portrait",
"or",
"landscape",
"and",
"resizes",
"accordingly",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L284-L315 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.get_size_by_fit | private function get_size_by_fit($new_width, $new_height)
{
$height_ratio = $this->height / $new_height;
$width_ratio = $this->width / $new_width;
$max = max($height_ratio, $width_ratio);
return array(
'optimal_width' => $this->width / $max,
'optimal_height' => $this->height / $max,
);
} | php | private function get_size_by_fit($new_width, $new_height)
{
$height_ratio = $this->height / $new_height;
$width_ratio = $this->width / $new_width;
$max = max($height_ratio, $width_ratio);
return array(
'optimal_width' => $this->width / $max,
'optimal_height' => $this->height / $max,
);
} | [
"private",
"function",
"get_size_by_fit",
"(",
"$",
"new_width",
",",
"$",
"new_height",
")",
"{",
"$",
"height_ratio",
"=",
"$",
"this",
"->",
"height",
"/",
"$",
"new_height",
";",
"$",
"width_ratio",
"=",
"$",
"this",
"->",
"width",
"/",
"$",
"new_wid... | Resizes an image so it fits entirely inside the given dimensions.
@param int $new_width The width of the image
@param int $new_height The height of the image
@return array | [
"Resizes",
"an",
"image",
"so",
"it",
"fits",
"entirely",
"inside",
"the",
"given",
"dimensions",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L325-L336 |
summerblue/administrator | src/Frozennode/Administrator/Includes/Resize.php | Resize.crop | private function crop($optimal_width, $optimal_height, $new_width, $new_height)
{
// Find center - this will be used for the crop
$crop_start_x = ($optimal_width / 2) - ($new_width / 2);
$crop_start_y = ($optimal_height / 2) - ($new_height / 2);
$crop = $this->image_resized;
$dest_offset_x = max(0, -$crop_start_x);
$dest_offset_y = max(0, -$crop_start_y);
$crop_start_x = max(0, $crop_start_x);
$crop_start_y = max(0, $crop_start_y);
$dest_width = min($optimal_width, $new_width);
$dest_height = min($optimal_height, $new_height);
// Now crop from center to exact requested size
$this->image_resized = imagecreatetruecolor($new_width, $new_height);
imagealphablending($crop, true);
imagealphablending($this->image_resized, false);
imagesavealpha($this->image_resized, true);
imagefilledrectangle($this->image_resized, 0, 0, $new_width, $new_height,
imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127)
);
imagecopyresampled($this->image_resized, $crop, $dest_offset_x, $dest_offset_y, $crop_start_x, $crop_start_y, $dest_width, $dest_height, $dest_width, $dest_height);
return true;
} | php | private function crop($optimal_width, $optimal_height, $new_width, $new_height)
{
// Find center - this will be used for the crop
$crop_start_x = ($optimal_width / 2) - ($new_width / 2);
$crop_start_y = ($optimal_height / 2) - ($new_height / 2);
$crop = $this->image_resized;
$dest_offset_x = max(0, -$crop_start_x);
$dest_offset_y = max(0, -$crop_start_y);
$crop_start_x = max(0, $crop_start_x);
$crop_start_y = max(0, $crop_start_y);
$dest_width = min($optimal_width, $new_width);
$dest_height = min($optimal_height, $new_height);
// Now crop from center to exact requested size
$this->image_resized = imagecreatetruecolor($new_width, $new_height);
imagealphablending($crop, true);
imagealphablending($this->image_resized, false);
imagesavealpha($this->image_resized, true);
imagefilledrectangle($this->image_resized, 0, 0, $new_width, $new_height,
imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127)
);
imagecopyresampled($this->image_resized, $crop, $dest_offset_x, $dest_offset_y, $crop_start_x, $crop_start_y, $dest_width, $dest_height, $dest_width, $dest_height);
return true;
} | [
"private",
"function",
"crop",
"(",
"$",
"optimal_width",
",",
"$",
"optimal_height",
",",
"$",
"new_width",
",",
"$",
"new_height",
")",
"{",
"// Find center - this will be used for the crop",
"$",
"crop_start_x",
"=",
"(",
"$",
"optimal_width",
"/",
"2",
")",
... | Crops an image from its center.
@param int $optimal_width The width of the image
@param int $optimal_height The height of the image
@param int $new_width The new width
@param int $new_height The new height
@return true | [
"Crops",
"an",
"image",
"from",
"its",
"center",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Includes/Resize.php#L377-L406 |
summerblue/administrator | src/Frozennode/Administrator/Actions/Factory.php | Factory.make | public function make($name, array $options)
{
//check the permission on this item
$options = $this->parseDefaults($name, $options);
//now we can instantiate the object
return $this->getActionObject($options);
} | php | public function make($name, array $options)
{
//check the permission on this item
$options = $this->parseDefaults($name, $options);
//now we can instantiate the object
return $this->getActionObject($options);
} | [
"public",
"function",
"make",
"(",
"$",
"name",
",",
"array",
"$",
"options",
")",
"{",
"//check the permission on this item",
"$",
"options",
"=",
"$",
"this",
"->",
"parseDefaults",
"(",
"$",
"name",
",",
"$",
"options",
")",
";",
"//now we can instantiate t... | Takes the model and an info array of options for the specific action.
@param string $name //the key name for this action
@param array $options
@return \Frozennode\Administrator\Actions\Action | [
"Takes",
"the",
"model",
"and",
"an",
"info",
"array",
"of",
"options",
"for",
"the",
"specific",
"action",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Actions/Factory.php#L91-L98 |
summerblue/administrator | src/Frozennode/Administrator/Actions/Factory.php | Factory.parseDefaults | public function parseDefaults($name, $options)
{
$model = $this->config->getDataModel();
//if the name is not a string or the options is not an array at this point, throw an error because we can't do anything with it
if (!is_string($name) || !is_array($options)) {
throw new \InvalidArgumentException('A custom action in your '.$this->config->getOption('action_name').' configuration file is invalid');
}
//set the action name
$options['action_name'] = $name;
//set the permission
$permission = $this->validator->arrayGet($options, 'permission', false);
$options['has_permission'] = is_callable($permission) ? $permission($model) : true;
//check if the messages array exists
$options['messages'] = $this->validator->arrayGet($options, 'messages', array());
$options['messages'] = is_array($options['messages']) ? $options['messages'] : array();
return $options;
} | php | public function parseDefaults($name, $options)
{
$model = $this->config->getDataModel();
//if the name is not a string or the options is not an array at this point, throw an error because we can't do anything with it
if (!is_string($name) || !is_array($options)) {
throw new \InvalidArgumentException('A custom action in your '.$this->config->getOption('action_name').' configuration file is invalid');
}
//set the action name
$options['action_name'] = $name;
//set the permission
$permission = $this->validator->arrayGet($options, 'permission', false);
$options['has_permission'] = is_callable($permission) ? $permission($model) : true;
//check if the messages array exists
$options['messages'] = $this->validator->arrayGet($options, 'messages', array());
$options['messages'] = is_array($options['messages']) ? $options['messages'] : array();
return $options;
} | [
"public",
"function",
"parseDefaults",
"(",
"$",
"name",
",",
"$",
"options",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"//if the name is not a string or the options is not an array at this point, throw an error becau... | Sets up the default values for the $options array.
@param string $name //the key name for this action
@param array $options
@return array | [
"Sets",
"up",
"the",
"default",
"values",
"for",
"the",
"$options",
"array",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Actions/Factory.php#L108-L129 |
summerblue/administrator | src/Frozennode/Administrator/Actions/Factory.php | Factory.getByName | public function getByName($name, $global = false)
{
$actions = $global ? $this->getGlobalActions() : $this->getActions();
//loop over the actions to find our culprit
foreach ($actions as $action) {
if ($action->getOption('action_name') === $name) {
return $action;
}
}
return false;
} | php | public function getByName($name, $global = false)
{
$actions = $global ? $this->getGlobalActions() : $this->getActions();
//loop over the actions to find our culprit
foreach ($actions as $action) {
if ($action->getOption('action_name') === $name) {
return $action;
}
}
return false;
} | [
"public",
"function",
"getByName",
"(",
"$",
"name",
",",
"$",
"global",
"=",
"false",
")",
"{",
"$",
"actions",
"=",
"$",
"global",
"?",
"$",
"this",
"->",
"getGlobalActions",
"(",
")",
":",
"$",
"this",
"->",
"getActions",
"(",
")",
";",
"//loop ov... | Gets an action by name.
@param string $name
@param bool $global //if true, search the global actions
@return mixed | [
"Gets",
"an",
"action",
"by",
"name",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Actions/Factory.php#L151-L163 |
summerblue/administrator | src/Frozennode/Administrator/Actions/Factory.php | Factory.getActions | public function getActions($override = false)
{
//make sure we only run this once and then return the cached version
if (empty($this->actions) || $override) {
$this->actions = array();
//loop over the actions to build the list
foreach ($this->config->getOption('actions') as $name => $options) {
$this->actions[] = $this->make($name, $options);
}
}
return $this->actions;
} | php | public function getActions($override = false)
{
//make sure we only run this once and then return the cached version
if (empty($this->actions) || $override) {
$this->actions = array();
//loop over the actions to build the list
foreach ($this->config->getOption('actions') as $name => $options) {
$this->actions[] = $this->make($name, $options);
}
}
return $this->actions;
} | [
"public",
"function",
"getActions",
"(",
"$",
"override",
"=",
"false",
")",
"{",
"//make sure we only run this once and then return the cached version",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"actions",
")",
"||",
"$",
"override",
")",
"{",
"$",
"this",
"-... | Gets all actions.
@param bool $override
@return array of Action objects | [
"Gets",
"all",
"actions",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Actions/Factory.php#L172-L185 |
summerblue/administrator | src/Frozennode/Administrator/Actions/Factory.php | Factory.getActionsOptions | public function getActionsOptions($override = false)
{
//make sure we only run this once and then return the cached version
if (empty($this->actionsOptions) || $override) {
$this->actionsOptions = array();
//loop over the actions to build the list
foreach ($this->getActions($override) as $name => $action) {
$this->actionsOptions[] = $action->getOptions(true);
}
}
return $this->actionsOptions;
} | php | public function getActionsOptions($override = false)
{
//make sure we only run this once and then return the cached version
if (empty($this->actionsOptions) || $override) {
$this->actionsOptions = array();
//loop over the actions to build the list
foreach ($this->getActions($override) as $name => $action) {
$this->actionsOptions[] = $action->getOptions(true);
}
}
return $this->actionsOptions;
} | [
"public",
"function",
"getActionsOptions",
"(",
"$",
"override",
"=",
"false",
")",
"{",
"//make sure we only run this once and then return the cached version",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"actionsOptions",
")",
"||",
"$",
"override",
")",
"{",
"$",
... | Gets all actions as arrays of options.
@param bool $override
@return array of Action options | [
"Gets",
"all",
"actions",
"as",
"arrays",
"of",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Actions/Factory.php#L194-L207 |
summerblue/administrator | src/Frozennode/Administrator/Http/Middleware/PostValidate.php | PostValidate.handle | public function handle($request, Closure $next)
{
$config = app('itemconfig');
//if the model doesn't exist at all, redirect to 404
if (!$config) {
abort(404, 'Page not found');
}
//check the permission
$p = $config->getOption('permission');
//if the user is simply not allowed permission to this model, redirect them to the dashboard
if (!$p) {
return redirect()->route('admin_dashboard');
}
//get the settings data if it's a settings page
if ($config->getType() === 'settings') {
$config->fetchData(app('admin_field_factory')->getEditFields());
}
//otherwise if this is a response, return that
if (is_a($p, 'Illuminate\Http\JsonResponse') || is_a($p, 'Illuminate\Http\Response') || is_a($p, 'Illuminate\\Http\\RedirectResponse')) {
return $p;
}
return $next($request);
} | php | public function handle($request, Closure $next)
{
$config = app('itemconfig');
//if the model doesn't exist at all, redirect to 404
if (!$config) {
abort(404, 'Page not found');
}
//check the permission
$p = $config->getOption('permission');
//if the user is simply not allowed permission to this model, redirect them to the dashboard
if (!$p) {
return redirect()->route('admin_dashboard');
}
//get the settings data if it's a settings page
if ($config->getType() === 'settings') {
$config->fetchData(app('admin_field_factory')->getEditFields());
}
//otherwise if this is a response, return that
if (is_a($p, 'Illuminate\Http\JsonResponse') || is_a($p, 'Illuminate\Http\Response') || is_a($p, 'Illuminate\\Http\\RedirectResponse')) {
return $p;
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"$",
"config",
"=",
"app",
"(",
"'itemconfig'",
")",
";",
"//if the model doesn't exist at all, redirect to 404",
"if",
"(",
"!",
"$",
"config",
")",
"{",
"abort",
"(... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Http/Middleware/PostValidate.php#L17-L45 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/Relationship.php | Relationship.build | public function build()
{
parent::build();
$options = $this->suppliedOptions;
$model = $this->config->getDataModel();
$relationship = $model->{$options['field_name']}();
//set the search fields to the name field if none exist
$searchFields = $this->validator->arrayGet($options, 'search_fields');
$nameField = $this->validator->arrayGet($options, 'name_field', $this->defaults['name_field']);
$options['search_fields'] = empty($searchFields) ? array($nameField) : $searchFields;
//determine if this is a self-relationship
$options['self_relationship'] = $relationship->getRelated()->getTable() === $model->getTable();
//make sure the options filter is set up
$options['options_filter'] = $this->validator->arrayGet($options, 'options_filter') ?: function () {};
//set up and check the constraints
$this->setUpConstraints($options);
//load up the relationship options
$this->loadRelationshipOptions($options);
$this->suppliedOptions = $options;
} | php | public function build()
{
parent::build();
$options = $this->suppliedOptions;
$model = $this->config->getDataModel();
$relationship = $model->{$options['field_name']}();
//set the search fields to the name field if none exist
$searchFields = $this->validator->arrayGet($options, 'search_fields');
$nameField = $this->validator->arrayGet($options, 'name_field', $this->defaults['name_field']);
$options['search_fields'] = empty($searchFields) ? array($nameField) : $searchFields;
//determine if this is a self-relationship
$options['self_relationship'] = $relationship->getRelated()->getTable() === $model->getTable();
//make sure the options filter is set up
$options['options_filter'] = $this->validator->arrayGet($options, 'options_filter') ?: function () {};
//set up and check the constraints
$this->setUpConstraints($options);
//load up the relationship options
$this->loadRelationshipOptions($options);
$this->suppliedOptions = $options;
} | [
"public",
"function",
"build",
"(",
")",
"{",
"parent",
"::",
"build",
"(",
")",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"suppliedOptions",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"$",
"relations... | Builds a few basic options. | [
"Builds",
"a",
"few",
"basic",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/Relationship.php#L59-L85 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/Relationship.php | Relationship.setUpConstraints | public function setUpConstraints(&$options)
{
$constraints = $this->validator->arrayGet($options, 'constraints');
$model = $this->config->getDataModel();
//set up and check the constraints
if (is_array($constraints) && sizeof($constraints)) {
$validConstraints = array();
//iterate over the constraints and only include the valid ones
foreach ($constraints as $field => $rel) {
//check if the supplied values are strings and that their methods exist on their respective models
if (is_string($field) && is_string($rel) && method_exists($model, $field)) {
$validConstraints[$field] = $rel;
}
}
$options['constraints'] = $validConstraints;
}
} | php | public function setUpConstraints(&$options)
{
$constraints = $this->validator->arrayGet($options, 'constraints');
$model = $this->config->getDataModel();
//set up and check the constraints
if (is_array($constraints) && sizeof($constraints)) {
$validConstraints = array();
//iterate over the constraints and only include the valid ones
foreach ($constraints as $field => $rel) {
//check if the supplied values are strings and that their methods exist on their respective models
if (is_string($field) && is_string($rel) && method_exists($model, $field)) {
$validConstraints[$field] = $rel;
}
}
$options['constraints'] = $validConstraints;
}
} | [
"public",
"function",
"setUpConstraints",
"(",
"&",
"$",
"options",
")",
"{",
"$",
"constraints",
"=",
"$",
"this",
"->",
"validator",
"->",
"arrayGet",
"(",
"$",
"options",
",",
"'constraints'",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
... | Sets up the constraints for a relationship field if provided. We do this so we can assume later that it will just work.
@param array $options | [
"Sets",
"up",
"the",
"constraints",
"for",
"a",
"relationship",
"field",
"if",
"provided",
".",
"We",
"do",
"this",
"so",
"we",
"can",
"assume",
"later",
"that",
"it",
"will",
"just",
"work",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/Relationship.php#L92-L111 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/Relationship.php | Relationship.loadRelationshipOptions | public function loadRelationshipOptions(&$options)
{
//if we want all of the possible items on the other model, load them up, otherwise leave the options empty
$items = array();
$model = $this->config->getDataModel();
$relationship = $model->{$options['field_name']}();
$relatedModel = $relationship->getRelated();
if ($this->validator->arrayGet($options, 'load_relationships')) {
//if a sort field was supplied, order the results by it
if ($optionsSortField = $this->validator->arrayGet($options, 'options_sort_field')) {
$optionsSortDirection = $this->validator->arrayGet($options, 'options_sort_direction', $this->defaults['options_sort_direction']);
$query = $relatedModel->orderBy($this->db->raw($optionsSortField), $optionsSortDirection);
}
//otherwise just pull back an unsorted list
else {
$query = $relatedModel->newQuery();
}
//run the options filter
$options['options_filter']($query);
//get the items
$items = $query->get();
}
//otherwise if there are relationship items, we need them in the initial options list
elseif ($relationshipItems = $relationship->get()) {
$items = $relationshipItems;
// if no related items exist, add default item, if set in options
if (count($items) == 0 && array_key_exists('value', $options)) {
$items = $relatedModel->where($relatedModel->getKeyName(), '=', $options['value'])->get();
}
}
//map the options to the options property where array('id': [key], 'text': [nameField])
$nameField = $this->validator->arrayGet($options, 'name_field', $this->defaults['name_field']);
$keyField = $relatedModel->getKeyName();
$options['options'] = $this->mapRelationshipOptions($items, $nameField, $keyField);
} | php | public function loadRelationshipOptions(&$options)
{
//if we want all of the possible items on the other model, load them up, otherwise leave the options empty
$items = array();
$model = $this->config->getDataModel();
$relationship = $model->{$options['field_name']}();
$relatedModel = $relationship->getRelated();
if ($this->validator->arrayGet($options, 'load_relationships')) {
//if a sort field was supplied, order the results by it
if ($optionsSortField = $this->validator->arrayGet($options, 'options_sort_field')) {
$optionsSortDirection = $this->validator->arrayGet($options, 'options_sort_direction', $this->defaults['options_sort_direction']);
$query = $relatedModel->orderBy($this->db->raw($optionsSortField), $optionsSortDirection);
}
//otherwise just pull back an unsorted list
else {
$query = $relatedModel->newQuery();
}
//run the options filter
$options['options_filter']($query);
//get the items
$items = $query->get();
}
//otherwise if there are relationship items, we need them in the initial options list
elseif ($relationshipItems = $relationship->get()) {
$items = $relationshipItems;
// if no related items exist, add default item, if set in options
if (count($items) == 0 && array_key_exists('value', $options)) {
$items = $relatedModel->where($relatedModel->getKeyName(), '=', $options['value'])->get();
}
}
//map the options to the options property where array('id': [key], 'text': [nameField])
$nameField = $this->validator->arrayGet($options, 'name_field', $this->defaults['name_field']);
$keyField = $relatedModel->getKeyName();
$options['options'] = $this->mapRelationshipOptions($items, $nameField, $keyField);
} | [
"public",
"function",
"loadRelationshipOptions",
"(",
"&",
"$",
"options",
")",
"{",
"//if we want all of the possible items on the other model, load them up, otherwise leave the options empty",
"$",
"items",
"=",
"array",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"-... | Loads the relationship options and sets the options option if load_relationships is true.
@param array $options | [
"Loads",
"the",
"relationship",
"options",
"and",
"sets",
"the",
"options",
"option",
"if",
"load_relationships",
"is",
"true",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/Relationship.php#L118-L158 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/Relationship.php | Relationship.mapRelationshipOptions | public function mapRelationshipOptions($items, $nameField, $keyField)
{
$result = array();
foreach ($items as $option) {
$result[] = array(
'id' => $option->{$keyField},
'text' => strval($option->{$nameField}),
);
}
return $result;
} | php | public function mapRelationshipOptions($items, $nameField, $keyField)
{
$result = array();
foreach ($items as $option) {
$result[] = array(
'id' => $option->{$keyField},
'text' => strval($option->{$nameField}),
);
}
return $result;
} | [
"public",
"function",
"mapRelationshipOptions",
"(",
"$",
"items",
",",
"$",
"nameField",
",",
"$",
"keyField",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"items",
"as",
"$",
"option",
")",
"{",
"$",
"result",
"[",
"]"... | Maps the relationship options to an array with 'id' and 'text' keys.
@param array $items
@param string $nameField
@param string $keyField
@return array | [
"Maps",
"the",
"relationship",
"options",
"to",
"an",
"array",
"with",
"id",
"and",
"text",
"keys",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/Relationship.php#L169-L181 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/BelongsTo.php | BelongsTo.fillModel | public function fillModel(&$model, $input)
{
$model->{$this->getOption('foreign_key')} = $input !== 'false' ? $input : null;
$model->__unset($this->getOption('field_name'));
} | php | public function fillModel(&$model, $input)
{
$model->{$this->getOption('foreign_key')} = $input !== 'false' ? $input : null;
$model->__unset($this->getOption('field_name'));
} | [
"public",
"function",
"fillModel",
"(",
"&",
"$",
"model",
",",
"$",
"input",
")",
"{",
"$",
"model",
"->",
"{",
"$",
"this",
"->",
"getOption",
"(",
"'foreign_key'",
")",
"}",
"=",
"$",
"input",
"!==",
"'false'",
"?",
"$",
"input",
":",
"null",
";... | Fill a model with input data.
@param \Illuminate\Database\Eloquent\Model $model
@param mixed $input
@return array | [
"Fill",
"a",
"model",
"with",
"input",
"data",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/BelongsTo.php#L46-L51 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/BelongsTo.php | BelongsTo.filterQuery | public function filterQuery(QueryBuilder &$query, &$selects = null)
{
//run the parent method
parent::filterQuery($query, $selects);
//if there is no value, return
if (!$this->getOption('value')) {
return;
}
$query->where($this->getOption('foreign_key'), '=', $this->getOption('value'));
} | php | public function filterQuery(QueryBuilder &$query, &$selects = null)
{
//run the parent method
parent::filterQuery($query, $selects);
//if there is no value, return
if (!$this->getOption('value')) {
return;
}
$query->where($this->getOption('foreign_key'), '=', $this->getOption('value'));
} | [
"public",
"function",
"filterQuery",
"(",
"QueryBuilder",
"&",
"$",
"query",
",",
"&",
"$",
"selects",
"=",
"null",
")",
"{",
"//run the parent method",
"parent",
"::",
"filterQuery",
"(",
"$",
"query",
",",
"$",
"selects",
")",
";",
"//if there is no value, r... | Filters a query object with this item's data given a model.
@param \Illuminate\Database\Query\Builder $query
@param array $selects | [
"Filters",
"a",
"query",
"object",
"with",
"this",
"item",
"s",
"data",
"given",
"a",
"model",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/BelongsTo.php#L59-L70 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.make | public function make($name, $primary = false)
{
//set the name so we can rebuild the config later if necessary
$this->name = $primary ? $name : $this->name;
//search the config menu for our item
$options = $this->searchMenu($name);
//return the config object if the file/array was found, or false if it wasn't
$config = $options ? $this->getItemConfigObject($options) : ($this->type === 'page' ? true : false);
//set the primary config
$this->config = $primary ? $config : $this->config;
//return the config object (or false if it fails to build)
return $config;
} | php | public function make($name, $primary = false)
{
//set the name so we can rebuild the config later if necessary
$this->name = $primary ? $name : $this->name;
//search the config menu for our item
$options = $this->searchMenu($name);
//return the config object if the file/array was found, or false if it wasn't
$config = $options ? $this->getItemConfigObject($options) : ($this->type === 'page' ? true : false);
//set the primary config
$this->config = $primary ? $config : $this->config;
//return the config object (or false if it fails to build)
return $config;
} | [
"public",
"function",
"make",
"(",
"$",
"name",
",",
"$",
"primary",
"=",
"false",
")",
"{",
"//set the name so we can rebuild the config later if necessary",
"$",
"this",
"->",
"name",
"=",
"$",
"primary",
"?",
"$",
"name",
":",
"$",
"this",
"->",
"name",
"... | Makes a config instance given an input string.
@param string $name
@param string $primary //if true, this is the primary itemconfig object and we want to store the instance
@return mixed | [
"Makes",
"a",
"config",
"instance",
"given",
"an",
"input",
"string",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L116-L132 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.updateConfigOptions | public function updateConfigOptions()
{
//search the config menu for our item
$options = $this->searchMenu($this->name);
//override the config's options
$this->getConfig()->setOptions($options);
} | php | public function updateConfigOptions()
{
//search the config menu for our item
$options = $this->searchMenu($this->name);
//override the config's options
$this->getConfig()->setOptions($options);
} | [
"public",
"function",
"updateConfigOptions",
"(",
")",
"{",
"//search the config menu for our item",
"$",
"options",
"=",
"$",
"this",
"->",
"searchMenu",
"(",
"$",
"this",
"->",
"name",
")",
";",
"//override the config's options",
"$",
"this",
"->",
"getConfig",
... | Updates the current item config's options. | [
"Updates",
"the",
"current",
"item",
"config",
"s",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L137-L144 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.parseType | public function parseType($name)
{
//if the name is prefixed with the settings prefix
if (strpos($name, $this->settingsPrefix) === 0) {
return $this->type = 'settings';
}
//otherwise if the name is prefixed with the page prefix
elseif (strpos($name, $this->pagePrefix) === 0) {
return $this->type = 'page';
}
//otherwise it's a model
else {
return $this->type = 'model';
}
} | php | public function parseType($name)
{
//if the name is prefixed with the settings prefix
if (strpos($name, $this->settingsPrefix) === 0) {
return $this->type = 'settings';
}
//otherwise if the name is prefixed with the page prefix
elseif (strpos($name, $this->pagePrefix) === 0) {
return $this->type = 'page';
}
//otherwise it's a model
else {
return $this->type = 'model';
}
} | [
"public",
"function",
"parseType",
"(",
"$",
"name",
")",
"{",
"//if the name is prefixed with the settings prefix",
"if",
"(",
"strpos",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"settingsPrefix",
")",
"===",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"typ... | Determines whether a string is a model or settings config.
@param string $name
@return string | [
"Determines",
"whether",
"a",
"string",
"is",
"a",
"model",
"or",
"settings",
"config",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L163-L177 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.searchMenu | public function searchMenu($name, $menu = false)
{
//parse the type based on the config name if this is the top-level item
if ($menu === false) {
$this->parseType($name);
}
$config = false;
$menu = $menu ? $menu : $this->options['menu'];
//iterate over all the items in the menu array
foreach ($menu as $key => $item) {
//if the item is a string, try to find the config file
if (is_string($item) && $item === $name) {
$config = $this->fetchConfigFile($name);
}
//if the item is an array, recursively run this method on it
elseif (is_array($item)) {
$config = $this->searchMenu($name, $item);
}
//if the config var was set, break the loop
if (is_array($config)) {
break;
}
}
return $config;
} | php | public function searchMenu($name, $menu = false)
{
//parse the type based on the config name if this is the top-level item
if ($menu === false) {
$this->parseType($name);
}
$config = false;
$menu = $menu ? $menu : $this->options['menu'];
//iterate over all the items in the menu array
foreach ($menu as $key => $item) {
//if the item is a string, try to find the config file
if (is_string($item) && $item === $name) {
$config = $this->fetchConfigFile($name);
}
//if the item is an array, recursively run this method on it
elseif (is_array($item)) {
$config = $this->searchMenu($name, $item);
}
//if the config var was set, break the loop
if (is_array($config)) {
break;
}
}
return $config;
} | [
"public",
"function",
"searchMenu",
"(",
"$",
"name",
",",
"$",
"menu",
"=",
"false",
")",
"{",
"//parse the type based on the config name if this is the top-level item",
"if",
"(",
"$",
"menu",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"parseType",
"(",
"$",... | Recursively searches the menu array for the desired settings config name.
@param string $name
@param array $menu
@return false|array //If found, an array of (unvalidated) config options will returned | [
"Recursively",
"searches",
"the",
"menu",
"array",
"for",
"the",
"desired",
"settings",
"config",
"name",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L187-L215 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.getPath | public function getPath()
{
$path = $this->type === 'settings' ? $this->options['settings_config_path'] : $this->options['model_config_path'];
return rtrim($path, '/').'/';
} | php | public function getPath()
{
$path = $this->type === 'settings' ? $this->options['settings_config_path'] : $this->options['model_config_path'];
return rtrim($path, '/').'/';
} | [
"public",
"function",
"getPath",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"type",
"===",
"'settings'",
"?",
"$",
"this",
"->",
"options",
"[",
"'settings_config_path'",
"]",
":",
"$",
"this",
"->",
"options",
"[",
"'model_config_path'",
"]",
"... | Gets the config directory path for the currently-searched item. | [
"Gets",
"the",
"config",
"directory",
"path",
"for",
"the",
"currently",
"-",
"searched",
"item",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L258-L263 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.getItemConfigObject | public function getItemConfigObject(array $options)
{
if ($this->type === 'settings') {
return new SettingsConfig($this->validator, $this->customValidator, $options);
} else {
return new ModelConfig($this->validator, $this->customValidator, $options);
}
} | php | public function getItemConfigObject(array $options)
{
if ($this->type === 'settings') {
return new SettingsConfig($this->validator, $this->customValidator, $options);
} else {
return new ModelConfig($this->validator, $this->customValidator, $options);
}
} | [
"public",
"function",
"getItemConfigObject",
"(",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"type",
"===",
"'settings'",
")",
"{",
"return",
"new",
"SettingsConfig",
"(",
"$",
"this",
"->",
"validator",
",",
"$",
"this",
"->",
"cus... | Gets an instance of the config.
@param array $options
@return \Frozennode\Administrator\Config\ConfigInterface | [
"Gets",
"an",
"instance",
"of",
"the",
"config",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L280-L287 |
summerblue/administrator | src/Frozennode/Administrator/Config/Factory.php | Factory.fetchConfigFile | public function fetchConfigFile($name)
{
$name = str_replace($this->getPrefix(), '', $name);
$path = $this->getPath().$name.'.php';
//check that this is a legitimate file
if (is_file($path)) {
//set the options var
$options = require $path;
//add the name in
$options['name'] = $name;
return $options;
}
return false;
} | php | public function fetchConfigFile($name)
{
$name = str_replace($this->getPrefix(), '', $name);
$path = $this->getPath().$name.'.php';
//check that this is a legitimate file
if (is_file($path)) {
//set the options var
$options = require $path;
//add the name in
$options['name'] = $name;
return $options;
}
return false;
} | [
"public",
"function",
"fetchConfigFile",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"str_replace",
"(",
"$",
"this",
"->",
"getPrefix",
"(",
")",
",",
"''",
",",
"$",
"name",
")",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
")",
... | Fetches a config file given a path.
@param string $name
@return mixed | [
"Fetches",
"a",
"config",
"file",
"given",
"a",
"path",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Factory.php#L296-L313 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.make | public function make($name, $options, $loadRelationships = true)
{
//make sure the options array has all the proper default values
$options = $this->prepareOptions($name, $options, $loadRelationships);
return $this->getFieldObject($options);
} | php | public function make($name, $options, $loadRelationships = true)
{
//make sure the options array has all the proper default values
$options = $this->prepareOptions($name, $options, $loadRelationships);
return $this->getFieldObject($options);
} | [
"public",
"function",
"make",
"(",
"$",
"name",
",",
"$",
"options",
",",
"$",
"loadRelationships",
"=",
"true",
")",
"{",
"//make sure the options array has all the proper default values",
"$",
"options",
"=",
"$",
"this",
"->",
"prepareOptions",
"(",
"$",
"name"... | Makes a field given an array of options.
@param mixed $name
@param mixed $options
@param bool $loadRelationships //determines whether or not to load the relationships
@return mixed | [
"Makes",
"a",
"field",
"given",
"an",
"array",
"of",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L132-L138 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.getFieldObject | public function getFieldObject($options)
{
$class = $this->getFieldTypeClass($options['type']);
return new $class($this->validator, $this->config, $this->db, $options);
} | php | public function getFieldObject($options)
{
$class = $this->getFieldTypeClass($options['type']);
return new $class($this->validator, $this->config, $this->db, $options);
} | [
"public",
"function",
"getFieldObject",
"(",
"$",
"options",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getFieldTypeClass",
"(",
"$",
"options",
"[",
"'type'",
"]",
")",
";",
"return",
"new",
"$",
"class",
"(",
"$",
"this",
"->",
"validator",
","... | Instantiates a field object.
@param array $options
@param bool $loadRelationships
@return Frozennode\Administrator\Fields\Field | [
"Instantiates",
"a",
"field",
"object",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L148-L153 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.prepareOptions | public function prepareOptions($name, $options, $loadRelationships = true)
{
//set the options array to the format we need
$options = $this->validateOptions($name, $options);
//make sure the 'title' option is set
$options['title'] = isset($options['title']) ? $options['title'] : $options['field_name'];
$options['hint'] = isset($options['hint']) ? $options['hint'] : '';
//ensure the type is set and then check that the field type exists
$this->ensureTypeIsSet($options);
//set the proper relationship options
$this->setRelationshipType($options, $loadRelationships);
//check that the type is a valid field class
$this->checkTypeExists($options);
return $options;
} | php | public function prepareOptions($name, $options, $loadRelationships = true)
{
//set the options array to the format we need
$options = $this->validateOptions($name, $options);
//make sure the 'title' option is set
$options['title'] = isset($options['title']) ? $options['title'] : $options['field_name'];
$options['hint'] = isset($options['hint']) ? $options['hint'] : '';
//ensure the type is set and then check that the field type exists
$this->ensureTypeIsSet($options);
//set the proper relationship options
$this->setRelationshipType($options, $loadRelationships);
//check that the type is a valid field class
$this->checkTypeExists($options);
return $options;
} | [
"public",
"function",
"prepareOptions",
"(",
"$",
"name",
",",
"$",
"options",
",",
"$",
"loadRelationships",
"=",
"true",
")",
"{",
"//set the options array to the format we need",
"$",
"options",
"=",
"$",
"this",
"->",
"validateOptions",
"(",
"$",
"name",
","... | Sets up an options array with the required base values.
@param mixed $name
@param mixed $options
@param bool $loadRelationships //determines whether or not to load the relationships
@return array | [
"Sets",
"up",
"an",
"options",
"array",
"with",
"the",
"required",
"base",
"values",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L176-L195 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.ensureTypeIsSet | public function ensureTypeIsSet(array &$options)
{
//if the 'type' option hasn't been set
if (!isset($options['type'])) {
//if this is a model and the field is equal to the primary key name, set it as a key field
if ($this->config->getType() === 'model' && $options['field_name'] === $this->config->getDataModel()->getKeyName()) {
$options['type'] = 'key';
}
//otherwise set it to the default 'text'
else {
$options['type'] = 'text';
}
}
} | php | public function ensureTypeIsSet(array &$options)
{
//if the 'type' option hasn't been set
if (!isset($options['type'])) {
//if this is a model and the field is equal to the primary key name, set it as a key field
if ($this->config->getType() === 'model' && $options['field_name'] === $this->config->getDataModel()->getKeyName()) {
$options['type'] = 'key';
}
//otherwise set it to the default 'text'
else {
$options['type'] = 'text';
}
}
} | [
"public",
"function",
"ensureTypeIsSet",
"(",
"array",
"&",
"$",
"options",
")",
"{",
"//if the 'type' option hasn't been set",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'type'",
"]",
")",
")",
"{",
"//if this is a model and the field is equal to the primary... | Ensures that the type option is set.
@param array $options | [
"Ensures",
"that",
"the",
"type",
"option",
"is",
"set",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L228-L241 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.setRelationshipType | public function setRelationshipType(array &$options, $loadRelationships)
{
//if this is a relationship
if ($this->validator->arrayGet($options, 'type') === 'relationship') {
//get the right key based on the relationship in the model
$options['type'] = $this->getRelationshipKey($options['field_name']);
//if we should load the relationships, set the option
$options['load_relationships'] = $loadRelationships && !$this->validator->arrayGet($options, 'autocomplete', false);
}
} | php | public function setRelationshipType(array &$options, $loadRelationships)
{
//if this is a relationship
if ($this->validator->arrayGet($options, 'type') === 'relationship') {
//get the right key based on the relationship in the model
$options['type'] = $this->getRelationshipKey($options['field_name']);
//if we should load the relationships, set the option
$options['load_relationships'] = $loadRelationships && !$this->validator->arrayGet($options, 'autocomplete', false);
}
} | [
"public",
"function",
"setRelationshipType",
"(",
"array",
"&",
"$",
"options",
",",
"$",
"loadRelationships",
")",
"{",
"//if this is a relationship",
"if",
"(",
"$",
"this",
"->",
"validator",
"->",
"arrayGet",
"(",
"$",
"options",
",",
"'type'",
")",
"===",... | Ensures that a relationship field is valid.
@param array $options
@param bool $loadRelationships | [
"Ensures",
"that",
"a",
"relationship",
"field",
"is",
"valid",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L249-L259 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.checkTypeExists | public function checkTypeExists(array &$options)
{
//if an improper value was supplied
if (!array_key_exists($options['type'], $this->fieldTypes)) {
throw new \InvalidArgumentException('The '.$options['type'].' field type in your '.$this->config->getOption('name').' configuration file is not valid');
}
//if this is a settings page and a field was supplied that is excluded
if ($this->config->getType() === 'settings' && in_array($options['type'], $this->settingsFieldExclusions)) {
throw new \InvalidArgumentException('The '.$options['type'].' field in your '.
$this->config->getOption('name').' settings page cannot be used on a settings page');
}
} | php | public function checkTypeExists(array &$options)
{
//if an improper value was supplied
if (!array_key_exists($options['type'], $this->fieldTypes)) {
throw new \InvalidArgumentException('The '.$options['type'].' field type in your '.$this->config->getOption('name').' configuration file is not valid');
}
//if this is a settings page and a field was supplied that is excluded
if ($this->config->getType() === 'settings' && in_array($options['type'], $this->settingsFieldExclusions)) {
throw new \InvalidArgumentException('The '.$options['type'].' field in your '.
$this->config->getOption('name').' settings page cannot be used on a settings page');
}
} | [
"public",
"function",
"checkTypeExists",
"(",
"array",
"&",
"$",
"options",
")",
"{",
"//if an improper value was supplied",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"options",
"[",
"'type'",
"]",
",",
"$",
"this",
"->",
"fieldTypes",
")",
")",
"{",
"th... | Check to see if the type is valid.
@param array $options | [
"Check",
"to",
"see",
"if",
"the",
"type",
"is",
"valid",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L266-L278 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.getEditFieldsArrays | public function getEditFieldsArrays($override = false)
{
$return = array();
foreach ($this->getEditFields(true, $override) as $fieldObject) {
$return[$fieldObject->getOption('field_name')] = $fieldObject->getOptions();
}
//get the key field if this is a model page
if ($this->config->getType() === 'model') {
$this->fillKeyField($return);
}
return $return;
} | php | public function getEditFieldsArrays($override = false)
{
$return = array();
foreach ($this->getEditFields(true, $override) as $fieldObject) {
$return[$fieldObject->getOption('field_name')] = $fieldObject->getOptions();
}
//get the key field if this is a model page
if ($this->config->getType() === 'model') {
$this->fillKeyField($return);
}
return $return;
} | [
"public",
"function",
"getEditFieldsArrays",
"(",
"$",
"override",
"=",
"false",
")",
"{",
"$",
"return",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getEditFields",
"(",
"true",
",",
"$",
"override",
")",
"as",
"$",
"fieldObject",
... | Gets the array version of the edit fields objects.
@param bool $override //this will override the cached version if set to true
@return array | [
"Gets",
"the",
"array",
"version",
"of",
"the",
"edit",
"fields",
"objects",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L383-L397 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.fillKeyField | public function fillKeyField(array &$fields)
{
$model = $this->config->getDataModel();
$keyName = $model->getKeyName();
//add the primary key field, which will be uneditable, but part of the data model
if ($this->config->getType() === 'model' && !isset($fields[$keyName])) {
$keyField = $this->make($keyName, array('visible' => false));
$fields[$keyName] = $keyField->getOptions();
}
} | php | public function fillKeyField(array &$fields)
{
$model = $this->config->getDataModel();
$keyName = $model->getKeyName();
//add the primary key field, which will be uneditable, but part of the data model
if ($this->config->getType() === 'model' && !isset($fields[$keyName])) {
$keyField = $this->make($keyName, array('visible' => false));
$fields[$keyName] = $keyField->getOptions();
}
} | [
"public",
"function",
"fillKeyField",
"(",
"array",
"&",
"$",
"fields",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"$",
"keyName",
"=",
"$",
"model",
"->",
"getKeyName",
"(",
")",
";",
"//add the prim... | Gets the key field for a model for the getEditFieldsArrays.
@param array $fields
@return array | [
"Gets",
"the",
"key",
"field",
"for",
"a",
"model",
"for",
"the",
"getEditFieldsArrays",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L406-L416 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.getDataModel | public function getDataModel()
{
$dataModel = array();
$model = $this->config->getDataModel();
foreach ($this->getEditFieldsArrays() as $name => $options) {
//if this is a key, set it to 0
if ($options['type'] === 'key') {
$dataModel[$name] = 0;
} else {
//if this is a collection, convert it to an array
if (is_a($model->$name, 'Illuminate\Database\Eloquent\Collection')) {
$dataModel[$name] = $model->$name->toArray();
} else {
$dataModel[$name] = isset($options['value']) ? $options['value'] : null;
}
}
}
return $dataModel;
} | php | public function getDataModel()
{
$dataModel = array();
$model = $this->config->getDataModel();
foreach ($this->getEditFieldsArrays() as $name => $options) {
//if this is a key, set it to 0
if ($options['type'] === 'key') {
$dataModel[$name] = 0;
} else {
//if this is a collection, convert it to an array
if (is_a($model->$name, 'Illuminate\Database\Eloquent\Collection')) {
$dataModel[$name] = $model->$name->toArray();
} else {
$dataModel[$name] = isset($options['value']) ? $options['value'] : null;
}
}
}
return $dataModel;
} | [
"public",
"function",
"getDataModel",
"(",
")",
"{",
"$",
"dataModel",
"=",
"array",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getEditFieldsArrays",
"(",
")",... | Gets the data model given the edit fields.
@return array | [
"Gets",
"the",
"data",
"model",
"given",
"the",
"edit",
"fields",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L423-L443 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.getFilters | public function getFilters()
{
//get the model's filter fields
$configFilters = $this->config->getOption('filters');
//make sure that the filters array hasn't been created before and that there are supplied filters in the config
if (empty($this->filters) && $configFilters) {
//iterate over the filters and create field objects for them
foreach ($configFilters as $name => $filter) {
if ($fieldObject = $this->make($name, $filter)) {
//the filters array is indexed on the field name and holds the arrayed values for the filters
$this->filters[$fieldObject->getOption('field_name')] = $fieldObject;
}
}
}
return $this->filters;
} | php | public function getFilters()
{
//get the model's filter fields
$configFilters = $this->config->getOption('filters');
//make sure that the filters array hasn't been created before and that there are supplied filters in the config
if (empty($this->filters) && $configFilters) {
//iterate over the filters and create field objects for them
foreach ($configFilters as $name => $filter) {
if ($fieldObject = $this->make($name, $filter)) {
//the filters array is indexed on the field name and holds the arrayed values for the filters
$this->filters[$fieldObject->getOption('field_name')] = $fieldObject;
}
}
}
return $this->filters;
} | [
"public",
"function",
"getFilters",
"(",
")",
"{",
"//get the model's filter fields",
"$",
"configFilters",
"=",
"$",
"this",
"->",
"config",
"->",
"getOption",
"(",
"'filters'",
")",
";",
"//make sure that the filters array hasn't been created before and that there are suppl... | Gets the filters for the given model config.
@return array | [
"Gets",
"the",
"filters",
"for",
"the",
"given",
"model",
"config",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L450-L467 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.getFiltersArrays | public function getFiltersArrays()
{
if (empty($this->filtersArrays)) {
foreach ($this->getFilters() as $name => $filter) {
$this->filtersArrays[$name] = $filter->getOptions();
}
}
return $this->filtersArrays;
} | php | public function getFiltersArrays()
{
if (empty($this->filtersArrays)) {
foreach ($this->getFilters() as $name => $filter) {
$this->filtersArrays[$name] = $filter->getOptions();
}
}
return $this->filtersArrays;
} | [
"public",
"function",
"getFiltersArrays",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"filtersArrays",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getFilters",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"filter",
")",
"{",
"$",
"... | Gets the filters array and converts the objects to arrays.
@return array | [
"Gets",
"the",
"filters",
"array",
"and",
"converts",
"the",
"objects",
"to",
"arrays",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L474-L483 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.getFieldObjectByName | public function getFieldObjectByName($field, $type)
{
$info = false;
//we want to get the correct options depending on the type of field it is
if ($type === 'filter') {
$fields = $this->getFilters();
} else {
$fields = $this->getEditFields();
}
//iterate over the fields to get the one for this $field value
foreach ($fields as $key => $val) {
if ($key === $field) {
$info = $val;
}
}
return $info;
} | php | public function getFieldObjectByName($field, $type)
{
$info = false;
//we want to get the correct options depending on the type of field it is
if ($type === 'filter') {
$fields = $this->getFilters();
} else {
$fields = $this->getEditFields();
}
//iterate over the fields to get the one for this $field value
foreach ($fields as $key => $val) {
if ($key === $field) {
$info = $val;
}
}
return $info;
} | [
"public",
"function",
"getFieldObjectByName",
"(",
"$",
"field",
",",
"$",
"type",
")",
"{",
"$",
"info",
"=",
"false",
";",
"//we want to get the correct options depending on the type of field it is",
"if",
"(",
"$",
"type",
"===",
"'filter'",
")",
"{",
"$",
"fie... | Finds a field's options given a field name and a type (filter/edit).
@param string $field
@param string $type
@return mixed | [
"Finds",
"a",
"field",
"s",
"options",
"given",
"a",
"field",
"name",
"and",
"a",
"type",
"(",
"filter",
"/",
"edit",
")",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L493-L512 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.updateRelationshipOptions | public function updateRelationshipOptions($field, $type, $constraints, $selectedItems, $term = null)
{
//first get the related model and fetch the field's options
$model = $this->config->getDataModel();
$relatedModel = $model->{$field}()->getRelated();
$relatedTable = $relatedModel->getTable();
$relatedKeyName = $relatedModel->getKeyName();
$relatedKeyTable = $relatedTable.'.'.$relatedKeyName;
$fieldObject = $this->getFieldObjectByName($field, $type);
//if we can't find the field, return an empty array
if (!$fieldObject) {
return array();
}
//make sure we're grouping by the model's id
$query = $relatedModel->newQuery();
//set up the selects
$query->select(array($this->db->raw($this->db->getTablePrefix().$relatedTable.'.*')));
//format the selected items into an array
$selectedItems = $this->formatSelectedItems($selectedItems);
//if this is an autocomplete field, check if there is a search term. If not, just return the selected items
if ($fieldObject->getOption('autocomplete') && !$term) {
if (is_array($selectedItems) && sizeof($selectedItems)) {
$this->filterQueryBySelectedItems($query, $selectedItems, $fieldObject, $relatedKeyTable);
return $this->formatSelectOptions($fieldObject, $query->get());
} else {
return array();
}
}
//applies constraints if there are any
$this->applyConstraints($constraints, $query, $fieldObject);
//if there is a search term, limit the result set by that term
$this->filterBySearchTerm($term, $query, $fieldObject, $selectedItems, $relatedKeyTable);
//perform any user-supplied options filter
$filter = $fieldObject->getOption('options_filter');
$filter($query);
//finally we can return the options
return $this->formatSelectOptions($fieldObject, $query->get());
} | php | public function updateRelationshipOptions($field, $type, $constraints, $selectedItems, $term = null)
{
//first get the related model and fetch the field's options
$model = $this->config->getDataModel();
$relatedModel = $model->{$field}()->getRelated();
$relatedTable = $relatedModel->getTable();
$relatedKeyName = $relatedModel->getKeyName();
$relatedKeyTable = $relatedTable.'.'.$relatedKeyName;
$fieldObject = $this->getFieldObjectByName($field, $type);
//if we can't find the field, return an empty array
if (!$fieldObject) {
return array();
}
//make sure we're grouping by the model's id
$query = $relatedModel->newQuery();
//set up the selects
$query->select(array($this->db->raw($this->db->getTablePrefix().$relatedTable.'.*')));
//format the selected items into an array
$selectedItems = $this->formatSelectedItems($selectedItems);
//if this is an autocomplete field, check if there is a search term. If not, just return the selected items
if ($fieldObject->getOption('autocomplete') && !$term) {
if (is_array($selectedItems) && sizeof($selectedItems)) {
$this->filterQueryBySelectedItems($query, $selectedItems, $fieldObject, $relatedKeyTable);
return $this->formatSelectOptions($fieldObject, $query->get());
} else {
return array();
}
}
//applies constraints if there are any
$this->applyConstraints($constraints, $query, $fieldObject);
//if there is a search term, limit the result set by that term
$this->filterBySearchTerm($term, $query, $fieldObject, $selectedItems, $relatedKeyTable);
//perform any user-supplied options filter
$filter = $fieldObject->getOption('options_filter');
$filter($query);
//finally we can return the options
return $this->formatSelectOptions($fieldObject, $query->get());
} | [
"public",
"function",
"updateRelationshipOptions",
"(",
"$",
"field",
",",
"$",
"type",
",",
"$",
"constraints",
",",
"$",
"selectedItems",
",",
"$",
"term",
"=",
"null",
")",
"{",
"//first get the related model and fetch the field's options",
"$",
"model",
"=",
"... | Given a model, field, type (filter or edit), and constraints (either int or array), returns an array of options.
@param string $field
@param string $type //either 'filter' or 'edit'
@param array $constraints //an array of ids of the other model's items
@param array $selectedItems //an array of ids that are currently selected
@param string $term //the search term
@return array | [
"Given",
"a",
"model",
"field",
"type",
"(",
"filter",
"or",
"edit",
")",
"and",
"constraints",
"(",
"either",
"int",
"or",
"array",
")",
"returns",
"an",
"array",
"of",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L525-L572 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.filterBySearchTerm | public function filterBySearchTerm($term, EloquentBuilder &$query, Field $fieldObject, array $selectedItems, $relatedKeyTable)
{
if ($term) {
$query->where(function ($query) use ($term, $fieldObject) {
foreach ($fieldObject->getOption('search_fields') as $search) {
$query->orWhere($this->db->raw($search), 'LIKE', '%'.$term.'%');
}
});
//exclude the currently-selected items if there are any
if (count($selectedItems)) {
$query->whereNotIn($relatedKeyTable, $selectedItems);
}
//set up the limits
$query->take($fieldObject->getOption('num_options') + count($selectedItems));
}
} | php | public function filterBySearchTerm($term, EloquentBuilder &$query, Field $fieldObject, array $selectedItems, $relatedKeyTable)
{
if ($term) {
$query->where(function ($query) use ($term, $fieldObject) {
foreach ($fieldObject->getOption('search_fields') as $search) {
$query->orWhere($this->db->raw($search), 'LIKE', '%'.$term.'%');
}
});
//exclude the currently-selected items if there are any
if (count($selectedItems)) {
$query->whereNotIn($relatedKeyTable, $selectedItems);
}
//set up the limits
$query->take($fieldObject->getOption('num_options') + count($selectedItems));
}
} | [
"public",
"function",
"filterBySearchTerm",
"(",
"$",
"term",
",",
"EloquentBuilder",
"&",
"$",
"query",
",",
"Field",
"$",
"fieldObject",
",",
"array",
"$",
"selectedItems",
",",
"$",
"relatedKeyTable",
")",
"{",
"if",
"(",
"$",
"term",
")",
"{",
"$",
"... | Filters a relationship options query by a search term.
@param mixed $term
@param \Illuminate\Database\Query\Builder $query
@param \Frozennode\Administrator\Fields\Field $fieldObject
@param array $selectedItems
@param string $relatedKeyTable | [
"Filters",
"a",
"relationship",
"options",
"query",
"by",
"a",
"search",
"term",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L583-L600 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.filterQueryBySelectedItems | public function filterQueryBySelectedItems(EloquentBuilder &$query, array $selectedItems, Field $fieldObject, $relatedKeyTable)
{
$query->whereIn($relatedKeyTable, $selectedItems);
//if this is a BelongsToMany and a sort field is set, order it by the sort field
if ($fieldObject->getOption('multiple_values') && $fieldObject->getOption('sort_field')) {
$query->orderBy($fieldObject->getOption('sort_field'));
}
//otherwise order it by the name field
else {
$query->orderBy($fieldObject->getOption('name_field'));
}
} | php | public function filterQueryBySelectedItems(EloquentBuilder &$query, array $selectedItems, Field $fieldObject, $relatedKeyTable)
{
$query->whereIn($relatedKeyTable, $selectedItems);
//if this is a BelongsToMany and a sort field is set, order it by the sort field
if ($fieldObject->getOption('multiple_values') && $fieldObject->getOption('sort_field')) {
$query->orderBy($fieldObject->getOption('sort_field'));
}
//otherwise order it by the name field
else {
$query->orderBy($fieldObject->getOption('name_field'));
}
} | [
"public",
"function",
"filterQueryBySelectedItems",
"(",
"EloquentBuilder",
"&",
"$",
"query",
",",
"array",
"$",
"selectedItems",
",",
"Field",
"$",
"fieldObject",
",",
"$",
"relatedKeyTable",
")",
"{",
"$",
"query",
"->",
"whereIn",
"(",
"$",
"relatedKeyTable"... | Takes the supplied $selectedItems mixed value and formats it to a usable array.
@param \Illuminate\Database\Query\Builder $query
@param array $selectedItems
@param \Frozennode\Administrator\Fields\Field $fieldObject
@param string $relatedKeyTable
@return array | [
"Takes",
"the",
"supplied",
"$selectedItems",
"mixed",
"value",
"and",
"formats",
"it",
"to",
"a",
"usable",
"array",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L629-L641 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Factory.php | Factory.formatSelectOptions | public function formatSelectOptions(Field $field, EloquentCollection $results)
{
$return = array();
foreach ($results as $m) {
$return[] = array(
'id' => $m->getKey(),
'text' => strval($m->{$field->getOption('name_field')}),
);
}
return $return;
} | php | public function formatSelectOptions(Field $field, EloquentCollection $results)
{
$return = array();
foreach ($results as $m) {
$return[] = array(
'id' => $m->getKey(),
'text' => strval($m->{$field->getOption('name_field')}),
);
}
return $return;
} | [
"public",
"function",
"formatSelectOptions",
"(",
"Field",
"$",
"field",
",",
"EloquentCollection",
"$",
"results",
")",
"{",
"$",
"return",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"results",
"as",
"$",
"m",
")",
"{",
"$",
"return",
"[",
"]",... | Takes an eloquent result array and turns it into an options array that can be used in the UI.
@param \Frozennode\Administrator\Fields\Field $field
@param \Illuminate\Database\Eloquent\Collection $results
@return array | [
"Takes",
"an",
"eloquent",
"result",
"array",
"and",
"turns",
"it",
"into",
"an",
"options",
"array",
"that",
"can",
"be",
"used",
"in",
"the",
"UI",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Factory.php#L688-L700 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Relationships/BelongsTo.php | BelongsTo.build | public function build()
{
$options = $this->suppliedOptions;
$this->tablePrefix = $this->db->getTablePrefix();
$nested = $this->getNestedRelationships($options['relationship']);
$relevantName = $nested['pieces'][sizeof($nested['pieces']) - 1];
$relevantModel = $nested['models'][sizeof($nested['models']) - 2];
$options['nested'] = $nested;
$relationship = $relevantModel->{$relevantName}();
$selectTable = $options['column_name'].'_'.$this->tablePrefix.$relationship->getRelated()->getTable();
//set the relationship object so we can use it later
$this->relationshipObject = $relationship;
//replace the (:table) with the generated $selectTable
$options['select'] = str_replace('(:table)', $selectTable, $options['select']);
$this->suppliedOptions = $options;
} | php | public function build()
{
$options = $this->suppliedOptions;
$this->tablePrefix = $this->db->getTablePrefix();
$nested = $this->getNestedRelationships($options['relationship']);
$relevantName = $nested['pieces'][sizeof($nested['pieces']) - 1];
$relevantModel = $nested['models'][sizeof($nested['models']) - 2];
$options['nested'] = $nested;
$relationship = $relevantModel->{$relevantName}();
$selectTable = $options['column_name'].'_'.$this->tablePrefix.$relationship->getRelated()->getTable();
//set the relationship object so we can use it later
$this->relationshipObject = $relationship;
//replace the (:table) with the generated $selectTable
$options['select'] = str_replace('(:table)', $selectTable, $options['select']);
$this->suppliedOptions = $options;
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"suppliedOptions",
";",
"$",
"this",
"->",
"tablePrefix",
"=",
"$",
"this",
"->",
"db",
"->",
"getTablePrefix",
"(",
")",
";",
"$",
"nested",
"=",
"$",
"this",
"->"... | Builds the necessary fields on the object. | [
"Builds",
"the",
"necessary",
"fields",
"on",
"the",
"object",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Relationships/BelongsTo.php#L26-L46 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Relationships/BelongsTo.php | BelongsTo.getNestedRelationships | public function getNestedRelationships($name)
{
$pieces = explode('.', $name);
$models = array();
$num_pieces = sizeof($pieces);
//iterate over the relationships to see if they're all valid
foreach ($pieces as $i => $rel) {
//if this is the first item, then the model is the config's model
if ($i === 0) {
$models[] = $this->config->getDataModel();
}
//if the model method doesn't exist for any of the pieces along the way, exit out
if (!method_exists($models[$i], $rel) || !is_a($models[$i]->{$rel}(), self::BELONGS_TO)) {
throw new \InvalidArgumentException("The '".$this->getOption('column_name')."' column in your ".$this->config->getOption('name').
" model configuration needs to be either a belongsTo relationship method name or a sequence of them connected with a '.'");
}
//we don't need the model of the last item
$models[] = $models[$i]->{$rel}()->getRelated();
}
return array('models' => $models, 'pieces' => $pieces);
} | php | public function getNestedRelationships($name)
{
$pieces = explode('.', $name);
$models = array();
$num_pieces = sizeof($pieces);
//iterate over the relationships to see if they're all valid
foreach ($pieces as $i => $rel) {
//if this is the first item, then the model is the config's model
if ($i === 0) {
$models[] = $this->config->getDataModel();
}
//if the model method doesn't exist for any of the pieces along the way, exit out
if (!method_exists($models[$i], $rel) || !is_a($models[$i]->{$rel}(), self::BELONGS_TO)) {
throw new \InvalidArgumentException("The '".$this->getOption('column_name')."' column in your ".$this->config->getOption('name').
" model configuration needs to be either a belongsTo relationship method name or a sequence of them connected with a '.'");
}
//we don't need the model of the last item
$models[] = $models[$i]->{$rel}()->getRelated();
}
return array('models' => $models, 'pieces' => $pieces);
} | [
"public",
"function",
"getNestedRelationships",
"(",
"$",
"name",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"'.'",
",",
"$",
"name",
")",
";",
"$",
"models",
"=",
"array",
"(",
")",
";",
"$",
"num_pieces",
"=",
"sizeof",
"(",
"$",
"pieces",
")",
... | Converts the relationship key.
@param string $name //the relationship name
@return false|array('models' => array(), 'pieces' => array()) | [
"Converts",
"the",
"relationship",
"key",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Relationships/BelongsTo.php#L55-L79 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Relationships/BelongsTo.php | BelongsTo.getIncludedColumn | public function getIncludedColumn()
{
$model = $this->config->getDataModel();
$nested = $this->getOption('nested');
$fk = $nested['models'][0]->{$nested['pieces'][0]}()->getForeignKey();
return array($fk => $model->getTable().'.'.$fk);
} | php | public function getIncludedColumn()
{
$model = $this->config->getDataModel();
$nested = $this->getOption('nested');
$fk = $nested['models'][0]->{$nested['pieces'][0]}()->getForeignKey();
return array($fk => $model->getTable().'.'.$fk);
} | [
"public",
"function",
"getIncludedColumn",
"(",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"$",
"nested",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'nested'",
")",
";",
"$",
"fk",
"=",
"$",
"nested... | Gets all default values.
@return array | [
"Gets",
"all",
"default",
"values",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Relationships/BelongsTo.php#L130-L137 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/HasMany.php | HasMany.fillModel | public function fillModel(&$model, $input)
{
// $input is an array of all foreign key IDs
//
// $model is the model for which the above answers should be associated to
$fieldName = $this->getOption('field_name');
$input = $input ? explode(',', $input) : array();
$relationship = $model->{$fieldName}();
// get the plain foreign key so we can set it to null:
$fkey = $relationship->getPlainForeignKey();
$relatedObjectClass = get_class($relationship->getRelated());
// first we "forget all the related models" (by setting their foreign key to null)
foreach ($relationship->get() as $related) {
$related->$fkey = null; // disassociate
$related->save();
}
// now associate new ones: (setting the correct order as well)
$i = 0;
foreach ($input as $foreign_id) {
$relatedObject = call_user_func($relatedObjectClass.'::find', $foreign_id);
if ($sortField = $this->getOption('sort_field')) {
$relatedObject->$sortField = $i++;
}
$relationship->save($relatedObject);
}
} | php | public function fillModel(&$model, $input)
{
// $input is an array of all foreign key IDs
//
// $model is the model for which the above answers should be associated to
$fieldName = $this->getOption('field_name');
$input = $input ? explode(',', $input) : array();
$relationship = $model->{$fieldName}();
// get the plain foreign key so we can set it to null:
$fkey = $relationship->getPlainForeignKey();
$relatedObjectClass = get_class($relationship->getRelated());
// first we "forget all the related models" (by setting their foreign key to null)
foreach ($relationship->get() as $related) {
$related->$fkey = null; // disassociate
$related->save();
}
// now associate new ones: (setting the correct order as well)
$i = 0;
foreach ($input as $foreign_id) {
$relatedObject = call_user_func($relatedObjectClass.'::find', $foreign_id);
if ($sortField = $this->getOption('sort_field')) {
$relatedObject->$sortField = $i++;
}
$relationship->save($relatedObject);
}
} | [
"public",
"function",
"fillModel",
"(",
"&",
"$",
"model",
",",
"$",
"input",
")",
"{",
"// $input is an array of all foreign key IDs",
"//",
"// $model is the model for which the above answers should be associated to",
"$",
"fieldName",
"=",
"$",
"this",
"->",
"getOption",... | Fill a model with input data.
@param \Illuminate\Database\Eloquent\Model $model
@param mixed $input
@return array | [
"Fill",
"a",
"model",
"with",
"input",
"data",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/HasMany.php#L28-L58 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Relationships/HasMany.php | HasMany.filterQuery | public function filterQuery(QueryBuilder &$query, &$selects = null)
{
//run the parent method
parent::filterQuery($query, $selects);
//get the values
$value = $this->getOption('value');
$table = $this->getOption('table');
$column = $this->getOption('column');
$column2 = $this->getOption('column2');
//if there is no value, return
if (!$value) {
return;
}
$model = $this->config->getDataModel();
//if the table hasn't been joined yet, join it
if (!$this->validator->isJoined($query, $table)) {
$query->join($table, $model->getTable().'.'.$model->getKeyName(), '=', $column);
}
//add where clause
$query->whereIn($column2, $value);
//add having clauses
$query->havingRaw('COUNT(DISTINCT '.$query->getConnection()->getTablePrefix().$column2.') = '.count($value));
//add select field
if ($selects && !in_array($column2, $selects)) {
$selects[] = $column2;
}
} | php | public function filterQuery(QueryBuilder &$query, &$selects = null)
{
//run the parent method
parent::filterQuery($query, $selects);
//get the values
$value = $this->getOption('value');
$table = $this->getOption('table');
$column = $this->getOption('column');
$column2 = $this->getOption('column2');
//if there is no value, return
if (!$value) {
return;
}
$model = $this->config->getDataModel();
//if the table hasn't been joined yet, join it
if (!$this->validator->isJoined($query, $table)) {
$query->join($table, $model->getTable().'.'.$model->getKeyName(), '=', $column);
}
//add where clause
$query->whereIn($column2, $value);
//add having clauses
$query->havingRaw('COUNT(DISTINCT '.$query->getConnection()->getTablePrefix().$column2.') = '.count($value));
//add select field
if ($selects && !in_array($column2, $selects)) {
$selects[] = $column2;
}
} | [
"public",
"function",
"filterQuery",
"(",
"QueryBuilder",
"&",
"$",
"query",
",",
"&",
"$",
"selects",
"=",
"null",
")",
"{",
"//run the parent method",
"parent",
"::",
"filterQuery",
"(",
"$",
"query",
",",
"$",
"selects",
")",
";",
"//get the values",
"$",... | Filters a query object with this item's data.
@param \Illuminate\Database\Query\Builder $query
@param array $selects | [
"Filters",
"a",
"query",
"object",
"with",
"this",
"item",
"s",
"data",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Relationships/HasMany.php#L66-L99 |
summerblue/administrator | src/Frozennode/Administrator/Actions/Action.php | Action.build | public function build()
{
$options = $this->suppliedOptions;
//build the string or callable values for title and confirmation
$this->buildStringOrCallable($options, array('confirmation', 'title'));
//build the string or callable values for the messages
$messages = $this->validator->arrayGet($options, 'messages', array());
$this->buildStringOrCallable($messages, array('active', 'success', 'error'));
$options['messages'] = $messages;
//override the supplied options
$this->suppliedOptions = $options;
} | php | public function build()
{
$options = $this->suppliedOptions;
//build the string or callable values for title and confirmation
$this->buildStringOrCallable($options, array('confirmation', 'title'));
//build the string or callable values for the messages
$messages = $this->validator->arrayGet($options, 'messages', array());
$this->buildStringOrCallable($messages, array('active', 'success', 'error'));
$options['messages'] = $messages;
//override the supplied options
$this->suppliedOptions = $options;
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"suppliedOptions",
";",
"//build the string or callable values for title and confirmation",
"$",
"this",
"->",
"buildStringOrCallable",
"(",
"$",
"options",
",",
"array",
"(",
"'co... | Builds the necessary fields on the object. | [
"Builds",
"the",
"necessary",
"fields",
"on",
"the",
"object",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Actions/Action.php#L98-L112 |
summerblue/administrator | src/Frozennode/Administrator/Http/Middleware/ValidateAdmin.php | ValidateAdmin.handle | public function handle($request, Closure $next)
{
$configFactory = app('admin_config_factory');
//get the admin check closure that should be supplied in the config
$permission = config('administrator.permission');
//if this is a simple false value, send the user to the login redirect
if (!$response = $permission()) {
$loginUrl = url(config('administrator.login_path', 'user/login'));
$redirectKey = config('administrator.login_redirect_key', 'redirect');
$redirectUri = $request->url();
return redirect()->guest($loginUrl)->with($redirectKey, $redirectUri);
}
//otherwise if this is a response, return that
elseif (is_a($response, 'Illuminate\Http\JsonResponse') || is_a($response, 'Illuminate\Http\Response')) {
return $response;
}
//if it's a redirect, send it back with the redirect uri
elseif (is_a($response, 'Illuminate\\Http\\RedirectResponse')) {
$redirectKey = config('administrator.login_redirect_key', 'redirect');
$redirectUri = $request->url();
return $response->with($redirectKey, $redirectUri);
}
return $next($request);
} | php | public function handle($request, Closure $next)
{
$configFactory = app('admin_config_factory');
//get the admin check closure that should be supplied in the config
$permission = config('administrator.permission');
//if this is a simple false value, send the user to the login redirect
if (!$response = $permission()) {
$loginUrl = url(config('administrator.login_path', 'user/login'));
$redirectKey = config('administrator.login_redirect_key', 'redirect');
$redirectUri = $request->url();
return redirect()->guest($loginUrl)->with($redirectKey, $redirectUri);
}
//otherwise if this is a response, return that
elseif (is_a($response, 'Illuminate\Http\JsonResponse') || is_a($response, 'Illuminate\Http\Response')) {
return $response;
}
//if it's a redirect, send it back with the redirect uri
elseif (is_a($response, 'Illuminate\\Http\\RedirectResponse')) {
$redirectKey = config('administrator.login_redirect_key', 'redirect');
$redirectUri = $request->url();
return $response->with($redirectKey, $redirectUri);
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"$",
"configFactory",
"=",
"app",
"(",
"'admin_config_factory'",
")",
";",
"//get the admin check closure that should be supplied in the config",
"$",
"permission",
"=",
"confi... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Http/Middleware/ValidateAdmin.php#L17-L47 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Relationships/HasOneOrMany.php | HasOneOrMany.filterQuery | public function filterQuery(&$selects)
{
$model = $this->config->getDataModel();
$joins = $where = '';
$columnName = $this->getOption('column_name');
$relationship = $model->{$this->getOption('relationship')}();
$from_table = $this->tablePrefix.$relationship->getRelated()->getTable();
$field_table = $columnName.'_'.$from_table;
//grab the existing where clauses that the user may have set on the relationship
$relationshipWheres = $this->getRelationshipWheres($relationship, $field_table);
$where = $this->tablePrefix.$relationship->getQualifiedParentKeyName().
' = '.
$field_table.'.'.$relationship->getPlainForeignKey()
.($relationshipWheres ? ' AND '.$relationshipWheres : '');
$selects[] = $this->db->raw('(SELECT '.$this->getOption('select').'
FROM '.$from_table.' AS '.$field_table.' '.$joins.'
WHERE '.$where.') AS '.$this->db->getQueryGrammar()->wrap($columnName));
} | php | public function filterQuery(&$selects)
{
$model = $this->config->getDataModel();
$joins = $where = '';
$columnName = $this->getOption('column_name');
$relationship = $model->{$this->getOption('relationship')}();
$from_table = $this->tablePrefix.$relationship->getRelated()->getTable();
$field_table = $columnName.'_'.$from_table;
//grab the existing where clauses that the user may have set on the relationship
$relationshipWheres = $this->getRelationshipWheres($relationship, $field_table);
$where = $this->tablePrefix.$relationship->getQualifiedParentKeyName().
' = '.
$field_table.'.'.$relationship->getPlainForeignKey()
.($relationshipWheres ? ' AND '.$relationshipWheres : '');
$selects[] = $this->db->raw('(SELECT '.$this->getOption('select').'
FROM '.$from_table.' AS '.$field_table.' '.$joins.'
WHERE '.$where.') AS '.$this->db->getQueryGrammar()->wrap($columnName));
} | [
"public",
"function",
"filterQuery",
"(",
"&",
"$",
"selects",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"$",
"joins",
"=",
"$",
"where",
"=",
"''",
";",
"$",
"columnName",
"=",
"$",
"this",
"->"... | Adds selects to a query.
@param array $selects | [
"Adds",
"selects",
"to",
"a",
"query",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Relationships/HasOneOrMany.php#L12-L33 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Enum.php | Enum.build | public function build()
{
parent::build();
$options = $this->suppliedOptions;
$dataOptions = $options['options'];
$options['options'] = array();
//iterate over the options to create the options assoc array
foreach ($dataOptions as $val => $text) {
$options['options'][] = array(
'id' => is_numeric($val) ? $text : $val,
'text' => $text,
);
}
$this->suppliedOptions = $options;
} | php | public function build()
{
parent::build();
$options = $this->suppliedOptions;
$dataOptions = $options['options'];
$options['options'] = array();
//iterate over the options to create the options assoc array
foreach ($dataOptions as $val => $text) {
$options['options'][] = array(
'id' => is_numeric($val) ? $text : $val,
'text' => $text,
);
}
$this->suppliedOptions = $options;
} | [
"public",
"function",
"build",
"(",
")",
"{",
"parent",
"::",
"build",
"(",
")",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"suppliedOptions",
";",
"$",
"dataOptions",
"=",
"$",
"options",
"[",
"'options'",
"]",
";",
"$",
"options",
"[",
"'options'",... | Builds a few basic options. | [
"Builds",
"a",
"few",
"basic",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Enum.php#L21-L39 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Enum.php | Enum.setFilter | public function setFilter($filter)
{
parent::setFilter($filter);
$this->userOptions['value'] = $this->getOption('value') === '' ? null : $this->getOption('value');
} | php | public function setFilter($filter)
{
parent::setFilter($filter);
$this->userOptions['value'] = $this->getOption('value') === '' ? null : $this->getOption('value');
} | [
"public",
"function",
"setFilter",
"(",
"$",
"filter",
")",
"{",
"parent",
"::",
"setFilter",
"(",
"$",
"filter",
")",
";",
"$",
"this",
"->",
"userOptions",
"[",
"'value'",
"]",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'value'",
")",
"===",
"''",
... | Sets the filter options for this item.
@param array $filter | [
"Sets",
"the",
"filter",
"options",
"for",
"this",
"item",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Enum.php#L57-L62 |
summerblue/administrator | src/Frozennode/Administrator/Fields/Enum.php | Enum.filterQuery | public function filterQuery(QueryBuilder &$query, &$selects = null)
{
//run the parent method
parent::filterQuery($query, $selects);
//if there is no value, return
if ($this->getFilterValue($this->getOption('value')) === false) {
return;
}
$query->where($this->config->getDataModel()->getTable().'.'.$this->getOption('field_name'), '=', $this->getOption('value'));
} | php | public function filterQuery(QueryBuilder &$query, &$selects = null)
{
//run the parent method
parent::filterQuery($query, $selects);
//if there is no value, return
if ($this->getFilterValue($this->getOption('value')) === false) {
return;
}
$query->where($this->config->getDataModel()->getTable().'.'.$this->getOption('field_name'), '=', $this->getOption('value'));
} | [
"public",
"function",
"filterQuery",
"(",
"QueryBuilder",
"&",
"$",
"query",
",",
"&",
"$",
"selects",
"=",
"null",
")",
"{",
"//run the parent method",
"parent",
"::",
"filterQuery",
"(",
"$",
"query",
",",
"$",
"selects",
")",
";",
"//if there is no value, r... | Filters a query object.
@param \Illuminate\Database\Query\Builder $query
@param array $selects | [
"Filters",
"a",
"query",
"object",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Fields/Enum.php#L70-L81 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Column.php | Column.build | public function build()
{
$model = $this->config->getDataModel();
$options = $this->suppliedOptions;
$this->tablePrefix = $this->db->getTablePrefix();
//set some options-based defaults
$options['title'] = $this->validator->arrayGet($options, 'title', $options['column_name']);
$options['sort_field'] = $this->validator->arrayGet($options, 'sort_field', $options['column_name']);
//if the supplied item is an accessor, make this unsortable for the moment
if (method_exists($model, camel_case('get_'.$options['column_name'].'_attribute')) && $options['column_name'] === $options['sort_field']) {
$options['sortable'] = false;
}
//however, if this is not a relation and the select option was supplied, str_replace the select option and make it sortable again
if ($select = $this->validator->arrayGet($options, 'select')) {
$options['select'] = str_replace('(:table)', $this->tablePrefix.$model->getTable(), $select);
}
//now we do some final organization to categorize these columns (useful later in the sorting)
if (method_exists($model, camel_case('get_'.$options['column_name'].'_attribute')) || $select) {
$options['is_computed'] = true;
} else {
$options['is_included'] = true;
}
//run the visible property closure if supplied
$visible = $this->validator->arrayGet($options, 'visible');
if (is_callable($visible)) {
$options['visible'] = $visible($this->config->getDataModel()) ? true : false;
}
$this->suppliedOptions = $options;
} | php | public function build()
{
$model = $this->config->getDataModel();
$options = $this->suppliedOptions;
$this->tablePrefix = $this->db->getTablePrefix();
//set some options-based defaults
$options['title'] = $this->validator->arrayGet($options, 'title', $options['column_name']);
$options['sort_field'] = $this->validator->arrayGet($options, 'sort_field', $options['column_name']);
//if the supplied item is an accessor, make this unsortable for the moment
if (method_exists($model, camel_case('get_'.$options['column_name'].'_attribute')) && $options['column_name'] === $options['sort_field']) {
$options['sortable'] = false;
}
//however, if this is not a relation and the select option was supplied, str_replace the select option and make it sortable again
if ($select = $this->validator->arrayGet($options, 'select')) {
$options['select'] = str_replace('(:table)', $this->tablePrefix.$model->getTable(), $select);
}
//now we do some final organization to categorize these columns (useful later in the sorting)
if (method_exists($model, camel_case('get_'.$options['column_name'].'_attribute')) || $select) {
$options['is_computed'] = true;
} else {
$options['is_included'] = true;
}
//run the visible property closure if supplied
$visible = $this->validator->arrayGet($options, 'visible');
if (is_callable($visible)) {
$options['visible'] = $visible($this->config->getDataModel()) ? true : false;
}
$this->suppliedOptions = $options;
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"config",
"->",
"getDataModel",
"(",
")",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"suppliedOptions",
";",
"$",
"this",
"->",
"tablePrefix",
"=",
"$",
"this",
"->... | Builds the necessary fields on the object. | [
"Builds",
"the",
"necessary",
"fields",
"on",
"the",
"object",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Column.php#L142-L177 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Column.php | Column.filterQuery | public function filterQuery(&$selects)
{
if ($select = $this->getOption('select')) {
$selects[] = $this->db->raw($select.' AS '.$this->db->getQueryGrammar()->wrap($this->getOption('column_name')));
}
} | php | public function filterQuery(&$selects)
{
if ($select = $this->getOption('select')) {
$selects[] = $this->db->raw($select.' AS '.$this->db->getQueryGrammar()->wrap($this->getOption('column_name')));
}
} | [
"public",
"function",
"filterQuery",
"(",
"&",
"$",
"selects",
")",
"{",
"if",
"(",
"$",
"select",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'select'",
")",
")",
"{",
"$",
"selects",
"[",
"]",
"=",
"$",
"this",
"->",
"db",
"->",
"raw",
"(",
"$",... | Adds selects to a query.
@param array $selects | [
"Adds",
"selects",
"to",
"a",
"query",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Column.php#L184-L189 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Column.php | Column.getOptions | public function getOptions()
{
//make sure the supplied options have been merged with the defaults
if (empty($this->options)) {
//validate the options and build them
$this->validateOptions();
$this->build();
$this->options = array_merge($this->getDefaults(), $this->suppliedOptions);
}
return $this->options;
} | php | public function getOptions()
{
//make sure the supplied options have been merged with the defaults
if (empty($this->options)) {
//validate the options and build them
$this->validateOptions();
$this->build();
$this->options = array_merge($this->getDefaults(), $this->suppliedOptions);
}
return $this->options;
} | [
"public",
"function",
"getOptions",
"(",
")",
"{",
"//make sure the supplied options have been merged with the defaults",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"options",
")",
")",
"{",
"//validate the options and build them",
"$",
"this",
"->",
"validateOptions",
... | Gets all user options.
@return array | [
"Gets",
"all",
"user",
"options",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Column.php#L196-L207 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Column.php | Column.getOption | public function getOption($key)
{
$options = $this->getOptions();
if (!array_key_exists($key, $options)) {
throw new \InvalidArgumentException("An invalid option was searched for in the '".$options['column_name']."' column");
}
return $options[$key];
} | php | public function getOption($key)
{
$options = $this->getOptions();
if (!array_key_exists($key, $options)) {
throw new \InvalidArgumentException("An invalid option was searched for in the '".$options['column_name']."' column");
}
return $options[$key];
} | [
"public",
"function",
"getOption",
"(",
"$",
"key",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"getOptions",
"(",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"options",
")",
")",
"{",
"throw",
"new",
"\\",
"Inval... | Gets a field's option.
@param string $key
@return mixed | [
"Gets",
"a",
"field",
"s",
"option",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Column.php#L216-L225 |
summerblue/administrator | src/Frozennode/Administrator/DataTable/Columns/Column.php | Column.renderOutput | public function renderOutput($value, $item = null)
{
$output = $this->getOption('output');
// default is xss secured untill u open `raw_output` option
// e() is laravel blade `{{ }}` for printing data
if ( ! $this->getOption('raw_output')) {
$value = e($value);
}
if (is_callable($output)) {
return $output($value, $item);
}
return str_replace('(:value)', $value, $output);
} | php | public function renderOutput($value, $item = null)
{
$output = $this->getOption('output');
// default is xss secured untill u open `raw_output` option
// e() is laravel blade `{{ }}` for printing data
if ( ! $this->getOption('raw_output')) {
$value = e($value);
}
if (is_callable($output)) {
return $output($value, $item);
}
return str_replace('(:value)', $value, $output);
} | [
"public",
"function",
"renderOutput",
"(",
"$",
"value",
",",
"$",
"item",
"=",
"null",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'output'",
")",
";",
"// default is xss secured untill u open `raw_output` option",
"// e() is laravel blade `... | Takes a column output string and renders the column with it (replacing '(:value)' with the column's field value).
@param $value string $value
@param \Illuminate\Database\Eloquent\Model $item
@return string | [
"Takes",
"a",
"column",
"output",
"string",
"and",
"renders",
"the",
"column",
"with",
"it",
"(",
"replacing",
"(",
":",
"value",
")",
"with",
"the",
"column",
"s",
"field",
"value",
")",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/DataTable/Columns/Column.php#L235-L250 |
summerblue/administrator | src/Frozennode/Administrator/Config/Settings/Config.php | Config.getStoragePath | public function getStoragePath()
{
$path = $this->getOption('storage_path');
$path = $path ? $path : storage_path().'/administrator_settings/';
return rtrim($path, '/').'/';
} | php | public function getStoragePath()
{
$path = $this->getOption('storage_path');
$path = $path ? $path : storage_path().'/administrator_settings/';
return rtrim($path, '/').'/';
} | [
"public",
"function",
"getStoragePath",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'storage_path'",
")",
";",
"$",
"path",
"=",
"$",
"path",
"?",
"$",
"path",
":",
"storage_path",
"(",
")",
".",
"'/administrator_settings/'",
"... | Gets the storage directory path. | [
"Gets",
"the",
"storage",
"directory",
"path",
"."
] | train | https://github.com/summerblue/administrator/blob/ef29593de6250b56776506b4590a3bbf91db9b37/src/Frozennode/Administrator/Config/Settings/Config.php#L77-L83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.