repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pxgamer/arionum-php | src/Arionum.php | Arionum.checkSignature | public function checkSignature(string $signature, string $data, string $publicKey): bool
{
return $this->getJson([
'q' => 'checkSignature',
'signature' => $signature,
'data' => $data,
'public_key' => $publicKey,
]);
} | php | public function checkSignature(string $signature, string $data, string $publicKey): bool
{
return $this->getJson([
'q' => 'checkSignature',
'signature' => $signature,
'data' => $data,
'public_key' => $publicKey,
]);
} | [
"public",
"function",
"checkSignature",
"(",
"string",
"$",
"signature",
",",
"string",
"$",
"data",
",",
"string",
"$",
"publicKey",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"getJson",
"(",
"[",
"'q'",
"=>",
"'checkSignature'",
",",
"'signature... | Check that a signature is valid against a public key.
@param string $signature
@param string $data
@param string $publicKey
@return bool
@throws ApiException
@api | [
"Check",
"that",
"a",
"signature",
"is",
"valid",
"against",
"a",
"public",
"key",
"."
] | 1d3e73f7b661878b864b3a910faad540e6af47bb | https://github.com/pxgamer/arionum-php/blob/1d3e73f7b661878b864b3a910faad540e6af47bb/src/Arionum.php#L336-L344 | train |
pxgamer/arionum-php | src/Arionum.php | Arionum.checkAddress | public function checkAddress(string $address, ?string $publicKey = null): bool
{
return $this->getJson([
'q' => 'checkAddress',
'account' => $address,
'public_key' => $publicKey,
]);
} | php | public function checkAddress(string $address, ?string $publicKey = null): bool
{
return $this->getJson([
'q' => 'checkAddress',
'account' => $address,
'public_key' => $publicKey,
]);
} | [
"public",
"function",
"checkAddress",
"(",
"string",
"$",
"address",
",",
"?",
"string",
"$",
"publicKey",
"=",
"null",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"getJson",
"(",
"[",
"'q'",
"=>",
"'checkAddress'",
",",
"'account'",
"=>",
"$",
... | Check that an address is valid.
Optionally validate it against the corresponding public key.
@param string $address
@param string|null $publicKey An optional corresponding public key.
@return bool
@throws ApiException
@api | [
"Check",
"that",
"an",
"address",
"is",
"valid",
".",
"Optionally",
"validate",
"it",
"against",
"the",
"corresponding",
"public",
"key",
"."
] | 1d3e73f7b661878b864b3a910faad540e6af47bb | https://github.com/pxgamer/arionum-php/blob/1d3e73f7b661878b864b3a910faad540e6af47bb/src/Arionum.php#L414-L421 | train |
nails/module-invoice | src/Model/Refund.php | Refund.setPending | public function setPending($iRefundId, $aData = [])
{
$aData['status'] = self::STATUS_PENDING;
return $this->update($iRefundId, $aData);
} | php | public function setPending($iRefundId, $aData = [])
{
$aData['status'] = self::STATUS_PENDING;
return $this->update($iRefundId, $aData);
} | [
"public",
"function",
"setPending",
"(",
"$",
"iRefundId",
",",
"$",
"aData",
"=",
"[",
"]",
")",
"{",
"$",
"aData",
"[",
"'status'",
"]",
"=",
"self",
"::",
"STATUS_PENDING",
";",
"return",
"$",
"this",
"->",
"update",
"(",
"$",
"iRefundId",
",",
"$... | Set a refund as PENDING
@param integer $iRefundId The refund to update
@param array $aData Any additional data to save to the transaction
@return boolean | [
"Set",
"a",
"refund",
"as",
"PENDING"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L222-L226 | train |
nails/module-invoice | src/Model/Refund.php | Refund.setProcessing | public function setProcessing($iRefundId, $aData = [])
{
$aData['status'] = self::STATUS_PROCESSING;
return $this->update($iRefundId, $aData);
} | php | public function setProcessing($iRefundId, $aData = [])
{
$aData['status'] = self::STATUS_PROCESSING;
return $this->update($iRefundId, $aData);
} | [
"public",
"function",
"setProcessing",
"(",
"$",
"iRefundId",
",",
"$",
"aData",
"=",
"[",
"]",
")",
"{",
"$",
"aData",
"[",
"'status'",
"]",
"=",
"self",
"::",
"STATUS_PROCESSING",
";",
"return",
"$",
"this",
"->",
"update",
"(",
"$",
"iRefundId",
","... | Set a refund as PROCESSING
@param integer $iRefundId The refund to update
@param array $aData Any additional data to save to the transaction
@return boolean | [
"Set",
"a",
"refund",
"as",
"PROCESSING"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L238-L242 | train |
nails/module-invoice | src/Model/Refund.php | Refund.setFailed | public function setFailed($iRefundId, $aData = [])
{
$aData['status'] = self::STATUS_FAILED;
return $this->update($iRefundId, $aData);
} | php | public function setFailed($iRefundId, $aData = [])
{
$aData['status'] = self::STATUS_FAILED;
return $this->update($iRefundId, $aData);
} | [
"public",
"function",
"setFailed",
"(",
"$",
"iRefundId",
",",
"$",
"aData",
"=",
"[",
"]",
")",
"{",
"$",
"aData",
"[",
"'status'",
"]",
"=",
"self",
"::",
"STATUS_FAILED",
";",
"return",
"$",
"this",
"->",
"update",
"(",
"$",
"iRefundId",
",",
"$",... | Set a refund as FAILED
@param integer $iRefundId The refund to update
@param array $aData Any additional data to save to the transaction
@return boolean | [
"Set",
"a",
"refund",
"as",
"FAILED"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L270-L274 | train |
nails/module-invoice | src/Model/Refund.php | Refund.sendReceipt | public function sendReceipt($iRefundId, $sEmailOverride = null)
{
try {
$oRefund = $this->getById(
$iRefundId,
[
'expand' => [
['invoice', ['expand' => ['customer']]],
'payment',
],
]
);
if (empty($oRefund)) {
throw new PaymentException('Invalid Payment ID', 1);
}
if (!in_array($oRefund->status->id, [self::STATUS_PROCESSING, self::STATUS_COMPLETE])) {
throw new PaymentException('Refund must be in a paid or processing state to send receipt.', 1);
}
$oEmail = new \stdClass();
if ($oRefund->status->id == self::STATUS_COMPLETE) {
$oEmail->type = 'refund_complete_receipt';
} else {
$oEmail->type = 'refund_processing_receipt';
}
$oEmail->data = [
'refund' => $oRefund,
];
if (!empty($sEmailOverride)) {
// @todo (Pablo - 2019-01-20) - validate email address (or addresses if an array)
$aEmails = explode(',', $sEmailOverride);
} elseif (!empty($oRefund->invoice->customer->billing_email)) {
$aEmails = explode(',', $oRefund->invoice->customer->billing_email);
} elseif (!empty($oRefund->invoice->customer->email)) {
$aEmails = [$oRefund->invoice->customer->email];
} else {
throw new PaymentException('No email address to send the receipt to.', 1);
}
$aEmails = array_unique($aEmails);
$aEmails = array_filter($aEmails);
$oEmailer = Factory::service('Emailer', 'nails/module-email');
$oInvoiceEmailModel = Factory::model('InvoiceEmail', 'nails/module-invoice');
foreach ($aEmails as $sEmail) {
$oEmail->to_email = $sEmail;
$oResult = $oEmailer->send($oEmail);
if (!empty($oResult)) {
$oInvoiceEmailModel->create(
[
'invoice_id' => $oRefund->invoice->id,
'email_id' => $oResult->id,
'email_type' => $oEmail->type,
'recipient' => $oEmail->to_email,
]
);
} else {
throw new PaymentException($oEmailer->lastError(), 1);
}
}
} catch (\Exception $e) {
$this->setError($e->getMessage());
return false;
}
return true;
} | php | public function sendReceipt($iRefundId, $sEmailOverride = null)
{
try {
$oRefund = $this->getById(
$iRefundId,
[
'expand' => [
['invoice', ['expand' => ['customer']]],
'payment',
],
]
);
if (empty($oRefund)) {
throw new PaymentException('Invalid Payment ID', 1);
}
if (!in_array($oRefund->status->id, [self::STATUS_PROCESSING, self::STATUS_COMPLETE])) {
throw new PaymentException('Refund must be in a paid or processing state to send receipt.', 1);
}
$oEmail = new \stdClass();
if ($oRefund->status->id == self::STATUS_COMPLETE) {
$oEmail->type = 'refund_complete_receipt';
} else {
$oEmail->type = 'refund_processing_receipt';
}
$oEmail->data = [
'refund' => $oRefund,
];
if (!empty($sEmailOverride)) {
// @todo (Pablo - 2019-01-20) - validate email address (or addresses if an array)
$aEmails = explode(',', $sEmailOverride);
} elseif (!empty($oRefund->invoice->customer->billing_email)) {
$aEmails = explode(',', $oRefund->invoice->customer->billing_email);
} elseif (!empty($oRefund->invoice->customer->email)) {
$aEmails = [$oRefund->invoice->customer->email];
} else {
throw new PaymentException('No email address to send the receipt to.', 1);
}
$aEmails = array_unique($aEmails);
$aEmails = array_filter($aEmails);
$oEmailer = Factory::service('Emailer', 'nails/module-email');
$oInvoiceEmailModel = Factory::model('InvoiceEmail', 'nails/module-invoice');
foreach ($aEmails as $sEmail) {
$oEmail->to_email = $sEmail;
$oResult = $oEmailer->send($oEmail);
if (!empty($oResult)) {
$oInvoiceEmailModel->create(
[
'invoice_id' => $oRefund->invoice->id,
'email_id' => $oResult->id,
'email_type' => $oEmail->type,
'recipient' => $oEmail->to_email,
]
);
} else {
throw new PaymentException($oEmailer->lastError(), 1);
}
}
} catch (\Exception $e) {
$this->setError($e->getMessage());
return false;
}
return true;
} | [
"public",
"function",
"sendReceipt",
"(",
"$",
"iRefundId",
",",
"$",
"sEmailOverride",
"=",
"null",
")",
"{",
"try",
"{",
"$",
"oRefund",
"=",
"$",
"this",
"->",
"getById",
"(",
"$",
"iRefundId",
",",
"[",
"'expand'",
"=>",
"[",
"[",
"'invoice'",
",",... | Sends refund receipt email
@param integer $iRefundId The ID of the refund
@param string $sEmailOverride The email address to send the email to
@return bool | [
"Sends",
"refund",
"receipt",
"email"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L286-L362 | train |
nails/module-invoice | src/Model/Refund.php | Refund.getRefundForEvent | protected function getRefundForEvent(int $iRefundId): Resource
{
$oRefund = $this->getById($iRefundId);
if (empty($oRefund)) {
throw new ModelException('Invalid refund ID');
}
return $oRefund;
} | php | protected function getRefundForEvent(int $iRefundId): Resource
{
$oRefund = $this->getById($iRefundId);
if (empty($oRefund)) {
throw new ModelException('Invalid refund ID');
}
return $oRefund;
} | [
"protected",
"function",
"getRefundForEvent",
"(",
"int",
"$",
"iRefundId",
")",
":",
"Resource",
"{",
"$",
"oRefund",
"=",
"$",
"this",
"->",
"getById",
"(",
"$",
"iRefundId",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"oRefund",
")",
")",
"{",
"throw",
... | Get a refund in a suitable format for the event triggers
@param int $iRefundId The refund ID
@return Resource
@throws ModelException | [
"Get",
"a",
"refund",
"in",
"a",
"suitable",
"format",
"for",
"the",
"event",
"triggers"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Refund.php#L374-L381 | train |
Saritasa/php-laravel-entity-services | src/LaravelEntityServicesServiceProvider.php | LaravelEntityServicesServiceProvider.boot | public function boot(): void
{
$this->publishes(
[
__DIR__ . '/../config/laravel_entity_services.php' =>
$this->app->make('path.config') . DIRECTORY_SEPARATOR . 'laravel_entity_services.php',
],
'laravel_repositories'
);
$this->mergeConfigFrom(__DIR__ . '/../config/laravel_entity_services.php', 'laravel_entity_services');
$this->registerCustomBindings();
} | php | public function boot(): void
{
$this->publishes(
[
__DIR__ . '/../config/laravel_entity_services.php' =>
$this->app->make('path.config') . DIRECTORY_SEPARATOR . 'laravel_entity_services.php',
],
'laravel_repositories'
);
$this->mergeConfigFrom(__DIR__ . '/../config/laravel_entity_services.php', 'laravel_entity_services');
$this->registerCustomBindings();
} | [
"public",
"function",
"boot",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/../config/laravel_entity_services.php'",
"=>",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"'path.config'",
")",
".",
"DIRECTORY_SEPARATOR",... | Make package settings needed to correct work.
@return void
@throws BindingResolutionException | [
"Make",
"package",
"settings",
"needed",
"to",
"correct",
"work",
"."
] | 7cac8e05d8a067ac269ce141e94b18b8b89e5493 | https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/LaravelEntityServicesServiceProvider.php#L33-L45 | train |
Saritasa/php-laravel-entity-services | src/LaravelEntityServicesServiceProvider.php | LaravelEntityServicesServiceProvider.registerCustomBindings | protected function registerCustomBindings(): void
{
$entityServiceFactory = $this->app->make(IEntityServiceFactory::class);
foreach (config('laravel_entity_services.bindings') as $className => $entityService) {
$entityServiceFactory->register($className, $entityService);
}
} | php | protected function registerCustomBindings(): void
{
$entityServiceFactory = $this->app->make(IEntityServiceFactory::class);
foreach (config('laravel_entity_services.bindings') as $className => $entityService) {
$entityServiceFactory->register($className, $entityService);
}
} | [
"protected",
"function",
"registerCustomBindings",
"(",
")",
":",
"void",
"{",
"$",
"entityServiceFactory",
"=",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"IEntityServiceFactory",
"::",
"class",
")",
";",
"foreach",
"(",
"config",
"(",
"'laravel_entity_servic... | Register custom entity services implementations.
@return void
@throws BindingResolutionException | [
"Register",
"custom",
"entity",
"services",
"implementations",
"."
] | 7cac8e05d8a067ac269ce141e94b18b8b89e5493 | https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/LaravelEntityServicesServiceProvider.php#L54-L61 | train |
Saritasa/php-laravel-entity-services | src/Services/EntityService.php | EntityService.getValidationRulesForAttributes | protected function getValidationRulesForAttributes(array $modelParams, array $rules = []): array
{
$modelRules = empty($rules) ? $this->getValidationRules() : $rules;
return array_intersect_key($modelRules, $modelParams);
} | php | protected function getValidationRulesForAttributes(array $modelParams, array $rules = []): array
{
$modelRules = empty($rules) ? $this->getValidationRules() : $rules;
return array_intersect_key($modelRules, $modelParams);
} | [
"protected",
"function",
"getValidationRulesForAttributes",
"(",
"array",
"$",
"modelParams",
",",
"array",
"$",
"rules",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"modelRules",
"=",
"empty",
"(",
"$",
"rules",
")",
"?",
"$",
"this",
"->",
"getValidation... | Return rules for given attributes.
@param array $modelParams Updating fields
@param array $rules Custom validation rules
@return array | [
"Return",
"rules",
"for",
"given",
"attributes",
"."
] | 7cac8e05d8a067ac269ce141e94b18b8b89e5493 | https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityService.php#L120-L124 | train |
Saritasa/php-laravel-entity-services | src/Services/EntityService.php | EntityService.validate | protected function validate(array $data, array $rules = null): void
{
$validator = $this->validatorFactory->make($data, $rules ?? $this->getValidationRules());
if ($validator->fails()) {
throw new ValidationException($validator);
}
} | php | protected function validate(array $data, array $rules = null): void
{
$validator = $this->validatorFactory->make($data, $rules ?? $this->getValidationRules());
if ($validator->fails()) {
throw new ValidationException($validator);
}
} | [
"protected",
"function",
"validate",
"(",
"array",
"$",
"data",
",",
"array",
"$",
"rules",
"=",
"null",
")",
":",
"void",
"{",
"$",
"validator",
"=",
"$",
"this",
"->",
"validatorFactory",
"->",
"make",
"(",
"$",
"data",
",",
"$",
"rules",
"??",
"$"... | Validates data.
@param array $data Data to validate
@param array|null $rules Validation rules
@throws ValidationException
@return void | [
"Validates",
"data",
"."
] | 7cac8e05d8a067ac269ce141e94b18b8b89e5493 | https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityService.php#L163-L169 | train |
Saritasa/php-laravel-entity-services | src/Services/EntityService.php | EntityService.getValidationRules | protected function getValidationRules(): array
{
$validationRulesFromRepository = $this->repository->getModelValidationRules();
return !empty($validationRulesFromRepository) ? $validationRulesFromRepository : $this->validationRules;
} | php | protected function getValidationRules(): array
{
$validationRulesFromRepository = $this->repository->getModelValidationRules();
return !empty($validationRulesFromRepository) ? $validationRulesFromRepository : $this->validationRules;
} | [
"protected",
"function",
"getValidationRules",
"(",
")",
":",
"array",
"{",
"$",
"validationRulesFromRepository",
"=",
"$",
"this",
"->",
"repository",
"->",
"getModelValidationRules",
"(",
")",
";",
"return",
"!",
"empty",
"(",
"$",
"validationRulesFromRepository",... | Returns validation rules.
@return array | [
"Returns",
"validation",
"rules",
"."
] | 7cac8e05d8a067ac269ce141e94b18b8b89e5493 | https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityService.php#L176-L181 | train |
canihavesomecoffee/theTVDbAPI | src/MultiLanguageWrapper/Route/EpisodesRouteLanguageFallback.php | EpisodesRouteLanguageFallback.getClosureById | public function getClosureById(int $episodeId): Closure
{
return function ($language) use ($episodeId) {
$json = $this->parent->performAPICallWithJsonResponse(
'get',
'/episodes/'.$episodeId,
[
'headers' => ['Accept-Language' => $language]
]
);
return DataParser::parseData($json, Episode::class);
};
} | php | public function getClosureById(int $episodeId): Closure
{
return function ($language) use ($episodeId) {
$json = $this->parent->performAPICallWithJsonResponse(
'get',
'/episodes/'.$episodeId,
[
'headers' => ['Accept-Language' => $language]
]
);
return DataParser::parseData($json, Episode::class);
};
} | [
"public",
"function",
"getClosureById",
"(",
"int",
"$",
"episodeId",
")",
":",
"Closure",
"{",
"return",
"function",
"(",
"$",
"language",
")",
"use",
"(",
"$",
"episodeId",
")",
"{",
"$",
"json",
"=",
"$",
"this",
"->",
"parent",
"->",
"performAPICallW... | Returns the closure used to fetch an episode by id
for a single language.
@param int $episodeId The episode to fetch.
@return Closure | [
"Returns",
"the",
"closure",
"used",
"to",
"fetch",
"an",
"episode",
"by",
"id",
"for",
"a",
"single",
"language",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/Route/EpisodesRouteLanguageFallback.php#L79-L91 | train |
QoboLtd/qobo-robo | src/AbstractTask.php | AbstractTask.printInfo | protected function printInfo($msg, $data = null)
{
// pass-through when no 'name' found in data
if ($data == null || !isset($data['name'])) {
return $this->printTaskInfo($msg, $data);
}
// doubt someone will use this ever in data
$key = 'print_task_info_name_replacement_macro';
// replace 'name' with above key both in data
// and in msg placeholders
$data[$key] = $data['name'];
unset($data['name']);
$msg = str_replace('{name}', '{' . $key . '}', $msg);
// print nice message
$result = $this->printTaskInfo($msg, $data);
return $result;
} | php | protected function printInfo($msg, $data = null)
{
// pass-through when no 'name' found in data
if ($data == null || !isset($data['name'])) {
return $this->printTaskInfo($msg, $data);
}
// doubt someone will use this ever in data
$key = 'print_task_info_name_replacement_macro';
// replace 'name' with above key both in data
// and in msg placeholders
$data[$key] = $data['name'];
unset($data['name']);
$msg = str_replace('{name}', '{' . $key . '}', $msg);
// print nice message
$result = $this->printTaskInfo($msg, $data);
return $result;
} | [
"protected",
"function",
"printInfo",
"(",
"$",
"msg",
",",
"$",
"data",
"=",
"null",
")",
"{",
"// pass-through when no 'name' found in data",
"if",
"(",
"$",
"data",
"==",
"null",
"||",
"!",
"isset",
"(",
"$",
"data",
"[",
"'name'",
"]",
")",
")",
"{",... | A quick fix on printInfo, as it is not very friendly
when you use 'name' placeholders or even just have 'name'
set in the data | [
"A",
"quick",
"fix",
"on",
"printInfo",
"as",
"it",
"is",
"not",
"very",
"friendly",
"when",
"you",
"use",
"name",
"placeholders",
"or",
"even",
"just",
"have",
"name",
"set",
"in",
"the",
"data"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/AbstractTask.php#L156-L176 | train |
byjg/restserver | src/HttpResponse.php | HttpResponse.addCookie | public function addCookie($name, $value, $expire = null, $path = null, $domain = null)
{
if (!is_null($expire)) {
$expire = time() + $expire;
}
setcookie($name, $value, $expire, $path, $domain);
} | php | public function addCookie($name, $value, $expire = null, $path = null, $domain = null)
{
if (!is_null($expire)) {
$expire = time() + $expire;
}
setcookie($name, $value, $expire, $path, $domain);
} | [
"public",
"function",
"addCookie",
"(",
"$",
"name",
",",
"$",
"value",
",",
"$",
"expire",
"=",
"null",
",",
"$",
"path",
"=",
"null",
",",
"$",
"domain",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"expire",
")",
")",
"{",
"$"... | Add a cookie value
@param string $name
@param string $value
@param int $expire (seconds from now)
@param int $path (directory into domain in which the cookie will be available on )
@param string $domain | [
"Add",
"a",
"cookie",
"value"
] | 1fdbd58f414f5d9958de0873d67eea961dc52fda | https://github.com/byjg/restserver/blob/1fdbd58f414f5d9958de0873d67eea961dc52fda/src/HttpResponse.php#L63-L69 | train |
byjg/restserver | src/HttpResponse.php | HttpResponse.writeDebug | public function writeDebug($key, $string)
{
if (is_null($this->responseDebug)) {
$this->responseDebug = new ResponseBag();
$this->response->add($this->responseDebug);
}
$this->responseDebug->add(['debug' => [$key => $string]]);
ErrorHandler::getInstance()->addExtraInfo($key, serialize($string));
} | php | public function writeDebug($key, $string)
{
if (is_null($this->responseDebug)) {
$this->responseDebug = new ResponseBag();
$this->response->add($this->responseDebug);
}
$this->responseDebug->add(['debug' => [$key => $string]]);
ErrorHandler::getInstance()->addExtraInfo($key, serialize($string));
} | [
"public",
"function",
"writeDebug",
"(",
"$",
"key",
",",
"$",
"string",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"responseDebug",
")",
")",
"{",
"$",
"this",
"->",
"responseDebug",
"=",
"new",
"ResponseBag",
"(",
")",
";",
"$",
"this"... | Added informations for debug purposes only.
In case the error it will showed and the result a node called "debug" will be added.
@param string $key
@param mixed $string | [
"Added",
"informations",
"for",
"debug",
"purposes",
"only",
".",
"In",
"case",
"the",
"error",
"it",
"will",
"showed",
"and",
"the",
"result",
"a",
"node",
"called",
"debug",
"will",
"be",
"added",
"."
] | 1fdbd58f414f5d9958de0873d67eea961dc52fda | https://github.com/byjg/restserver/blob/1fdbd58f414f5d9958de0873d67eea961dc52fda/src/HttpResponse.php#L110-L118 | train |
wikimedia/mediawiki-oauthclient-php | src/Client.php | Client.makeOAuthCall | public function makeOAuthCall(
/*Token*/ $token, $url, $isPost = false, array $postFields = null
) {
// Figure out if there is a file in postFields
$hasFile = false;
if ( is_array( $postFields ) ) {
foreach ( $postFields as $field ) {
if ( is_a( $field, 'CurlFile' ) ) {
$hasFile = true;
break;
}
}
}
$params = [];
// Get any params from the url
if ( strpos( $url, '?' ) ) {
$parsed = parse_url( $url );
parse_str( $parsed['query'], $params );
}
$params += $this->extraParams;
if ( $isPost && $postFields && !$hasFile ) {
$params += $postFields;
}
$method = $isPost ? 'POST' : 'GET';
$req = Request::fromConsumerAndToken(
$this->config->consumer,
$token,
$method,
$url,
$params
);
$req->signRequest(
new HmacSha1(),
$this->config->consumer,
$token
);
$this->lastNonce = $req->getParameter( 'oauth_nonce' );
return $this->makeCurlCall(
$url,
$req->toHeader(),
$isPost,
$postFields,
$hasFile
);
} | php | public function makeOAuthCall(
/*Token*/ $token, $url, $isPost = false, array $postFields = null
) {
// Figure out if there is a file in postFields
$hasFile = false;
if ( is_array( $postFields ) ) {
foreach ( $postFields as $field ) {
if ( is_a( $field, 'CurlFile' ) ) {
$hasFile = true;
break;
}
}
}
$params = [];
// Get any params from the url
if ( strpos( $url, '?' ) ) {
$parsed = parse_url( $url );
parse_str( $parsed['query'], $params );
}
$params += $this->extraParams;
if ( $isPost && $postFields && !$hasFile ) {
$params += $postFields;
}
$method = $isPost ? 'POST' : 'GET';
$req = Request::fromConsumerAndToken(
$this->config->consumer,
$token,
$method,
$url,
$params
);
$req->signRequest(
new HmacSha1(),
$this->config->consumer,
$token
);
$this->lastNonce = $req->getParameter( 'oauth_nonce' );
return $this->makeCurlCall(
$url,
$req->toHeader(),
$isPost,
$postFields,
$hasFile
);
} | [
"public",
"function",
"makeOAuthCall",
"(",
"/*Token*/",
"$",
"token",
",",
"$",
"url",
",",
"$",
"isPost",
"=",
"false",
",",
"array",
"$",
"postFields",
"=",
"null",
")",
"{",
"// Figure out if there is a file in postFields",
"$",
"hasFile",
"=",
"false",
";... | Make a signed request to MediaWiki
@param Token $token additional token to use in signature, besides
the consumer token. In most cases, this will be the access token you
got from complete(), but we set it to the request token when
finishing the handshake.
@param string $url URL to call
@param bool $isPost true if this should be a POST request
@param array|null $postFields POST parameters, only if $isPost is also true
@return string Body from the curl request
@throws Exception On curl failure | [
"Make",
"a",
"signed",
"request",
"to",
"MediaWiki"
] | 1c8b33ff91273ba50e987d380724add7051d31ea | https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Client.php#L224-L269 | train |
wikimedia/mediawiki-oauthclient-php | src/Client.php | Client.compareHash | private function compareHash( $hash1, $hash2 ) {
$result = strlen( $hash1 ) ^ strlen( $hash2 );
$len = min( strlen( $hash1 ), strlen( $hash2 ) ) - 1;
for ( $i = 0; $i < $len; $i++ ) {
$result |= ord( $hash1{$i} ) ^ ord( $hash2{$i} );
}
return $result == 0;
} | php | private function compareHash( $hash1, $hash2 ) {
$result = strlen( $hash1 ) ^ strlen( $hash2 );
$len = min( strlen( $hash1 ), strlen( $hash2 ) ) - 1;
for ( $i = 0; $i < $len; $i++ ) {
$result |= ord( $hash1{$i} ) ^ ord( $hash2{$i} );
}
return $result == 0;
} | [
"private",
"function",
"compareHash",
"(",
"$",
"hash1",
",",
"$",
"hash2",
")",
"{",
"$",
"result",
"=",
"strlen",
"(",
"$",
"hash1",
")",
"^",
"strlen",
"(",
"$",
"hash2",
")",
";",
"$",
"len",
"=",
"min",
"(",
"strlen",
"(",
"$",
"hash1",
")",... | Constant time comparison
@param string $hash1
@param string $hash2
@return bool | [
"Constant",
"time",
"comparison"
] | 1c8b33ff91273ba50e987d380724add7051d31ea | https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Client.php#L410-L417 | train |
wikimedia/mediawiki-oauthclient-php | src/Client.php | Client.decodeJson | private function decodeJson( $json ) {
$error = $errorMsg = null;
$return = json_decode( $json );
if ( $return === null && trim( $json ) !== 'null' ) {
$error = json_last_error();
$errorMsg = json_last_error_msg();
} elseif ( !$return || !is_object( $return ) ) {
$error = 128;
$errorMsg = 'Response must be an object';
}
if ( $error ) {
$this->logger->error(
'Failed to decode server response as JSON: {message}',
[
'response' => $json,
'code' => json_last_error(),
'message' => json_last_error_msg(),
]
);
throw new Exception( 'Decoding server response failed: ' . json_last_error_msg()
. " (Raw response: $json)" );
}
return $return;
} | php | private function decodeJson( $json ) {
$error = $errorMsg = null;
$return = json_decode( $json );
if ( $return === null && trim( $json ) !== 'null' ) {
$error = json_last_error();
$errorMsg = json_last_error_msg();
} elseif ( !$return || !is_object( $return ) ) {
$error = 128;
$errorMsg = 'Response must be an object';
}
if ( $error ) {
$this->logger->error(
'Failed to decode server response as JSON: {message}',
[
'response' => $json,
'code' => json_last_error(),
'message' => json_last_error_msg(),
]
);
throw new Exception( 'Decoding server response failed: ' . json_last_error_msg()
. " (Raw response: $json)" );
}
return $return;
} | [
"private",
"function",
"decodeJson",
"(",
"$",
"json",
")",
"{",
"$",
"error",
"=",
"$",
"errorMsg",
"=",
"null",
";",
"$",
"return",
"=",
"json_decode",
"(",
"$",
"json",
")",
";",
"if",
"(",
"$",
"return",
"===",
"null",
"&&",
"trim",
"(",
"$",
... | Like json_decode but with sane error handling.
Assumes that null is not a valid value for the JSON string.
@param string $json
@return mixed
@throws Exception On invalid JSON | [
"Like",
"json_decode",
"but",
"with",
"sane",
"error",
"handling",
".",
"Assumes",
"that",
"null",
"is",
"not",
"a",
"valid",
"value",
"for",
"the",
"JSON",
"string",
"."
] | 1c8b33ff91273ba50e987d380724add7051d31ea | https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Client.php#L426-L450 | train |
QoboLtd/qobo-robo | src/Command/Project/Version.php | Version.projectVersion | public function projectVersion($opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskDotenvReload()->run();
$envVersion = getenv('GIT_BRANCH');
if (!empty($envVersion)) {
return new PropertyList(['version' => $envVersion]);
}
$result = $this->taskGitHash()->run();
if ($result->wasSuccessful()) {
return new PropertyList(['version' => $result->getData()['data'][0]['message'] ]);
}
return new PropertyList(['version' => 'Unknown']);
} | php | public function projectVersion($opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskDotenvReload()->run();
$envVersion = getenv('GIT_BRANCH');
if (!empty($envVersion)) {
return new PropertyList(['version' => $envVersion]);
}
$result = $this->taskGitHash()->run();
if ($result->wasSuccessful()) {
return new PropertyList(['version' => $result->getData()['data'][0]['message'] ]);
}
return new PropertyList(['version' => 'Unknown']);
} | [
"public",
"function",
"projectVersion",
"(",
"$",
"opts",
"=",
"[",
"'format'",
"=>",
"'table'",
",",
"'fields'",
"=>",
"''",
"]",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"taskDotenvReload",
"(",
")",
"->",
"run",
"(",
")",
";",
"$",
"envVer... | Get project version
@option string $format Output format (table, list, csv, json, xml)
@option string $fields Limit output to given fields, comma-separated
@return PropertyList result | [
"Get",
"project",
"version"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Project/Version.php#L27-L42 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.getStates | public function getStates(): array
{
return [
self::STATE_DRAFT => 'Draft',
self::STATE_OPEN => 'Open',
self::STATE_PAID_PARTIAL => 'Partially Paid',
self::STATE_PAID_PROCESSING => 'Paid (payments processing)',
self::STATE_PAID => 'Paid',
self::STATE_WRITTEN_OFF => 'Written Off',
self::STATE_CANCELLED => 'Cancelled',
];
} | php | public function getStates(): array
{
return [
self::STATE_DRAFT => 'Draft',
self::STATE_OPEN => 'Open',
self::STATE_PAID_PARTIAL => 'Partially Paid',
self::STATE_PAID_PROCESSING => 'Paid (payments processing)',
self::STATE_PAID => 'Paid',
self::STATE_WRITTEN_OFF => 'Written Off',
self::STATE_CANCELLED => 'Cancelled',
];
} | [
"public",
"function",
"getStates",
"(",
")",
":",
"array",
"{",
"return",
"[",
"self",
"::",
"STATE_DRAFT",
"=>",
"'Draft'",
",",
"self",
"::",
"STATE_OPEN",
"=>",
"'Open'",
",",
"self",
"::",
"STATE_PAID_PARTIAL",
"=>",
"'Partially Paid'",
",",
"self",
"::"... | Returns the invoice states with human friendly names
@return array | [
"Returns",
"the",
"invoice",
"states",
"with",
"human",
"friendly",
"names"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L120-L131 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.update | public function update($mIds, array $aData = []): bool
{
// @todo (Pablo - 2019-03-06) - Support passing in multiple IDs so as to be compatible with parent
$oDb = Factory::service('Database');
try {
$sKeyExistsCustomerId = array_key_exists('customer_id', $aData);
$sKeyExistsEmail = array_key_exists('email', $aData);
if ($sKeyExistsCustomerId && $sKeyExistsEmail) {
throw new InvoiceException('An invoice cannot be assigned to both an email and a customer.', 1);
}
if ($sKeyExistsCustomerId && empty($aData['customer_id'])) {
throw new InvoiceException('If supplied, "customer_id" cannot be empty.', 1);
} elseif ($sKeyExistsCustomerId && $sKeyExistsEmail) {
// Ensure the email field is empty if it has been supplied
$aData['email'] = null;
}
if ($sKeyExistsEmail && empty($aData['email'])) {
throw new InvoiceException('If supplied, "email" cannot be empty.', 1);
} elseif ($sKeyExistsEmail && $sKeyExistsCustomerId) {
// Ensure the customer_id field is empty if it has been supplied
$aData['customer_id'] = null;
}
$oDb->trans_begin();
$this->prepareInvoice($aData, $mIds);
if (array_key_exists('items', $aData)) {
$aItems = $aData['items'];
unset($aData['items']);
}
unset($aData['ref']);
unset($aData['token']);
$bResult = parent::update($mIds, $aData);
if (!$bResult) {
throw new InvoiceException('Failed to update invoice.', 1);
}
if (!empty($aItems)) {
$this->updateLineItems($mIds, $aItems);
}
$oDb->trans_commit();
$this->triggerEvent(
Events::INVOICE_UPDATED,
[$this->getInvoiceForEvent($mIds)]
);
return $bResult;
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->setError($e->getMessage());
return false;
}
} | php | public function update($mIds, array $aData = []): bool
{
// @todo (Pablo - 2019-03-06) - Support passing in multiple IDs so as to be compatible with parent
$oDb = Factory::service('Database');
try {
$sKeyExistsCustomerId = array_key_exists('customer_id', $aData);
$sKeyExistsEmail = array_key_exists('email', $aData);
if ($sKeyExistsCustomerId && $sKeyExistsEmail) {
throw new InvoiceException('An invoice cannot be assigned to both an email and a customer.', 1);
}
if ($sKeyExistsCustomerId && empty($aData['customer_id'])) {
throw new InvoiceException('If supplied, "customer_id" cannot be empty.', 1);
} elseif ($sKeyExistsCustomerId && $sKeyExistsEmail) {
// Ensure the email field is empty if it has been supplied
$aData['email'] = null;
}
if ($sKeyExistsEmail && empty($aData['email'])) {
throw new InvoiceException('If supplied, "email" cannot be empty.', 1);
} elseif ($sKeyExistsEmail && $sKeyExistsCustomerId) {
// Ensure the customer_id field is empty if it has been supplied
$aData['customer_id'] = null;
}
$oDb->trans_begin();
$this->prepareInvoice($aData, $mIds);
if (array_key_exists('items', $aData)) {
$aItems = $aData['items'];
unset($aData['items']);
}
unset($aData['ref']);
unset($aData['token']);
$bResult = parent::update($mIds, $aData);
if (!$bResult) {
throw new InvoiceException('Failed to update invoice.', 1);
}
if (!empty($aItems)) {
$this->updateLineItems($mIds, $aItems);
}
$oDb->trans_commit();
$this->triggerEvent(
Events::INVOICE_UPDATED,
[$this->getInvoiceForEvent($mIds)]
);
return $bResult;
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->setError($e->getMessage());
return false;
}
} | [
"public",
"function",
"update",
"(",
"$",
"mIds",
",",
"array",
"$",
"aData",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"// @todo (Pablo - 2019-03-06) - Support passing in multiple IDs so as to be compatible with parent",
"$",
"oDb",
"=",
"Factory",
"::",
"service",
"(",... | Update an invoice
@param int|array $mIds The ID (or array of IDs) of the object(s) to update
@param array $aData The data to update the object(s) with
@return bool
@throws FactoryException | [
"Update",
"an",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L341-L405 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.updateLineItems | protected function updateLineItems(int $iInvoiceId, array $aItems): void
{
$oItemModel = Factory::model('InvoiceItem', 'nails/module-invoice');
$aTouchedIds = [];
// Update/insert all known items
foreach ($aItems as $aItem) {
$aData = [
'label' => getFromArray('label', $aItem, null),
'body' => getFromArray('body', $aItem, null),
'order' => getFromArray('order', $aItem, 0),
'currency' => getFromArray('currency', $aItem, null),
'unit' => getFromArray('unit', $aItem, null),
'tax_id' => getFromArray('tax_id', $aItem, null),
'quantity' => getFromArray('quantity', $aItem, 1),
'unit_cost' => getFromArray('unit_cost', $aItem, 0),
'sub_total' => getFromArray('sub_total', $aItem, 0),
'tax_total' => getFromArray('tax_total', $aItem, 0),
'grand_total' => getFromArray('grand_total', $aItem, 0),
'callback_data' => getFromArray('callback_data', $aItem, null),
];
// Ensure callback data is encoded as JSON
if (array_key_exists('callback_data', $aData)) {
$aData['callback_data'] = json_encode($aData['callback_data']);
}
if (!empty($aItem['id'])) {
// Update
if (!$oItemModel->update($aItem['id'], $aData)) {
throw new InvoiceException('Failed to update invoice item.', 1);
} else {
$aTouchedIds[] = $aItem['id'];
}
} else {
// Insert
$aData['invoice_id'] = $iInvoiceId;
$iItemId = $oItemModel->create($aData);
if (!$iItemId) {
throw new InvoiceException('Failed to create invoice item.', 1);
} else {
$aTouchedIds[] = $iItemId;
}
}
}
// Delete those we no longer require
if (!empty($aTouchedIds)) {
$oDb = Factory::service('Database');
$oDb->where_not_in('id', $aTouchedIds);
$oDb->where('invoice_id', $iInvoiceId);
if (!$oDb->delete($oItemModel->getTableName())) {
throw new InvoiceException('Failed to delete old invoice items.', 1);
}
}
} | php | protected function updateLineItems(int $iInvoiceId, array $aItems): void
{
$oItemModel = Factory::model('InvoiceItem', 'nails/module-invoice');
$aTouchedIds = [];
// Update/insert all known items
foreach ($aItems as $aItem) {
$aData = [
'label' => getFromArray('label', $aItem, null),
'body' => getFromArray('body', $aItem, null),
'order' => getFromArray('order', $aItem, 0),
'currency' => getFromArray('currency', $aItem, null),
'unit' => getFromArray('unit', $aItem, null),
'tax_id' => getFromArray('tax_id', $aItem, null),
'quantity' => getFromArray('quantity', $aItem, 1),
'unit_cost' => getFromArray('unit_cost', $aItem, 0),
'sub_total' => getFromArray('sub_total', $aItem, 0),
'tax_total' => getFromArray('tax_total', $aItem, 0),
'grand_total' => getFromArray('grand_total', $aItem, 0),
'callback_data' => getFromArray('callback_data', $aItem, null),
];
// Ensure callback data is encoded as JSON
if (array_key_exists('callback_data', $aData)) {
$aData['callback_data'] = json_encode($aData['callback_data']);
}
if (!empty($aItem['id'])) {
// Update
if (!$oItemModel->update($aItem['id'], $aData)) {
throw new InvoiceException('Failed to update invoice item.', 1);
} else {
$aTouchedIds[] = $aItem['id'];
}
} else {
// Insert
$aData['invoice_id'] = $iInvoiceId;
$iItemId = $oItemModel->create($aData);
if (!$iItemId) {
throw new InvoiceException('Failed to create invoice item.', 1);
} else {
$aTouchedIds[] = $iItemId;
}
}
}
// Delete those we no longer require
if (!empty($aTouchedIds)) {
$oDb = Factory::service('Database');
$oDb->where_not_in('id', $aTouchedIds);
$oDb->where('invoice_id', $iInvoiceId);
if (!$oDb->delete($oItemModel->getTableName())) {
throw new InvoiceException('Failed to delete old invoice items.', 1);
}
}
} | [
"protected",
"function",
"updateLineItems",
"(",
"int",
"$",
"iInvoiceId",
",",
"array",
"$",
"aItems",
")",
":",
"void",
"{",
"$",
"oItemModel",
"=",
"Factory",
"::",
"model",
"(",
"'InvoiceItem'",
",",
"'nails/module-invoice'",
")",
";",
"$",
"aTouchedIds",
... | Update the line items of an invoice
@param int $iInvoiceId The invoice ID
@param array $aItems The items to update
@throws FactoryException
@throws InvoiceException | [
"Update",
"the",
"line",
"items",
"of",
"an",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L638-L699 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.generateValidRef | public function generateValidRef(): string
{
Factory::helper('string');
$oDb = Factory::service('Database');
$oNow = Factory::factory('DateTime');
do {
$sRef = $oNow->format('Ym') . '-' . strtoupper(random_string('alnum'));
$oDb->where('ref', $sRef);
$bRefExists = (bool) $oDb->count_all_results($this->table);
} while ($bRefExists);
return $sRef;
} | php | public function generateValidRef(): string
{
Factory::helper('string');
$oDb = Factory::service('Database');
$oNow = Factory::factory('DateTime');
do {
$sRef = $oNow->format('Ym') . '-' . strtoupper(random_string('alnum'));
$oDb->where('ref', $sRef);
$bRefExists = (bool) $oDb->count_all_results($this->table);
} while ($bRefExists);
return $sRef;
} | [
"public",
"function",
"generateValidRef",
"(",
")",
":",
"string",
"{",
"Factory",
"::",
"helper",
"(",
"'string'",
")",
";",
"$",
"oDb",
"=",
"Factory",
"::",
"service",
"(",
"'Database'",
")",
";",
"$",
"oNow",
"=",
"Factory",
"::",
"factory",
"(",
"... | Generates a valid invoice ref
@return string
@throws FactoryException | [
"Generates",
"a",
"valid",
"invoice",
"ref"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L725-L741 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.isPaid | public function isPaid(int $iInvoiceId, bool $bIncludeProcessing = false): bool
{
$oInvoice = $this->getById($iInvoiceId);
if (!empty($oInvoice)) {
$iPaid = $oInvoice->totals->raw->paid;
if ($bIncludeProcessing) {
$iPaid += $oInvoice->totals->raw->processing;
}
return $iPaid >= $oInvoice->totals->raw->grand;
}
return false;
} | php | public function isPaid(int $iInvoiceId, bool $bIncludeProcessing = false): bool
{
$oInvoice = $this->getById($iInvoiceId);
if (!empty($oInvoice)) {
$iPaid = $oInvoice->totals->raw->paid;
if ($bIncludeProcessing) {
$iPaid += $oInvoice->totals->raw->processing;
}
return $iPaid >= $oInvoice->totals->raw->grand;
}
return false;
} | [
"public",
"function",
"isPaid",
"(",
"int",
"$",
"iInvoiceId",
",",
"bool",
"$",
"bIncludeProcessing",
"=",
"false",
")",
":",
"bool",
"{",
"$",
"oInvoice",
"=",
"$",
"this",
"->",
"getById",
"(",
"$",
"iInvoiceId",
")",
";",
"if",
"(",
"!",
"empty",
... | Whether an invoice has been fully paid or not
@param int $iInvoiceId The Invoice to query
@param bool $bIncludeProcessing Whether to include payments which are still processing
@return bool
@throws ModelException | [
"Whether",
"an",
"invoice",
"has",
"been",
"fully",
"paid",
"or",
"not"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L838-L853 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.setPaid | public function setPaid($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_PAID,
'paid' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_PAID,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | php | public function setPaid($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_PAID,
'paid' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_PAID,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | [
"public",
"function",
"setPaid",
"(",
"$",
"iInvoiceId",
")",
":",
"bool",
"{",
"$",
"oNow",
"=",
"Factory",
"::",
"factory",
"(",
"'DateTime'",
")",
";",
"$",
"bResult",
"=",
"$",
"this",
"->",
"update",
"(",
"$",
"iInvoiceId",
",",
"[",
"'state'",
... | Set an invoice as paid
@param int $iInvoiceId The Invoice to query
@return bool
@throws ModelException
@throws FactoryException | [
"Set",
"an",
"invoice",
"as",
"paid"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L866-L885 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.setPaidProcessing | public function setPaidProcessing($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_PAID_PROCESSING,
'paid' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_PAID_PROCESSING,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | php | public function setPaidProcessing($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_PAID_PROCESSING,
'paid' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_PAID_PROCESSING,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | [
"public",
"function",
"setPaidProcessing",
"(",
"$",
"iInvoiceId",
")",
":",
"bool",
"{",
"$",
"oNow",
"=",
"Factory",
"::",
"factory",
"(",
"'DateTime'",
")",
";",
"$",
"bResult",
"=",
"$",
"this",
"->",
"update",
"(",
"$",
"iInvoiceId",
",",
"[",
"'s... | Set an invoice as paid but with processing payments
@param int $iInvoiceId The Invoice to query
@return bool
@throws ModelException
@throws FactoryException | [
"Set",
"an",
"invoice",
"as",
"paid",
"but",
"with",
"processing",
"payments"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L898-L917 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.setWrittenOff | public function setWrittenOff($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_WRITTEN_OFF,
'written_off' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_WRITTEN_OFF,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | php | public function setWrittenOff($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_WRITTEN_OFF,
'written_off' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_WRITTEN_OFF,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | [
"public",
"function",
"setWrittenOff",
"(",
"$",
"iInvoiceId",
")",
":",
"bool",
"{",
"$",
"oNow",
"=",
"Factory",
"::",
"factory",
"(",
"'DateTime'",
")",
";",
"$",
"bResult",
"=",
"$",
"this",
"->",
"update",
"(",
"$",
"iInvoiceId",
",",
"[",
"'state... | Set an invoice as written off
@param int $iInvoiceId The Invoice to query
@return bool
@throws ModelException
@throws FactoryException | [
"Set",
"an",
"invoice",
"as",
"written",
"off"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L930-L949 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.setCancelled | public function setCancelled($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_CANCELLED,
'written_off' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_CANCELLED,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | php | public function setCancelled($iInvoiceId): bool
{
$oNow = Factory::factory('DateTime');
$bResult = $this->update(
$iInvoiceId,
[
'state' => self::STATE_CANCELLED,
'written_off' => $oNow->format('Y-m-d H:i:s'),
]
);
if ($bResult) {
$this->triggerEvent(
Events::INVOICE_CANCELLED,
[$this->getInvoiceForEvent($iInvoiceId)]
);
}
return $bResult;
} | [
"public",
"function",
"setCancelled",
"(",
"$",
"iInvoiceId",
")",
":",
"bool",
"{",
"$",
"oNow",
"=",
"Factory",
"::",
"factory",
"(",
"'DateTime'",
")",
";",
"$",
"bResult",
"=",
"$",
"this",
"->",
"update",
"(",
"$",
"iInvoiceId",
",",
"[",
"'state'... | Set an invoice as cancelled
@param int $iInvoiceId The Invoice to query
@return bool
@throws ModelException
@throws FactoryException | [
"Set",
"an",
"invoice",
"as",
"cancelled"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L962-L981 | train |
nails/module-invoice | src/Model/Invoice.php | Invoice.getInvoiceForEvent | protected function getInvoiceForEvent(int $iInvoiceId): Resource
{
$oInvoice = $this->getById($iInvoiceId, ['expand' => ['customer', 'items']]);
if (empty($oInvoice)) {
throw new ModelException('Invalid invoice ID');
}
return $oInvoice;
} | php | protected function getInvoiceForEvent(int $iInvoiceId): Resource
{
$oInvoice = $this->getById($iInvoiceId, ['expand' => ['customer', 'items']]);
if (empty($oInvoice)) {
throw new ModelException('Invalid invoice ID');
}
return $oInvoice;
} | [
"protected",
"function",
"getInvoiceForEvent",
"(",
"int",
"$",
"iInvoiceId",
")",
":",
"Resource",
"{",
"$",
"oInvoice",
"=",
"$",
"this",
"->",
"getById",
"(",
"$",
"iInvoiceId",
",",
"[",
"'expand'",
"=>",
"[",
"'customer'",
",",
"'items'",
"]",
"]",
... | Get an invoice in a suitable format for the event triggers
@param int $iInvoiceId The invoice ID
@return Resource
@throws ModelException | [
"Get",
"an",
"invoice",
"in",
"a",
"suitable",
"format",
"for",
"the",
"event",
"triggers"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Model/Invoice.php#L993-L1000 | train |
canihavesomecoffee/theTVDbAPI | src/DataParser.php | DataParser.parseDataArray | public static function parseDataArray($json, string $returnClass): array
{
$result = [];
if (is_array($json)) {
foreach ($json as $entry) {
$result[] = static::parseData($entry, $returnClass);
}
}
return $result;
} | php | public static function parseDataArray($json, string $returnClass): array
{
$result = [];
if (is_array($json)) {
foreach ($json as $entry) {
$result[] = static::parseData($entry, $returnClass);
}
}
return $result;
} | [
"public",
"static",
"function",
"parseDataArray",
"(",
"$",
"json",
",",
"string",
"$",
"returnClass",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"json",
")",
")",
"{",
"foreach",
"(",
"$",
"json",
"... | Parses the given JSON data into an array of return_class instances.
@param object $json The JSON data. Must be valid
@param string $returnClass The expected return class
@return array | [
"Parses",
"the",
"given",
"JSON",
"data",
"into",
"an",
"array",
"of",
"return_class",
"instances",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/DataParser.php#L75-L84 | train |
canihavesomecoffee/theTVDbAPI | src/DataParser.php | DataParser.getSerializer | private static function getSerializer(): Serializer
{
if (static::$serializer === null) {
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
static::$serializer = new Serializer(
[new ObjectNormalizer(null, null, null, $extractor)],
[new JsonEncoder()]
);
}
return static::$serializer;
} | php | private static function getSerializer(): Serializer
{
if (static::$serializer === null) {
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
static::$serializer = new Serializer(
[new ObjectNormalizer(null, null, null, $extractor)],
[new JsonEncoder()]
);
}
return static::$serializer;
} | [
"private",
"static",
"function",
"getSerializer",
"(",
")",
":",
"Serializer",
"{",
"if",
"(",
"static",
"::",
"$",
"serializer",
"===",
"null",
")",
"{",
"$",
"extractor",
"=",
"new",
"PropertyInfoExtractor",
"(",
"[",
"]",
",",
"[",
"new",
"PhpDocExtract... | Gets the serializer instance.
@return Serializer An instance of the Serializer. | [
"Gets",
"the",
"serializer",
"instance",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/DataParser.php#L91-L101 | train |
nails/module-invoice | src/Factory/ResponseBase.php | ResponseBase.setStatus | public function setStatus($sStatus)
{
if (!$this->bIsLocked) {
$aStatuses = $this->getStatuses();
if (!in_array($sStatus, $aStatuses)) {
throw new ResponseException('"' . $sStatus . '" is an invalid response status.', 1);
}
$this->sStatus = $sStatus;
}
return $this;
} | php | public function setStatus($sStatus)
{
if (!$this->bIsLocked) {
$aStatuses = $this->getStatuses();
if (!in_array($sStatus, $aStatuses)) {
throw new ResponseException('"' . $sStatus . '" is an invalid response status.', 1);
}
$this->sStatus = $sStatus;
}
return $this;
} | [
"public",
"function",
"setStatus",
"(",
"$",
"sStatus",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"bIsLocked",
")",
"{",
"$",
"aStatuses",
"=",
"$",
"this",
"->",
"getStatuses",
"(",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"sStatus",
","... | Returns the current status of the response
@param string $sStatus The status to set
@throws ResponseException
@return string | [
"Returns",
"the",
"current",
"status",
"of",
"the",
"response"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ResponseBase.php#L94-L107 | train |
nails/module-invoice | src/Factory/ResponseBase.php | ResponseBase.setStatusFailed | public function setStatusFailed($sReasonMsg, $sReasonCode, $sUserFeedback = '')
{
$this->sErrorMsg = trim($sReasonMsg);
$this->sErrorCode = trim($sReasonCode);
$this->sErrorUser = trim($sUserFeedback);
return $this->setStatus(self::STATUS_FAILED);
} | php | public function setStatusFailed($sReasonMsg, $sReasonCode, $sUserFeedback = '')
{
$this->sErrorMsg = trim($sReasonMsg);
$this->sErrorCode = trim($sReasonCode);
$this->sErrorUser = trim($sUserFeedback);
return $this->setStatus(self::STATUS_FAILED);
} | [
"public",
"function",
"setStatusFailed",
"(",
"$",
"sReasonMsg",
",",
"$",
"sReasonCode",
",",
"$",
"sUserFeedback",
"=",
"''",
")",
"{",
"$",
"this",
"->",
"sErrorMsg",
"=",
"trim",
"(",
"$",
"sReasonMsg",
")",
";",
"$",
"this",
"->",
"sErrorCode",
"=",... | Set the status as FAILED
@param string $sReasonMsg The exception message, logged against the payment and not shown to the customer
@param string $sReasonCode The exception code, logged against the payment and not shown to the customer
@param string $sUserFeedback The message to show to the user explaining the error
@return string | [
"Set",
"the",
"status",
"as",
"FAILED"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/ResponseBase.php#L153-L160 | train |
anomalylabs/variables-module | src/Http/Controller/Admin/VersionsController.php | VersionsController.index | public function index(VersionTableBuilder $table)
{
/**
* Mimic the parent controllers method.
*/
$table
->setType($this->getModel())
->setId($this->request->route('id'));
$versionable = $table->getVersionableInstance();
if ($current = $versionable->getCurrentVersion()) {
$table->setCurrent($current);
}
/* @var ControlPanelBuilder $controlPanel */
$controlPanel = $this->container->make(ControlPanelBuilder::class);
$section = $controlPanel->getControlPanelActiveSection();
/**
* Mimic the default table buttons handler
* and override the href so that we edit
* the group and not the versionable ID.
*/
$table->setButtons(
[
'load' => [
'href' => $section->getHref(
'edit/{request.input.group}?version={entry.version}&versionable={entry.versionable_type}'
),
'disabled' => function (VersionInterface $entry) use ($current) {
if ($current->getVersion() !== $entry->getVersion()) {
return false;
}
return true;
},
],
]
);
return $table->render();
} | php | public function index(VersionTableBuilder $table)
{
/**
* Mimic the parent controllers method.
*/
$table
->setType($this->getModel())
->setId($this->request->route('id'));
$versionable = $table->getVersionableInstance();
if ($current = $versionable->getCurrentVersion()) {
$table->setCurrent($current);
}
/* @var ControlPanelBuilder $controlPanel */
$controlPanel = $this->container->make(ControlPanelBuilder::class);
$section = $controlPanel->getControlPanelActiveSection();
/**
* Mimic the default table buttons handler
* and override the href so that we edit
* the group and not the versionable ID.
*/
$table->setButtons(
[
'load' => [
'href' => $section->getHref(
'edit/{request.input.group}?version={entry.version}&versionable={entry.versionable_type}'
),
'disabled' => function (VersionInterface $entry) use ($current) {
if ($current->getVersion() !== $entry->getVersion()) {
return false;
}
return true;
},
],
]
);
return $table->render();
} | [
"public",
"function",
"index",
"(",
"VersionTableBuilder",
"$",
"table",
")",
"{",
"/**\n * Mimic the parent controllers method.\n */",
"$",
"table",
"->",
"setType",
"(",
"$",
"this",
"->",
"getModel",
"(",
")",
")",
"->",
"setId",
"(",
"$",
"this... | Return a list of versions for the variable group.
@param VersionTableBuilder $table
@param $id
@return \Symfony\Component\HttpFoundation\Response | [
"Return",
"a",
"list",
"of",
"versions",
"for",
"the",
"variable",
"group",
"."
] | bcd903670471a175f07aba3123693cb3a3c07d0b | https://github.com/anomalylabs/variables-module/blob/bcd903670471a175f07aba3123693cb3a3c07d0b/src/Http/Controller/Admin/VersionsController.php#L45-L90 | train |
canihavesomecoffee/theTVDbAPI | src/MultiLanguageWrapper/ClassValidator.php | ClassValidator.isValid | public function isValid(string $returnTypeClass, $instance): bool
{
if (array_key_exists($returnTypeClass, $this->getRequiredFields()) === false) {
return false;
}
foreach ($this->getRequiredFields()[$returnTypeClass] as $property) {
if (is_array($instance)) {
foreach ($instance as $item) {
if ($item->{$property} === null) {
return false;
}
}
} elseif ($instance->{$property} === null) {
return false;
}
}
return true;
} | php | public function isValid(string $returnTypeClass, $instance): bool
{
if (array_key_exists($returnTypeClass, $this->getRequiredFields()) === false) {
return false;
}
foreach ($this->getRequiredFields()[$returnTypeClass] as $property) {
if (is_array($instance)) {
foreach ($instance as $item) {
if ($item->{$property} === null) {
return false;
}
}
} elseif ($instance->{$property} === null) {
return false;
}
}
return true;
} | [
"public",
"function",
"isValid",
"(",
"string",
"$",
"returnTypeClass",
",",
"$",
"instance",
")",
":",
"bool",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"returnTypeClass",
",",
"$",
"this",
"->",
"getRequiredFields",
"(",
")",
")",
"===",
"false",
")"... | Checks if for a given instance the required fields are not null.
@param string $returnTypeClass The class type of the instance.
@param object|array $instance The instance to check.
@return bool | [
"Checks",
"if",
"for",
"a",
"given",
"instance",
"the",
"required",
"fields",
"are",
"not",
"null",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/ClassValidator.php#L52-L69 | train |
canihavesomecoffee/theTVDbAPI | src/MultiLanguageWrapper/ClassValidator.php | ClassValidator.merge | public function merge(string $returnTypeClass, $existingInstance, $newInstance)
{
if ($existingInstance === null) {
return $newInstance;
}
if (array_key_exists($returnTypeClass, $this->getRequiredFields()) && $newInstance !== null) {
foreach ($this->getRequiredFields()[$returnTypeClass] as $property) {
if (is_array($existingInstance)) {
$existingInstanceSize = sizeof($existingInstance);
for ($index = 0; $index < $existingInstanceSize; $index++) {
if ($existingInstance[$index]->{$property} === null) {
$existingInstance[$index]->{$property} = $newInstance[$index]->{$property};
}
}
} elseif ($existingInstance->{$property} === null) {
$existingInstance->{$property} = $newInstance->{$property};
}
}
}
return $existingInstance;
} | php | public function merge(string $returnTypeClass, $existingInstance, $newInstance)
{
if ($existingInstance === null) {
return $newInstance;
}
if (array_key_exists($returnTypeClass, $this->getRequiredFields()) && $newInstance !== null) {
foreach ($this->getRequiredFields()[$returnTypeClass] as $property) {
if (is_array($existingInstance)) {
$existingInstanceSize = sizeof($existingInstance);
for ($index = 0; $index < $existingInstanceSize; $index++) {
if ($existingInstance[$index]->{$property} === null) {
$existingInstance[$index]->{$property} = $newInstance[$index]->{$property};
}
}
} elseif ($existingInstance->{$property} === null) {
$existingInstance->{$property} = $newInstance->{$property};
}
}
}
return $existingInstance;
} | [
"public",
"function",
"merge",
"(",
"string",
"$",
"returnTypeClass",
",",
"$",
"existingInstance",
",",
"$",
"newInstance",
")",
"{",
"if",
"(",
"$",
"existingInstance",
"===",
"null",
")",
"{",
"return",
"$",
"newInstance",
";",
"}",
"if",
"(",
"array_ke... | Merges two instances together by replacing missing values that are required.
@param string $returnTypeClass The class type of the instances.
@param object|array $existingInstance The instance that already exists.
@param object|array $newInstance The instance to be merged.
@return mixed | [
"Merges",
"two",
"instances",
"together",
"by",
"replacing",
"missing",
"values",
"that",
"are",
"required",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/MultiLanguageWrapper/ClassValidator.php#L80-L100 | train |
nails/module-invoice | admin/controllers/Customer.php | Customer.edit | public function edit()
{
if (!userHasPermission('admin:invoice:customer:edit')) {
unauthorised();
}
$oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
$oUri = Factory::service('Uri');
$itemId = (int) $oUri->segment(5);
$this->data['item'] = $oCustomerModel->getById(
$itemId,
['expand' => $oCustomerModel::EXPAND_ALL]
);
if (empty($this->data['item'])) {
show404();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
if ($oInput->post()) {
try {
$this->formValidation();
if (!$oCustomerModel->update($itemId, $this->prepPostData())) {
throw new NailsException('Failed to update item. ' . $oCustomerModel->lastError(), 1);
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('success', 'Item updated successfully.');
redirect('admin/invoice/customer');
} catch (\Exception $e) {
$this->data['error'] = $e->getMessage();
}
}
// --------------------------------------------------------------------------
$this->data['page']->title = 'Edit customer';
Helper::loadView('edit');
} | php | public function edit()
{
if (!userHasPermission('admin:invoice:customer:edit')) {
unauthorised();
}
$oCustomerModel = Factory::model('Customer', 'nails/module-invoice');
$oUri = Factory::service('Uri');
$itemId = (int) $oUri->segment(5);
$this->data['item'] = $oCustomerModel->getById(
$itemId,
['expand' => $oCustomerModel::EXPAND_ALL]
);
if (empty($this->data['item'])) {
show404();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
if ($oInput->post()) {
try {
$this->formValidation();
if (!$oCustomerModel->update($itemId, $this->prepPostData())) {
throw new NailsException('Failed to update item. ' . $oCustomerModel->lastError(), 1);
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('success', 'Item updated successfully.');
redirect('admin/invoice/customer');
} catch (\Exception $e) {
$this->data['error'] = $e->getMessage();
}
}
// --------------------------------------------------------------------------
$this->data['page']->title = 'Edit customer';
Helper::loadView('edit');
} | [
"public",
"function",
"edit",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:invoice:customer:edit'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"$",
"oCustomerModel",
"=",
"Factory",
"::",
"model",
"(",
"'Customer'",
",",
"'nails/m... | Edit an existing customer
@return void | [
"Edit",
"an",
"existing",
"customer"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Customer.php#L189-L234 | train |
nails/module-invoice | admin/controllers/Customer.php | Customer.formValidation | protected function formValidation()
{
$aRules = [
'first_name' => 'max_length[255]',
'last_name' => 'max_length[255]',
'organisation' => 'max_length[255]',
'email' => 'max_length[255]|valid_email|required',
'billing_email' => 'max_length[255]|valid_email',
'telephone' => 'max_length[25]',
'vat_number' => 'max_length[25]',
'billing_address_line_1' => 'max_length[255]',
'billing_address_line_2' => 'max_length[255]',
'billing_address_town' => 'max_length[255]',
'billing_address_county' => 'max_length[255]',
'billing_address_postcode' => 'max_length[255]',
'billing_address_country' => 'max_length[255]',
];
$oFormValidation = Factory::service('FormValidation');
foreach ($aRules as $sKey => $sRule) {
$oFormValidation->set_rules($sKey, '', $sRule);
}
$oFormValidation->set_message('required', lang('fv_required'));
$oFormValidation->set_message('max_length', lang('fv_max_length'));
$oFormValidation->set_message('valid_email', lang('fv_valid_email'));
if (!$oFormValidation->run()) {
throw new NailsException(lang('fv_there_were_errors'), 1);
}
// First/Last name is required if no organisation is provided
$oInput = Factory::service('Input');
$sOrganisation = $oInput->post('organisation');
$sFirstName = $oInput->post('first_name');
$sLastName = $oInput->post('last_name');
if (empty($sOrganisation) && (empty($sFirstName) || empty($sLastName))) {
throw new NailsException('First name and surname are required if not providing an organisation.', 1);
}
} | php | protected function formValidation()
{
$aRules = [
'first_name' => 'max_length[255]',
'last_name' => 'max_length[255]',
'organisation' => 'max_length[255]',
'email' => 'max_length[255]|valid_email|required',
'billing_email' => 'max_length[255]|valid_email',
'telephone' => 'max_length[25]',
'vat_number' => 'max_length[25]',
'billing_address_line_1' => 'max_length[255]',
'billing_address_line_2' => 'max_length[255]',
'billing_address_town' => 'max_length[255]',
'billing_address_county' => 'max_length[255]',
'billing_address_postcode' => 'max_length[255]',
'billing_address_country' => 'max_length[255]',
];
$oFormValidation = Factory::service('FormValidation');
foreach ($aRules as $sKey => $sRule) {
$oFormValidation->set_rules($sKey, '', $sRule);
}
$oFormValidation->set_message('required', lang('fv_required'));
$oFormValidation->set_message('max_length', lang('fv_max_length'));
$oFormValidation->set_message('valid_email', lang('fv_valid_email'));
if (!$oFormValidation->run()) {
throw new NailsException(lang('fv_there_were_errors'), 1);
}
// First/Last name is required if no organisation is provided
$oInput = Factory::service('Input');
$sOrganisation = $oInput->post('organisation');
$sFirstName = $oInput->post('first_name');
$sLastName = $oInput->post('last_name');
if (empty($sOrganisation) && (empty($sFirstName) || empty($sLastName))) {
throw new NailsException('First name and surname are required if not providing an organisation.', 1);
}
} | [
"protected",
"function",
"formValidation",
"(",
")",
"{",
"$",
"aRules",
"=",
"[",
"'first_name'",
"=>",
"'max_length[255]'",
",",
"'last_name'",
"=>",
"'max_length[255]'",
",",
"'organisation'",
"=>",
"'max_length[255]'",
",",
"'email'",
"=>",
"'max_length[255]|valid... | Runs form validation
@return void | [
"Runs",
"form",
"validation"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Customer.php#L242-L281 | train |
canihavesomecoffee/theTVDbAPI | src/Route/UsersRoute.php | UsersRoute.removeFavorite | public function removeFavorite(int $seriesId): bool
{
$response = $this->parent->performAPICall('delete', '/user/favorites/'.$seriesId);
return $response->getStatusCode() === 200;
} | php | public function removeFavorite(int $seriesId): bool
{
$response = $this->parent->performAPICall('delete', '/user/favorites/'.$seriesId);
return $response->getStatusCode() === 200;
} | [
"public",
"function",
"removeFavorite",
"(",
"int",
"$",
"seriesId",
")",
":",
"bool",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parent",
"->",
"performAPICall",
"(",
"'delete'",
",",
"'/user/favorites/'",
".",
"$",
"seriesId",
")",
";",
"return",
"$"... | Remove series from favorites.
@param int $seriesId The id of the series to remove.
@return bool True if the series was removed from the user's favourites. | [
"Remove",
"series",
"from",
"favorites",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Route/UsersRoute.php#L76-L80 | train |
canihavesomecoffee/theTVDbAPI | src/Route/UsersRoute.php | UsersRoute.addRating | public function addRating(Rating $rating): bool
{
$response = $this->parent->performAPICall(
'put',
'user/ratings/'.$rating->getRatingType().'/'.$rating->ratingItemId.'/'.$rating->rating
);
return $response->getStatusCode() === 200;
} | php | public function addRating(Rating $rating): bool
{
$response = $this->parent->performAPICall(
'put',
'user/ratings/'.$rating->getRatingType().'/'.$rating->ratingItemId.'/'.$rating->rating
);
return $response->getStatusCode() === 200;
} | [
"public",
"function",
"addRating",
"(",
"Rating",
"$",
"rating",
")",
":",
"bool",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"parent",
"->",
"performAPICall",
"(",
"'put'",
",",
"'user/ratings/'",
".",
"$",
"rating",
"->",
"getRatingType",
"(",
")",
... | Adds a user rating.
@param Rating $rating The rating to add.
@return bool True on success, false on failure. | [
"Adds",
"a",
"user",
"rating",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Route/UsersRoute.php#L127-L134 | train |
canihavesomecoffee/theTVDbAPI | src/Model/PaginatedResults.php | PaginatedResults.getLinkElement | private function getLinkElement(string $key): int
{
$link = -1;
if (array_key_exists($key, $this->links)) {
$link = intval($this->links[$key], 10);
}
return $link;
} | php | private function getLinkElement(string $key): int
{
$link = -1;
if (array_key_exists($key, $this->links)) {
$link = intval($this->links[$key], 10);
}
return $link;
} | [
"private",
"function",
"getLinkElement",
"(",
"string",
"$",
"key",
")",
":",
"int",
"{",
"$",
"link",
"=",
"-",
"1",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"links",
")",
")",
"{",
"$",
"link",
"=",
"intval",
... | Fetches a link element from the array.
@param string $key The element to retrieve.
@return int The element if found, or -1 if not. | [
"Fetches",
"a",
"link",
"element",
"from",
"the",
"array",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Model/PaginatedResults.php#L123-L130 | train |
Saritasa/php-laravel-entity-services | src/Services/EntityServiceFactory.php | EntityServiceFactory.buildEntityService | protected function buildEntityService(string $modelClass): IEntityService
{
try {
if (isset($this->registeredServices[$modelClass])) {
return $this->container->make($this->registeredServices[$modelClass]);
}
return $this->container->make(EntityService::class, [
'className' => $modelClass,
'repository' => $this->repositoryFactory->getRepository($modelClass),
]);
} catch (RepositoryException $exception) {
throw new EntityServiceException($exception->getMessage(), $exception->getCode(), $exception);
}
} | php | protected function buildEntityService(string $modelClass): IEntityService
{
try {
if (isset($this->registeredServices[$modelClass])) {
return $this->container->make($this->registeredServices[$modelClass]);
}
return $this->container->make(EntityService::class, [
'className' => $modelClass,
'repository' => $this->repositoryFactory->getRepository($modelClass),
]);
} catch (RepositoryException $exception) {
throw new EntityServiceException($exception->getMessage(), $exception->getCode(), $exception);
}
} | [
"protected",
"function",
"buildEntityService",
"(",
"string",
"$",
"modelClass",
")",
":",
"IEntityService",
"{",
"try",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"registeredServices",
"[",
"$",
"modelClass",
"]",
")",
")",
"{",
"return",
"$",
"this... | Build entity service by model class from registered instances or creates default.
@param string $modelClass Model class to build entity service
@return IEntityService
@throws EntityServiceException
@throws BindingResolutionException | [
"Build",
"entity",
"service",
"by",
"model",
"class",
"from",
"registered",
"instances",
"or",
"creates",
"default",
"."
] | 7cac8e05d8a067ac269ce141e94b18b8b89e5493 | https://github.com/Saritasa/php-laravel-entity-services/blob/7cac8e05d8a067ac269ce141e94b18b8b89e5493/src/Services/EntityServiceFactory.php#L83-L97 | train |
wikimedia/mediawiki-oauthclient-php | src/Request.php | Request.fromRequest | public static function fromRequest(
$method = null,
$url = null,
array $params = null
) {
$scheme = ( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] != 'on' ) ?
'http' : 'https';
$url = ( $url ?: $scheme ) .
'://' . $_SERVER['SERVER_NAME'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
$method = $method ?: $_SERVER['REQUEST_METHOD'];
// We weren't handed any params, so let's find the ones relevant
// to this request. If you run XML-RPC or similar you should use this
// to provide your own parsed parameter-list
if ( !$params ) {
// Find request headers
$headers = Util::getHeaders();
// Parse the query-string to find GET params
$params = Util::parseParameters( $_SERVER['QUERY_STRING'] );
// It's a POST request of the proper content-type, so parse POST
// params and add those overriding any duplicates from GET
if ( $method === 'POST' &&
isset( $headers['Content-Type'] ) &&
strstr( $headers['Content-Type'],
'application/x-www-form-urlencoded'
)
) {
$post_data = Util::parseParameters(
file_get_contents( self::$POST_INPUT )
);
$params = array_merge( $params, $post_data );
}
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
if ( isset( $headers['Authorization'] ) &&
substr( $headers['Authorization'], 0, 6 ) === 'OAuth '
) {
$header_params = Util::splitHeader( $headers['Authorization'] );
$params = array_merge( $params, $header_params );
}
}
return new Request( $method, $url, $params );
} | php | public static function fromRequest(
$method = null,
$url = null,
array $params = null
) {
$scheme = ( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] != 'on' ) ?
'http' : 'https';
$url = ( $url ?: $scheme ) .
'://' . $_SERVER['SERVER_NAME'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
$method = $method ?: $_SERVER['REQUEST_METHOD'];
// We weren't handed any params, so let's find the ones relevant
// to this request. If you run XML-RPC or similar you should use this
// to provide your own parsed parameter-list
if ( !$params ) {
// Find request headers
$headers = Util::getHeaders();
// Parse the query-string to find GET params
$params = Util::parseParameters( $_SERVER['QUERY_STRING'] );
// It's a POST request of the proper content-type, so parse POST
// params and add those overriding any duplicates from GET
if ( $method === 'POST' &&
isset( $headers['Content-Type'] ) &&
strstr( $headers['Content-Type'],
'application/x-www-form-urlencoded'
)
) {
$post_data = Util::parseParameters(
file_get_contents( self::$POST_INPUT )
);
$params = array_merge( $params, $post_data );
}
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
if ( isset( $headers['Authorization'] ) &&
substr( $headers['Authorization'], 0, 6 ) === 'OAuth '
) {
$header_params = Util::splitHeader( $headers['Authorization'] );
$params = array_merge( $params, $header_params );
}
}
return new Request( $method, $url, $params );
} | [
"public",
"static",
"function",
"fromRequest",
"(",
"$",
"method",
"=",
"null",
",",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"params",
"=",
"null",
")",
"{",
"$",
"scheme",
"=",
"(",
"!",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
")",
... | Attempt to build up a request from what was passed to the server
@param string|null $method
@param string|null $url
@param array|null $params
@return Request | [
"Attempt",
"to",
"build",
"up",
"a",
"request",
"from",
"what",
"was",
"passed",
"to",
"the",
"server"
] | 1c8b33ff91273ba50e987d380724add7051d31ea | https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Request.php#L84-L133 | train |
wikimedia/mediawiki-oauthclient-php | src/Request.php | Request.toUrl | public function toUrl() {
$post_data = $this->toPostData();
$out = $this->getNormalizedUrl();
if ( $post_data ) {
$out .= '?' . $post_data;
}
return $out;
} | php | public function toUrl() {
$post_data = $this->toPostData();
$out = $this->getNormalizedUrl();
if ( $post_data ) {
$out .= '?' . $post_data;
}
return $out;
} | [
"public",
"function",
"toUrl",
"(",
")",
"{",
"$",
"post_data",
"=",
"$",
"this",
"->",
"toPostData",
"(",
")",
";",
"$",
"out",
"=",
"$",
"this",
"->",
"getNormalizedUrl",
"(",
")",
";",
"if",
"(",
"$",
"post_data",
")",
"{",
"$",
"out",
".=",
"... | Builds a url usable for a GET request
@return string | [
"Builds",
"a",
"url",
"usable",
"for",
"a",
"GET",
"request"
] | 1c8b33ff91273ba50e987d380724add7051d31ea | https://github.com/wikimedia/mediawiki-oauthclient-php/blob/1c8b33ff91273ba50e987d380724add7051d31ea/src/Request.php#L278-L285 | train |
anomalylabs/variables-module | src/Http/Controller/Admin/VariablesController.php | VariablesController.edit | public function edit(StreamRepositoryInterface $streams, VariableFormBuilder $form, $id)
{
/* @var StreamInterface $group */
$group = $streams->find($id);
$entry = $group->getEntryModel()->firstOrNew([]);
return $form->setModel($group->getEntryModelName())->render($entry);
} | php | public function edit(StreamRepositoryInterface $streams, VariableFormBuilder $form, $id)
{
/* @var StreamInterface $group */
$group = $streams->find($id);
$entry = $group->getEntryModel()->firstOrNew([]);
return $form->setModel($group->getEntryModelName())->render($entry);
} | [
"public",
"function",
"edit",
"(",
"StreamRepositoryInterface",
"$",
"streams",
",",
"VariableFormBuilder",
"$",
"form",
",",
"$",
"id",
")",
"{",
"/* @var StreamInterface $group */",
"$",
"group",
"=",
"$",
"streams",
"->",
"find",
"(",
"$",
"id",
")",
";",
... | Return a form to edit the variables.
@param StreamRepositoryInterface $streams
@param VariableFormBuilder $form
@param $id
@return \Symfony\Component\HttpFoundation\Response | [
"Return",
"a",
"form",
"to",
"edit",
"the",
"variables",
"."
] | bcd903670471a175f07aba3123693cb3a3c07d0b | https://github.com/anomalylabs/variables-module/blob/bcd903670471a175f07aba3123693cb3a3c07d0b/src/Http/Controller/Admin/VariablesController.php#L40-L48 | train |
orchestral/support | src/Providers/Concerns/AliasesProvider.php | AliasesProvider.registerFacadesAliases | protected function registerFacadesAliases(): void
{
$loader = AliasLoader::getInstance();
foreach ((array) $this->facades as $facade => $aliases) {
foreach ((array) $aliases as $alias) {
$loader->alias($alias, $facade);
}
}
} | php | protected function registerFacadesAliases(): void
{
$loader = AliasLoader::getInstance();
foreach ((array) $this->facades as $facade => $aliases) {
foreach ((array) $aliases as $alias) {
$loader->alias($alias, $facade);
}
}
} | [
"protected",
"function",
"registerFacadesAliases",
"(",
")",
":",
"void",
"{",
"$",
"loader",
"=",
"AliasLoader",
"::",
"getInstance",
"(",
")",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"facades",
"as",
"$",
"facade",
"=>",
"$",
"aliase... | Register facades aliases.
@return void | [
"Register",
"facades",
"aliases",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Providers/Concerns/AliasesProvider.php#L14-L23 | train |
nails/module-invoice | src/Factory/Invoice.php | Invoice.addItem | public function addItem(Item $oItem)
{
if (empty(!$this->iId)) {
throw new InvoiceException('Invoice has been saved and cannot be modified.');
}
$this->aItems[] = $oItem;
return $this;
} | php | public function addItem(Item $oItem)
{
if (empty(!$this->iId)) {
throw new InvoiceException('Invoice has been saved and cannot be modified.');
}
$this->aItems[] = $oItem;
return $this;
} | [
"public",
"function",
"addItem",
"(",
"Item",
"$",
"oItem",
")",
"{",
"if",
"(",
"empty",
"(",
"!",
"$",
"this",
"->",
"iId",
")",
")",
"{",
"throw",
"new",
"InvoiceException",
"(",
"'Invoice has been saved and cannot be modified.'",
")",
";",
"}",
"$",
"t... | Add an item to the invoice
@param Item $oItem the item to add
@return $this
@throws InvoiceException | [
"Add",
"an",
"item",
"to",
"the",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L153-L160 | train |
nails/module-invoice | src/Factory/Invoice.php | Invoice.save | public function save()
{
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
if (empty($this->iId)) {
$oInvoice = $oInvoiceModel->create($this->toArray(), true);
if (empty($oInvoice)) {
throw new InvoiceException($oInvoiceModel->lastError());
}
$this->iId = $oInvoice->id;
$this->sRef = $oInvoice->ref;
} else {
$oInvoice = $oInvoiceModel->getById($this->iId);
}
return $oInvoice;
} | php | public function save()
{
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
if (empty($this->iId)) {
$oInvoice = $oInvoiceModel->create($this->toArray(), true);
if (empty($oInvoice)) {
throw new InvoiceException($oInvoiceModel->lastError());
}
$this->iId = $oInvoice->id;
$this->sRef = $oInvoice->ref;
} else {
$oInvoice = $oInvoiceModel->getById($this->iId);
}
return $oInvoice;
} | [
"public",
"function",
"save",
"(",
")",
"{",
"$",
"oInvoiceModel",
"=",
"Factory",
"::",
"model",
"(",
"'Invoice'",
",",
"'nails/module-invoice'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"iId",
")",
")",
"{",
"$",
"oInvoice",
"=",
"$",
... | Saves a new invoice
@return \stdClass
@throws InvoiceException | [
"Saves",
"a",
"new",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L186-L200 | train |
nails/module-invoice | src/Factory/Invoice.php | Invoice.delete | public function delete()
{
if (!empty($this->iId)) {
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
if (!$oInvoiceModel->delete($this->iId)) {
throw new InvoiceException('Failed to delete invoice.');
}
}
return $this;
} | php | public function delete()
{
if (!empty($this->iId)) {
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
if (!$oInvoiceModel->delete($this->iId)) {
throw new InvoiceException('Failed to delete invoice.');
}
}
return $this;
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"iId",
")",
")",
"{",
"$",
"oInvoiceModel",
"=",
"Factory",
"::",
"model",
"(",
"'Invoice'",
",",
"'nails/module-invoice'",
")",
";",
"if",
"(",
"!",
"$",... | Deletes an invoice
@return $this
@throws InvoiceException | [
"Deletes",
"an",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L209-L219 | train |
nails/module-invoice | src/Factory/Invoice.php | Invoice.writeOff | public function writeOff()
{
if (!empty($this->iId)) {
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
if (!$oInvoiceModel->setWrittenOff($this->iId)) {
throw new InvoiceException('Failed to write off invoice.');
}
}
return $this;
} | php | public function writeOff()
{
if (!empty($this->iId)) {
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
if (!$oInvoiceModel->setWrittenOff($this->iId)) {
throw new InvoiceException('Failed to write off invoice.');
}
}
return $this;
} | [
"public",
"function",
"writeOff",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"iId",
")",
")",
"{",
"$",
"oInvoiceModel",
"=",
"Factory",
"::",
"model",
"(",
"'Invoice'",
",",
"'nails/module-invoice'",
")",
";",
"if",
"(",
"!",
"$... | Writes an invoice off
@return $this
@throws InvoiceException | [
"Writes",
"an",
"invoice",
"off"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L228-L238 | train |
nails/module-invoice | src/Factory/Invoice.php | Invoice.charge | public function charge(ChargeRequest $oChargeRequest)
{
if (empty($this->iId)) {
$oInvoice = $this->save();
} else {
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
$oInvoice = $oInvoiceModel->getById($this->iId);
}
$oChargeRequest->setInvoice($this->iId);
$oChargeRequest->setDescription('Payment for invoice ' . $this->sRef);
return $oChargeRequest->execute(
$oInvoice->totals->raw->grand,
$oInvoice->currency->code
);
} | php | public function charge(ChargeRequest $oChargeRequest)
{
if (empty($this->iId)) {
$oInvoice = $this->save();
} else {
$oInvoiceModel = Factory::model('Invoice', 'nails/module-invoice');
$oInvoice = $oInvoiceModel->getById($this->iId);
}
$oChargeRequest->setInvoice($this->iId);
$oChargeRequest->setDescription('Payment for invoice ' . $this->sRef);
return $oChargeRequest->execute(
$oInvoice->totals->raw->grand,
$oInvoice->currency->code
);
} | [
"public",
"function",
"charge",
"(",
"ChargeRequest",
"$",
"oChargeRequest",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"iId",
")",
")",
"{",
"$",
"oInvoice",
"=",
"$",
"this",
"->",
"save",
"(",
")",
";",
"}",
"else",
"{",
"$",
"oInvoic... | Charges an invoice
@param ChargeRequest $oChargeRequest
@return ChargeResponse
@throws InvoiceException | [
"Charges",
"an",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/src/Factory/Invoice.php#L250-L265 | train |
QoboLtd/qobo-robo | src/Utility/Template.php | Template.getTokens | public static function getTokens($template, $pre = '%%', $post = '%%')
{
$tokens = [];
$regex = "/$pre(.*?)$post/";
if (preg_match_all($regex, $template, $matches)) {
$tokens = array_unique($matches[1]);
}
natsort($tokens);
return $tokens;
} | php | public static function getTokens($template, $pre = '%%', $post = '%%')
{
$tokens = [];
$regex = "/$pre(.*?)$post/";
if (preg_match_all($regex, $template, $matches)) {
$tokens = array_unique($matches[1]);
}
natsort($tokens);
return $tokens;
} | [
"public",
"static",
"function",
"getTokens",
"(",
"$",
"template",
",",
"$",
"pre",
"=",
"'%%'",
",",
"$",
"post",
"=",
"'%%'",
")",
"{",
"$",
"tokens",
"=",
"[",
"]",
";",
"$",
"regex",
"=",
"\"/$pre(.*?)$post/\"",
";",
"if",
"(",
"preg_match_all",
... | Returns a list of unique tokens found in a given template
@param string $template Template content
@param string $pre Token prefix
@param string $post Token postfix
@return array List of tokens | [
"Returns",
"a",
"list",
"of",
"unique",
"tokens",
"found",
"in",
"a",
"given",
"template"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Utility/Template.php#L40-L51 | train |
QoboLtd/qobo-robo | src/Utility/Template.php | Template.parse | public static function parse(
$template,
array $tokens,
$pre = '%%',
$post = '%%',
$flags = self::FLAG_RECURSIVE | self::FLAG_STRICT
) {
// nothing to do with empty templates or when no tokens given
if (empty($template) || empty($tokens)) {
return $template;
}
// FLAG_EMPTY_MISSING and FLAG_STRICT are mutually exclusive
if (($flags & self::FLAG_EMPTY_MISSING) && ($flags & self::FLAG_STRICT)) {
throw new InvalidArgumentException("Can't use FLAG_EMPTY_MISSING and FLAG_STRICT together");
}
// replace the tokens with their values
$result = $template;
foreach ($tokens as $token => $replacement) {
$token = "$pre$token$post";
$result = str_replace($token, $replacement, $result);
}
if ($flags & self::FLAG_RECURSIVE) {
$recursiveResult = self::parse($result, $tokens, $pre, $post, $flags xor self::FLAG_RECURSIVE);
if ($result <> $recursiveResult) {
$result = self::parse($result, $pre, $post, $flags);
}
}
// check for any tokens left in the result
$remainingTokens = self::getTokens($result, $pre, $post);
// ok if no tokens left
if (empty($remainingTokens)) {
return $result;
}
// throw exception if in strict mode
if ($flags & self::FLAG_STRICT) {
throw new RuntimeException("Missing values for [" . implode(", ", $remainingTokens) . "] tokens");
}
// replace unknown tokens with empty string if FLAG_EMPTY_MISSING
if ($flags & self::FLAG_EMPTY_MISSING) {
$tokens = [];
foreach ($remainingTokens as $token) {
$tokens[$token] = "";
}
return self::parse($result, $tokens, $pre, $post);
}
return $result;
} | php | public static function parse(
$template,
array $tokens,
$pre = '%%',
$post = '%%',
$flags = self::FLAG_RECURSIVE | self::FLAG_STRICT
) {
// nothing to do with empty templates or when no tokens given
if (empty($template) || empty($tokens)) {
return $template;
}
// FLAG_EMPTY_MISSING and FLAG_STRICT are mutually exclusive
if (($flags & self::FLAG_EMPTY_MISSING) && ($flags & self::FLAG_STRICT)) {
throw new InvalidArgumentException("Can't use FLAG_EMPTY_MISSING and FLAG_STRICT together");
}
// replace the tokens with their values
$result = $template;
foreach ($tokens as $token => $replacement) {
$token = "$pre$token$post";
$result = str_replace($token, $replacement, $result);
}
if ($flags & self::FLAG_RECURSIVE) {
$recursiveResult = self::parse($result, $tokens, $pre, $post, $flags xor self::FLAG_RECURSIVE);
if ($result <> $recursiveResult) {
$result = self::parse($result, $pre, $post, $flags);
}
}
// check for any tokens left in the result
$remainingTokens = self::getTokens($result, $pre, $post);
// ok if no tokens left
if (empty($remainingTokens)) {
return $result;
}
// throw exception if in strict mode
if ($flags & self::FLAG_STRICT) {
throw new RuntimeException("Missing values for [" . implode(", ", $remainingTokens) . "] tokens");
}
// replace unknown tokens with empty string if FLAG_EMPTY_MISSING
if ($flags & self::FLAG_EMPTY_MISSING) {
$tokens = [];
foreach ($remainingTokens as $token) {
$tokens[$token] = "";
}
return self::parse($result, $tokens, $pre, $post);
}
return $result;
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"template",
",",
"array",
"$",
"tokens",
",",
"$",
"pre",
"=",
"'%%'",
",",
"$",
"post",
"=",
"'%%'",
",",
"$",
"flags",
"=",
"self",
"::",
"FLAG_RECURSIVE",
"|",
"self",
"::",
"FLAG_STRICT",
")",
"{... | Parse template with given tokens
@param string $template Template content
@param array $tokens List of key value tokens array
@param string $pre Token prefix
@param string $post Token postfix
@param int $flags Additianal flags for parsing
@return string Parsed template | [
"Parse",
"template",
"with",
"given",
"tokens"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Utility/Template.php#L64-L120 | train |
QoboLtd/qobo-robo | src/Command/Project/DotenvCreate.php | DotenvCreate.projectDotenvCreate | public function projectDotenvCreate(
$envPath = '.env',
$templatePath = '.env.example',
$env = '',
$opts = ['format' => 'table', 'fields' => '']
) {
$task = $this->taskProjectDotenvCreate()
->env($envPath)
->template($templatePath);
$vars = explode(',', $env);
foreach ($vars as $var) {
$var = trim($var);
if (preg_match('/^(.*?)=(.*?)$/', $var, $matches)) {
$task->set($matches[1], $matches[2]);
}
}
$result = $task->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
$data = $result->getData()['data'];
$lines = array_map(function ($k, $v) {
return "$k=$v";
}, array_keys($data), $data);
$result = $this->taskWriteToFile($envPath)
->lines($lines)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return new PropertyList($data);
} | php | public function projectDotenvCreate(
$envPath = '.env',
$templatePath = '.env.example',
$env = '',
$opts = ['format' => 'table', 'fields' => '']
) {
$task = $this->taskProjectDotenvCreate()
->env($envPath)
->template($templatePath);
$vars = explode(',', $env);
foreach ($vars as $var) {
$var = trim($var);
if (preg_match('/^(.*?)=(.*?)$/', $var, $matches)) {
$task->set($matches[1], $matches[2]);
}
}
$result = $task->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
$data = $result->getData()['data'];
$lines = array_map(function ($k, $v) {
return "$k=$v";
}, array_keys($data), $data);
$result = $this->taskWriteToFile($envPath)
->lines($lines)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return new PropertyList($data);
} | [
"public",
"function",
"projectDotenvCreate",
"(",
"$",
"envPath",
"=",
"'.env'",
",",
"$",
"templatePath",
"=",
"'.env.example'",
",",
"$",
"env",
"=",
"''",
",",
"$",
"opts",
"=",
"[",
"'format'",
"=>",
"'table'",
",",
"'fields'",
"=>",
"''",
"]",
")",
... | Create dotenv file
@param string $envPath Path to dotenv file
@param string $templatePath Path to dotenv template
@param string $env Custom dotenv in KEY1=VALUE1,KEY2=VALUE2 format
@option string $format Output format (table, list, csv, json, xml)
@option string $fields Limit output to given fields, comma-separated
@return PropertyList | [
"Create",
"dotenv",
"file"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Project/DotenvCreate.php#L32-L71 | train |
orchestral/support | src/Support/Concerns/DataContainer.php | DataContainer.get | public function get(string $key, $default = null)
{
$value = Arr::get($this->items, $key);
if (\is_null($value)) {
return \value($default);
}
return $value;
} | php | public function get(string $key, $default = null)
{
$value = Arr::get($this->items, $key);
if (\is_null($value)) {
return \value($default);
}
return $value;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"value",
"=",
"Arr",
"::",
"get",
"(",
"$",
"this",
"->",
"items",
",",
"$",
"key",
")",
";",
"if",
"(",
"\\",
"is_null",
"(",
"$",
"value"... | Get a item value.
@param string $key
@param mixed $default
@return mixed | [
"Get",
"a",
"item",
"value",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L41-L50 | train |
orchestral/support | src/Support/Concerns/DataContainer.php | DataContainer.secureGet | public function secureGet(string $key, $default = null)
{
$value = $this->get($key, $default);
if ($this->encrypter instanceof Encrypter) {
try {
return $this->encrypter->decrypt($value);
} catch (DecryptException $e) {
//
}
}
return $value;
} | php | public function secureGet(string $key, $default = null)
{
$value = $this->get($key, $default);
if ($this->encrypter instanceof Encrypter) {
try {
return $this->encrypter->decrypt($value);
} catch (DecryptException $e) {
//
}
}
return $value;
} | [
"public",
"function",
"secureGet",
"(",
"string",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"key",
",",
"$",
"default",
")",
";",
"if",
"(",
"$",
"this",
"->",
"encrypter",
"ins... | Get an encrypted item value.
@param string $key
@param mixed $default
@return mixed | [
"Get",
"an",
"encrypted",
"item",
"value",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L60-L73 | train |
orchestral/support | src/Support/Concerns/DataContainer.php | DataContainer.set | public function set(string $key, $value = null)
{
return Arr::set($this->items, $key, \value($value));
} | php | public function set(string $key, $value = null)
{
return Arr::set($this->items, $key, \value($value));
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"key",
",",
"$",
"value",
"=",
"null",
")",
"{",
"return",
"Arr",
"::",
"set",
"(",
"$",
"this",
"->",
"items",
",",
"$",
"key",
",",
"\\",
"value",
"(",
"$",
"value",
")",
")",
";",
"}"
] | Set a item value.
@param string $key
@param mixed $value
@return mixed | [
"Set",
"a",
"item",
"value",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L83-L86 | train |
orchestral/support | src/Support/Concerns/DataContainer.php | DataContainer.secureSet | public function secureSet(string $key, $value = null)
{
try {
if ($this->encrypter instanceof Encrypter) {
$value = $this->encrypter->encrypt($value);
}
} catch (EncryptException $e) {
//
}
return $this->set($key, $value);
} | php | public function secureSet(string $key, $value = null)
{
try {
if ($this->encrypter instanceof Encrypter) {
$value = $this->encrypter->encrypt($value);
}
} catch (EncryptException $e) {
//
}
return $this->set($key, $value);
} | [
"public",
"function",
"secureSet",
"(",
"string",
"$",
"key",
",",
"$",
"value",
"=",
"null",
")",
"{",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"encrypter",
"instanceof",
"Encrypter",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"encrypter",
"->... | Set an ecrypted item value.
@param string $key
@param mixed $value
@return mixed | [
"Set",
"an",
"ecrypted",
"item",
"value",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L96-L107 | train |
orchestral/support | src/Support/Concerns/DataContainer.php | DataContainer.forget | public function forget(string $key): bool
{
$items = $this->items;
\array_push($this->removedItems, $key);
Arr::forget($items, $key);
$this->items = $items;
return true;
} | php | public function forget(string $key): bool
{
$items = $this->items;
\array_push($this->removedItems, $key);
Arr::forget($items, $key);
$this->items = $items;
return true;
} | [
"public",
"function",
"forget",
"(",
"string",
"$",
"key",
")",
":",
"bool",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"items",
";",
"\\",
"array_push",
"(",
"$",
"this",
"->",
"removedItems",
",",
"$",
"key",
")",
";",
"Arr",
"::",
"forget",
"(",... | Remove a item key.
@param string $key
@return bool | [
"Remove",
"a",
"item",
"key",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L128-L138 | train |
orchestral/support | src/Support/Concerns/DataContainer.php | DataContainer.allWithRemoved | public function allWithRemoved(): array
{
$items = $this->all();
foreach ($this->removedItems as $deleted) {
Arr::set($items, $deleted, null);
}
return $items;
} | php | public function allWithRemoved(): array
{
$items = $this->all();
foreach ($this->removedItems as $deleted) {
Arr::set($items, $deleted, null);
}
return $items;
} | [
"public",
"function",
"allWithRemoved",
"(",
")",
":",
"array",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"all",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"removedItems",
"as",
"$",
"deleted",
")",
"{",
"Arr",
"::",
"set",
"(",
"$",
"items... | Get all available items including deleted.
@return array | [
"Get",
"all",
"available",
"items",
"including",
"deleted",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/DataContainer.php#L155-L164 | train |
nails/module-invoice | invoice/controllers/Payment.php | Payment.complete | protected function complete($oPayment)
{
$oPaymentModel = Factory::model('Payment', 'nails/module-invoice');
$this->data['oPayment'] = $oPayment;
$this->data['oInvoice'] = $oPayment->invoice;
if ($oPayment->status->id === $oPaymentModel::STATUS_FAILED) {
// Payments which FAILED should be ignored
show404();
} elseif ($oPayment->status->id === $oPaymentModel::STATUS_COMPLETE) {
// Payment is already complete
redirect($oPayment->urls->thanks);
} elseif ($oPayment->status->id === $oPaymentModel::STATUS_PROCESSING) {
// Payment is already complete and is being processed
redirect($oPayment->urls->processing);
} else {
try {
// Set up CompleteRequest object
$oCompleteRequest = Factory::factory('CompleteRequest', 'nails/module-invoice');
// Set the driver to use for the request
$oCompleteRequest->setDriver($oPayment->driver->slug);
// Set the payment we're completing
$oCompleteRequest->setPayment($oPayment->id);
// Set the invoice we're completing
$oCompleteRequest->setInvoice($oPayment->invoice->id);
// Set the complete URL, if there is one
$oCompleteRequest->setContinueUrl($oPayment->urls->continue);
// Attempt completion
$oInput = Factory::service('Input');
$oCompleteResponse = $oCompleteRequest->execute(
$oInput->get(),
$oInput->post()
);
if ($oCompleteResponse->isProcessing()) {
// Payment was successful but has not been confirmed
if ($oCompleteRequest->getContinueUrl()) {
redirect($oCompleteRequest->getContinueUrl());
} else {
redirect($oPayment->urls->processing);
}
} elseif ($oCompleteResponse->isComplete()) {
// Payment has completed fully
if ($oCompleteRequest->getContinueUrl()) {
redirect($oCompleteRequest->getContinueUrl());
} else {
redirect($oPayment->urls->thanks);
}
} elseif ($oCompleteResponse->isFailed()) {
throw new NailsException('Payment failed: ' . $oCompleteResponse->getError()->user, 1);
} else {
throw new NailsException('Payment failed.', 1);
}
} catch (\Exception $e) {
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('error', $e->getMessage());
redirect($oPayment->invoice->urls->payment);
}
}
} | php | protected function complete($oPayment)
{
$oPaymentModel = Factory::model('Payment', 'nails/module-invoice');
$this->data['oPayment'] = $oPayment;
$this->data['oInvoice'] = $oPayment->invoice;
if ($oPayment->status->id === $oPaymentModel::STATUS_FAILED) {
// Payments which FAILED should be ignored
show404();
} elseif ($oPayment->status->id === $oPaymentModel::STATUS_COMPLETE) {
// Payment is already complete
redirect($oPayment->urls->thanks);
} elseif ($oPayment->status->id === $oPaymentModel::STATUS_PROCESSING) {
// Payment is already complete and is being processed
redirect($oPayment->urls->processing);
} else {
try {
// Set up CompleteRequest object
$oCompleteRequest = Factory::factory('CompleteRequest', 'nails/module-invoice');
// Set the driver to use for the request
$oCompleteRequest->setDriver($oPayment->driver->slug);
// Set the payment we're completing
$oCompleteRequest->setPayment($oPayment->id);
// Set the invoice we're completing
$oCompleteRequest->setInvoice($oPayment->invoice->id);
// Set the complete URL, if there is one
$oCompleteRequest->setContinueUrl($oPayment->urls->continue);
// Attempt completion
$oInput = Factory::service('Input');
$oCompleteResponse = $oCompleteRequest->execute(
$oInput->get(),
$oInput->post()
);
if ($oCompleteResponse->isProcessing()) {
// Payment was successful but has not been confirmed
if ($oCompleteRequest->getContinueUrl()) {
redirect($oCompleteRequest->getContinueUrl());
} else {
redirect($oPayment->urls->processing);
}
} elseif ($oCompleteResponse->isComplete()) {
// Payment has completed fully
if ($oCompleteRequest->getContinueUrl()) {
redirect($oCompleteRequest->getContinueUrl());
} else {
redirect($oPayment->urls->thanks);
}
} elseif ($oCompleteResponse->isFailed()) {
throw new NailsException('Payment failed: ' . $oCompleteResponse->getError()->user, 1);
} else {
throw new NailsException('Payment failed.', 1);
}
} catch (\Exception $e) {
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData('error', $e->getMessage());
redirect($oPayment->invoice->urls->payment);
}
}
} | [
"protected",
"function",
"complete",
"(",
"$",
"oPayment",
")",
"{",
"$",
"oPaymentModel",
"=",
"Factory",
"::",
"model",
"(",
"'Payment'",
",",
"'nails/module-invoice'",
")",
";",
"$",
"this",
"->",
"data",
"[",
"'oPayment'",
"]",
"=",
"$",
"oPayment",
";... | Completes a payment
@param \stdClass $oPayment The invoice object
@return void | [
"Completes",
"a",
"payment"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/invoice/controllers/Payment.php#L26-L103 | train |
nails/module-invoice | invoice/controllers/Payment.php | Payment.thanks | protected function thanks($oPayment)
{
if ($oPayment->status->id === 'PROCESSING') {
redirect($oPayment->urls->processing);
} elseif ($oPayment->status->id !== 'COMPLETE') {
show404();
}
$this->data['oPayment'] = $oPayment;
$this->data['headerOverride'] = 'structure/header/blank';
$this->data['footerOverride'] = 'structure/footer/blank';
// --------------------------------------------------------------------------
$oView = Factory::service('View');
$this->loadStyles(NAILS_APP_PATH . 'application/modules/invoice/views/thanks/index.php');
$oView->load('structure/header', $this->data);
$oView->load('invoice/thanks/index', $this->data);
$oView->load('structure/footer', $this->data);
} | php | protected function thanks($oPayment)
{
if ($oPayment->status->id === 'PROCESSING') {
redirect($oPayment->urls->processing);
} elseif ($oPayment->status->id !== 'COMPLETE') {
show404();
}
$this->data['oPayment'] = $oPayment;
$this->data['headerOverride'] = 'structure/header/blank';
$this->data['footerOverride'] = 'structure/footer/blank';
// --------------------------------------------------------------------------
$oView = Factory::service('View');
$this->loadStyles(NAILS_APP_PATH . 'application/modules/invoice/views/thanks/index.php');
$oView->load('structure/header', $this->data);
$oView->load('invoice/thanks/index', $this->data);
$oView->load('structure/footer', $this->data);
} | [
"protected",
"function",
"thanks",
"(",
"$",
"oPayment",
")",
"{",
"if",
"(",
"$",
"oPayment",
"->",
"status",
"->",
"id",
"===",
"'PROCESSING'",
")",
"{",
"redirect",
"(",
"$",
"oPayment",
"->",
"urls",
"->",
"processing",
")",
";",
"}",
"elseif",
"("... | Shows a thank you page
@param \stdClass $oPayment The invoice object
@return void | [
"Shows",
"a",
"thank",
"you",
"page"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/invoice/controllers/Payment.php#L114-L133 | train |
canihavesomecoffee/theTVDbAPI | src/Exception/ResourceNotFoundException.php | ResourceNotFoundException.createErrorMessage | public static function createErrorMessage(string $baseMessage, string $path = null, array $parameters = []): string
{
$errorMessage = $baseMessage;
if ($path !== null) {
$errorMessage .= sprintf(
static::PATH_MESSAGE,
$path,
\GuzzleHttp\Psr7\build_query($parameters)
);
}
return $errorMessage;
} | php | public static function createErrorMessage(string $baseMessage, string $path = null, array $parameters = []): string
{
$errorMessage = $baseMessage;
if ($path !== null) {
$errorMessage .= sprintf(
static::PATH_MESSAGE,
$path,
\GuzzleHttp\Psr7\build_query($parameters)
);
}
return $errorMessage;
} | [
"public",
"static",
"function",
"createErrorMessage",
"(",
"string",
"$",
"baseMessage",
",",
"string",
"$",
"path",
"=",
"null",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
":",
"string",
"{",
"$",
"errorMessage",
"=",
"$",
"baseMessage",
";",
... | Creates an error message for a not found exception.
@param string $baseMessage The base error message
@param string $path The requested path
@param array $parameters The query parameters (if defined)
@return string | [
"Creates",
"an",
"error",
"message",
"for",
"a",
"not",
"found",
"exception",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Exception/ResourceNotFoundException.php#L64-L75 | train |
canihavesomecoffee/theTVDbAPI | src/Exception/ResourceNotFoundException.php | ResourceNotFoundException.notFound | public static function notFound(string $path = null, array $options = []): ResourceNotFoundException
{
$query = [];
if (array_key_exists('query', $options)) {
$query = $options['query'];
}
return new static(static::createErrorMessage(static::NOT_FOUND_MESSAGE, $path, $query));
} | php | public static function notFound(string $path = null, array $options = []): ResourceNotFoundException
{
$query = [];
if (array_key_exists('query', $options)) {
$query = $options['query'];
}
return new static(static::createErrorMessage(static::NOT_FOUND_MESSAGE, $path, $query));
} | [
"public",
"static",
"function",
"notFound",
"(",
"string",
"$",
"path",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"ResourceNotFoundException",
"{",
"$",
"query",
"=",
"[",
"]",
";",
"if",
"(",
"array_key_exists",
"(",
"'query'",... | Returns a new instance for the resource not found exception.
@param string $path The requested path
@param array $options The options passed to the request
@return ResourceNotFoundException | [
"Returns",
"a",
"new",
"instance",
"for",
"the",
"resource",
"not",
"found",
"exception",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Exception/ResourceNotFoundException.php#L85-L92 | train |
canihavesomecoffee/theTVDbAPI | src/Exception/ResourceNotFoundException.php | ResourceNotFoundException.noTranslationAvailable | public static function noTranslationAvailable(string $path = null, array $options = []): ResourceNotFoundException
{
$query = [];
if (array_key_exists('query', $options)) {
$query = $options['query'];
}
return new static(static::createErrorMessage(static::NO_TRANSLATION_MESSAGE, $path, $query));
} | php | public static function noTranslationAvailable(string $path = null, array $options = []): ResourceNotFoundException
{
$query = [];
if (array_key_exists('query', $options)) {
$query = $options['query'];
}
return new static(static::createErrorMessage(static::NO_TRANSLATION_MESSAGE, $path, $query));
} | [
"public",
"static",
"function",
"noTranslationAvailable",
"(",
"string",
"$",
"path",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"ResourceNotFoundException",
"{",
"$",
"query",
"=",
"[",
"]",
";",
"if",
"(",
"array_key_exists",
"("... | Returns a new instance for the resource not found exception for missing translations
@param string $path The requested path
@param array $options The options passed to the request
@return ResourceNotFoundException | [
"Returns",
"a",
"new",
"instance",
"for",
"the",
"resource",
"not",
"found",
"exception",
"for",
"missing",
"translations"
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Exception/ResourceNotFoundException.php#L102-L109 | train |
orchestral/support | src/Support/Concerns/Descendible.php | Descendible.descendants | protected function descendants(array $array, ?string $key = null)
{
if (\is_null($key)) {
return $array;
}
$keys = \explode('.', $key);
$first = \array_shift($keys);
if (! isset($array[$first])) {
return null;
}
return $this->resolveLastDecendant($array[$first], $keys);
} | php | protected function descendants(array $array, ?string $key = null)
{
if (\is_null($key)) {
return $array;
}
$keys = \explode('.', $key);
$first = \array_shift($keys);
if (! isset($array[$first])) {
return null;
}
return $this->resolveLastDecendant($array[$first], $keys);
} | [
"protected",
"function",
"descendants",
"(",
"array",
"$",
"array",
",",
"?",
"string",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"\\",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"array",
";",
"}",
"$",
"keys",
"=",
"\\",
"expl... | Get last descendant node from items recursively.
@param array $array
@param string|null $key
@return \Illuminate\Support\Fluent|array|null | [
"Get",
"last",
"descendant",
"node",
"from",
"items",
"recursively",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/Descendible.php#L17-L31 | train |
orchestral/support | src/Support/Concerns/Descendible.php | Descendible.resolveLastDecendant | protected function resolveLastDecendant($array, array $keys): ?Fluent
{
$isLastDescendant = function ($array, $segment) {
return ! \is_array($array->childs) || ! isset($array->childs[$segment]);
};
// To retrieve the array item using dot syntax, we'll iterate through
// each segment in the key and look for that value. If it exists,
// we will return it, otherwise we will set the depth of the array
// and look for the next segment.
foreach ($keys as $segment) {
if ($isLastDescendant($array, $segment)) {
return $array;
}
$array = $array->childs[$segment];
}
return $array;
} | php | protected function resolveLastDecendant($array, array $keys): ?Fluent
{
$isLastDescendant = function ($array, $segment) {
return ! \is_array($array->childs) || ! isset($array->childs[$segment]);
};
// To retrieve the array item using dot syntax, we'll iterate through
// each segment in the key and look for that value. If it exists,
// we will return it, otherwise we will set the depth of the array
// and look for the next segment.
foreach ($keys as $segment) {
if ($isLastDescendant($array, $segment)) {
return $array;
}
$array = $array->childs[$segment];
}
return $array;
} | [
"protected",
"function",
"resolveLastDecendant",
"(",
"$",
"array",
",",
"array",
"$",
"keys",
")",
":",
"?",
"Fluent",
"{",
"$",
"isLastDescendant",
"=",
"function",
"(",
"$",
"array",
",",
"$",
"segment",
")",
"{",
"return",
"!",
"\\",
"is_array",
"(",... | Resolve last descendant node from items.
@param mixed $array
@param array $keys
@return \Orchestra\Support\Fluent|null | [
"Resolve",
"last",
"descendant",
"node",
"from",
"items",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/Descendible.php#L41-L60 | train |
silktide/syringe | src/MasterConfig.php | MasterConfig.stableWeightSort | protected function stableWeightSort(array &$array)
{
foreach ($array as $i => &$value) {
$value["key"] = $i;
}
unset($value);
usort($array, function(array $v1, array $v2) {
$byWeight = $v1["weight"] - $v2["weight"];
if ($byWeight === 0) {
return $v1["key"] - $v2["key"];
}
return $byWeight;
});
} | php | protected function stableWeightSort(array &$array)
{
foreach ($array as $i => &$value) {
$value["key"] = $i;
}
unset($value);
usort($array, function(array $v1, array $v2) {
$byWeight = $v1["weight"] - $v2["weight"];
if ($byWeight === 0) {
return $v1["key"] - $v2["key"];
}
return $byWeight;
});
} | [
"protected",
"function",
"stableWeightSort",
"(",
"array",
"&",
"$",
"array",
")",
"{",
"foreach",
"(",
"$",
"array",
"as",
"$",
"i",
"=>",
"&",
"$",
"value",
")",
"{",
"$",
"value",
"[",
"\"key\"",
"]",
"=",
"$",
"i",
";",
"}",
"unset",
"(",
"$"... | All of these should be ordered by weight, but keep their order if they were equal, aka, a stable sort
Unfortunately, all of PHPs underlying sorting is done by QuickSort, so we have to do the sorting ourselves
@param array $array
@return array | [
"All",
"of",
"these",
"should",
"be",
"ordered",
"by",
"weight",
"but",
"keep",
"their",
"order",
"if",
"they",
"were",
"equal",
"aka",
"a",
"stable",
"sort",
"Unfortunately",
"all",
"of",
"PHPs",
"underlying",
"sorting",
"is",
"done",
"by",
"QuickSort",
"... | afff52640aaaacb44e58f65722a5d717648c15fd | https://github.com/silktide/syringe/blob/afff52640aaaacb44e58f65722a5d717648c15fd/src/MasterConfig.php#L76-L90 | train |
canihavesomecoffee/theTVDbAPI | src/Route/UpdatesRoute.php | UpdatesRoute.query | public function query(DateTime $fromTime, DateTime $toTime = null): array
{
$options = ['query' => ['fromTime' => $fromTime->getTimestamp()]];
if ($toTime !== null) {
$options['query']['toTime'] = $toTime->getTimestamp();
}
$json = $this->parent->performAPICallWithJsonResponse('get', '/updated/query', $options);
return DataParser::parseDataArray($json, UpdateInfo::class);
} | php | public function query(DateTime $fromTime, DateTime $toTime = null): array
{
$options = ['query' => ['fromTime' => $fromTime->getTimestamp()]];
if ($toTime !== null) {
$options['query']['toTime'] = $toTime->getTimestamp();
}
$json = $this->parent->performAPICallWithJsonResponse('get', '/updated/query', $options);
return DataParser::parseDataArray($json, UpdateInfo::class);
} | [
"public",
"function",
"query",
"(",
"DateTime",
"$",
"fromTime",
",",
"DateTime",
"$",
"toTime",
"=",
"null",
")",
":",
"array",
"{",
"$",
"options",
"=",
"[",
"'query'",
"=>",
"[",
"'fromTime'",
"=>",
"$",
"fromTime",
"->",
"getTimestamp",
"(",
")",
"... | Fetches the series that were updated between the given timestamps. If the toTime variable is left null, the API
will take the current timestamp for this.
@param DateTime $fromTime Fetch series that were updated after this timestamp.
@param DateTime|null $toTime Fetch series that were updated before this timestamp.
@return array An array with UpdateInfo instances. | [
"Fetches",
"the",
"series",
"that",
"were",
"updated",
"between",
"the",
"given",
"timestamps",
".",
"If",
"the",
"toTime",
"variable",
"is",
"left",
"null",
"the",
"API",
"will",
"take",
"the",
"current",
"timestamp",
"for",
"this",
"."
] | f23f544029269fe2a244818209b060d08654eca6 | https://github.com/canihavesomecoffee/theTVDbAPI/blob/f23f544029269fe2a244818209b060d08654eca6/src/Route/UpdatesRoute.php#L54-L63 | train |
nails/module-invoice | admin/controllers/Invoice.php | Invoice.view | public function view()
{
if (!userHasPermission('admin:invoice:invoice:edit')) {
unauthorised();
}
$oUri = Factory::service('Uri');
$oModel = $this->oInvoiceModel;
$iInvoiceId = (int) $oUri->segment(5);
$this->data['invoice'] = $this->oInvoiceModel->getById(
$iInvoiceId,
['expand' => $oModel::EXPAND_ALL]
);
if (!$this->data['invoice'] || $this->data['invoice']->state->id == 'DRAFT') {
show404();
}
$this->data['page']->title = 'View Invoice › ' . $this->data['invoice']->ref;
$oAsset = Factory::service('Asset');
$oAsset->load('admin.invoice.view.min.js', 'nails/module-invoice');
Helper::loadView('view');
} | php | public function view()
{
if (!userHasPermission('admin:invoice:invoice:edit')) {
unauthorised();
}
$oUri = Factory::service('Uri');
$oModel = $this->oInvoiceModel;
$iInvoiceId = (int) $oUri->segment(5);
$this->data['invoice'] = $this->oInvoiceModel->getById(
$iInvoiceId,
['expand' => $oModel::EXPAND_ALL]
);
if (!$this->data['invoice'] || $this->data['invoice']->state->id == 'DRAFT') {
show404();
}
$this->data['page']->title = 'View Invoice › ' . $this->data['invoice']->ref;
$oAsset = Factory::service('Asset');
$oAsset->load('admin.invoice.view.min.js', 'nails/module-invoice');
Helper::loadView('view');
} | [
"public",
"function",
"view",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:invoice:invoice:edit'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"$",
"oUri",
"=",
"Factory",
"::",
"service",
"(",
"'Uri'",
")",
";",
"$",
"oModel",... | View an invoice
@throws \Nails\Common\Exception\FactoryException | [
"View",
"an",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Invoice.php#L447-L471 | train |
nails/module-invoice | admin/controllers/Invoice.php | Invoice._callbackValidCurrency | public function _callbackValidCurrency($sCode)
{
$oFormValidation = Factory::service('FormValidation');
$oFormValidation->set_message('_callbackValidCurrency', 'Invalid currency.');
$oCurrency = Factory::service('Currency', 'nails/module-currency');
$aEnabled = $oCurrency->getAllEnabled();
foreach ($aEnabled as $oCurrency) {
if ($oCurrency->code === $sCode) {
return true;
}
}
return false;
} | php | public function _callbackValidCurrency($sCode)
{
$oFormValidation = Factory::service('FormValidation');
$oFormValidation->set_message('_callbackValidCurrency', 'Invalid currency.');
$oCurrency = Factory::service('Currency', 'nails/module-currency');
$aEnabled = $oCurrency->getAllEnabled();
foreach ($aEnabled as $oCurrency) {
if ($oCurrency->code === $sCode) {
return true;
}
}
return false;
} | [
"public",
"function",
"_callbackValidCurrency",
"(",
"$",
"sCode",
")",
"{",
"$",
"oFormValidation",
"=",
"Factory",
"::",
"service",
"(",
"'FormValidation'",
")",
";",
"$",
"oFormValidation",
"->",
"set_message",
"(",
"'_callbackValidCurrency'",
",",
"'Invalid curr... | Form validation cal;back to validate currency selection
@param string $sCode the currency code
@return bool
@throws \Nails\Common\Exception\FactoryException | [
"Form",
"validation",
"cal",
";",
"back",
"to",
"validate",
"currency",
"selection"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Invoice.php#L483-L498 | train |
nails/module-invoice | admin/controllers/Invoice.php | Invoice.make_draft | public function make_draft()
{
if (!userHasPermission('admin:invoice:invoice:edit')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oUri = Factory::service('Uri');
$oInvoice = $this->oInvoiceModel->getById($oUri->segment(5));
if (!$oInvoice) {
show404();
}
// --------------------------------------------------------------------------
// Allow getting a constant
$oInvoiceModel = $this->oInvoiceModel;
$aData = [
'state' => $oInvoiceModel::STATE_DRAFT,
];
if ($this->oInvoiceModel->update($oInvoice->id, $aData)) {
$sStatus = 'success';
$sMessage = 'Invoice updated successfully!';
} else {
$sStatus = 'error';
$sMessage = 'Invoice failed to update invoice. ' . $this->oInvoiceModel->lastError();
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData($sStatus, $sMessage);
redirect('admin/invoice/invoice/edit/' . $oInvoice->id);
} | php | public function make_draft()
{
if (!userHasPermission('admin:invoice:invoice:edit')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oUri = Factory::service('Uri');
$oInvoice = $this->oInvoiceModel->getById($oUri->segment(5));
if (!$oInvoice) {
show404();
}
// --------------------------------------------------------------------------
// Allow getting a constant
$oInvoiceModel = $this->oInvoiceModel;
$aData = [
'state' => $oInvoiceModel::STATE_DRAFT,
];
if ($this->oInvoiceModel->update($oInvoice->id, $aData)) {
$sStatus = 'success';
$sMessage = 'Invoice updated successfully!';
} else {
$sStatus = 'error';
$sMessage = 'Invoice failed to update invoice. ' . $this->oInvoiceModel->lastError();
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData($sStatus, $sMessage);
redirect('admin/invoice/invoice/edit/' . $oInvoice->id);
} | [
"public",
"function",
"make_draft",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:invoice:invoice:edit'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"// --------------------------------------------------------------------------",
"$",
"oUri",
... | Make an invoice a draft
@throws \Nails\Common\Exception\FactoryException | [
"Make",
"an",
"invoice",
"a",
"draft"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Invoice.php#L507-L541 | train |
nails/module-invoice | admin/controllers/Invoice.php | Invoice.delete | public function delete()
{
if (!userHasPermission('admin:invoice:invoice:delete')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oUri = Factory::service('Uri');
$oInvoice = $this->oInvoiceModel->getById($oUri->segment(5));
if (!$oInvoice) {
show404();
}
// --------------------------------------------------------------------------
if ($this->oInvoiceModel->delete($oInvoice->id)) {
$sStatus = 'success';
$sMessage = 'Invoice deleted successfully!';
} else {
$sStatus = 'error';
$sMessage = 'Invoice failed to delete. ' . $this->oInvoiceModel->lastError();
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData($sStatus, $sMessage);
redirect('admin/invoice/invoice/index');
} | php | public function delete()
{
if (!userHasPermission('admin:invoice:invoice:delete')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oUri = Factory::service('Uri');
$oInvoice = $this->oInvoiceModel->getById($oUri->segment(5));
if (!$oInvoice) {
show404();
}
// --------------------------------------------------------------------------
if ($this->oInvoiceModel->delete($oInvoice->id)) {
$sStatus = 'success';
$sMessage = 'Invoice deleted successfully!';
} else {
$sStatus = 'error';
$sMessage = 'Invoice failed to delete. ' . $this->oInvoiceModel->lastError();
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData($sStatus, $sMessage);
redirect('admin/invoice/invoice/index');
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:invoice:invoice:delete'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"// --------------------------------------------------------------------------",
"$",
"oUri",
"=... | Delete an invoice
@throws \Nails\Common\Exception\FactoryException | [
"Delete",
"an",
"invoice"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Invoice.php#L593-L621 | train |
nails/module-invoice | admin/controllers/Invoice.php | Invoice.validatePost | protected function validatePost()
{
$oFormValidation = Factory::service('FormValidation');
$aRules = [
'ref' => 'trim',
'state' => 'trim|required',
'dated' => 'trim|required|valid_date',
'currency' => 'trim|required|callback__callbackValidCurrency',
'terms' => 'trim|is_natural',
'customer_id' => 'trim',
'additional_text' => 'trim',
'items' => '',
];
$aRulesFV = [];
foreach ($aRules as $sKey => $sRules) {
$aRulesFV[] = [
'field' => $sKey,
'label' => '',
'rules' => $sRules,
];
}
$oFormValidation->set_rules($aRulesFV);
$oFormValidation->set_message('required', lang('fv_required'));
$oFormValidation->set_message('valid_date', lang('fv_valid_date'));
$oFormValidation->set_message('is_natural', lang('fv_is_natural'));
$oFormValidation->set_message('valid_email', lang('fv_valid_email'));
return $oFormValidation->run($this);
} | php | protected function validatePost()
{
$oFormValidation = Factory::service('FormValidation');
$aRules = [
'ref' => 'trim',
'state' => 'trim|required',
'dated' => 'trim|required|valid_date',
'currency' => 'trim|required|callback__callbackValidCurrency',
'terms' => 'trim|is_natural',
'customer_id' => 'trim',
'additional_text' => 'trim',
'items' => '',
];
$aRulesFV = [];
foreach ($aRules as $sKey => $sRules) {
$aRulesFV[] = [
'field' => $sKey,
'label' => '',
'rules' => $sRules,
];
}
$oFormValidation->set_rules($aRulesFV);
$oFormValidation->set_message('required', lang('fv_required'));
$oFormValidation->set_message('valid_date', lang('fv_valid_date'));
$oFormValidation->set_message('is_natural', lang('fv_is_natural'));
$oFormValidation->set_message('valid_email', lang('fv_valid_email'));
return $oFormValidation->run($this);
} | [
"protected",
"function",
"validatePost",
"(",
")",
"{",
"$",
"oFormValidation",
"=",
"Factory",
"::",
"service",
"(",
"'FormValidation'",
")",
";",
"$",
"aRules",
"=",
"[",
"'ref'",
"=>",
"'trim'",
",",
"'state'",
"=>",
"'trim|required'",
",",
"'dated'",
"=>... | Validate the POST data
@return boolean
@throws \Nails\Common\Exception\FactoryException | [
"Validate",
"the",
"POST",
"data"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Invoice.php#L631-L663 | train |
nails/module-invoice | admin/controllers/Invoice.php | Invoice.getObjectFromPost | protected function getObjectFromPost()
{
$oInput = Factory::service('Input');
$oUri = Factory::service('Uri');
$aData = [
'ref' => $oInput->post('ref') ?: null,
'state' => $oInput->post('state') ?: null,
'dated' => $oInput->post('dated') ?: null,
'currency' => $oInput->post('currency') ?: null,
'terms' => (int) $oInput->post('terms') ?: 0,
'customer_id' => (int) $oInput->post('customer_id') ?: null,
'additional_text' => $oInput->post('additional_text') ?: null,
'items' => [],
'currency' => $oInput->post('currency'),
];
if ($oInput->post('items')) {
foreach ($oInput->post('items') as $aItem) {
// @todo convert to pence using a model
$aData['items'][] = [
'id' => array_key_exists('id', $aItem) ? $aItem['id'] : null,
'quantity' => array_key_exists('quantity', $aItem) ? $aItem['quantity'] : null,
'unit' => array_key_exists('unit', $aItem) ? $aItem['unit'] : null,
'label' => array_key_exists('label', $aItem) ? $aItem['label'] : null,
'body' => array_key_exists('body', $aItem) ? $aItem['body'] : null,
'unit_cost' => array_key_exists('unit_cost', $aItem) ? intval($aItem['unit_cost'] * 100) : null,
'tax_id' => array_key_exists('tax_id', $aItem) ? $aItem['tax_id'] : null,
];
}
}
if ($oUri->rsegment(5) == 'edit') {
unset($aData['ref']);
}
return $aData;
} | php | protected function getObjectFromPost()
{
$oInput = Factory::service('Input');
$oUri = Factory::service('Uri');
$aData = [
'ref' => $oInput->post('ref') ?: null,
'state' => $oInput->post('state') ?: null,
'dated' => $oInput->post('dated') ?: null,
'currency' => $oInput->post('currency') ?: null,
'terms' => (int) $oInput->post('terms') ?: 0,
'customer_id' => (int) $oInput->post('customer_id') ?: null,
'additional_text' => $oInput->post('additional_text') ?: null,
'items' => [],
'currency' => $oInput->post('currency'),
];
if ($oInput->post('items')) {
foreach ($oInput->post('items') as $aItem) {
// @todo convert to pence using a model
$aData['items'][] = [
'id' => array_key_exists('id', $aItem) ? $aItem['id'] : null,
'quantity' => array_key_exists('quantity', $aItem) ? $aItem['quantity'] : null,
'unit' => array_key_exists('unit', $aItem) ? $aItem['unit'] : null,
'label' => array_key_exists('label', $aItem) ? $aItem['label'] : null,
'body' => array_key_exists('body', $aItem) ? $aItem['body'] : null,
'unit_cost' => array_key_exists('unit_cost', $aItem) ? intval($aItem['unit_cost'] * 100) : null,
'tax_id' => array_key_exists('tax_id', $aItem) ? $aItem['tax_id'] : null,
];
}
}
if ($oUri->rsegment(5) == 'edit') {
unset($aData['ref']);
}
return $aData;
} | [
"protected",
"function",
"getObjectFromPost",
"(",
")",
"{",
"$",
"oInput",
"=",
"Factory",
"::",
"service",
"(",
"'Input'",
")",
";",
"$",
"oUri",
"=",
"Factory",
"::",
"service",
"(",
"'Uri'",
")",
";",
"$",
"aData",
"=",
"[",
"'ref'",
"=>",
"$",
"... | Get an object generated from the POST data
@return array
@throws \Nails\Common\Exception\FactoryException | [
"Get",
"an",
"object",
"generated",
"from",
"the",
"POST",
"data"
] | 3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716 | https://github.com/nails/module-invoice/blob/3e62067f9de1b0ddb6b0ce0eddeb3eea4ee85716/admin/controllers/Invoice.php#L673-L710 | train |
rinvex/cortex-console | src/Http/Controllers/Adminarea/TerminalController.php | TerminalController.index | public function index(Request $request, Terminal $terminal)
{
$token = null;
if ($request->hasSession() === true) {
$token = $request->session()->token();
}
$terminal->call('list --ansi');
$options = json_encode([
'username' => 'LARAVEL',
'hostname' => php_uname('n'),
'os' => PHP_OS,
'csrfToken' => $token,
'helpInfo' => $terminal->output(),
'basePath' => app()->basePath(),
'environment' => app()->environment(),
'version' => app()->version(),
'endpoint' => route('adminarea.console.terminal.execute'),
'interpreters' => [
'mysql' => 'mysql',
'artisan tinker' => 'tinker',
'tinker' => 'tinker',
],
'confirmToProceed' => [
'artisan' => [
'migrate',
'migrate:install',
'migrate:refresh',
'migrate:reset',
'migrate:rollback',
'db:seed',
],
],
]);
return view('cortex/console::adminarea.pages.terminal', compact('options'));
} | php | public function index(Request $request, Terminal $terminal)
{
$token = null;
if ($request->hasSession() === true) {
$token = $request->session()->token();
}
$terminal->call('list --ansi');
$options = json_encode([
'username' => 'LARAVEL',
'hostname' => php_uname('n'),
'os' => PHP_OS,
'csrfToken' => $token,
'helpInfo' => $terminal->output(),
'basePath' => app()->basePath(),
'environment' => app()->environment(),
'version' => app()->version(),
'endpoint' => route('adminarea.console.terminal.execute'),
'interpreters' => [
'mysql' => 'mysql',
'artisan tinker' => 'tinker',
'tinker' => 'tinker',
],
'confirmToProceed' => [
'artisan' => [
'migrate',
'migrate:install',
'migrate:refresh',
'migrate:reset',
'migrate:rollback',
'db:seed',
],
],
]);
return view('cortex/console::adminarea.pages.terminal', compact('options'));
} | [
"public",
"function",
"index",
"(",
"Request",
"$",
"request",
",",
"Terminal",
"$",
"terminal",
")",
"{",
"$",
"token",
"=",
"null",
";",
"if",
"(",
"$",
"request",
"->",
"hasSession",
"(",
")",
"===",
"true",
")",
"{",
"$",
"token",
"=",
"$",
"re... | Show terminal index.
@param \Illuminate\Http\Request $request
@param \Cortex\Console\Services\Terminal $terminal
@return \Illuminate\View\View | [
"Show",
"terminal",
"index",
"."
] | 218307609effc38f16b00dba46786a296246f3b5 | https://github.com/rinvex/cortex-console/blob/218307609effc38f16b00dba46786a296246f3b5/src/Http/Controllers/Adminarea/TerminalController.php#L27-L64 | train |
QoboLtd/qobo-robo | src/Command/Project/DotenvReload.php | DotenvReload.projectDotenvReload | public function projectDotenvReload($envPath = '.env', $opts = ['format' => 'table', 'fields' => ''])
{
// Reload
$result = $this->taskDotenvReload()
->path($envPath)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return new PropertyList($result->getData());
} | php | public function projectDotenvReload($envPath = '.env', $opts = ['format' => 'table', 'fields' => ''])
{
// Reload
$result = $this->taskDotenvReload()
->path($envPath)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return new PropertyList($result->getData());
} | [
"public",
"function",
"projectDotenvReload",
"(",
"$",
"envPath",
"=",
"'.env'",
",",
"$",
"opts",
"=",
"[",
"'format'",
"=>",
"'table'",
",",
"'fields'",
"=>",
"''",
"]",
")",
"{",
"// Reload",
"$",
"result",
"=",
"$",
"this",
"->",
"taskDotenvReload",
... | Reload environment from given dotenv file
@param string $envPath Path to dotenv file
@option string $format Output format (table, list, csv, json, xml)
@option string $fields Limit output to given fields, comma-separated
@return PropertyList result | [
"Reload",
"environment",
"from",
"given",
"dotenv",
"file"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Project/DotenvReload.php#L28-L40 | train |
QoboLtd/qobo-robo | src/Command/Mysql/Export.php | Export.mysqlExport | public function mysqlExport($db, $file = 'etc/mysql.sql', $user = 'root', $pass = null, $host = null, $port = null, $opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskMysqlExport()
->db($db)
->file($file)
->user($user)
->pass($pass)
->host($host)
->port($port)
->hide($pass)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return true;
} | php | public function mysqlExport($db, $file = 'etc/mysql.sql', $user = 'root', $pass = null, $host = null, $port = null, $opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskMysqlExport()
->db($db)
->file($file)
->user($user)
->pass($pass)
->host($host)
->port($port)
->hide($pass)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return true;
} | [
"public",
"function",
"mysqlExport",
"(",
"$",
"db",
",",
"$",
"file",
"=",
"'etc/mysql.sql'",
",",
"$",
"user",
"=",
"'root'",
",",
"$",
"pass",
"=",
"null",
",",
"$",
"host",
"=",
"null",
",",
"$",
"port",
"=",
"null",
",",
"$",
"opts",
"=",
"[... | Dump mysql database
@param string $db Database name
@param string $file Destination file for a dump
@param string $user MySQL user to bind with
@param string $pass (Optional) MySQL user password
@param string $host (Optional) MySQL server host
@param string $port (Optional) MySQL server port
@option string $format Output format (table, list, csv, json, xml)
@option string $fields Limit output to given fields, comma-separated
@return PropertyList result | [
"Dump",
"mysql",
"database"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Mysql/Export.php#L33-L50 | train |
doganoo/PHPUtil | src/Util/NumberUtil.php | NumberUtil.format | public static function format($value, int $decimals = 2): ?string {
if (!\is_numeric($value)) {
return null;
}
return \number_format($value, $decimals);
} | php | public static function format($value, int $decimals = 2): ?string {
if (!\is_numeric($value)) {
return null;
}
return \number_format($value, $decimals);
} | [
"public",
"static",
"function",
"format",
"(",
"$",
"value",
",",
"int",
"$",
"decimals",
"=",
"2",
")",
":",
"?",
"string",
"{",
"if",
"(",
"!",
"\\",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"\\",
"n... | returns the formatted number with grouped thousands
@param $value
@param int $decimals
@return null|string | [
"returns",
"the",
"formatted",
"number",
"with",
"grouped",
"thousands"
] | 4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5 | https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/Util/NumberUtil.php#L44-L49 | train |
doganoo/PHPUtil | src/Util/NumberUtil.php | NumberUtil.stripNonInteger | public static function stripNonInteger(array $array): array {
$newArray = [];
foreach ($array as $value) {
if (!NumberUtil::isInteger($value)) continue;
$newArray[] = \intval($value);
}
return $newArray;
} | php | public static function stripNonInteger(array $array): array {
$newArray = [];
foreach ($array as $value) {
if (!NumberUtil::isInteger($value)) continue;
$newArray[] = \intval($value);
}
return $newArray;
} | [
"public",
"static",
"function",
"stripNonInteger",
"(",
"array",
"$",
"array",
")",
":",
"array",
"{",
"$",
"newArray",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"array",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"NumberUtil",
"::",
"isInteger",
"... | strips all non integer fields from the input and returns all
values as integer data type.
@param array $array
@return array | [
"strips",
"all",
"non",
"integer",
"fields",
"from",
"the",
"input",
"and",
"returns",
"all",
"values",
"as",
"integer",
"data",
"type",
"."
] | 4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5 | https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/Util/NumberUtil.php#L112-L119 | train |
QoboLtd/qobo-robo | src/Command/Template/Tokens.php | Tokens.templateTokens | public function templateTokens($path, $pre = '%%', $post = '%%', $opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskTemplateTokens()
->path($path)
->pre($pre)
->post($post)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
$data = $result->getData();
if (empty($data) || !isset($data['data'])) {
return new RowsOfFields([]);
}
natsort($data['data']);
$data['data'] = array_map(function ($item) {
return ['Token' => $item];
}, $data['data']);
return new RowsOfFields($data['data']);
} | php | public function templateTokens($path, $pre = '%%', $post = '%%', $opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskTemplateTokens()
->path($path)
->pre($pre)
->post($post)
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
$data = $result->getData();
if (empty($data) || !isset($data['data'])) {
return new RowsOfFields([]);
}
natsort($data['data']);
$data['data'] = array_map(function ($item) {
return ['Token' => $item];
}, $data['data']);
return new RowsOfFields($data['data']);
} | [
"public",
"function",
"templateTokens",
"(",
"$",
"path",
",",
"$",
"pre",
"=",
"'%%'",
",",
"$",
"post",
"=",
"'%%'",
",",
"$",
"opts",
"=",
"[",
"'format'",
"=>",
"'table'",
",",
"'fields'",
"=>",
"''",
"]",
")",
"{",
"$",
"result",
"=",
"$",
"... | List all present tokens in a given template
@param string $path Path to template
@param string $pre Token prefix
@param string $post Token postfix
@option string $format Output format (table, list, csv, json, xml)
@option string $fields Limit output to given fields, comma-separated
@return RowsOfFields|false on success, false on failure | [
"List",
"all",
"present",
"tokens",
"in",
"a",
"given",
"template"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Template/Tokens.php#L30-L53 | train |
g4code/data-mapper | src/Bulk/Solr.php | Solr.markForSetAtomic | public function markForSetAtomic(\G4\DataMapper\Domain\DomainAbstract $domain)
{
$this->data[] = $this->addMethodToData(self::METHOD_SET, array_filter($domain->getRawData()));
return $this;
} | php | public function markForSetAtomic(\G4\DataMapper\Domain\DomainAbstract $domain)
{
$this->data[] = $this->addMethodToData(self::METHOD_SET, array_filter($domain->getRawData()));
return $this;
} | [
"public",
"function",
"markForSetAtomic",
"(",
"\\",
"G4",
"\\",
"DataMapper",
"\\",
"Domain",
"\\",
"DomainAbstract",
"$",
"domain",
")",
"{",
"$",
"this",
"->",
"data",
"[",
"]",
"=",
"$",
"this",
"->",
"addMethodToData",
"(",
"self",
"::",
"METHOD_SET",... | Atomic update of all fields that are not null
@param \G4\DataMapper\Domain\DomainAbstract $domain
@return $this | [
"Atomic",
"update",
"of",
"all",
"fields",
"that",
"are",
"not",
"null"
] | ac794cb5b02d277b524fb9e65f59ba87170afd97 | https://github.com/g4code/data-mapper/blob/ac794cb5b02d277b524fb9e65f59ba87170afd97/src/Bulk/Solr.php#L86-L90 | train |
doganoo/PHPUtil | src/HTTP/Session.php | Session.readArray | public function readArray($index) {
return isset ($_SESSION [$index]) && is_array($_SESSION [$index]) ? $_SESSION [$index] : [];
} | php | public function readArray($index) {
return isset ($_SESSION [$index]) && is_array($_SESSION [$index]) ? $_SESSION [$index] : [];
} | [
"public",
"function",
"readArray",
"(",
"$",
"index",
")",
"{",
"return",
"isset",
"(",
"$",
"_SESSION",
"[",
"$",
"index",
"]",
")",
"&&",
"is_array",
"(",
"$",
"_SESSION",
"[",
"$",
"index",
"]",
")",
"?",
"$",
"_SESSION",
"[",
"$",
"index",
"]",... | reads an array from the session
@param $index
@return array | [
"reads",
"an",
"array",
"from",
"the",
"session"
] | 4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5 | https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/HTTP/Session.php#L54-L56 | train |
rinvex/cortex-console | src/Http/Controllers/Adminarea/RoutesController.php | RoutesController.index | public function index(RoutesDataTable $routesDataTable)
{
$middlewareClosure = function ($middleware) {
return $middleware instanceof Closure ? 'Closure' : $middleware;
};
return $routesDataTable->with([
'id' => 'adminarea-routes-index-table',
'middlewareClosure' => $middlewareClosure,
])->render('cortex/foundation::adminarea.pages.datatable-index');
} | php | public function index(RoutesDataTable $routesDataTable)
{
$middlewareClosure = function ($middleware) {
return $middleware instanceof Closure ? 'Closure' : $middleware;
};
return $routesDataTable->with([
'id' => 'adminarea-routes-index-table',
'middlewareClosure' => $middlewareClosure,
])->render('cortex/foundation::adminarea.pages.datatable-index');
} | [
"public",
"function",
"index",
"(",
"RoutesDataTable",
"$",
"routesDataTable",
")",
"{",
"$",
"middlewareClosure",
"=",
"function",
"(",
"$",
"middleware",
")",
"{",
"return",
"$",
"middleware",
"instanceof",
"Closure",
"?",
"'Closure'",
":",
"$",
"middleware",
... | List all routes.
@param \Cortex\Console\DataTables\Adminarea\RoutesDataTable $routesDataTable
@return \Illuminate\Http\JsonResponse|\Illuminate\View\View | [
"List",
"all",
"routes",
"."
] | 218307609effc38f16b00dba46786a296246f3b5 | https://github.com/rinvex/cortex-console/blob/218307609effc38f16b00dba46786a296246f3b5/src/Http/Controllers/Adminarea/RoutesController.php#L25-L35 | train |
QoboLtd/qobo-robo | src/Command/Template/Process.php | Process.templateProcess | public function templateProcess($src, $dst, $opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskDotenvFileRead()
->path('.env')
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
$data = $result->getData();
if (!isset($data['data'])) {
$this->exitError("Failed to run command");
}
$result = $this->taskTemplateProcess()
->src($src)
->dst($dst)
->wrap('%%')
->tokens($data['data'])
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return true;
} | php | public function templateProcess($src, $dst, $opts = ['format' => 'table', 'fields' => ''])
{
$result = $this->taskDotenvFileRead()
->path('.env')
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
$data = $result->getData();
if (!isset($data['data'])) {
$this->exitError("Failed to run command");
}
$result = $this->taskTemplateProcess()
->src($src)
->dst($dst)
->wrap('%%')
->tokens($data['data'])
->run();
if (!$result->wasSuccessful()) {
$this->exitError("Failed to run command");
}
return true;
} | [
"public",
"function",
"templateProcess",
"(",
"$",
"src",
",",
"$",
"dst",
",",
"$",
"opts",
"=",
"[",
"'format'",
"=>",
"'table'",
",",
"'fields'",
"=>",
"''",
"]",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"taskDotenvFileRead",
"(",
")",
"->... | Process given template with tokens from environment variables
@param string $src Path to template
@param string $dst Path to final file
@option string $format Output format (table, list, csv, json, xml)
@option string $fields Limit output to given fields, comma-separated
@return bool true on success, false on failure | [
"Process",
"given",
"template",
"with",
"tokens",
"from",
"environment",
"variables"
] | ea10f778bb046ad41324d22b27fce5a2fb8915ce | https://github.com/QoboLtd/qobo-robo/blob/ea10f778bb046ad41324d22b27fce5a2fb8915ce/src/Command/Template/Process.php#L29-L55 | train |
orchestral/support | src/Support/Serializer.php | Serializer.serializeBasicDataset | final protected function serializeBasicDataset($dataset): array
{
$key = $this->resolveSerializerKey($dataset);
if ($dataset instanceof Paginator) {
$collection = $dataset->toArray();
$collection[$key] = $collection['data'];
unset($collection['data']);
return $collection;
}
return [
$key => $dataset->toArray(),
];
} | php | final protected function serializeBasicDataset($dataset): array
{
$key = $this->resolveSerializerKey($dataset);
if ($dataset instanceof Paginator) {
$collection = $dataset->toArray();
$collection[$key] = $collection['data'];
unset($collection['data']);
return $collection;
}
return [
$key => $dataset->toArray(),
];
} | [
"final",
"protected",
"function",
"serializeBasicDataset",
"(",
"$",
"dataset",
")",
":",
"array",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"resolveSerializerKey",
"(",
"$",
"dataset",
")",
";",
"if",
"(",
"$",
"dataset",
"instanceof",
"Paginator",
")",
"{... | Resolve paginated dataset.
@param mixed $dataset
@return array | [
"Resolve",
"paginated",
"dataset",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Serializer.php#L40-L56 | train |
orchestral/support | src/Support/Serializer.php | Serializer.resolveSerializerKey | protected function resolveSerializerKey($dataset): string
{
if ($dataset instanceof BaseCollection || $dataset instanceof Paginator) {
return Str::plural($this->getKey());
}
return $this->getKey();
} | php | protected function resolveSerializerKey($dataset): string
{
if ($dataset instanceof BaseCollection || $dataset instanceof Paginator) {
return Str::plural($this->getKey());
}
return $this->getKey();
} | [
"protected",
"function",
"resolveSerializerKey",
"(",
"$",
"dataset",
")",
":",
"string",
"{",
"if",
"(",
"$",
"dataset",
"instanceof",
"BaseCollection",
"||",
"$",
"dataset",
"instanceof",
"Paginator",
")",
"{",
"return",
"Str",
"::",
"plural",
"(",
"$",
"t... | Resolve serializer key.
@param mixed $dataset
@return string | [
"Resolve",
"serializer",
"key",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Serializer.php#L75-L82 | train |
doganoo/PHPUtil | src/Log/Logger.php | Logger.log | private static function log(string $message, int $level) {
\Logger::configure(self::getConfiguration());
$logger = \Logger::getRootLogger();
$logger->setLevel(self::getLoggerLevel());
switch ($level) {
case Logger::DEBUG:
$logger->debug($message);
break;
case Logger::INFO:
$logger->info($message);
break;
case Logger::WARN:
$logger->warn($message);
break;
case Logger::ERROR:
$logger->error($message);
break;
case Logger::FATAL:
$logger->fatal($message);
break;
case Logger::TRACE:
$logger->trace($message);
break;
default:
}
} | php | private static function log(string $message, int $level) {
\Logger::configure(self::getConfiguration());
$logger = \Logger::getRootLogger();
$logger->setLevel(self::getLoggerLevel());
switch ($level) {
case Logger::DEBUG:
$logger->debug($message);
break;
case Logger::INFO:
$logger->info($message);
break;
case Logger::WARN:
$logger->warn($message);
break;
case Logger::ERROR:
$logger->error($message);
break;
case Logger::FATAL:
$logger->fatal($message);
break;
case Logger::TRACE:
$logger->trace($message);
break;
default:
}
} | [
"private",
"static",
"function",
"log",
"(",
"string",
"$",
"message",
",",
"int",
"$",
"level",
")",
"{",
"\\",
"Logger",
"::",
"configure",
"(",
"self",
"::",
"getConfiguration",
"(",
")",
")",
";",
"$",
"logger",
"=",
"\\",
"Logger",
"::",
"getRootL... | logs a message to the console
@param string $message
@param int $level | [
"logs",
"a",
"message",
"to",
"the",
"console"
] | 4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5 | https://github.com/doganoo/PHPUtil/blob/4415a014b4448b1ddf6d2e3f0f0d39cd1a83b8f5/src/Log/Logger.php#L136-L162 | train |
orchestral/support | src/Support/Concerns/Validation.php | Validation.bindToValidation | final public function bindToValidation(array $bindings): self
{
$this->validationBindings = \array_merge($this->validationBindings, $bindings);
return $this;
} | php | final public function bindToValidation(array $bindings): self
{
$this->validationBindings = \array_merge($this->validationBindings, $bindings);
return $this;
} | [
"final",
"public",
"function",
"bindToValidation",
"(",
"array",
"$",
"bindings",
")",
":",
"self",
"{",
"$",
"this",
"->",
"validationBindings",
"=",
"\\",
"array_merge",
"(",
"$",
"this",
"->",
"validationBindings",
",",
"$",
"bindings",
")",
";",
"return"... | Add bindings.
@param array $bindings
@return $this | [
"Add",
"bindings",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/Validation.php#L63-L68 | train |
orchestral/support | src/Support/Concerns/Validation.php | Validation.getBindedRules | protected function getBindedRules(): array
{
$rules = $this->getValidationRules();
if (! empty($this->validationBindings)) {
foreach ($rules as $key => $value) {
$rules[$key] = Str::replace($value, $this->validationBindings);
}
}
return $rules;
} | php | protected function getBindedRules(): array
{
$rules = $this->getValidationRules();
if (! empty($this->validationBindings)) {
foreach ($rules as $key => $value) {
$rules[$key] = Str::replace($value, $this->validationBindings);
}
}
return $rules;
} | [
"protected",
"function",
"getBindedRules",
"(",
")",
":",
"array",
"{",
"$",
"rules",
"=",
"$",
"this",
"->",
"getValidationRules",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"validationBindings",
")",
")",
"{",
"foreach",
"(",
"$"... | Run rules bindings.
@return array | [
"Run",
"rules",
"bindings",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/Validation.php#L99-L110 | train |
byjg/restserver | src/HttpRequest.php | HttpRequest.request | public function request($value)
{
if (!isset($this->request[$value])) {
return false;
} else {
return $this->request[$value];
}
} | php | public function request($value)
{
if (!isset($this->request[$value])) {
return false;
} else {
return $this->request[$value];
}
} | [
"public",
"function",
"request",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"request",
"[",
"$",
"value",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"$",
"this",
"->",
"request",
"["... | Get a value from any of get, post, server, cookie or session. If not found return false.
@param string $value
@return string|boolean | [
"Get",
"a",
"value",
"from",
"any",
"of",
"get",
"post",
"server",
"cookie",
"or",
"session",
".",
"If",
"not",
"found",
"return",
"false",
"."
] | 1fdbd58f414f5d9958de0873d67eea961dc52fda | https://github.com/byjg/restserver/blob/1fdbd58f414f5d9958de0873d67eea961dc52fda/src/HttpRequest.php#L115-L122 | train |
byjg/restserver | src/HttpRequest.php | HttpRequest.getRequestIp | public function getRequestIp()
{
$headers = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
];
foreach ($headers as $header) {
if ($this->server($header) !== false) {
return $this->server($header);
}
}
return 'UNKNOWN';
} | php | public function getRequestIp()
{
$headers = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
];
foreach ($headers as $header) {
if ($this->server($header) !== false) {
return $this->server($header);
}
}
return 'UNKNOWN';
} | [
"public",
"function",
"getRequestIp",
"(",
")",
"{",
"$",
"headers",
"=",
"[",
"'HTTP_CLIENT_IP'",
",",
"'HTTP_X_FORWARDED_FOR'",
",",
"'HTTP_X_FORWARDED'",
",",
"'HTTP_FORWARDED_FOR'",
",",
"'HTTP_FORWARDED'",
",",
"'REMOTE_ADDR'",
",",
"]",
";",
"foreach",
"(",
... | Use this method to get the CLIENT REQUEST IP.
Note that if you behing a Proxy, the variable REMOTE_ADDR will always have the same IP
@return string | [
"Use",
"this",
"method",
"to",
"get",
"the",
"CLIENT",
"REQUEST",
"IP",
".",
"Note",
"that",
"if",
"you",
"behing",
"a",
"Proxy",
"the",
"variable",
"REMOTE_ADDR",
"will",
"always",
"have",
"the",
"same",
"IP"
] | 1fdbd58f414f5d9958de0873d67eea961dc52fda | https://github.com/byjg/restserver/blob/1fdbd58f414f5d9958de0873d67eea961dc52fda/src/HttpRequest.php#L145-L162 | train |
hiqdev/hipanel-rbac | src/SetterTrait.php | SetterTrait.setPermission | public function setPermission($name, $description = null)
{
$permission = $this->getPermission($name) ?: $this->createPermission($name);
if ($description) {
$permission->description = $description;
}
$this->add($permission);
return $permission;
} | php | public function setPermission($name, $description = null)
{
$permission = $this->getPermission($name) ?: $this->createPermission($name);
if ($description) {
$permission->description = $description;
}
$this->add($permission);
return $permission;
} | [
"public",
"function",
"setPermission",
"(",
"$",
"name",
",",
"$",
"description",
"=",
"null",
")",
"{",
"$",
"permission",
"=",
"$",
"this",
"->",
"getPermission",
"(",
"$",
"name",
")",
"?",
":",
"$",
"this",
"->",
"createPermission",
"(",
"$",
"name... | Set permission.
@param string $name
@param string $description
@return Item | [
"Set",
"permission",
"."
] | 8fb14f035db3eb7b87bf6c0bcd894535097f14ef | https://github.com/hiqdev/hipanel-rbac/blob/8fb14f035db3eb7b87bf6c0bcd894535097f14ef/src/SetterTrait.php#L31-L40 | train |
hiqdev/hipanel-rbac | src/SetterTrait.php | SetterTrait.setRole | public function setRole($name, $description = null)
{
$role = $this->getRole($name) ?: $this->createRole($name);
if ($description) {
$role->description = $description;
}
$this->add($role);
return $role;
} | php | public function setRole($name, $description = null)
{
$role = $this->getRole($name) ?: $this->createRole($name);
if ($description) {
$role->description = $description;
}
$this->add($role);
return $role;
} | [
"public",
"function",
"setRole",
"(",
"$",
"name",
",",
"$",
"description",
"=",
"null",
")",
"{",
"$",
"role",
"=",
"$",
"this",
"->",
"getRole",
"(",
"$",
"name",
")",
"?",
":",
"$",
"this",
"->",
"createRole",
"(",
"$",
"name",
")",
";",
"if",... | Set role.
@param string $name
@param string $description
@return Item | [
"Set",
"role",
"."
] | 8fb14f035db3eb7b87bf6c0bcd894535097f14ef | https://github.com/hiqdev/hipanel-rbac/blob/8fb14f035db3eb7b87bf6c0bcd894535097f14ef/src/SetterTrait.php#L48-L57 | train |
hiqdev/hipanel-rbac | src/SetterTrait.php | SetterTrait.setChild | public function setChild($parent, $child)
{
if (is_string($parent)) {
$name = $parent;
$parent = $this->getItem($parent);
if (is_null($parent)) {
throw new Exception("Unknown parent:$name at setChild");
}
}
if (is_string($child)) {
$name = $child;
$child = $this->getItem($child);
if (is_null($child)) {
throw new Exception("Unknown child:$name at setChild");
}
}
if (isset($this->children[$parent->name][$child->name])) {
return false;
}
return $this->addChild($parent, $child);
} | php | public function setChild($parent, $child)
{
if (is_string($parent)) {
$name = $parent;
$parent = $this->getItem($parent);
if (is_null($parent)) {
throw new Exception("Unknown parent:$name at setChild");
}
}
if (is_string($child)) {
$name = $child;
$child = $this->getItem($child);
if (is_null($child)) {
throw new Exception("Unknown child:$name at setChild");
}
}
if (isset($this->children[$parent->name][$child->name])) {
return false;
}
return $this->addChild($parent, $child);
} | [
"public",
"function",
"setChild",
"(",
"$",
"parent",
",",
"$",
"child",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"parent",
")",
")",
"{",
"$",
"name",
"=",
"$",
"parent",
";",
"$",
"parent",
"=",
"$",
"this",
"->",
"getItem",
"(",
"$",
"paren... | Set child.
@param string|Item $parent
@param string|Item $child
@return bool | [
"Set",
"child",
"."
] | 8fb14f035db3eb7b87bf6c0bcd894535097f14ef | https://github.com/hiqdev/hipanel-rbac/blob/8fb14f035db3eb7b87bf6c0bcd894535097f14ef/src/SetterTrait.php#L65-L86 | train |
hiqdev/hipanel-rbac | src/SetterTrait.php | SetterTrait.setAssignments | public function setAssignments($items, $userId)
{
if (is_string($items)) {
$items = explode(',', $items);
}
foreach ($items as $item) {
$this->setAssignment($item, $userId);
}
} | php | public function setAssignments($items, $userId)
{
if (is_string($items)) {
$items = explode(',', $items);
}
foreach ($items as $item) {
$this->setAssignment($item, $userId);
}
} | [
"public",
"function",
"setAssignments",
"(",
"$",
"items",
",",
"$",
"userId",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"items",
")",
")",
"{",
"$",
"items",
"=",
"explode",
"(",
"','",
",",
"$",
"items",
")",
";",
"}",
"foreach",
"(",
"$",
"i... | Assigns items to a user.
@param string|array $items
@param string|integer $userId | [
"Assigns",
"items",
"to",
"a",
"user",
"."
] | 8fb14f035db3eb7b87bf6c0bcd894535097f14ef | https://github.com/hiqdev/hipanel-rbac/blob/8fb14f035db3eb7b87bf6c0bcd894535097f14ef/src/SetterTrait.php#L132-L140 | train |
orchestral/support | src/Support/Concerns/Uploadable.php | Uploadable.getUploadedFilename | protected function getUploadedFilename(UploadedFile $file): string
{
$extension = $file->getClientOriginalExtension();
return \sprintf('%s.%s', Str::random(10), $extension);
} | php | protected function getUploadedFilename(UploadedFile $file): string
{
$extension = $file->getClientOriginalExtension();
return \sprintf('%s.%s', Str::random(10), $extension);
} | [
"protected",
"function",
"getUploadedFilename",
"(",
"UploadedFile",
"$",
"file",
")",
":",
"string",
"{",
"$",
"extension",
"=",
"$",
"file",
"->",
"getClientOriginalExtension",
"(",
")",
";",
"return",
"\\",
"sprintf",
"(",
"'%s.%s'",
",",
"Str",
"::",
"ra... | Get uploaded filename.
@param \Symfony\Component\HttpFoundation\File\UploadedFile $file
@return string | [
"Get",
"uploaded",
"filename",
"."
] | b56f0469f967737e39fc9a33d40ae7439f4f6884 | https://github.com/orchestral/support/blob/b56f0469f967737e39fc9a33d40ae7439f4f6884/src/Support/Concerns/Uploadable.php#L45-L50 | train |
anomalylabs/variables-module | src/Variable/VariableRepository.php | VariableRepository.presenter | public function presenter($group, $field)
{
if (!$group = $this->group($group)) {
return null;
}
return (new Decorator())->decorate($group)->{$field};
} | php | public function presenter($group, $field)
{
if (!$group = $this->group($group)) {
return null;
}
return (new Decorator())->decorate($group)->{$field};
} | [
"public",
"function",
"presenter",
"(",
"$",
"group",
",",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"$",
"group",
"=",
"$",
"this",
"->",
"group",
"(",
"$",
"group",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"(",
"new",
"Decorator",
"("... | Get a variable presenter.
@param $group
@param $field
@return FieldTypePresenter|null | [
"Get",
"a",
"variable",
"presenter",
"."
] | bcd903670471a175f07aba3123693cb3a3c07d0b | https://github.com/anomalylabs/variables-module/blob/bcd903670471a175f07aba3123693cb3a3c07d0b/src/Variable/VariableRepository.php#L61-L68 | train |
hiqdev/hipanel-module-domain | src/repositories/DomainTariffRepository.php | DomainTariffRepository.getTariff | public function getTariff()
{
if ($this->app->user->isGuest) {
$seller = $this->app->user->seller;
$client_id = null;
} else {
$seller = $this->app->user->identity->seller;
$client_id = $this->app->user->id;
}
return $this->app->get('cache')->getOrSet([__METHOD__, $seller, $client_id], function () use ($seller, $client_id) {
$res = Tariff::find()
->action('get-available-info')
->joinWith('resources')
->andFilterWhere(['type' => 'domain'])
->andFilterWhere(['seller' => $seller])
->andWhere(['with_resources' => true])
->all();
if (is_array($res) && !empty($res)) {
return reset($res);
}
return null;
}, 3600);
} | php | public function getTariff()
{
if ($this->app->user->isGuest) {
$seller = $this->app->user->seller;
$client_id = null;
} else {
$seller = $this->app->user->identity->seller;
$client_id = $this->app->user->id;
}
return $this->app->get('cache')->getOrSet([__METHOD__, $seller, $client_id], function () use ($seller, $client_id) {
$res = Tariff::find()
->action('get-available-info')
->joinWith('resources')
->andFilterWhere(['type' => 'domain'])
->andFilterWhere(['seller' => $seller])
->andWhere(['with_resources' => true])
->all();
if (is_array($res) && !empty($res)) {
return reset($res);
}
return null;
}, 3600);
} | [
"public",
"function",
"getTariff",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"app",
"->",
"user",
"->",
"isGuest",
")",
"{",
"$",
"seller",
"=",
"$",
"this",
"->",
"app",
"->",
"user",
"->",
"seller",
";",
"$",
"client_id",
"=",
"null",
";",
"... | Returns the tariff for the domain operations
Caches the API request for 3600 seconds and depends on client id and seller login.
@return Tariff|null The domain tariff or boolean `false` when no tariff was found | [
"Returns",
"the",
"tariff",
"for",
"the",
"domain",
"operations",
"Caches",
"the",
"API",
"request",
"for",
"3600",
"seconds",
"and",
"depends",
"on",
"client",
"id",
"and",
"seller",
"login",
"."
] | b1b02782fcb69970cacafe6c6ead238b14b54209 | https://github.com/hiqdev/hipanel-module-domain/blob/b1b02782fcb69970cacafe6c6ead238b14b54209/src/repositories/DomainTariffRepository.php#L33-L58 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.