repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
silverstripe/silverstripe-fulltextsearch | src/Search/Processors/SearchUpdateCommitJobProcessor.php | SearchUpdateCommitJobProcessor.getAllIndexes | public function getAllIndexes()
{
if (empty($this->indexes)) {
$indexes = FullTextSearch::get_indexes();
$this->indexes = array_keys($indexes);
}
return $this->indexes;
} | php | public function getAllIndexes()
{
if (empty($this->indexes)) {
$indexes = FullTextSearch::get_indexes();
$this->indexes = array_keys($indexes);
}
return $this->indexes;
} | [
"public",
"function",
"getAllIndexes",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"indexes",
")",
")",
"{",
"$",
"indexes",
"=",
"FullTextSearch",
"::",
"get_indexes",
"(",
")",
";",
"$",
"this",
"->",
"indexes",
"=",
"array_keys",
"(",
"$",
"indexes",
")",
";",
"}",
"return",
"$",
"this",
"->",
"indexes",
";",
"}"
] | Get the list of index names we should process
@return array | [
"Get",
"the",
"list",
"of",
"index",
"names",
"we",
"should",
"process"
] | train | https://github.com/silverstripe/silverstripe-fulltextsearch/blob/d6a119ce202f1af0112fb0ed046d578fe878aeb4/src/Search/Processors/SearchUpdateCommitJobProcessor.php#L125-L132 |
silverstripe/silverstripe-fulltextsearch | src/Search/Processors/SearchUpdateCommitJobProcessor.php | SearchUpdateCommitJobProcessor.discardJob | protected function discardJob()
{
$this->skipped = true;
// If we do not have dirty records, then assume that these dirty records were committed
// already this request (but probably another job), so we don't need to commit anything else.
// This could occur if we completed multiple searchupdate jobs in a prior request, and
// we only need one commit job to commit all of them in the current request.
if (empty(static::$dirty_indexes)) {
$this->addMessage("Indexing already completed this request: Discarding this job");
return;
}
// If any commit has run, but some (or all) indexes are un-comitted, we must re-schedule this task.
// This could occur if we completed a searchupdate job in a prior request, as well as in
// the current request
$cooldown = Config::inst()->get(__CLASS__, 'cooldown');
$now = new DateTime(DBDatetime::now()->getValue());
$now->add(new DateInterval('PT' . $cooldown . 'S'));
$runat = $now->Format('Y-m-d H:i:s');
$this->addMessage("Indexing already run this request, but incomplete. Re-scheduling for {$runat}");
// Queue after the given cooldown
static::queue(false, $runat);
} | php | protected function discardJob()
{
$this->skipped = true;
// If we do not have dirty records, then assume that these dirty records were committed
// already this request (but probably another job), so we don't need to commit anything else.
// This could occur if we completed multiple searchupdate jobs in a prior request, and
// we only need one commit job to commit all of them in the current request.
if (empty(static::$dirty_indexes)) {
$this->addMessage("Indexing already completed this request: Discarding this job");
return;
}
// If any commit has run, but some (or all) indexes are un-comitted, we must re-schedule this task.
// This could occur if we completed a searchupdate job in a prior request, as well as in
// the current request
$cooldown = Config::inst()->get(__CLASS__, 'cooldown');
$now = new DateTime(DBDatetime::now()->getValue());
$now->add(new DateInterval('PT' . $cooldown . 'S'));
$runat = $now->Format('Y-m-d H:i:s');
$this->addMessage("Indexing already run this request, but incomplete. Re-scheduling for {$runat}");
// Queue after the given cooldown
static::queue(false, $runat);
} | [
"protected",
"function",
"discardJob",
"(",
")",
"{",
"$",
"this",
"->",
"skipped",
"=",
"true",
";",
"// If we do not have dirty records, then assume that these dirty records were committed",
"// already this request (but probably another job), so we don't need to commit anything else.",
"// This could occur if we completed multiple searchupdate jobs in a prior request, and",
"// we only need one commit job to commit all of them in the current request.",
"if",
"(",
"empty",
"(",
"static",
"::",
"$",
"dirty_indexes",
")",
")",
"{",
"$",
"this",
"->",
"addMessage",
"(",
"\"Indexing already completed this request: Discarding this job\"",
")",
";",
"return",
";",
"}",
"// If any commit has run, but some (or all) indexes are un-comitted, we must re-schedule this task.",
"// This could occur if we completed a searchupdate job in a prior request, as well as in",
"// the current request",
"$",
"cooldown",
"=",
"Config",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"__CLASS__",
",",
"'cooldown'",
")",
";",
"$",
"now",
"=",
"new",
"DateTime",
"(",
"DBDatetime",
"::",
"now",
"(",
")",
"->",
"getValue",
"(",
")",
")",
";",
"$",
"now",
"->",
"add",
"(",
"new",
"DateInterval",
"(",
"'PT'",
".",
"$",
"cooldown",
".",
"'S'",
")",
")",
";",
"$",
"runat",
"=",
"$",
"now",
"->",
"Format",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"this",
"->",
"addMessage",
"(",
"\"Indexing already run this request, but incomplete. Re-scheduling for {$runat}\"",
")",
";",
"// Queue after the given cooldown",
"static",
"::",
"queue",
"(",
"false",
",",
"$",
"runat",
")",
";",
"}"
] | Abort this job, potentially rescheduling a replacement if there is still work to do | [
"Abort",
"this",
"job",
"potentially",
"rescheduling",
"a",
"replacement",
"if",
"there",
"is",
"still",
"work",
"to",
"do"
] | train | https://github.com/silverstripe/silverstripe-fulltextsearch/blob/d6a119ce202f1af0112fb0ed046d578fe878aeb4/src/Search/Processors/SearchUpdateCommitJobProcessor.php#L154-L180 |
silverstripe/silverstripe-fulltextsearch | src/Search/Processors/SearchUpdateCommitJobProcessor.php | SearchUpdateCommitJobProcessor.commitIndex | protected function commitIndex($index)
{
// Skip index if this is already complete
$name = get_class($index);
if (in_array($name, $this->completed)) {
$this->addMessage("Skipping already comitted index {$name}");
return;
}
// Bypass SolrIndex::commit exception handling so that queuedjobs can handle the error
$this->addMessage("Committing index {$name}");
$index->getService()->commit(false, false, false);
$this->addMessage("Committing index {$name} was successful");
// If this index is currently marked as dirty, it's now clean
if (in_array($name, static::$dirty_indexes)) {
static::$dirty_indexes = array_diff(static::$dirty_indexes, array($name));
}
// Mark complete
$this->completed[] = $name;
} | php | protected function commitIndex($index)
{
// Skip index if this is already complete
$name = get_class($index);
if (in_array($name, $this->completed)) {
$this->addMessage("Skipping already comitted index {$name}");
return;
}
// Bypass SolrIndex::commit exception handling so that queuedjobs can handle the error
$this->addMessage("Committing index {$name}");
$index->getService()->commit(false, false, false);
$this->addMessage("Committing index {$name} was successful");
// If this index is currently marked as dirty, it's now clean
if (in_array($name, static::$dirty_indexes)) {
static::$dirty_indexes = array_diff(static::$dirty_indexes, array($name));
}
// Mark complete
$this->completed[] = $name;
} | [
"protected",
"function",
"commitIndex",
"(",
"$",
"index",
")",
"{",
"// Skip index if this is already complete",
"$",
"name",
"=",
"get_class",
"(",
"$",
"index",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"completed",
")",
")",
"{",
"$",
"this",
"->",
"addMessage",
"(",
"\"Skipping already comitted index {$name}\"",
")",
";",
"return",
";",
"}",
"// Bypass SolrIndex::commit exception handling so that queuedjobs can handle the error",
"$",
"this",
"->",
"addMessage",
"(",
"\"Committing index {$name}\"",
")",
";",
"$",
"index",
"->",
"getService",
"(",
")",
"->",
"commit",
"(",
"false",
",",
"false",
",",
"false",
")",
";",
"$",
"this",
"->",
"addMessage",
"(",
"\"Committing index {$name} was successful\"",
")",
";",
"// If this index is currently marked as dirty, it's now clean",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"static",
"::",
"$",
"dirty_indexes",
")",
")",
"{",
"static",
"::",
"$",
"dirty_indexes",
"=",
"array_diff",
"(",
"static",
"::",
"$",
"dirty_indexes",
",",
"array",
"(",
"$",
"name",
")",
")",
";",
"}",
"// Mark complete",
"$",
"this",
"->",
"completed",
"[",
"]",
"=",
"$",
"name",
";",
"}"
] | Commits a specific index
@param SolrIndex $index
@throws Exception | [
"Commits",
"a",
"specific",
"index"
] | train | https://github.com/silverstripe/silverstripe-fulltextsearch/blob/d6a119ce202f1af0112fb0ed046d578fe878aeb4/src/Search/Processors/SearchUpdateCommitJobProcessor.php#L212-L233 |
nesk/rialto | src/Exceptions/Node/HandlesNodeErrors.php | HandlesNodeErrors.isNodeError | protected static function isNodeError(string $error): bool
{
$error = json_decode($error, true);
return ($error['__rialto_error__'] ?? false) === true;
} | php | protected static function isNodeError(string $error): bool
{
$error = json_decode($error, true);
return ($error['__rialto_error__'] ?? false) === true;
} | [
"protected",
"static",
"function",
"isNodeError",
"(",
"string",
"$",
"error",
")",
":",
"bool",
"{",
"$",
"error",
"=",
"json_decode",
"(",
"$",
"error",
",",
"true",
")",
";",
"return",
"(",
"$",
"error",
"[",
"'__rialto_error__'",
"]",
"??",
"false",
")",
"===",
"true",
";",
"}"
] | Determines if the string contains a Node error. | [
"Determines",
"if",
"the",
"string",
"contains",
"a",
"Node",
"error",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Exceptions/Node/HandlesNodeErrors.php#L17-L22 |
nesk/rialto | src/Exceptions/Node/HandlesNodeErrors.php | HandlesNodeErrors.setTraceAndGetMessage | protected function setTraceAndGetMessage($error, bool $appendStackTraceToMessage = false): string
{
$error = is_string($error) ? json_decode($error, true) : $error;
$this->originalTrace = $error['stack'] ?? null;
$message = $error['message'];
if ($appendStackTraceToMessage) {
$message .= "\n\n".$error['stack'];
}
return $message;
} | php | protected function setTraceAndGetMessage($error, bool $appendStackTraceToMessage = false): string
{
$error = is_string($error) ? json_decode($error, true) : $error;
$this->originalTrace = $error['stack'] ?? null;
$message = $error['message'];
if ($appendStackTraceToMessage) {
$message .= "\n\n".$error['stack'];
}
return $message;
} | [
"protected",
"function",
"setTraceAndGetMessage",
"(",
"$",
"error",
",",
"bool",
"$",
"appendStackTraceToMessage",
"=",
"false",
")",
":",
"string",
"{",
"$",
"error",
"=",
"is_string",
"(",
"$",
"error",
")",
"?",
"json_decode",
"(",
"$",
"error",
",",
"true",
")",
":",
"$",
"error",
";",
"$",
"this",
"->",
"originalTrace",
"=",
"$",
"error",
"[",
"'stack'",
"]",
"??",
"null",
";",
"$",
"message",
"=",
"$",
"error",
"[",
"'message'",
"]",
";",
"if",
"(",
"$",
"appendStackTraceToMessage",
")",
"{",
"$",
"message",
".=",
"\"\\n\\n\"",
".",
"$",
"error",
"[",
"'stack'",
"]",
";",
"}",
"return",
"$",
"message",
";",
"}"
] | Set the original trace and return the message. | [
"Set",
"the",
"original",
"trace",
"and",
"return",
"the",
"message",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Exceptions/Node/HandlesNodeErrors.php#L27-L40 |
nesk/rialto | src/AbstractEntryPoint.php | AbstractEntryPoint.consolidateOptions | protected function consolidateOptions(array $implementationOptions, array $userOptions): array
{
// Filter out the forbidden option
$userOptions = array_diff_key($userOptions, array_flip($this->forbiddenOptions));
// Merge the user options with the implementation ones
return array_merge($implementationOptions, $userOptions);
} | php | protected function consolidateOptions(array $implementationOptions, array $userOptions): array
{
// Filter out the forbidden option
$userOptions = array_diff_key($userOptions, array_flip($this->forbiddenOptions));
// Merge the user options with the implementation ones
return array_merge($implementationOptions, $userOptions);
} | [
"protected",
"function",
"consolidateOptions",
"(",
"array",
"$",
"implementationOptions",
",",
"array",
"$",
"userOptions",
")",
":",
"array",
"{",
"// Filter out the forbidden option",
"$",
"userOptions",
"=",
"array_diff_key",
"(",
"$",
"userOptions",
",",
"array_flip",
"(",
"$",
"this",
"->",
"forbiddenOptions",
")",
")",
";",
"// Merge the user options with the implementation ones",
"return",
"array_merge",
"(",
"$",
"implementationOptions",
",",
"$",
"userOptions",
")",
";",
"}"
] | Clean the user options. | [
"Clean",
"the",
"user",
"options",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/AbstractEntryPoint.php#L39-L46 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.logProcessStandardStreams | protected function logProcessStandardStreams(): void
{
if (!empty($output = $this->process->getIncrementalOutput())) {
$this->logger->notice('Received data on stdout: {output}', [
'pid' => $this->processPid,
'stream' => 'stdout',
'output' => $output,
]);
}
if (!empty($errorOutput = $this->process->getIncrementalErrorOutput())) {
$this->logger->error('Received data on stderr: {output}', [
'pid' => $this->processPid,
'stream' => 'stderr',
'output' => $errorOutput,
]);
}
} | php | protected function logProcessStandardStreams(): void
{
if (!empty($output = $this->process->getIncrementalOutput())) {
$this->logger->notice('Received data on stdout: {output}', [
'pid' => $this->processPid,
'stream' => 'stdout',
'output' => $output,
]);
}
if (!empty($errorOutput = $this->process->getIncrementalErrorOutput())) {
$this->logger->error('Received data on stderr: {output}', [
'pid' => $this->processPid,
'stream' => 'stderr',
'output' => $errorOutput,
]);
}
} | [
"protected",
"function",
"logProcessStandardStreams",
"(",
")",
":",
"void",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"output",
"=",
"$",
"this",
"->",
"process",
"->",
"getIncrementalOutput",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"notice",
"(",
"'Received data on stdout: {output}'",
",",
"[",
"'pid'",
"=>",
"$",
"this",
"->",
"processPid",
",",
"'stream'",
"=>",
"'stdout'",
",",
"'output'",
"=>",
"$",
"output",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"errorOutput",
"=",
"$",
"this",
"->",
"process",
"->",
"getIncrementalErrorOutput",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'Received data on stderr: {output}'",
",",
"[",
"'pid'",
"=>",
"$",
"this",
"->",
"processPid",
",",
"'stream'",
"=>",
"'stderr'",
",",
"'output'",
"=>",
"$",
"errorOutput",
",",
"]",
")",
";",
"}",
"}"
] | Log data from the process standard streams. | [
"Log",
"data",
"from",
"the",
"process",
"standard",
"streams",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L180-L197 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.applyOptions | protected function applyOptions(array $options): void
{
$this->logger->info('Applying options...', ['options' => $options]);
$this->options = array_merge($this->options, $options);
$this->logger->debug('Options applied and merged with defaults', ['options' => $this->options]);
} | php | protected function applyOptions(array $options): void
{
$this->logger->info('Applying options...', ['options' => $options]);
$this->options = array_merge($this->options, $options);
$this->logger->debug('Options applied and merged with defaults', ['options' => $this->options]);
} | [
"protected",
"function",
"applyOptions",
"(",
"array",
"$",
"options",
")",
":",
"void",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Applying options...'",
",",
"[",
"'options'",
"=>",
"$",
"options",
"]",
")",
";",
"$",
"this",
"->",
"options",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"options",
",",
"$",
"options",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Options applied and merged with defaults'",
",",
"[",
"'options'",
"=>",
"$",
"this",
"->",
"options",
"]",
")",
";",
"}"
] | Apply the options. | [
"Apply",
"the",
"options",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L202-L209 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.getProcessScriptPath | protected function getProcessScriptPath(): string {
static $scriptPath = null;
if ($scriptPath !== null) {
return $scriptPath;
}
// The script path in local development
$scriptPath = __DIR__.'/node-process/serve.js';
$process = new SymfonyProcess([
$this->options['executable_path'],
'-e',
"process.stdout.write(require.resolve('@nesk/rialto/src/node-process/serve.js'))",
]);
$exitCode = $process->run();
if ($exitCode === 0) {
// The script path in production
$scriptPath = $process->getOutput();
}
return $scriptPath;
} | php | protected function getProcessScriptPath(): string {
static $scriptPath = null;
if ($scriptPath !== null) {
return $scriptPath;
}
// The script path in local development
$scriptPath = __DIR__.'/node-process/serve.js';
$process = new SymfonyProcess([
$this->options['executable_path'],
'-e',
"process.stdout.write(require.resolve('@nesk/rialto/src/node-process/serve.js'))",
]);
$exitCode = $process->run();
if ($exitCode === 0) {
// The script path in production
$scriptPath = $process->getOutput();
}
return $scriptPath;
} | [
"protected",
"function",
"getProcessScriptPath",
"(",
")",
":",
"string",
"{",
"static",
"$",
"scriptPath",
"=",
"null",
";",
"if",
"(",
"$",
"scriptPath",
"!==",
"null",
")",
"{",
"return",
"$",
"scriptPath",
";",
"}",
"// The script path in local development",
"$",
"scriptPath",
"=",
"__DIR__",
".",
"'/node-process/serve.js'",
";",
"$",
"process",
"=",
"new",
"SymfonyProcess",
"(",
"[",
"$",
"this",
"->",
"options",
"[",
"'executable_path'",
"]",
",",
"'-e'",
",",
"\"process.stdout.write(require.resolve('@nesk/rialto/src/node-process/serve.js'))\"",
",",
"]",
")",
";",
"$",
"exitCode",
"=",
"$",
"process",
"->",
"run",
"(",
")",
";",
"if",
"(",
"$",
"exitCode",
"===",
"0",
")",
"{",
"// The script path in production",
"$",
"scriptPath",
"=",
"$",
"process",
"->",
"getOutput",
"(",
")",
";",
"}",
"return",
"$",
"scriptPath",
";",
"}"
] | Return the script path of the Node process.
In production, the script path must target the NPM package. In local development, the script path targets the
Composer package (since the NPM package is not installed).
This avoids double declarations of some JS classes in production, due to a require with two different paths (one
with the NPM path, the other one with the Composer path). | [
"Return",
"the",
"script",
"path",
"of",
"the",
"Node",
"process",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L220-L244 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.createNewProcess | protected function createNewProcess(string $connectionDelegatePath): SymfonyProcess
{
$realConnectionDelegatePath = realpath($connectionDelegatePath);
if ($realConnectionDelegatePath === false) {
throw new RuntimeException("Cannot find file or directory '$connectionDelegatePath'.");
}
// Remove useless options for the process
$processOptions = array_diff_key($this->options, array_flip(self::USELESS_OPTIONS_FOR_PROCESS));
return new SymfonyProcess(array_merge(
[$this->options['executable_path']],
$this->options['debug'] ? ['--inspect'] : [],
[$this->getProcessScriptPath()],
[$realConnectionDelegatePath],
[json_encode((object) $processOptions)]
));
} | php | protected function createNewProcess(string $connectionDelegatePath): SymfonyProcess
{
$realConnectionDelegatePath = realpath($connectionDelegatePath);
if ($realConnectionDelegatePath === false) {
throw new RuntimeException("Cannot find file or directory '$connectionDelegatePath'.");
}
// Remove useless options for the process
$processOptions = array_diff_key($this->options, array_flip(self::USELESS_OPTIONS_FOR_PROCESS));
return new SymfonyProcess(array_merge(
[$this->options['executable_path']],
$this->options['debug'] ? ['--inspect'] : [],
[$this->getProcessScriptPath()],
[$realConnectionDelegatePath],
[json_encode((object) $processOptions)]
));
} | [
"protected",
"function",
"createNewProcess",
"(",
"string",
"$",
"connectionDelegatePath",
")",
":",
"SymfonyProcess",
"{",
"$",
"realConnectionDelegatePath",
"=",
"realpath",
"(",
"$",
"connectionDelegatePath",
")",
";",
"if",
"(",
"$",
"realConnectionDelegatePath",
"===",
"false",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Cannot find file or directory '$connectionDelegatePath'.\"",
")",
";",
"}",
"// Remove useless options for the process",
"$",
"processOptions",
"=",
"array_diff_key",
"(",
"$",
"this",
"->",
"options",
",",
"array_flip",
"(",
"self",
"::",
"USELESS_OPTIONS_FOR_PROCESS",
")",
")",
";",
"return",
"new",
"SymfonyProcess",
"(",
"array_merge",
"(",
"[",
"$",
"this",
"->",
"options",
"[",
"'executable_path'",
"]",
"]",
",",
"$",
"this",
"->",
"options",
"[",
"'debug'",
"]",
"?",
"[",
"'--inspect'",
"]",
":",
"[",
"]",
",",
"[",
"$",
"this",
"->",
"getProcessScriptPath",
"(",
")",
"]",
",",
"[",
"$",
"realConnectionDelegatePath",
"]",
",",
"[",
"json_encode",
"(",
"(",
"object",
")",
"$",
"processOptions",
")",
"]",
")",
")",
";",
"}"
] | Create a new Node process.
@throws RuntimeException if the path to the connection delegate cannot be found. | [
"Create",
"a",
"new",
"Node",
"process",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L251-L269 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.startProcess | protected function startProcess(SymfonyProcess $process): int
{
$this->logger->info('Starting process with command line: {commandline}', [
'commandline' => $process->getCommandLine(),
]);
$process->start();
$pid = $process->getPid();
$this->logger->info('Process started with PID {pid}', ['pid' => $pid]);
return $pid;
} | php | protected function startProcess(SymfonyProcess $process): int
{
$this->logger->info('Starting process with command line: {commandline}', [
'commandline' => $process->getCommandLine(),
]);
$process->start();
$pid = $process->getPid();
$this->logger->info('Process started with PID {pid}', ['pid' => $pid]);
return $pid;
} | [
"protected",
"function",
"startProcess",
"(",
"SymfonyProcess",
"$",
"process",
")",
":",
"int",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Starting process with command line: {commandline}'",
",",
"[",
"'commandline'",
"=>",
"$",
"process",
"->",
"getCommandLine",
"(",
")",
",",
"]",
")",
";",
"$",
"process",
"->",
"start",
"(",
")",
";",
"$",
"pid",
"=",
"$",
"process",
"->",
"getPid",
"(",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Process started with PID {pid}'",
",",
"[",
"'pid'",
"=>",
"$",
"pid",
"]",
")",
";",
"return",
"$",
"pid",
";",
"}"
] | Start the Node process. | [
"Start",
"the",
"Node",
"process",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L274-L287 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.checkProcessStatus | protected function checkProcessStatus(): void
{
$this->logProcessStandardStreams();
$process = $this->process;
if (!empty($process->getErrorOutput())) {
if (IdleTimeoutException::exceptionApplies($process)) {
throw new IdleTimeoutException(
$this->options['idle_timeout'],
new NodeFatalException($process, $this->options['debug'])
);
} else if (NodeFatalException::exceptionApplies($process)) {
throw new NodeFatalException($process, $this->options['debug']);
} elseif ($process->isTerminated() && !$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
}
if ($process->isTerminated()) {
throw new Exceptions\ProcessUnexpectedlyTerminatedException($process);
}
} | php | protected function checkProcessStatus(): void
{
$this->logProcessStandardStreams();
$process = $this->process;
if (!empty($process->getErrorOutput())) {
if (IdleTimeoutException::exceptionApplies($process)) {
throw new IdleTimeoutException(
$this->options['idle_timeout'],
new NodeFatalException($process, $this->options['debug'])
);
} else if (NodeFatalException::exceptionApplies($process)) {
throw new NodeFatalException($process, $this->options['debug']);
} elseif ($process->isTerminated() && !$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
}
if ($process->isTerminated()) {
throw new Exceptions\ProcessUnexpectedlyTerminatedException($process);
}
} | [
"protected",
"function",
"checkProcessStatus",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"logProcessStandardStreams",
"(",
")",
";",
"$",
"process",
"=",
"$",
"this",
"->",
"process",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"process",
"->",
"getErrorOutput",
"(",
")",
")",
")",
"{",
"if",
"(",
"IdleTimeoutException",
"::",
"exceptionApplies",
"(",
"$",
"process",
")",
")",
"{",
"throw",
"new",
"IdleTimeoutException",
"(",
"$",
"this",
"->",
"options",
"[",
"'idle_timeout'",
"]",
",",
"new",
"NodeFatalException",
"(",
"$",
"process",
",",
"$",
"this",
"->",
"options",
"[",
"'debug'",
"]",
")",
")",
";",
"}",
"else",
"if",
"(",
"NodeFatalException",
"::",
"exceptionApplies",
"(",
"$",
"process",
")",
")",
"{",
"throw",
"new",
"NodeFatalException",
"(",
"$",
"process",
",",
"$",
"this",
"->",
"options",
"[",
"'debug'",
"]",
")",
";",
"}",
"elseif",
"(",
"$",
"process",
"->",
"isTerminated",
"(",
")",
"&&",
"!",
"$",
"process",
"->",
"isSuccessful",
"(",
")",
")",
"{",
"throw",
"new",
"ProcessFailedException",
"(",
"$",
"process",
")",
";",
"}",
"}",
"if",
"(",
"$",
"process",
"->",
"isTerminated",
"(",
")",
")",
"{",
"throw",
"new",
"Exceptions",
"\\",
"ProcessUnexpectedlyTerminatedException",
"(",
"$",
"process",
")",
";",
"}",
"}"
] | Check if the process is still running without errors.
@throws \Symfony\Component\Process\Exception\ProcessFailedException | [
"Check",
"if",
"the",
"process",
"is",
"still",
"running",
"without",
"errors",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L294-L316 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.serverPort | protected function serverPort(): int
{
if ($this->serverPort !== null) {
return $this->serverPort;
}
$iterator = $this->process->getIterator(SymfonyProcess::ITER_SKIP_ERR | SymfonyProcess::ITER_KEEP_OUTPUT);
foreach ($iterator as $data) {
return $this->serverPort = (int) $data;
}
// If the iterator didn't execute properly, then the process must have failed, we must check to be sure.
$this->checkProcessStatus();
} | php | protected function serverPort(): int
{
if ($this->serverPort !== null) {
return $this->serverPort;
}
$iterator = $this->process->getIterator(SymfonyProcess::ITER_SKIP_ERR | SymfonyProcess::ITER_KEEP_OUTPUT);
foreach ($iterator as $data) {
return $this->serverPort = (int) $data;
}
// If the iterator didn't execute properly, then the process must have failed, we must check to be sure.
$this->checkProcessStatus();
} | [
"protected",
"function",
"serverPort",
"(",
")",
":",
"int",
"{",
"if",
"(",
"$",
"this",
"->",
"serverPort",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"serverPort",
";",
"}",
"$",
"iterator",
"=",
"$",
"this",
"->",
"process",
"->",
"getIterator",
"(",
"SymfonyProcess",
"::",
"ITER_SKIP_ERR",
"|",
"SymfonyProcess",
"::",
"ITER_KEEP_OUTPUT",
")",
";",
"foreach",
"(",
"$",
"iterator",
"as",
"$",
"data",
")",
"{",
"return",
"$",
"this",
"->",
"serverPort",
"=",
"(",
"int",
")",
"$",
"data",
";",
"}",
"// If the iterator didn't execute properly, then the process must have failed, we must check to be sure.",
"$",
"this",
"->",
"checkProcessStatus",
"(",
")",
";",
"}"
] | Return the port of the server. | [
"Return",
"the",
"port",
"of",
"the",
"server",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L331-L345 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.executeInstruction | public function executeInstruction(Instruction $instruction, bool $instructionShouldBeLogged = true)
{
// Check the process status because it could have crash in idle status.
$this->checkProcessStatus();
$serializedInstruction = json_encode($instruction);
if ($instructionShouldBeLogged) {
$this->logger->debug('Sending an instruction to the port {port}...', [
'pid' => $this->processPid,
'port' => $this->serverPort(),
// The instruction must be fully encoded and decoded to appear properly in the logs (this way,
// JS functions and resources are serialized too).
'instruction' => json_decode($serializedInstruction, true),
]);
}
$this->client->selectWrite(1);
$this->client->write($serializedInstruction);
$value = $this->readNextProcessValue($instructionShouldBeLogged);
// Check the process status if the value is null because, if the process crash while executing the instruction,
// the socket closes and returns an empty value (which is converted to `null`).
if ($value === null) {
$this->checkProcessStatus();
}
return $value;
} | php | public function executeInstruction(Instruction $instruction, bool $instructionShouldBeLogged = true)
{
// Check the process status because it could have crash in idle status.
$this->checkProcessStatus();
$serializedInstruction = json_encode($instruction);
if ($instructionShouldBeLogged) {
$this->logger->debug('Sending an instruction to the port {port}...', [
'pid' => $this->processPid,
'port' => $this->serverPort(),
// The instruction must be fully encoded and decoded to appear properly in the logs (this way,
// JS functions and resources are serialized too).
'instruction' => json_decode($serializedInstruction, true),
]);
}
$this->client->selectWrite(1);
$this->client->write($serializedInstruction);
$value = $this->readNextProcessValue($instructionShouldBeLogged);
// Check the process status if the value is null because, if the process crash while executing the instruction,
// the socket closes and returns an empty value (which is converted to `null`).
if ($value === null) {
$this->checkProcessStatus();
}
return $value;
} | [
"public",
"function",
"executeInstruction",
"(",
"Instruction",
"$",
"instruction",
",",
"bool",
"$",
"instructionShouldBeLogged",
"=",
"true",
")",
"{",
"// Check the process status because it could have crash in idle status.",
"$",
"this",
"->",
"checkProcessStatus",
"(",
")",
";",
"$",
"serializedInstruction",
"=",
"json_encode",
"(",
"$",
"instruction",
")",
";",
"if",
"(",
"$",
"instructionShouldBeLogged",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Sending an instruction to the port {port}...'",
",",
"[",
"'pid'",
"=>",
"$",
"this",
"->",
"processPid",
",",
"'port'",
"=>",
"$",
"this",
"->",
"serverPort",
"(",
")",
",",
"// The instruction must be fully encoded and decoded to appear properly in the logs (this way,",
"// JS functions and resources are serialized too).",
"'instruction'",
"=>",
"json_decode",
"(",
"$",
"serializedInstruction",
",",
"true",
")",
",",
"]",
")",
";",
"}",
"$",
"this",
"->",
"client",
"->",
"selectWrite",
"(",
"1",
")",
";",
"$",
"this",
"->",
"client",
"->",
"write",
"(",
"$",
"serializedInstruction",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"readNextProcessValue",
"(",
"$",
"instructionShouldBeLogged",
")",
";",
"// Check the process status if the value is null because, if the process crash while executing the instruction,",
"// the socket closes and returns an empty value (which is converted to `null`).",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"checkProcessStatus",
"(",
")",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | Send an instruction to the process for execution. | [
"Send",
"an",
"instruction",
"to",
"the",
"process",
"for",
"execution",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L361-L391 |
nesk/rialto | src/ProcessSupervisor.php | ProcessSupervisor.readNextProcessValue | protected function readNextProcessValue(bool $valueShouldBeLogged = true)
{
$readTimeout = $this->options['read_timeout'];
$payload = '';
try {
$startTimestamp = microtime(true);
do {
$this->client->selectRead($readTimeout);
$packet = $this->client->read(static::SOCKET_PACKET_SIZE);
$chunksLeft = (int) substr($packet, 0, static::SOCKET_HEADER_SIZE);
$chunk = substr($packet, static::SOCKET_HEADER_SIZE);
$payload .= $chunk;
if ($chunksLeft > 0) {
// The next chunk might be an empty string if don't wait a short period on slow environments.
usleep(self::SOCKET_NEXT_CHUNK_DELAY * 1000);
}
} while ($chunksLeft > 0);
} catch (SocketException $exception) {
$this->waitForProcessTermination();
$this->checkProcessStatus();
// Extract the socket error code to throw more specific exceptions
preg_match('/\(([A-Z_]+?)\)$/', $exception->getMessage(), $socketErrorMatches);
$socketErrorCode = constant($socketErrorMatches[1]);
$elapsedTime = microtime(true) - $startTimestamp;
if ($socketErrorCode === SOCKET_EAGAIN && $readTimeout !== null && $elapsedTime >= $readTimeout) {
throw new Exceptions\ReadSocketTimeoutException($readTimeout, $exception);
}
throw $exception;
}
$this->logProcessStandardStreams();
['logs' => $logs, 'value' => $value] = json_decode(base64_decode($payload), true);
foreach ($logs ?: [] as $log) {
$level = (new \ReflectionClass(LogLevel::class))->getConstant($log['level']);
$messageContainsLineBreaks = strstr($log['message'], PHP_EOL) !== false;
$formattedMessage = $messageContainsLineBreaks ? "\n{log}\n" : '{log}';
$this->logger->log($level, "Received a $log[origin] log: $formattedMessage", [
'pid' => $this->processPid,
'port' => $this->serverPort(),
'log' => $log['message'],
]);
}
$value = $this->unserialize($value);
if ($valueShouldBeLogged) {
$this->logger->debug('Received data from the port {port}...', [
'pid' => $this->processPid,
'port' => $this->serverPort(),
'data' => $value,
]);
}
if ($value instanceof NodeException) {
throw $value;
}
return $value;
} | php | protected function readNextProcessValue(bool $valueShouldBeLogged = true)
{
$readTimeout = $this->options['read_timeout'];
$payload = '';
try {
$startTimestamp = microtime(true);
do {
$this->client->selectRead($readTimeout);
$packet = $this->client->read(static::SOCKET_PACKET_SIZE);
$chunksLeft = (int) substr($packet, 0, static::SOCKET_HEADER_SIZE);
$chunk = substr($packet, static::SOCKET_HEADER_SIZE);
$payload .= $chunk;
if ($chunksLeft > 0) {
// The next chunk might be an empty string if don't wait a short period on slow environments.
usleep(self::SOCKET_NEXT_CHUNK_DELAY * 1000);
}
} while ($chunksLeft > 0);
} catch (SocketException $exception) {
$this->waitForProcessTermination();
$this->checkProcessStatus();
// Extract the socket error code to throw more specific exceptions
preg_match('/\(([A-Z_]+?)\)$/', $exception->getMessage(), $socketErrorMatches);
$socketErrorCode = constant($socketErrorMatches[1]);
$elapsedTime = microtime(true) - $startTimestamp;
if ($socketErrorCode === SOCKET_EAGAIN && $readTimeout !== null && $elapsedTime >= $readTimeout) {
throw new Exceptions\ReadSocketTimeoutException($readTimeout, $exception);
}
throw $exception;
}
$this->logProcessStandardStreams();
['logs' => $logs, 'value' => $value] = json_decode(base64_decode($payload), true);
foreach ($logs ?: [] as $log) {
$level = (new \ReflectionClass(LogLevel::class))->getConstant($log['level']);
$messageContainsLineBreaks = strstr($log['message'], PHP_EOL) !== false;
$formattedMessage = $messageContainsLineBreaks ? "\n{log}\n" : '{log}';
$this->logger->log($level, "Received a $log[origin] log: $formattedMessage", [
'pid' => $this->processPid,
'port' => $this->serverPort(),
'log' => $log['message'],
]);
}
$value = $this->unserialize($value);
if ($valueShouldBeLogged) {
$this->logger->debug('Received data from the port {port}...', [
'pid' => $this->processPid,
'port' => $this->serverPort(),
'data' => $value,
]);
}
if ($value instanceof NodeException) {
throw $value;
}
return $value;
} | [
"protected",
"function",
"readNextProcessValue",
"(",
"bool",
"$",
"valueShouldBeLogged",
"=",
"true",
")",
"{",
"$",
"readTimeout",
"=",
"$",
"this",
"->",
"options",
"[",
"'read_timeout'",
"]",
";",
"$",
"payload",
"=",
"''",
";",
"try",
"{",
"$",
"startTimestamp",
"=",
"microtime",
"(",
"true",
")",
";",
"do",
"{",
"$",
"this",
"->",
"client",
"->",
"selectRead",
"(",
"$",
"readTimeout",
")",
";",
"$",
"packet",
"=",
"$",
"this",
"->",
"client",
"->",
"read",
"(",
"static",
"::",
"SOCKET_PACKET_SIZE",
")",
";",
"$",
"chunksLeft",
"=",
"(",
"int",
")",
"substr",
"(",
"$",
"packet",
",",
"0",
",",
"static",
"::",
"SOCKET_HEADER_SIZE",
")",
";",
"$",
"chunk",
"=",
"substr",
"(",
"$",
"packet",
",",
"static",
"::",
"SOCKET_HEADER_SIZE",
")",
";",
"$",
"payload",
".=",
"$",
"chunk",
";",
"if",
"(",
"$",
"chunksLeft",
">",
"0",
")",
"{",
"// The next chunk might be an empty string if don't wait a short period on slow environments.",
"usleep",
"(",
"self",
"::",
"SOCKET_NEXT_CHUNK_DELAY",
"*",
"1000",
")",
";",
"}",
"}",
"while",
"(",
"$",
"chunksLeft",
">",
"0",
")",
";",
"}",
"catch",
"(",
"SocketException",
"$",
"exception",
")",
"{",
"$",
"this",
"->",
"waitForProcessTermination",
"(",
")",
";",
"$",
"this",
"->",
"checkProcessStatus",
"(",
")",
";",
"// Extract the socket error code to throw more specific exceptions",
"preg_match",
"(",
"'/\\(([A-Z_]+?)\\)$/'",
",",
"$",
"exception",
"->",
"getMessage",
"(",
")",
",",
"$",
"socketErrorMatches",
")",
";",
"$",
"socketErrorCode",
"=",
"constant",
"(",
"$",
"socketErrorMatches",
"[",
"1",
"]",
")",
";",
"$",
"elapsedTime",
"=",
"microtime",
"(",
"true",
")",
"-",
"$",
"startTimestamp",
";",
"if",
"(",
"$",
"socketErrorCode",
"===",
"SOCKET_EAGAIN",
"&&",
"$",
"readTimeout",
"!==",
"null",
"&&",
"$",
"elapsedTime",
">=",
"$",
"readTimeout",
")",
"{",
"throw",
"new",
"Exceptions",
"\\",
"ReadSocketTimeoutException",
"(",
"$",
"readTimeout",
",",
"$",
"exception",
")",
";",
"}",
"throw",
"$",
"exception",
";",
"}",
"$",
"this",
"->",
"logProcessStandardStreams",
"(",
")",
";",
"[",
"'logs'",
"=>",
"$",
"logs",
",",
"'value'",
"=>",
"$",
"value",
"]",
"=",
"json_decode",
"(",
"base64_decode",
"(",
"$",
"payload",
")",
",",
"true",
")",
";",
"foreach",
"(",
"$",
"logs",
"?",
":",
"[",
"]",
"as",
"$",
"log",
")",
"{",
"$",
"level",
"=",
"(",
"new",
"\\",
"ReflectionClass",
"(",
"LogLevel",
"::",
"class",
")",
")",
"->",
"getConstant",
"(",
"$",
"log",
"[",
"'level'",
"]",
")",
";",
"$",
"messageContainsLineBreaks",
"=",
"strstr",
"(",
"$",
"log",
"[",
"'message'",
"]",
",",
"PHP_EOL",
")",
"!==",
"false",
";",
"$",
"formattedMessage",
"=",
"$",
"messageContainsLineBreaks",
"?",
"\"\\n{log}\\n\"",
":",
"'{log}'",
";",
"$",
"this",
"->",
"logger",
"->",
"log",
"(",
"$",
"level",
",",
"\"Received a $log[origin] log: $formattedMessage\"",
",",
"[",
"'pid'",
"=>",
"$",
"this",
"->",
"processPid",
",",
"'port'",
"=>",
"$",
"this",
"->",
"serverPort",
"(",
")",
",",
"'log'",
"=>",
"$",
"log",
"[",
"'message'",
"]",
",",
"]",
")",
";",
"}",
"$",
"value",
"=",
"$",
"this",
"->",
"unserialize",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"valueShouldBeLogged",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'Received data from the port {port}...'",
",",
"[",
"'pid'",
"=>",
"$",
"this",
"->",
"processPid",
",",
"'port'",
"=>",
"$",
"this",
"->",
"serverPort",
"(",
")",
",",
"'data'",
"=>",
"$",
"value",
",",
"]",
")",
";",
"}",
"if",
"(",
"$",
"value",
"instanceof",
"NodeException",
")",
"{",
"throw",
"$",
"value",
";",
"}",
"return",
"$",
"value",
";",
"}"
] | Read the next value written by the process.
@throws \Nesk\Rialto\Exceptions\ReadSocketTimeoutException if reading the socket exceeded the timeout.
@throws \Nesk\Rialto\Exceptions\Node\Exception if the process returned an error. | [
"Read",
"the",
"next",
"value",
"written",
"by",
"the",
"process",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/ProcessSupervisor.php#L399-L468 |
nesk/rialto | src/Data/JsFunction.php | JsFunction.create | public static function create(...$arguments)
{
trigger_error(__METHOD__.'() has been deprecated and will be removed from v2.', E_USER_DEPRECATED);
if (isset($arguments[0]) && is_string($arguments[0])) {
return new static([], $arguments[0], $arguments[1] ?? []);
}
return new static(...$arguments);
} | php | public static function create(...$arguments)
{
trigger_error(__METHOD__.'() has been deprecated and will be removed from v2.', E_USER_DEPRECATED);
if (isset($arguments[0]) && is_string($arguments[0])) {
return new static([], $arguments[0], $arguments[1] ?? []);
}
return new static(...$arguments);
} | [
"public",
"static",
"function",
"create",
"(",
"...",
"$",
"arguments",
")",
"{",
"trigger_error",
"(",
"__METHOD__",
".",
"'() has been deprecated and will be removed from v2.'",
",",
"E_USER_DEPRECATED",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"arguments",
"[",
"0",
"]",
")",
"&&",
"is_string",
"(",
"$",
"arguments",
"[",
"0",
"]",
")",
")",
"{",
"return",
"new",
"static",
"(",
"[",
"]",
",",
"$",
"arguments",
"[",
"0",
"]",
",",
"$",
"arguments",
"[",
"1",
"]",
"??",
"[",
"]",
")",
";",
"}",
"return",
"new",
"static",
"(",
"...",
"$",
"arguments",
")",
";",
"}"
] | Create a new JS function.
@deprecated 2.0.0 Chaining methods should be used instead. | [
"Create",
"a",
"new",
"JS",
"function",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Data/JsFunction.php#L40-L49 |
nesk/rialto | src/Data/JsFunction.php | JsFunction.jsonSerialize | public function jsonSerialize(): array
{
return [
'__rialto_function__' => true,
'parameters' => (object) $this->parameters,
'body' => $this->body,
'scope' => (object) $this->scope,
'async' => $this->async,
];
} | php | public function jsonSerialize(): array
{
return [
'__rialto_function__' => true,
'parameters' => (object) $this->parameters,
'body' => $this->body,
'scope' => (object) $this->scope,
'async' => $this->async,
];
} | [
"public",
"function",
"jsonSerialize",
"(",
")",
":",
"array",
"{",
"return",
"[",
"'__rialto_function__'",
"=>",
"true",
",",
"'parameters'",
"=>",
"(",
"object",
")",
"$",
"this",
"->",
"parameters",
",",
"'body'",
"=>",
"$",
"this",
"->",
"body",
",",
"'scope'",
"=>",
"(",
"object",
")",
"$",
"this",
"->",
"scope",
",",
"'async'",
"=>",
"$",
"this",
"->",
"async",
",",
"]",
";",
"}"
] | Serialize the object to a value that can be serialized natively by {@see json_encode}. | [
"Serialize",
"the",
"object",
"to",
"a",
"value",
"that",
"can",
"be",
"serialized",
"natively",
"by",
"{"
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Data/JsFunction.php#L100-L109 |
nesk/rialto | src/Instruction.php | Instruction.call | public function call(string $name, ...$arguments): self
{
$this->type = self::TYPE_CALL;
$this->name = $name;
$this->setValue($arguments, $this->type);
return $this;
} | php | public function call(string $name, ...$arguments): self
{
$this->type = self::TYPE_CALL;
$this->name = $name;
$this->setValue($arguments, $this->type);
return $this;
} | [
"public",
"function",
"call",
"(",
"string",
"$",
"name",
",",
"...",
"$",
"arguments",
")",
":",
"self",
"{",
"$",
"this",
"->",
"type",
"=",
"self",
"::",
"TYPE_CALL",
";",
"$",
"this",
"->",
"name",
"=",
"$",
"name",
";",
"$",
"this",
"->",
"setValue",
"(",
"$",
"arguments",
",",
"$",
"this",
"->",
"type",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Define a method call. | [
"Define",
"a",
"method",
"call",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Instruction.php#L63-L70 |
nesk/rialto | src/Instruction.php | Instruction.get | public function get(string $name): self
{
$this->type = self::TYPE_GET;
$this->name = $name;
$this->setValue(null, $this->type);
return $this;
} | php | public function get(string $name): self
{
$this->type = self::TYPE_GET;
$this->name = $name;
$this->setValue(null, $this->type);
return $this;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
")",
":",
"self",
"{",
"$",
"this",
"->",
"type",
"=",
"self",
"::",
"TYPE_GET",
";",
"$",
"this",
"->",
"name",
"=",
"$",
"name",
";",
"$",
"this",
"->",
"setValue",
"(",
"null",
",",
"$",
"this",
"->",
"type",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Define a getter. | [
"Define",
"a",
"getter",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Instruction.php#L75-L82 |
nesk/rialto | src/Instruction.php | Instruction.set | public function set(string $name, $value): self
{
$this->type = self::TYPE_SET;
$this->name = $name;
$this->setValue($value, $this->type);
return $this;
} | php | public function set(string $name, $value): self
{
$this->type = self::TYPE_SET;
$this->name = $name;
$this->setValue($value, $this->type);
return $this;
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"name",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"this",
"->",
"type",
"=",
"self",
"::",
"TYPE_SET",
";",
"$",
"this",
"->",
"name",
"=",
"$",
"name",
";",
"$",
"this",
"->",
"setValue",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"type",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Define a setter. | [
"Define",
"a",
"setter",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Instruction.php#L87-L94 |
nesk/rialto | src/Instruction.php | Instruction.setValue | protected function setValue($value, string $type)
{
$this->value = $type !== self::TYPE_CALL
? $this->validateValue($value)
: array_map(function ($value) {
return $this->validateValue($value);
}, $value);
} | php | protected function setValue($value, string $type)
{
$this->value = $type !== self::TYPE_CALL
? $this->validateValue($value)
: array_map(function ($value) {
return $this->validateValue($value);
}, $value);
} | [
"protected",
"function",
"setValue",
"(",
"$",
"value",
",",
"string",
"$",
"type",
")",
"{",
"$",
"this",
"->",
"value",
"=",
"$",
"type",
"!==",
"self",
"::",
"TYPE_CALL",
"?",
"$",
"this",
"->",
"validateValue",
"(",
"$",
"value",
")",
":",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"validateValue",
"(",
"$",
"value",
")",
";",
"}",
",",
"$",
"value",
")",
";",
"}"
] | Set the instruction value. | [
"Set",
"the",
"instruction",
"value",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Instruction.php#L119-L126 |
nesk/rialto | src/Instruction.php | Instruction.jsonSerialize | public function jsonSerialize(): array
{
$instruction = ['type' => $this->type];
if ($this->type !== self::TYPE_NOOP) {
$instruction = array_merge($instruction, [
'name' => $this->name,
'catched' => $this->shouldCatchErrors,
]);
if ($this->type !== self::TYPE_GET) {
$instruction['value'] = $this->value;
}
if ($this->resource !== null) {
$instruction['resource'] = $this->resource;
}
}
return $instruction;
} | php | public function jsonSerialize(): array
{
$instruction = ['type' => $this->type];
if ($this->type !== self::TYPE_NOOP) {
$instruction = array_merge($instruction, [
'name' => $this->name,
'catched' => $this->shouldCatchErrors,
]);
if ($this->type !== self::TYPE_GET) {
$instruction['value'] = $this->value;
}
if ($this->resource !== null) {
$instruction['resource'] = $this->resource;
}
}
return $instruction;
} | [
"public",
"function",
"jsonSerialize",
"(",
")",
":",
"array",
"{",
"$",
"instruction",
"=",
"[",
"'type'",
"=>",
"$",
"this",
"->",
"type",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"type",
"!==",
"self",
"::",
"TYPE_NOOP",
")",
"{",
"$",
"instruction",
"=",
"array_merge",
"(",
"$",
"instruction",
",",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"'catched'",
"=>",
"$",
"this",
"->",
"shouldCatchErrors",
",",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"type",
"!==",
"self",
"::",
"TYPE_GET",
")",
"{",
"$",
"instruction",
"[",
"'value'",
"]",
"=",
"$",
"this",
"->",
"value",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"resource",
"!==",
"null",
")",
"{",
"$",
"instruction",
"[",
"'resource'",
"]",
"=",
"$",
"this",
"->",
"resource",
";",
"}",
"}",
"return",
"$",
"instruction",
";",
"}"
] | Serialize the object to a value that can be serialized natively by {@see json_encode}. | [
"Serialize",
"the",
"object",
"to",
"a",
"value",
"that",
"can",
"be",
"serialized",
"natively",
"by",
"{"
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Instruction.php#L145-L165 |
nesk/rialto | src/Exceptions/IdleTimeoutException.php | IdleTimeoutException.exceptionApplies | public static function exceptionApplies(Process $process): bool
{
if (Node\FatalException::exceptionApplies($process)) {
$error = json_decode($process->getErrorOutput(), true);
return $error['message'] === 'The idle timeout has been reached.';
}
return false;
} | php | public static function exceptionApplies(Process $process): bool
{
if (Node\FatalException::exceptionApplies($process)) {
$error = json_decode($process->getErrorOutput(), true);
return $error['message'] === 'The idle timeout has been reached.';
}
return false;
} | [
"public",
"static",
"function",
"exceptionApplies",
"(",
"Process",
"$",
"process",
")",
":",
"bool",
"{",
"if",
"(",
"Node",
"\\",
"FatalException",
"::",
"exceptionApplies",
"(",
"$",
"process",
")",
")",
"{",
"$",
"error",
"=",
"json_decode",
"(",
"$",
"process",
"->",
"getErrorOutput",
"(",
")",
",",
"true",
")",
";",
"return",
"$",
"error",
"[",
"'message'",
"]",
"===",
"'The idle timeout has been reached.'",
";",
"}",
"return",
"false",
";",
"}"
] | Check if the exception can be applied to the process. | [
"Check",
"if",
"the",
"exception",
"can",
"be",
"applied",
"to",
"the",
"process",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Exceptions/IdleTimeoutException.php#L12-L21 |
nesk/rialto | src/Traits/CommunicatesWithProcessSupervisor.php | CommunicatesWithProcessSupervisor.setProcessSupervisor | public function setProcessSupervisor(ProcessSupervisor $processSupervisor): void
{
if ($this->processSupervisor !== null) {
throw new RuntimeException('The process supervisor has already been set.');
}
$this->processSupervisor = $processSupervisor;
} | php | public function setProcessSupervisor(ProcessSupervisor $processSupervisor): void
{
if ($this->processSupervisor !== null) {
throw new RuntimeException('The process supervisor has already been set.');
}
$this->processSupervisor = $processSupervisor;
} | [
"public",
"function",
"setProcessSupervisor",
"(",
"ProcessSupervisor",
"$",
"processSupervisor",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"processSupervisor",
"!==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'The process supervisor has already been set.'",
")",
";",
"}",
"$",
"this",
"->",
"processSupervisor",
"=",
"$",
"processSupervisor",
";",
"}"
] | Set the process supervisor.
@throws \RuntimeException if the process supervisor has already been set. | [
"Set",
"the",
"process",
"supervisor",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Traits/CommunicatesWithProcessSupervisor.php#L37-L44 |
nesk/rialto | src/Traits/CommunicatesWithProcessSupervisor.php | CommunicatesWithProcessSupervisor.proxyAction | protected function proxyAction(string $actionType, string $name, $value = null)
{
switch ($actionType) {
case Instruction::TYPE_CALL:
$value = $value ?? [];
$instruction = Instruction::withCall($name, ...$value);
break;
case Instruction::TYPE_GET:
$instruction = Instruction::withGet($name);
break;
case Instruction::TYPE_SET:
$instruction = Instruction::withSet($name, $value);
break;
}
$identifiesResource = $this instanceof ShouldIdentifyResource;
$instruction->linkToResource($identifiesResource ? $this : null);
if ($this->catchInstructionErrors) {
$instruction->shouldCatchErrors(true);
}
return $this->getProcessSupervisor()->executeInstruction($instruction);
} | php | protected function proxyAction(string $actionType, string $name, $value = null)
{
switch ($actionType) {
case Instruction::TYPE_CALL:
$value = $value ?? [];
$instruction = Instruction::withCall($name, ...$value);
break;
case Instruction::TYPE_GET:
$instruction = Instruction::withGet($name);
break;
case Instruction::TYPE_SET:
$instruction = Instruction::withSet($name, $value);
break;
}
$identifiesResource = $this instanceof ShouldIdentifyResource;
$instruction->linkToResource($identifiesResource ? $this : null);
if ($this->catchInstructionErrors) {
$instruction->shouldCatchErrors(true);
}
return $this->getProcessSupervisor()->executeInstruction($instruction);
} | [
"protected",
"function",
"proxyAction",
"(",
"string",
"$",
"actionType",
",",
"string",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"switch",
"(",
"$",
"actionType",
")",
"{",
"case",
"Instruction",
"::",
"TYPE_CALL",
":",
"$",
"value",
"=",
"$",
"value",
"??",
"[",
"]",
";",
"$",
"instruction",
"=",
"Instruction",
"::",
"withCall",
"(",
"$",
"name",
",",
"...",
"$",
"value",
")",
";",
"break",
";",
"case",
"Instruction",
"::",
"TYPE_GET",
":",
"$",
"instruction",
"=",
"Instruction",
"::",
"withGet",
"(",
"$",
"name",
")",
";",
"break",
";",
"case",
"Instruction",
"::",
"TYPE_SET",
":",
"$",
"instruction",
"=",
"Instruction",
"::",
"withSet",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"break",
";",
"}",
"$",
"identifiesResource",
"=",
"$",
"this",
"instanceof",
"ShouldIdentifyResource",
";",
"$",
"instruction",
"->",
"linkToResource",
"(",
"$",
"identifiesResource",
"?",
"$",
"this",
":",
"null",
")",
";",
"if",
"(",
"$",
"this",
"->",
"catchInstructionErrors",
")",
"{",
"$",
"instruction",
"->",
"shouldCatchErrors",
"(",
"true",
")",
";",
"}",
"return",
"$",
"this",
"->",
"getProcessSupervisor",
"(",
")",
"->",
"executeInstruction",
"(",
"$",
"instruction",
")",
";",
"}"
] | Proxy an action. | [
"Proxy",
"an",
"action",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Traits/CommunicatesWithProcessSupervisor.php#L61-L85 |
nesk/rialto | src/Logger.php | Logger.notice | public function notice($message, array $context = []): void {
$this->log(LogLevel::NOTICE, $message, $context);
} | php | public function notice($message, array $context = []): void {
$this->log(LogLevel::NOTICE, $message, $context);
} | [
"public",
"function",
"notice",
"(",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"void",
"{",
"$",
"this",
"->",
"log",
"(",
"LogLevel",
"::",
"NOTICE",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
] | {@inheritDoc}
@param string $message | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Logger.php#L74-L76 |
nesk/rialto | src/Logger.php | Logger.log | public function log($level, $message, array $context = []): void {
if ($this->logger instanceof LoggerInterface) {
$message = $this->interpolate($message, $context);
$this->logger->log($level, $message, $context);
}
} | php | public function log($level, $message, array $context = []): void {
if ($this->logger instanceof LoggerInterface) {
$message = $this->interpolate($message, $context);
$this->logger->log($level, $message, $context);
}
} | [
"public",
"function",
"log",
"(",
"$",
"level",
",",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"interpolate",
"(",
"$",
"message",
",",
"$",
"context",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"log",
"(",
"$",
"level",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}",
"}"
] | {@inheritDoc}
@param mixed $level
@param string $message | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Logger.php#L102-L107 |
nesk/rialto | src/Traits/IdentifiesResource.php | IdentifiesResource.setResourceIdentity | public function setResourceIdentity(ResourceIdentity $identity): void
{
if ($this->resourceIdentity !== null) {
throw new RuntimeException('The resource identity has already been set.');
}
$this->resourceIdentity = $identity;
} | php | public function setResourceIdentity(ResourceIdentity $identity): void
{
if ($this->resourceIdentity !== null) {
throw new RuntimeException('The resource identity has already been set.');
}
$this->resourceIdentity = $identity;
} | [
"public",
"function",
"setResourceIdentity",
"(",
"ResourceIdentity",
"$",
"identity",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"resourceIdentity",
"!==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'The resource identity has already been set.'",
")",
";",
"}",
"$",
"this",
"->",
"resourceIdentity",
"=",
"$",
"identity",
";",
"}"
] | Set the identity of the resource.
@throws \RuntimeException if the resource identity has already been set. | [
"Set",
"the",
"identity",
"of",
"the",
"resource",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Traits/IdentifiesResource.php#L30-L37 |
nesk/rialto | src/Data/UnserializesData.php | UnserializesData.unserialize | protected function unserialize($value)
{
if (!is_array($value)) {
return $value;
} else {
if (($value['__rialto_error__'] ?? false) === true) {
return new Exception($value, $this->options['debug']);
} else if (($value['__rialto_resource__'] ?? false) === true) {
if ($this->delegate instanceof ShouldHandleProcessDelegation) {
$classPath = $this->delegate->resourceFromOriginalClassName($value['class_name'])
?: $this->delegate->defaultResource();
} else {
$classPath = $this->defaultResource();
}
$resource = new $classPath;
if ($resource instanceof ShouldIdentifyResource) {
$resource->setResourceIdentity(new ResourceIdentity($value['class_name'], $value['id']));
}
if ($resource instanceof ShouldCommunicateWithProcessSupervisor) {
$resource->setProcessSupervisor($this);
}
return $resource;
} else {
return array_map(function ($value) {
return $this->unserialize($value);
}, $value);
}
}
} | php | protected function unserialize($value)
{
if (!is_array($value)) {
return $value;
} else {
if (($value['__rialto_error__'] ?? false) === true) {
return new Exception($value, $this->options['debug']);
} else if (($value['__rialto_resource__'] ?? false) === true) {
if ($this->delegate instanceof ShouldHandleProcessDelegation) {
$classPath = $this->delegate->resourceFromOriginalClassName($value['class_name'])
?: $this->delegate->defaultResource();
} else {
$classPath = $this->defaultResource();
}
$resource = new $classPath;
if ($resource instanceof ShouldIdentifyResource) {
$resource->setResourceIdentity(new ResourceIdentity($value['class_name'], $value['id']));
}
if ($resource instanceof ShouldCommunicateWithProcessSupervisor) {
$resource->setProcessSupervisor($this);
}
return $resource;
} else {
return array_map(function ($value) {
return $this->unserialize($value);
}, $value);
}
}
} | [
"protected",
"function",
"unserialize",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"else",
"{",
"if",
"(",
"(",
"$",
"value",
"[",
"'__rialto_error__'",
"]",
"??",
"false",
")",
"===",
"true",
")",
"{",
"return",
"new",
"Exception",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"options",
"[",
"'debug'",
"]",
")",
";",
"}",
"else",
"if",
"(",
"(",
"$",
"value",
"[",
"'__rialto_resource__'",
"]",
"??",
"false",
")",
"===",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"delegate",
"instanceof",
"ShouldHandleProcessDelegation",
")",
"{",
"$",
"classPath",
"=",
"$",
"this",
"->",
"delegate",
"->",
"resourceFromOriginalClassName",
"(",
"$",
"value",
"[",
"'class_name'",
"]",
")",
"?",
":",
"$",
"this",
"->",
"delegate",
"->",
"defaultResource",
"(",
")",
";",
"}",
"else",
"{",
"$",
"classPath",
"=",
"$",
"this",
"->",
"defaultResource",
"(",
")",
";",
"}",
"$",
"resource",
"=",
"new",
"$",
"classPath",
";",
"if",
"(",
"$",
"resource",
"instanceof",
"ShouldIdentifyResource",
")",
"{",
"$",
"resource",
"->",
"setResourceIdentity",
"(",
"new",
"ResourceIdentity",
"(",
"$",
"value",
"[",
"'class_name'",
"]",
",",
"$",
"value",
"[",
"'id'",
"]",
")",
")",
";",
"}",
"if",
"(",
"$",
"resource",
"instanceof",
"ShouldCommunicateWithProcessSupervisor",
")",
"{",
"$",
"resource",
"->",
"setProcessSupervisor",
"(",
"$",
"this",
")",
";",
"}",
"return",
"$",
"resource",
";",
"}",
"else",
"{",
"return",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"unserialize",
"(",
"$",
"value",
")",
";",
"}",
",",
"$",
"value",
")",
";",
"}",
"}",
"}"
] | Unserialize a value. | [
"Unserialize",
"a",
"value",
"."
] | train | https://github.com/nesk/rialto/blob/2403adc6b5f8fd4114d1ec00d9cce2e6ce3a5656/src/Data/UnserializesData.php#L14-L46 |
nexylan/slack-bundle | src/DependencyInjection/NexySlackExtension.php | NexySlackExtension.load | public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('nexy_slack.endpoint', $config['endpoint']);
$container->setAlias('nexy_slack.http.client', new Alias($config['http']['client'], false));
// Unset the not needed keys for the Slack config.
unset($config['http'], $config['endpoint']);
$container->setParameter('nexy_slack.config', $config);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('client.xml');
} | php | public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('nexy_slack.endpoint', $config['endpoint']);
$container->setAlias('nexy_slack.http.client', new Alias($config['http']['client'], false));
// Unset the not needed keys for the Slack config.
unset($config['http'], $config['endpoint']);
$container->setParameter('nexy_slack.config', $config);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('client.xml');
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
":",
"void",
"{",
"$",
"configuration",
"=",
"new",
"Configuration",
"(",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"processConfiguration",
"(",
"$",
"configuration",
",",
"$",
"configs",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'nexy_slack.endpoint'",
",",
"$",
"config",
"[",
"'endpoint'",
"]",
")",
";",
"$",
"container",
"->",
"setAlias",
"(",
"'nexy_slack.http.client'",
",",
"new",
"Alias",
"(",
"$",
"config",
"[",
"'http'",
"]",
"[",
"'client'",
"]",
",",
"false",
")",
")",
";",
"// Unset the not needed keys for the Slack config.",
"unset",
"(",
"$",
"config",
"[",
"'http'",
"]",
",",
"$",
"config",
"[",
"'endpoint'",
"]",
")",
";",
"$",
"container",
"->",
"setParameter",
"(",
"'nexy_slack.config'",
",",
"$",
"config",
")",
";",
"$",
"loader",
"=",
"new",
"XmlFileLoader",
"(",
"$",
"container",
",",
"new",
"FileLocator",
"(",
"__DIR__",
".",
"'/../Resources/config'",
")",
")",
";",
"$",
"loader",
"->",
"load",
"(",
"'client.xml'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/nexylan/slack-bundle/blob/4e55be5f6931047e99a97a0907b444b57a26397f/src/DependencyInjection/NexySlackExtension.php#L27-L41 |
matthiasmullie/path-converter | src/Converter.php | Converter.convert | public function convert($path)
{
// quit early if conversion makes no sense
if ($this->from === $this->to) {
return $path;
}
$path = $this->normalize($path);
// if we're not dealing with a relative path, just return absolute
if (strpos($path, '/') === 0) {
return $path;
}
// normalize paths
$path = $this->normalize($this->from.'/'.$path);
// strip shared ancestor paths
$shared = $this->shared($path, $this->to);
$path = mb_substr($path, mb_strlen($shared));
$to = mb_substr($this->to, mb_strlen($shared));
// add .. for every directory that needs to be traversed to new path
$to = str_repeat('../', count(array_filter(explode('/', $to))));
return $to.ltrim($path, '/');
} | php | public function convert($path)
{
// quit early if conversion makes no sense
if ($this->from === $this->to) {
return $path;
}
$path = $this->normalize($path);
// if we're not dealing with a relative path, just return absolute
if (strpos($path, '/') === 0) {
return $path;
}
// normalize paths
$path = $this->normalize($this->from.'/'.$path);
// strip shared ancestor paths
$shared = $this->shared($path, $this->to);
$path = mb_substr($path, mb_strlen($shared));
$to = mb_substr($this->to, mb_strlen($shared));
// add .. for every directory that needs to be traversed to new path
$to = str_repeat('../', count(array_filter(explode('/', $to))));
return $to.ltrim($path, '/');
} | [
"public",
"function",
"convert",
"(",
"$",
"path",
")",
"{",
"// quit early if conversion makes no sense",
"if",
"(",
"$",
"this",
"->",
"from",
"===",
"$",
"this",
"->",
"to",
")",
"{",
"return",
"$",
"path",
";",
"}",
"$",
"path",
"=",
"$",
"this",
"->",
"normalize",
"(",
"$",
"path",
")",
";",
"// if we're not dealing with a relative path, just return absolute",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"'/'",
")",
"===",
"0",
")",
"{",
"return",
"$",
"path",
";",
"}",
"// normalize paths",
"$",
"path",
"=",
"$",
"this",
"->",
"normalize",
"(",
"$",
"this",
"->",
"from",
".",
"'/'",
".",
"$",
"path",
")",
";",
"// strip shared ancestor paths",
"$",
"shared",
"=",
"$",
"this",
"->",
"shared",
"(",
"$",
"path",
",",
"$",
"this",
"->",
"to",
")",
";",
"$",
"path",
"=",
"mb_substr",
"(",
"$",
"path",
",",
"mb_strlen",
"(",
"$",
"shared",
")",
")",
";",
"$",
"to",
"=",
"mb_substr",
"(",
"$",
"this",
"->",
"to",
",",
"mb_strlen",
"(",
"$",
"shared",
")",
")",
";",
"// add .. for every directory that needs to be traversed to new path",
"$",
"to",
"=",
"str_repeat",
"(",
"'../'",
",",
"count",
"(",
"array_filter",
"(",
"explode",
"(",
"'/'",
",",
"$",
"to",
")",
")",
")",
")",
";",
"return",
"$",
"to",
".",
"ltrim",
"(",
"$",
"path",
",",
"'/'",
")",
";",
"}"
] | Convert paths relative from 1 file to another.
E.g.
../images/img.gif relative to /home/forkcms/frontend/core/layout/css
should become:
../../core/layout/images/img.gif relative to
/home/forkcms/frontend/cache/minified_css
@param string $path The relative path that needs to be converted
@return string The new relative path | [
"Convert",
"paths",
"relative",
"from",
"1",
"file",
"to",
"another",
"."
] | train | https://github.com/matthiasmullie/path-converter/blob/5e4b121c8b9f97c80835c1d878b0812ba1d607c9/src/Converter.php#L137-L162 |
kamermans/guzzle-oauth2-subscriber | src/OAuth2Subscriber.php | OAuth2Subscriber.onBefore | public function onBefore(BeforeEvent $event)
{
$request = $event->getRequest();
// Only sign requests using "auth"="oauth"
if ('oauth' !== $request->getConfig()['auth']) {
return;
}
$this->signRequest($request);
} | php | public function onBefore(BeforeEvent $event)
{
$request = $event->getRequest();
// Only sign requests using "auth"="oauth"
if ('oauth' !== $request->getConfig()['auth']) {
return;
}
$this->signRequest($request);
} | [
"public",
"function",
"onBefore",
"(",
"BeforeEvent",
"$",
"event",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"// Only sign requests using \"auth\"=\"oauth\"",
"if",
"(",
"'oauth'",
"!==",
"$",
"request",
"->",
"getConfig",
"(",
")",
"[",
"'auth'",
"]",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"signRequest",
"(",
"$",
"request",
")",
";",
"}"
] | Request before-send event handler.
Adds the Authorization header if an access token was found.
@param BeforeEvent $event Event received | [
"Request",
"before",
"-",
"send",
"event",
"handler",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/OAuth2Subscriber.php#L32-L42 |
kamermans/guzzle-oauth2-subscriber | src/OAuth2Subscriber.php | OAuth2Subscriber.onError | public function onError(ErrorEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
// Only sign requests using "auth"="oauth"
if ('oauth' !== $request->getConfig()['auth']) {
return;
}
// Only deal with Unauthorized response.
if ($response && $response->getStatusCode() != 401) {
return;
}
// If we already retried once, give up.
if ($request->getHeader('X-Guzzle-Retry')) {
return;
}
// Delete the previous access token, if any
$this->deleteAccessToken();
// Acquire a new access token, and retry the request.
$accessToken = $this->getAccessToken();
if ($accessToken != null) {
$newRequest = clone $request;
$newRequest->setHeader('X-Guzzle-Retry', '1');
$this->accessTokenSigner->sign($newRequest, $accessToken);
$event->intercept(
$event->getClient()->send($newRequest)
);
}
} | php | public function onError(ErrorEvent $event)
{
$request = $event->getRequest();
$response = $event->getResponse();
// Only sign requests using "auth"="oauth"
if ('oauth' !== $request->getConfig()['auth']) {
return;
}
// Only deal with Unauthorized response.
if ($response && $response->getStatusCode() != 401) {
return;
}
// If we already retried once, give up.
if ($request->getHeader('X-Guzzle-Retry')) {
return;
}
// Delete the previous access token, if any
$this->deleteAccessToken();
// Acquire a new access token, and retry the request.
$accessToken = $this->getAccessToken();
if ($accessToken != null) {
$newRequest = clone $request;
$newRequest->setHeader('X-Guzzle-Retry', '1');
$this->accessTokenSigner->sign($newRequest, $accessToken);
$event->intercept(
$event->getClient()->send($newRequest)
);
}
} | [
"public",
"function",
"onError",
"(",
"ErrorEvent",
"$",
"event",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(",
")",
";",
"$",
"response",
"=",
"$",
"event",
"->",
"getResponse",
"(",
")",
";",
"// Only sign requests using \"auth\"=\"oauth\"",
"if",
"(",
"'oauth'",
"!==",
"$",
"request",
"->",
"getConfig",
"(",
")",
"[",
"'auth'",
"]",
")",
"{",
"return",
";",
"}",
"// Only deal with Unauthorized response.",
"if",
"(",
"$",
"response",
"&&",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"!=",
"401",
")",
"{",
"return",
";",
"}",
"// If we already retried once, give up.",
"if",
"(",
"$",
"request",
"->",
"getHeader",
"(",
"'X-Guzzle-Retry'",
")",
")",
"{",
"return",
";",
"}",
"// Delete the previous access token, if any",
"$",
"this",
"->",
"deleteAccessToken",
"(",
")",
";",
"// Acquire a new access token, and retry the request.",
"$",
"accessToken",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"if",
"(",
"$",
"accessToken",
"!=",
"null",
")",
"{",
"$",
"newRequest",
"=",
"clone",
"$",
"request",
";",
"$",
"newRequest",
"->",
"setHeader",
"(",
"'X-Guzzle-Retry'",
",",
"'1'",
")",
";",
"$",
"this",
"->",
"accessTokenSigner",
"->",
"sign",
"(",
"$",
"newRequest",
",",
"$",
"accessToken",
")",
";",
"$",
"event",
"->",
"intercept",
"(",
"$",
"event",
"->",
"getClient",
"(",
")",
"->",
"send",
"(",
"$",
"newRequest",
")",
")",
";",
"}",
"}"
] | Request error event handler.
Handles unauthorized errors by acquiring a new access token and
retrying the request.
@param ErrorEvent $event Event received | [
"Request",
"error",
"event",
"handler",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/OAuth2Subscriber.php#L52-L87 |
kamermans/guzzle-oauth2-subscriber | src/GrantType/Specific/GithubApplication.php | GithubApplication.parseLinkHeader | public static function parseLinkHeader(Response $response)
{
$linkHeader = $response->getHeader('Link');
if (!strpos($linkHeader, 'rel')) {
return null;
}
$out = [
"next" => null,
"last" => null,
"prev" => null,
"first" => null,
];
$links = explode(',', $linkHeader);
foreach ($links as $link) {
$parts = explode(';', $link);
if (count($parts) < 2) {
continue;
}
// Get the URL
$url = trim(array_shift($parts), '<> ');
$relParts = explode('=', trim(array_shift($parts)));
if (count($relParts) !== 2 || $relParts[0] != 'rel') {
continue;
}
// Get the rel="" value (next, prev, first, last)
$rel = trim($relParts[1], ' "\'');
$out[$rel] = $url;
}
return $out;
} | php | public static function parseLinkHeader(Response $response)
{
$linkHeader = $response->getHeader('Link');
if (!strpos($linkHeader, 'rel')) {
return null;
}
$out = [
"next" => null,
"last" => null,
"prev" => null,
"first" => null,
];
$links = explode(',', $linkHeader);
foreach ($links as $link) {
$parts = explode(';', $link);
if (count($parts) < 2) {
continue;
}
// Get the URL
$url = trim(array_shift($parts), '<> ');
$relParts = explode('=', trim(array_shift($parts)));
if (count($relParts) !== 2 || $relParts[0] != 'rel') {
continue;
}
// Get the rel="" value (next, prev, first, last)
$rel = trim($relParts[1], ' "\'');
$out[$rel] = $url;
}
return $out;
} | [
"public",
"static",
"function",
"parseLinkHeader",
"(",
"Response",
"$",
"response",
")",
"{",
"$",
"linkHeader",
"=",
"$",
"response",
"->",
"getHeader",
"(",
"'Link'",
")",
";",
"if",
"(",
"!",
"strpos",
"(",
"$",
"linkHeader",
",",
"'rel'",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"out",
"=",
"[",
"\"next\"",
"=>",
"null",
",",
"\"last\"",
"=>",
"null",
",",
"\"prev\"",
"=>",
"null",
",",
"\"first\"",
"=>",
"null",
",",
"]",
";",
"$",
"links",
"=",
"explode",
"(",
"','",
",",
"$",
"linkHeader",
")",
";",
"foreach",
"(",
"$",
"links",
"as",
"$",
"link",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"';'",
",",
"$",
"link",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parts",
")",
"<",
"2",
")",
"{",
"continue",
";",
"}",
"// Get the URL",
"$",
"url",
"=",
"trim",
"(",
"array_shift",
"(",
"$",
"parts",
")",
",",
"'<> '",
")",
";",
"$",
"relParts",
"=",
"explode",
"(",
"'='",
",",
"trim",
"(",
"array_shift",
"(",
"$",
"parts",
")",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"relParts",
")",
"!==",
"2",
"||",
"$",
"relParts",
"[",
"0",
"]",
"!=",
"'rel'",
")",
"{",
"continue",
";",
"}",
"// Get the rel=\"\" value (next, prev, first, last)",
"$",
"rel",
"=",
"trim",
"(",
"$",
"relParts",
"[",
"1",
"]",
",",
"' \"\\''",
")",
";",
"$",
"out",
"[",
"$",
"rel",
"]",
"=",
"$",
"url",
";",
"}",
"return",
"$",
"out",
";",
"}"
] | Helper function to parse the GitHub HTTP Response header "Link", which
contains links to next and/or previous "pages" of data.
@param GuzzleHttpMessageResponse $response
@return array Array containing keys: next, prev, first, last | [
"Helper",
"function",
"to",
"parse",
"the",
"GitHub",
"HTTP",
"Response",
"header",
"Link",
"which",
"contains",
"links",
"to",
"next",
"and",
"/",
"or",
"previous",
"pages",
"of",
"data",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/GrantType/Specific/GithubApplication.php#L141-L177 |
kamermans/guzzle-oauth2-subscriber | src/GrantType/Specific/GithubApplication.php | GithubApplication.getAllResults | public static function getAllResults(ClientInterface $client, $url)
{
$data = [];
do {
$response = $client->get($url);
$data = array_merge($data, $response->json());
$url = GithubApplication::parseLinkHeader($response)['next'];
} while ($url);
return $data;
} | php | public static function getAllResults(ClientInterface $client, $url)
{
$data = [];
do {
$response = $client->get($url);
$data = array_merge($data, $response->json());
$url = GithubApplication::parseLinkHeader($response)['next'];
} while ($url);
return $data;
} | [
"public",
"static",
"function",
"getAllResults",
"(",
"ClientInterface",
"$",
"client",
",",
"$",
"url",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"do",
"{",
"$",
"response",
"=",
"$",
"client",
"->",
"get",
"(",
"$",
"url",
")",
";",
"$",
"data",
"=",
"array_merge",
"(",
"$",
"data",
",",
"$",
"response",
"->",
"json",
"(",
")",
")",
";",
"$",
"url",
"=",
"GithubApplication",
"::",
"parseLinkHeader",
"(",
"$",
"response",
")",
"[",
"'next'",
"]",
";",
"}",
"while",
"(",
"$",
"url",
")",
";",
"return",
"$",
"data",
";",
"}"
] | Helper function to retrieve all the "pages" of results from a GitHub API call
and returns them as a single array
@param ClientInterface $client
@param string $url
@return array | [
"Helper",
"function",
"to",
"retrieve",
"all",
"the",
"pages",
"of",
"results",
"from",
"a",
"GitHub",
"API",
"call",
"and",
"returns",
"them",
"as",
"a",
"single",
"array"
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/GrantType/Specific/GithubApplication.php#L187-L198 |
kamermans/guzzle-oauth2-subscriber | src/OAuth2Middleware.php | OAuth2Middleware.onFulfilled | private function onFulfilled(RequestInterface $request, array $options, $handler)
{
return function ($response) use ($request, $options, $handler) {
// Only deal with Unauthorized response.
if ($response && $response->getStatusCode() != 401) {
return $response;
}
// If we already retried once, give up.
// This is extremely unlikely in Guzzle 6+ since we're using promises
// to check the response - looping should be impossible, but I'm leaving
// the code here in case something interferes with the Middleware
if ($request->hasHeader('X-Guzzle-Retry')) {
return $response;
}
// Delete the previous access token, if any
$this->deleteAccessToken();
// Acquire a new access token, and retry the request.
$accessToken = $this->getAccessToken();
if ($accessToken === null) {
return $response;
}
$request = $request->withHeader('X-Guzzle-Retry', '1');
$request = $this->signRequest($request);
return $handler($request, $options);
};
} | php | private function onFulfilled(RequestInterface $request, array $options, $handler)
{
return function ($response) use ($request, $options, $handler) {
// Only deal with Unauthorized response.
if ($response && $response->getStatusCode() != 401) {
return $response;
}
// If we already retried once, give up.
// This is extremely unlikely in Guzzle 6+ since we're using promises
// to check the response - looping should be impossible, but I'm leaving
// the code here in case something interferes with the Middleware
if ($request->hasHeader('X-Guzzle-Retry')) {
return $response;
}
// Delete the previous access token, if any
$this->deleteAccessToken();
// Acquire a new access token, and retry the request.
$accessToken = $this->getAccessToken();
if ($accessToken === null) {
return $response;
}
$request = $request->withHeader('X-Guzzle-Retry', '1');
$request = $this->signRequest($request);
return $handler($request, $options);
};
} | [
"private",
"function",
"onFulfilled",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
"options",
",",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"$",
"response",
")",
"use",
"(",
"$",
"request",
",",
"$",
"options",
",",
"$",
"handler",
")",
"{",
"// Only deal with Unauthorized response.",
"if",
"(",
"$",
"response",
"&&",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
"!=",
"401",
")",
"{",
"return",
"$",
"response",
";",
"}",
"// If we already retried once, give up.",
"// This is extremely unlikely in Guzzle 6+ since we're using promises",
"// to check the response - looping should be impossible, but I'm leaving",
"// the code here in case something interferes with the Middleware",
"if",
"(",
"$",
"request",
"->",
"hasHeader",
"(",
"'X-Guzzle-Retry'",
")",
")",
"{",
"return",
"$",
"response",
";",
"}",
"// Delete the previous access token, if any",
"$",
"this",
"->",
"deleteAccessToken",
"(",
")",
";",
"// Acquire a new access token, and retry the request.",
"$",
"accessToken",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"if",
"(",
"$",
"accessToken",
"===",
"null",
")",
"{",
"return",
"$",
"response",
";",
"}",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'X-Guzzle-Retry'",
",",
"'1'",
")",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"signRequest",
"(",
"$",
"request",
")",
";",
"return",
"$",
"handler",
"(",
"$",
"request",
",",
"$",
"options",
")",
";",
"}",
";",
"}"
] | Request error event handler.
Handles unauthorized errors by acquiring a new access token and
retrying the request.
@param ErrorEvent $event Event received | [
"Request",
"error",
"event",
"handler",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/OAuth2Middleware.php#L47-L77 |
kamermans/guzzle-oauth2-subscriber | src/OAuth2Handler.php | OAuth2Handler.setAccessToken | public function setAccessToken($token)
{
if ($token instanceof Token\TokenInterface) {
$this->rawToken = $token;
} else {
$this->rawToken = is_array($token) ?
$this->tokenFactory($token) :
$this->tokenFactory(['access_token' => $token]);
}
if ($this->rawToken === null) {
throw new Exception\OAuth2Exception("setAccessToken() takes a string, array or TokenInterface object");
}
return $this;
} | php | public function setAccessToken($token)
{
if ($token instanceof Token\TokenInterface) {
$this->rawToken = $token;
} else {
$this->rawToken = is_array($token) ?
$this->tokenFactory($token) :
$this->tokenFactory(['access_token' => $token]);
}
if ($this->rawToken === null) {
throw new Exception\OAuth2Exception("setAccessToken() takes a string, array or TokenInterface object");
}
return $this;
} | [
"public",
"function",
"setAccessToken",
"(",
"$",
"token",
")",
"{",
"if",
"(",
"$",
"token",
"instanceof",
"Token",
"\\",
"TokenInterface",
")",
"{",
"$",
"this",
"->",
"rawToken",
"=",
"$",
"token",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"rawToken",
"=",
"is_array",
"(",
"$",
"token",
")",
"?",
"$",
"this",
"->",
"tokenFactory",
"(",
"$",
"token",
")",
":",
"$",
"this",
"->",
"tokenFactory",
"(",
"[",
"'access_token'",
"=>",
"$",
"token",
"]",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"rawToken",
"===",
"null",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"OAuth2Exception",
"(",
"\"setAccessToken() takes a string, array or TokenInterface object\"",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Manually set the access token.
@param string|array|TokenInterface $token An array of token data, an access token string, or a TokenInterface object | [
"Manually",
"set",
"the",
"access",
"token",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/OAuth2Handler.php#L133-L148 |
kamermans/guzzle-oauth2-subscriber | src/OAuth2Handler.php | OAuth2Handler.getAccessToken | public function getAccessToken()
{
// If token is not set try to get it from the persistent storage.
if ($this->rawToken === null) {
$this->rawToken = $this->tokenPersistence->restoreToken(new Token\RawToken());
}
// If token is not set or expired then try to acquire a new one...
if ($this->rawToken === null || $this->rawToken->isExpired()) {
$this->tokenPersistence->deleteToken();
// Hydrate `rawToken` with a new access token
$this->requestNewAccessToken();
// ...and save it.
if ($this->rawToken) {
$this->tokenPersistence->saveToken($this->rawToken);
}
}
return $this->rawToken? $this->rawToken->getAccessToken(): null;
} | php | public function getAccessToken()
{
// If token is not set try to get it from the persistent storage.
if ($this->rawToken === null) {
$this->rawToken = $this->tokenPersistence->restoreToken(new Token\RawToken());
}
// If token is not set or expired then try to acquire a new one...
if ($this->rawToken === null || $this->rawToken->isExpired()) {
$this->tokenPersistence->deleteToken();
// Hydrate `rawToken` with a new access token
$this->requestNewAccessToken();
// ...and save it.
if ($this->rawToken) {
$this->tokenPersistence->saveToken($this->rawToken);
}
}
return $this->rawToken? $this->rawToken->getAccessToken(): null;
} | [
"public",
"function",
"getAccessToken",
"(",
")",
"{",
"// If token is not set try to get it from the persistent storage.",
"if",
"(",
"$",
"this",
"->",
"rawToken",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"rawToken",
"=",
"$",
"this",
"->",
"tokenPersistence",
"->",
"restoreToken",
"(",
"new",
"Token",
"\\",
"RawToken",
"(",
")",
")",
";",
"}",
"// If token is not set or expired then try to acquire a new one...",
"if",
"(",
"$",
"this",
"->",
"rawToken",
"===",
"null",
"||",
"$",
"this",
"->",
"rawToken",
"->",
"isExpired",
"(",
")",
")",
"{",
"$",
"this",
"->",
"tokenPersistence",
"->",
"deleteToken",
"(",
")",
";",
"// Hydrate `rawToken` with a new access token",
"$",
"this",
"->",
"requestNewAccessToken",
"(",
")",
";",
"// ...and save it.",
"if",
"(",
"$",
"this",
"->",
"rawToken",
")",
"{",
"$",
"this",
"->",
"tokenPersistence",
"->",
"saveToken",
"(",
"$",
"this",
"->",
"rawToken",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"rawToken",
"?",
"$",
"this",
"->",
"rawToken",
"->",
"getAccessToken",
"(",
")",
":",
"null",
";",
"}"
] | Get a valid access token.
@return string|null A valid access token or null if unable to get one
@throws AccessTokenRequestException while trying to run `requestNewAccessToken` method | [
"Get",
"a",
"valid",
"access",
"token",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/OAuth2Handler.php#L166-L187 |
kamermans/guzzle-oauth2-subscriber | src/OAuth2Handler.php | OAuth2Handler.requestNewAccessToken | protected function requestNewAccessToken()
{
if ($this->refreshTokenGrantType && $this->rawToken && $this->rawToken->getRefreshToken()) {
try {
// Get an access token using the stored refresh token.
$rawData = $this->refreshTokenGrantType->getRawData(
$this->clientCredentialsSigner,
$this->rawToken->getRefreshToken()
);
$this->rawToken = $this->tokenFactory($rawData, $this->rawToken);
return;
} catch (BadResponseException $e) {
// If the refresh token is invalid, then clear the entire token information.
$this->rawToken = null;
}
}
if ($this->grantType === null) {
throw new Exception\ReauthorizationException('You must specify a grantType class to request an access token');
}
try {
// Request an access token using the main grant type.
$rawData = $this->grantType->getRawData($this->clientCredentialsSigner);
$this->rawToken = $this->tokenFactory($rawData);
} catch (BadResponseException $e) {
throw new Exception\AccessTokenRequestException('Unable to request a new access token', $e);
}
} | php | protected function requestNewAccessToken()
{
if ($this->refreshTokenGrantType && $this->rawToken && $this->rawToken->getRefreshToken()) {
try {
// Get an access token using the stored refresh token.
$rawData = $this->refreshTokenGrantType->getRawData(
$this->clientCredentialsSigner,
$this->rawToken->getRefreshToken()
);
$this->rawToken = $this->tokenFactory($rawData, $this->rawToken);
return;
} catch (BadResponseException $e) {
// If the refresh token is invalid, then clear the entire token information.
$this->rawToken = null;
}
}
if ($this->grantType === null) {
throw new Exception\ReauthorizationException('You must specify a grantType class to request an access token');
}
try {
// Request an access token using the main grant type.
$rawData = $this->grantType->getRawData($this->clientCredentialsSigner);
$this->rawToken = $this->tokenFactory($rawData);
} catch (BadResponseException $e) {
throw new Exception\AccessTokenRequestException('Unable to request a new access token', $e);
}
} | [
"protected",
"function",
"requestNewAccessToken",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"refreshTokenGrantType",
"&&",
"$",
"this",
"->",
"rawToken",
"&&",
"$",
"this",
"->",
"rawToken",
"->",
"getRefreshToken",
"(",
")",
")",
"{",
"try",
"{",
"// Get an access token using the stored refresh token.",
"$",
"rawData",
"=",
"$",
"this",
"->",
"refreshTokenGrantType",
"->",
"getRawData",
"(",
"$",
"this",
"->",
"clientCredentialsSigner",
",",
"$",
"this",
"->",
"rawToken",
"->",
"getRefreshToken",
"(",
")",
")",
";",
"$",
"this",
"->",
"rawToken",
"=",
"$",
"this",
"->",
"tokenFactory",
"(",
"$",
"rawData",
",",
"$",
"this",
"->",
"rawToken",
")",
";",
"return",
";",
"}",
"catch",
"(",
"BadResponseException",
"$",
"e",
")",
"{",
"// If the refresh token is invalid, then clear the entire token information.",
"$",
"this",
"->",
"rawToken",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"grantType",
"===",
"null",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"ReauthorizationException",
"(",
"'You must specify a grantType class to request an access token'",
")",
";",
"}",
"try",
"{",
"// Request an access token using the main grant type.",
"$",
"rawData",
"=",
"$",
"this",
"->",
"grantType",
"->",
"getRawData",
"(",
"$",
"this",
"->",
"clientCredentialsSigner",
")",
";",
"$",
"this",
"->",
"rawToken",
"=",
"$",
"this",
"->",
"tokenFactory",
"(",
"$",
"rawData",
")",
";",
"}",
"catch",
"(",
"BadResponseException",
"$",
"e",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"AccessTokenRequestException",
"(",
"'Unable to request a new access token'",
",",
"$",
"e",
")",
";",
"}",
"}"
] | Acquire a new access token from the server.
@return TokenInterface|null
@throws AccessTokenRequestException | [
"Acquire",
"a",
"new",
"access",
"token",
"from",
"the",
"server",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/OAuth2Handler.php#L227-L258 |
kamermans/guzzle-oauth2-subscriber | src/Token/TokenSerializer.php | TokenSerializer.unserialize | public function unserialize(array $data)
{
if (!isset($data['access_token'])) {
throw new \InvalidArgumentException('Unable to create a RawToken without an "access_token"');
}
$this->accessToken = $data['access_token'];
$this->refreshToken = isset($data['refresh_token']) ? $data['refresh_token'] : null;
$this->expiresAt = isset($data['expires_at']) ? $data['expires_at'] : null;
return $this;
} | php | public function unserialize(array $data)
{
if (!isset($data['access_token'])) {
throw new \InvalidArgumentException('Unable to create a RawToken without an "access_token"');
}
$this->accessToken = $data['access_token'];
$this->refreshToken = isset($data['refresh_token']) ? $data['refresh_token'] : null;
$this->expiresAt = isset($data['expires_at']) ? $data['expires_at'] : null;
return $this;
} | [
"public",
"function",
"unserialize",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"'access_token'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unable to create a RawToken without an \"access_token\"'",
")",
";",
"}",
"$",
"this",
"->",
"accessToken",
"=",
"$",
"data",
"[",
"'access_token'",
"]",
";",
"$",
"this",
"->",
"refreshToken",
"=",
"isset",
"(",
"$",
"data",
"[",
"'refresh_token'",
"]",
")",
"?",
"$",
"data",
"[",
"'refresh_token'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"expiresAt",
"=",
"isset",
"(",
"$",
"data",
"[",
"'expires_at'",
"]",
")",
"?",
"$",
"data",
"[",
"'expires_at'",
"]",
":",
"null",
";",
"return",
"$",
"this",
";",
"}"
] | Unserialize token data
@return self | [
"Unserialize",
"token",
"data"
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/Token/TokenSerializer.php#L45-L56 |
kamermans/guzzle-oauth2-subscriber | src/Utils/Collection.php | Collection.add | public function add($key, $value)
{
if (!array_key_exists($key, $this->data)) {
$this->data[$key] = $value;
} elseif (is_array($this->data[$key])) {
$this->data[$key][] = $value;
} else {
$this->data[$key] = [$this->data[$key], $value];
}
return $this;
} | php | public function add($key, $value)
{
if (!array_key_exists($key, $this->data)) {
$this->data[$key] = $value;
} elseif (is_array($this->data[$key])) {
$this->data[$key][] = $value;
} else {
$this->data[$key] = [$this->data[$key], $value];
}
return $this;
} | [
"public",
"function",
"add",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"data",
")",
")",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"elseif",
"(",
"is_array",
"(",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
"=",
"[",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
",",
"$",
"value",
"]",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add a value to a key. If a key of the same name has already been added,
the key value will be converted into an array and the new value will be
pushed to the end of the array.
@param string $key Key to add
@param mixed $value Value to add to the key
@return Collection Returns a reference to the object. | [
"Add",
"a",
"value",
"to",
"a",
"key",
".",
"If",
"a",
"key",
"of",
"the",
"same",
"name",
"has",
"already",
"been",
"added",
"the",
"key",
"value",
"will",
"be",
"converted",
"into",
"an",
"array",
"and",
"the",
"new",
"value",
"will",
"be",
"pushed",
"to",
"the",
"end",
"of",
"the",
"array",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/Utils/Collection.php#L138-L149 |
kamermans/guzzle-oauth2-subscriber | src/Utils/Collection.php | Collection.map | public function map(callable $closure, array $context = [])
{
$collection = new static();
foreach ($this as $key => $value) {
$collection[$key] = $closure($key, $value, $context);
}
return $collection;
} | php | public function map(callable $closure, array $context = [])
{
$collection = new static();
foreach ($this as $key => $value) {
$collection[$key] = $closure($key, $value, $context);
}
return $collection;
} | [
"public",
"function",
"map",
"(",
"callable",
"$",
"closure",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"collection",
"=",
"new",
"static",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"collection",
"[",
"$",
"key",
"]",
"=",
"$",
"closure",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"context",
")",
";",
"}",
"return",
"$",
"collection",
";",
"}"
] | Returns a Collection containing all the elements of the collection after
applying the callback function to each one.
The callable should accept three arguments:
- (string) $key
- (string) $value
- (array) $context
The callable must return a the altered or unaltered value.
@param callable $closure Map function to apply
@param array $context Context to pass to the callable
@return Collection | [
"Returns",
"a",
"Collection",
"containing",
"all",
"the",
"elements",
"of",
"the",
"collection",
"after",
"applying",
"the",
"callback",
"function",
"to",
"each",
"one",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/Utils/Collection.php#L269-L277 |
kamermans/guzzle-oauth2-subscriber | src/Utils/Collection.php | Collection.filter | public function filter(callable $closure)
{
$collection = new static();
foreach ($this->data as $key => $value) {
if ($closure($key, $value)) {
$collection[$key] = $value;
}
}
return $collection;
} | php | public function filter(callable $closure)
{
$collection = new static();
foreach ($this->data as $key => $value) {
if ($closure($key, $value)) {
$collection[$key] = $value;
}
}
return $collection;
} | [
"public",
"function",
"filter",
"(",
"callable",
"$",
"closure",
")",
"{",
"$",
"collection",
"=",
"new",
"static",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"closure",
"(",
"$",
"key",
",",
"$",
"value",
")",
")",
"{",
"$",
"collection",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"collection",
";",
"}"
] | Iterates over each key value pair in the collection passing them to the
callable. If the callable returns true, the current value from input is
returned into the result Collection.
The callable must accept two arguments:
- (string) $key
- (string) $value
@param callable $closure Evaluation function
@return Collection | [
"Iterates",
"over",
"each",
"key",
"value",
"pair",
"in",
"the",
"collection",
"passing",
"them",
"to",
"the",
"callable",
".",
"If",
"the",
"callable",
"returns",
"true",
"the",
"current",
"value",
"from",
"input",
"is",
"returned",
"into",
"the",
"result",
"Collection",
"."
] | train | https://github.com/kamermans/guzzle-oauth2-subscriber/blob/e6ded1ed4c93aca1fdbb185aa624a966edf78cac/src/Utils/Collection.php#L292-L302 |
ARCANEDEV/Support | src/Traits/Templatable.php | Templatable.view | protected function view($name, array $data = [])
{
$this->viewExistsOrFail($name);
$this->data = array_merge($this->data, $data);
$this->beforeViewRender();
$view = $this->renderView($name);
$this->afterViewRender();
return $view;
} | php | protected function view($name, array $data = [])
{
$this->viewExistsOrFail($name);
$this->data = array_merge($this->data, $data);
$this->beforeViewRender();
$view = $this->renderView($name);
$this->afterViewRender();
return $view;
} | [
"protected",
"function",
"view",
"(",
"$",
"name",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"viewExistsOrFail",
"(",
"$",
"name",
")",
";",
"$",
"this",
"->",
"data",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"data",
",",
"$",
"data",
")",
";",
"$",
"this",
"->",
"beforeViewRender",
"(",
")",
";",
"$",
"view",
"=",
"$",
"this",
"->",
"renderView",
"(",
"$",
"name",
")",
";",
"$",
"this",
"->",
"afterViewRender",
"(",
")",
";",
"return",
"$",
"view",
";",
"}"
] | Display the view.
@param string $name
@param array $data
@return \Illuminate\View\View | [
"Display",
"the",
"view",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Traits/Templatable.php#L74-L85 |
ARCANEDEV/Support | src/Traits/Templatable.php | Templatable.renderView | private function renderView($name)
{
return $this->layout
->with($this->data)
->nest('content', $name, $this->data);
} | php | private function renderView($name)
{
return $this->layout
->with($this->data)
->nest('content', $name, $this->data);
} | [
"private",
"function",
"renderView",
"(",
"$",
"name",
")",
"{",
"return",
"$",
"this",
"->",
"layout",
"->",
"with",
"(",
"$",
"this",
"->",
"data",
")",
"->",
"nest",
"(",
"'content'",
",",
"$",
"name",
",",
"$",
"this",
"->",
"data",
")",
";",
"}"
] | Render the view.
@param string $name
@return \Illuminate\View\View | [
"Render",
"the",
"view",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Traits/Templatable.php#L102-L107 |
ARCANEDEV/Support | src/Traits/Templatable.php | Templatable.viewExistsOrFail | protected function viewExistsOrFail($view, $message = 'The view [:view] not found')
{
if ( ! $this->isViewExists($view)) {
abort(500, str_replace(':view', $view, $message));
}
} | php | protected function viewExistsOrFail($view, $message = 'The view [:view] not found')
{
if ( ! $this->isViewExists($view)) {
abort(500, str_replace(':view', $view, $message));
}
} | [
"protected",
"function",
"viewExistsOrFail",
"(",
"$",
"view",
",",
"$",
"message",
"=",
"'The view [:view] not found'",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isViewExists",
"(",
"$",
"view",
")",
")",
"{",
"abort",
"(",
"500",
",",
"str_replace",
"(",
"':view'",
",",
"$",
"view",
",",
"$",
"message",
")",
")",
";",
"}",
"}"
] | Check if view exists or fail.
@param string $view
@param string $message | [
"Check",
"if",
"view",
"exists",
"or",
"fail",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Traits/Templatable.php#L143-L148 |
ARCANEDEV/Support | src/Traits/Templatable.php | Templatable.setupLayout | protected function setupLayout()
{
if (is_null($this->template)) {
abort(500, 'The layout is not set');
}
$this->viewExistsOrFail(
$this->template,
"The layout [$this->template] not found"
);
$this->layout = view($this->template);
} | php | protected function setupLayout()
{
if (is_null($this->template)) {
abort(500, 'The layout is not set');
}
$this->viewExistsOrFail(
$this->template,
"The layout [$this->template] not found"
);
$this->layout = view($this->template);
} | [
"protected",
"function",
"setupLayout",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"template",
")",
")",
"{",
"abort",
"(",
"500",
",",
"'The layout is not set'",
")",
";",
"}",
"$",
"this",
"->",
"viewExistsOrFail",
"(",
"$",
"this",
"->",
"template",
",",
"\"The layout [$this->template] not found\"",
")",
";",
"$",
"this",
"->",
"layout",
"=",
"view",
"(",
"$",
"this",
"->",
"template",
")",
";",
"}"
] | Setup the template/layout. | [
"Setup",
"the",
"template",
"/",
"layout",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Traits/Templatable.php#L173-L185 |
ARCANEDEV/Support | src/Stub.php | Stub.getPath | public function getPath()
{
$path = $this->path;
if ( ! empty(static::$basePath)) {
$path = static::$basePath.DS.ltrim($path, DS);
}
return $path;
} | php | public function getPath()
{
$path = $this->path;
if ( ! empty(static::$basePath)) {
$path = static::$basePath.DS.ltrim($path, DS);
}
return $path;
} | [
"public",
"function",
"getPath",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"path",
";",
"if",
"(",
"!",
"empty",
"(",
"static",
"::",
"$",
"basePath",
")",
")",
"{",
"$",
"path",
"=",
"static",
"::",
"$",
"basePath",
".",
"DS",
".",
"ltrim",
"(",
"$",
"path",
",",
"DS",
")",
";",
"}",
"return",
"$",
"path",
";",
"}"
] | Get stub path.
@return string | [
"Get",
"stub",
"path",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Stub.php#L64-L73 |
ARCANEDEV/Support | src/Stub.php | Stub.createFromPath | public static function createFromPath($path, array $replaces = [])
{
return tap(new static($path, $replaces), function (self $stub) {
$stub->setBasePath('');
});
} | php | public static function createFromPath($path, array $replaces = [])
{
return tap(new static($path, $replaces), function (self $stub) {
$stub->setBasePath('');
});
} | [
"public",
"static",
"function",
"createFromPath",
"(",
"$",
"path",
",",
"array",
"$",
"replaces",
"=",
"[",
"]",
")",
"{",
"return",
"tap",
"(",
"new",
"static",
"(",
"$",
"path",
",",
"$",
"replaces",
")",
",",
"function",
"(",
"self",
"$",
"stub",
")",
"{",
"$",
"stub",
"->",
"setBasePath",
"(",
"''",
")",
";",
"}",
")",
";",
"}"
] | Create new self instance from full path.
@param string $path
@param array $replaces
@return self | [
"Create",
"new",
"self",
"instance",
"from",
"full",
"path",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Stub.php#L171-L176 |
ARCANEDEV/Support | src/Stub.php | Stub.getContents | public function getContents()
{
$contents = file_get_contents($this->getPath());
foreach ($this->getReplaces() as $search => $replace) {
$contents = str_replace('$'.strtoupper($search).'$', $replace, $contents);
}
return $contents;
} | php | public function getContents()
{
$contents = file_get_contents($this->getPath());
foreach ($this->getReplaces() as $search => $replace) {
$contents = str_replace('$'.strtoupper($search).'$', $replace, $contents);
}
return $contents;
} | [
"public",
"function",
"getContents",
"(",
")",
"{",
"$",
"contents",
"=",
"file_get_contents",
"(",
"$",
"this",
"->",
"getPath",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getReplaces",
"(",
")",
"as",
"$",
"search",
"=>",
"$",
"replace",
")",
"{",
"$",
"contents",
"=",
"str_replace",
"(",
"'$'",
".",
"strtoupper",
"(",
"$",
"search",
")",
".",
"'$'",
",",
"$",
"replace",
",",
"$",
"contents",
")",
";",
"}",
"return",
"$",
"contents",
";",
"}"
] | Get stub contents.
@return string|mixed | [
"Get",
"stub",
"contents",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Stub.php#L218-L227 |
ARCANEDEV/Support | src/Database/Seeder.php | Seeder.run | public function run()
{
Eloquent::unguard();
foreach ($this->seeds as $seed) {
$this->call($seed);
}
Eloquent::reguard();
} | php | public function run()
{
Eloquent::unguard();
foreach ($this->seeds as $seed) {
$this->call($seed);
}
Eloquent::reguard();
} | [
"public",
"function",
"run",
"(",
")",
"{",
"Eloquent",
"::",
"unguard",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"seeds",
"as",
"$",
"seed",
")",
"{",
"$",
"this",
"->",
"call",
"(",
"$",
"seed",
")",
";",
"}",
"Eloquent",
"::",
"reguard",
"(",
")",
";",
"}"
] | Run the database seeds. | [
"Run",
"the",
"database",
"seeds",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Database/Seeder.php#L34-L43 |
ARCANEDEV/Support | src/Database/Migration.php | Migration.getSchemaBuilder | protected function getSchemaBuilder()
{
/** @var \Illuminate\Database\DatabaseManager $db */
$db = app()->make('db');
return $db->connection($this->hasConnection() ? $this->getConnection() : null)
->getSchemaBuilder();
} | php | protected function getSchemaBuilder()
{
/** @var \Illuminate\Database\DatabaseManager $db */
$db = app()->make('db');
return $db->connection($this->hasConnection() ? $this->getConnection() : null)
->getSchemaBuilder();
} | [
"protected",
"function",
"getSchemaBuilder",
"(",
")",
"{",
"/** @var \\Illuminate\\Database\\DatabaseManager $db */",
"$",
"db",
"=",
"app",
"(",
")",
"->",
"make",
"(",
"'db'",
")",
";",
"return",
"$",
"db",
"->",
"connection",
"(",
"$",
"this",
"->",
"hasConnection",
"(",
")",
"?",
"$",
"this",
"->",
"getConnection",
"(",
")",
":",
"null",
")",
"->",
"getSchemaBuilder",
"(",
")",
";",
"}"
] | Get a schema builder instance for the connection.
@return \Illuminate\Database\Schema\Builder | [
"Get",
"a",
"schema",
"builder",
"instance",
"for",
"the",
"connection",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Database/Migration.php#L43-L50 |
ARCANEDEV/Support | src/Middleware/VerifyJsonRequest.php | VerifyJsonRequest.handle | public function handle(Request $request, Closure $next, $methods = null)
{
if ($this->isJsonRequestValid($request, $methods)) {
return $next($request);
}
return response()->json([
'status' => 'error',
'code' => 400,
'message' => 'Request must be json',
], 400);
} | php | public function handle(Request $request, Closure $next, $methods = null)
{
if ($this->isJsonRequestValid($request, $methods)) {
return $next($request);
}
return response()->json([
'status' => 'error',
'code' => 400,
'message' => 'Request must be json',
], 400);
} | [
"public",
"function",
"handle",
"(",
"Request",
"$",
"request",
",",
"Closure",
"$",
"next",
",",
"$",
"methods",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isJsonRequestValid",
"(",
"$",
"request",
",",
"$",
"methods",
")",
")",
"{",
"return",
"$",
"next",
"(",
"$",
"request",
")",
";",
"}",
"return",
"response",
"(",
")",
"->",
"json",
"(",
"[",
"'status'",
"=>",
"'error'",
",",
"'code'",
"=>",
"400",
",",
"'message'",
"=>",
"'Request must be json'",
",",
"]",
",",
"400",
")",
";",
"}"
] | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string|array|null $methods
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Middleware/VerifyJsonRequest.php#L38-L49 |
ARCANEDEV/Support | src/Middleware/VerifyJsonRequest.php | VerifyJsonRequest.isJsonRequestValid | private function isJsonRequestValid(Request $request, $methods)
{
$methods = $this->getMethods($methods);
return ! (
in_array($request->method(), $methods) &&
! $request->isJson()
);
} | php | private function isJsonRequestValid(Request $request, $methods)
{
$methods = $this->getMethods($methods);
return ! (
in_array($request->method(), $methods) &&
! $request->isJson()
);
} | [
"private",
"function",
"isJsonRequestValid",
"(",
"Request",
"$",
"request",
",",
"$",
"methods",
")",
"{",
"$",
"methods",
"=",
"$",
"this",
"->",
"getMethods",
"(",
"$",
"methods",
")",
";",
"return",
"!",
"(",
"in_array",
"(",
"$",
"request",
"->",
"method",
"(",
")",
",",
"$",
"methods",
")",
"&&",
"!",
"$",
"request",
"->",
"isJson",
"(",
")",
")",
";",
"}"
] | Validate json Request.
@param Request $request
@param string|array|null $methods
@return bool | [
"Validate",
"json",
"Request",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Middleware/VerifyJsonRequest.php#L63-L71 |
ARCANEDEV/Support | src/Middleware/VerifyJsonRequest.php | VerifyJsonRequest.getMethods | private function getMethods($methods)
{
$methods = $methods ?? $this->methods;
if (is_string($methods))
$methods = (array) $methods;
return is_array($methods) ? array_map('strtoupper', $methods) : [];
} | php | private function getMethods($methods)
{
$methods = $methods ?? $this->methods;
if (is_string($methods))
$methods = (array) $methods;
return is_array($methods) ? array_map('strtoupper', $methods) : [];
} | [
"private",
"function",
"getMethods",
"(",
"$",
"methods",
")",
"{",
"$",
"methods",
"=",
"$",
"methods",
"??",
"$",
"this",
"->",
"methods",
";",
"if",
"(",
"is_string",
"(",
"$",
"methods",
")",
")",
"$",
"methods",
"=",
"(",
"array",
")",
"$",
"methods",
";",
"return",
"is_array",
"(",
"$",
"methods",
")",
"?",
"array_map",
"(",
"'strtoupper'",
",",
"$",
"methods",
")",
":",
"[",
"]",
";",
"}"
] | Get request methods.
@param string|array|null $methods
@return array | [
"Get",
"request",
"methods",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Middleware/VerifyJsonRequest.php#L80-L88 |
ARCANEDEV/Support | src/Providers/EventServiceProvider.php | EventServiceProvider.boot | public function boot()
{
foreach ($this->listens() as $event => $listeners) {
foreach ($listeners as $listener) {
Event::listen($event, $listener);
}
}
foreach ($this->subscribe as $subscriber) {
Event::subscribe($subscriber);
}
} | php | public function boot()
{
foreach ($this->listens() as $event => $listeners) {
foreach ($listeners as $listener) {
Event::listen($event, $listener);
}
}
foreach ($this->subscribe as $subscriber) {
Event::subscribe($subscriber);
}
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"listens",
"(",
")",
"as",
"$",
"event",
"=>",
"$",
"listeners",
")",
"{",
"foreach",
"(",
"$",
"listeners",
"as",
"$",
"listener",
")",
"{",
"Event",
"::",
"listen",
"(",
"$",
"event",
",",
"$",
"listener",
")",
";",
"}",
"}",
"foreach",
"(",
"$",
"this",
"->",
"subscribe",
"as",
"$",
"subscriber",
")",
"{",
"Event",
"::",
"subscribe",
"(",
"$",
"subscriber",
")",
";",
"}",
"}"
] | Register the application's event listeners. | [
"Register",
"the",
"application",
"s",
"event",
"listeners",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Providers/EventServiceProvider.php#L56-L67 |
ARCANEDEV/Support | src/ServiceProvider.php | ServiceProvider.bind | public function bind($abstract, $concrete = null, $shared = false)
{
$this->app->bind($abstract, $concrete, $shared);
} | php | public function bind($abstract, $concrete = null, $shared = false)
{
$this->app->bind($abstract, $concrete, $shared);
} | [
"public",
"function",
"bind",
"(",
"$",
"abstract",
",",
"$",
"concrete",
"=",
"null",
",",
"$",
"shared",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"$",
"abstract",
",",
"$",
"concrete",
",",
"$",
"shared",
")",
";",
"}"
] | Register a binding with the container.
@param string|array $abstract
@param \Closure|string|null $concrete
@param bool $shared | [
"Register",
"a",
"binding",
"with",
"the",
"container",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/ServiceProvider.php#L86-L89 |
ARCANEDEV/Support | src/ServiceProvider.php | ServiceProvider.registerProvider | protected function registerProvider($provider, array $options = [], $force = false)
{
return $this->app->register($provider, $options, $force);
} | php | protected function registerProvider($provider, array $options = [], $force = false)
{
return $this->app->register($provider, $options, $force);
} | [
"protected",
"function",
"registerProvider",
"(",
"$",
"provider",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"force",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"app",
"->",
"register",
"(",
"$",
"provider",
",",
"$",
"options",
",",
"$",
"force",
")",
";",
"}"
] | Register a service provider.
@param \Illuminate\Support\ServiceProvider|string $provider
@param array $options
@param bool $force
@return \Illuminate\Support\ServiceProvider | [
"Register",
"a",
"service",
"provider",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/ServiceProvider.php#L111-L114 |
ARCANEDEV/Support | src/ServiceProvider.php | ServiceProvider.registerConsoleServiceProvider | protected function registerConsoleServiceProvider($provider, array $options = [], $force = false)
{
if ($this->app->runningInConsole())
return $this->registerProvider($provider, $options, $force);
return null;
} | php | protected function registerConsoleServiceProvider($provider, array $options = [], $force = false)
{
if ($this->app->runningInConsole())
return $this->registerProvider($provider, $options, $force);
return null;
} | [
"protected",
"function",
"registerConsoleServiceProvider",
"(",
"$",
"provider",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"app",
"->",
"runningInConsole",
"(",
")",
")",
"return",
"$",
"this",
"->",
"registerProvider",
"(",
"$",
"provider",
",",
"$",
"options",
",",
"$",
"force",
")",
";",
"return",
"null",
";",
"}"
] | Register a console service provider.
@param \Illuminate\Support\ServiceProvider|string $provider
@param array $options
@param bool $force
@return \Illuminate\Support\ServiceProvider|null | [
"Register",
"a",
"console",
"service",
"provider",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/ServiceProvider.php#L137-L143 |
ARCANEDEV/Support | src/ServiceProvider.php | ServiceProvider.registerAliases | protected function registerAliases()
{
$loader = $this->aliasLoader;
$this->app->booting(function() use ($loader) {
foreach ($this->aliases as $class => $alias) {
$loader->alias($class, $alias);
}
});
} | php | protected function registerAliases()
{
$loader = $this->aliasLoader;
$this->app->booting(function() use ($loader) {
foreach ($this->aliases as $class => $alias) {
$loader->alias($class, $alias);
}
});
} | [
"protected",
"function",
"registerAliases",
"(",
")",
"{",
"$",
"loader",
"=",
"$",
"this",
"->",
"aliasLoader",
";",
"$",
"this",
"->",
"app",
"->",
"booting",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"loader",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"aliases",
"as",
"$",
"class",
"=>",
"$",
"alias",
")",
"{",
"$",
"loader",
"->",
"alias",
"(",
"$",
"class",
",",
"$",
"alias",
")",
";",
"}",
"}",
")",
";",
"}"
] | Register aliases (Facades). | [
"Register",
"aliases",
"(",
"Facades",
")",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/ServiceProvider.php#L148-L157 |
ARCANEDEV/Support | src/Bases/Command.php | Command.frame | protected function frame($text)
{
$line = '+'.str_repeat('-', strlen($text) + 4).'+';
$this->info($line);
$this->info("| $text |");
$this->info($line);
} | php | protected function frame($text)
{
$line = '+'.str_repeat('-', strlen($text) + 4).'+';
$this->info($line);
$this->info("| $text |");
$this->info($line);
} | [
"protected",
"function",
"frame",
"(",
"$",
"text",
")",
"{",
"$",
"line",
"=",
"'+'",
".",
"str_repeat",
"(",
"'-'",
",",
"strlen",
"(",
"$",
"text",
")",
"+",
"4",
")",
".",
"'+'",
";",
"$",
"this",
"->",
"info",
"(",
"$",
"line",
")",
";",
"$",
"this",
"->",
"info",
"(",
"\"| $text |\"",
")",
";",
"$",
"this",
"->",
"info",
"(",
"$",
"line",
")",
";",
"}"
] | Display frame the text info.
@param string $text | [
"Display",
"frame",
"the",
"text",
"info",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Bases/Command.php#L56-L62 |
ARCANEDEV/Support | src/Http/Controller.php | Controller.setData | protected function setData($name, $value = null)
{
if (is_array($name)) {
$this->data = array_merge($this->data, $name);
}
elseif (is_string($name)) {
$this->data[$name] = $value;
}
return $this;
} | php | protected function setData($name, $value = null)
{
if (is_array($name)) {
$this->data = array_merge($this->data, $name);
}
elseif (is_string($name)) {
$this->data[$name] = $value;
}
return $this;
} | [
"protected",
"function",
"setData",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"data",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"data",
",",
"$",
"name",
")",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Set view data.
@param string|array $name
@param mixed $value
@return self | [
"Set",
"view",
"data",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Http/Controller.php#L69-L79 |
ARCANEDEV/Support | src/Bases/Policy.php | Policy.policies | public static function policies()
{
$abilities = array_values(
(new \ReflectionClass($instance = new static))->getConstants()
);
return array_map(function ($constant) use ($instance) {
$method = Str::camel(last(explode('.', $constant)).'Policy');
if ( ! method_exists($instance, $method))
throw new MissingPolicyException("Missing policy [$method] method in ".get_class($instance).".");
return $method;
}, array_combine($abilities, $abilities));
} | php | public static function policies()
{
$abilities = array_values(
(new \ReflectionClass($instance = new static))->getConstants()
);
return array_map(function ($constant) use ($instance) {
$method = Str::camel(last(explode('.', $constant)).'Policy');
if ( ! method_exists($instance, $method))
throw new MissingPolicyException("Missing policy [$method] method in ".get_class($instance).".");
return $method;
}, array_combine($abilities, $abilities));
} | [
"public",
"static",
"function",
"policies",
"(",
")",
"{",
"$",
"abilities",
"=",
"array_values",
"(",
"(",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"instance",
"=",
"new",
"static",
")",
")",
"->",
"getConstants",
"(",
")",
")",
";",
"return",
"array_map",
"(",
"function",
"(",
"$",
"constant",
")",
"use",
"(",
"$",
"instance",
")",
"{",
"$",
"method",
"=",
"Str",
"::",
"camel",
"(",
"last",
"(",
"explode",
"(",
"'.'",
",",
"$",
"constant",
")",
")",
".",
"'Policy'",
")",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"instance",
",",
"$",
"method",
")",
")",
"throw",
"new",
"MissingPolicyException",
"(",
"\"Missing policy [$method] method in \"",
".",
"get_class",
"(",
"$",
"instance",
")",
".",
"\".\"",
")",
";",
"return",
"$",
"method",
";",
"}",
",",
"array_combine",
"(",
"$",
"abilities",
",",
"$",
"abilities",
")",
")",
";",
"}"
] | Get the policies.
@return array | [
"Get",
"the",
"policies",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/Bases/Policy.php#L24-L38 |
ARCANEDEV/Support | src/PackageServiceProvider.php | PackageServiceProvider.registerConfig | protected function registerConfig($separator = '.')
{
$this->multiConfigs
? $this->registerMultipleConfigs($separator)
: $this->mergeConfigFrom($this->getConfigFile(), $this->getConfigKey());
} | php | protected function registerConfig($separator = '.')
{
$this->multiConfigs
? $this->registerMultipleConfigs($separator)
: $this->mergeConfigFrom($this->getConfigFile(), $this->getConfigKey());
} | [
"protected",
"function",
"registerConfig",
"(",
"$",
"separator",
"=",
"'.'",
")",
"{",
"$",
"this",
"->",
"multiConfigs",
"?",
"$",
"this",
"->",
"registerMultipleConfigs",
"(",
"$",
"separator",
")",
":",
"$",
"this",
"->",
"mergeConfigFrom",
"(",
"$",
"this",
"->",
"getConfigFile",
"(",
")",
",",
"$",
"this",
"->",
"getConfigKey",
"(",
")",
")",
";",
"}"
] | Register configs.
@param string $separator | [
"Register",
"configs",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/PackageServiceProvider.php#L228-L233 |
ARCANEDEV/Support | src/PackageServiceProvider.php | PackageServiceProvider.registerMultipleConfigs | private function registerMultipleConfigs($separator = '.')
{
foreach (glob($this->getConfigFolder().'/*.php') as $configPath) {
$this->mergeConfigFrom(
$configPath, $this->getConfigKey().$separator.basename($configPath, '.php')
);
}
} | php | private function registerMultipleConfigs($separator = '.')
{
foreach (glob($this->getConfigFolder().'/*.php') as $configPath) {
$this->mergeConfigFrom(
$configPath, $this->getConfigKey().$separator.basename($configPath, '.php')
);
}
} | [
"private",
"function",
"registerMultipleConfigs",
"(",
"$",
"separator",
"=",
"'.'",
")",
"{",
"foreach",
"(",
"glob",
"(",
"$",
"this",
"->",
"getConfigFolder",
"(",
")",
".",
"'/*.php'",
")",
"as",
"$",
"configPath",
")",
"{",
"$",
"this",
"->",
"mergeConfigFrom",
"(",
"$",
"configPath",
",",
"$",
"this",
"->",
"getConfigKey",
"(",
")",
".",
"$",
"separator",
".",
"basename",
"(",
"$",
"configPath",
",",
"'.php'",
")",
")",
";",
"}",
"}"
] | Register all package configs.
@param string $separator | [
"Register",
"all",
"package",
"configs",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/PackageServiceProvider.php#L240-L247 |
ARCANEDEV/Support | src/PackageServiceProvider.php | PackageServiceProvider.publishViews | protected function publishViews($load = true)
{
$this->publishes([
$this->getViewsPath() => $this->getViewsDestinationPath()
], 'views');
if ($load) $this->loadViews();
} | php | protected function publishViews($load = true)
{
$this->publishes([
$this->getViewsPath() => $this->getViewsDestinationPath()
], 'views');
if ($load) $this->loadViews();
} | [
"protected",
"function",
"publishViews",
"(",
"$",
"load",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"publishes",
"(",
"[",
"$",
"this",
"->",
"getViewsPath",
"(",
")",
"=>",
"$",
"this",
"->",
"getViewsDestinationPath",
"(",
")",
"]",
",",
"'views'",
")",
";",
"if",
"(",
"$",
"load",
")",
"$",
"this",
"->",
"loadViews",
"(",
")",
";",
"}"
] | Publish and load the views if $load argument is true.
@param bool $load | [
"Publish",
"and",
"load",
"the",
"views",
"if",
"$load",
"argument",
"is",
"true",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/PackageServiceProvider.php#L285-L292 |
ARCANEDEV/Support | src/PackageServiceProvider.php | PackageServiceProvider.publishTranslations | protected function publishTranslations($load = true)
{
$this->publishes([
$this->getTranslationsPath() => $this->getTranslationsDestinationPath()
], 'lang');
if ($load) $this->loadTranslations();
} | php | protected function publishTranslations($load = true)
{
$this->publishes([
$this->getTranslationsPath() => $this->getTranslationsDestinationPath()
], 'lang');
if ($load) $this->loadTranslations();
} | [
"protected",
"function",
"publishTranslations",
"(",
"$",
"load",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"publishes",
"(",
"[",
"$",
"this",
"->",
"getTranslationsPath",
"(",
")",
"=>",
"$",
"this",
"->",
"getTranslationsDestinationPath",
"(",
")",
"]",
",",
"'lang'",
")",
";",
"if",
"(",
"$",
"load",
")",
"$",
"this",
"->",
"loadTranslations",
"(",
")",
";",
"}"
] | Publish and load the translations if $load argument is true.
@param bool $load | [
"Publish",
"and",
"load",
"the",
"translations",
"if",
"$load",
"argument",
"is",
"true",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/PackageServiceProvider.php#L299-L306 |
ARCANEDEV/Support | src/PackageServiceProvider.php | PackageServiceProvider.publishAll | protected function publishAll($load = true)
{
$this->publishConfig();
$this->publishMigrations();
$this->publishViews($load);
$this->publishTranslations($load);
$this->publishFactories();
} | php | protected function publishAll($load = true)
{
$this->publishConfig();
$this->publishMigrations();
$this->publishViews($load);
$this->publishTranslations($load);
$this->publishFactories();
} | [
"protected",
"function",
"publishAll",
"(",
"$",
"load",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"publishConfig",
"(",
")",
";",
"$",
"this",
"->",
"publishMigrations",
"(",
")",
";",
"$",
"this",
"->",
"publishViews",
"(",
"$",
"load",
")",
";",
"$",
"this",
"->",
"publishTranslations",
"(",
"$",
"load",
")",
";",
"$",
"this",
"->",
"publishFactories",
"(",
")",
";",
"}"
] | Publish all the package files.
@param bool $load | [
"Publish",
"all",
"the",
"package",
"files",
"."
] | train | https://github.com/ARCANEDEV/Support/blob/2bb6e901404a12caa440520676b6507569d20715/src/PackageServiceProvider.php#L323-L330 |
sensiolabs/melody | src/SensioLabs/Melody/Handler/FileHandler.php | FileHandler.createResource | public function createResource($filename)
{
$stat = stat($filename);
$metadata = new Metadata(
$stat['ino'],
$stat['uid'],
new \DateTime(date('c', $stat['ctime'])),
new \DateTime(date('c', $stat['mtime'])),
1,
sprintf('file://%s', realpath($filename))
);
return new LocalResource($filename, file_get_contents($filename), $metadata);
} | php | public function createResource($filename)
{
$stat = stat($filename);
$metadata = new Metadata(
$stat['ino'],
$stat['uid'],
new \DateTime(date('c', $stat['ctime'])),
new \DateTime(date('c', $stat['mtime'])),
1,
sprintf('file://%s', realpath($filename))
);
return new LocalResource($filename, file_get_contents($filename), $metadata);
} | [
"public",
"function",
"createResource",
"(",
"$",
"filename",
")",
"{",
"$",
"stat",
"=",
"stat",
"(",
"$",
"filename",
")",
";",
"$",
"metadata",
"=",
"new",
"Metadata",
"(",
"$",
"stat",
"[",
"'ino'",
"]",
",",
"$",
"stat",
"[",
"'uid'",
"]",
",",
"new",
"\\",
"DateTime",
"(",
"date",
"(",
"'c'",
",",
"$",
"stat",
"[",
"'ctime'",
"]",
")",
")",
",",
"new",
"\\",
"DateTime",
"(",
"date",
"(",
"'c'",
",",
"$",
"stat",
"[",
"'mtime'",
"]",
")",
")",
",",
"1",
",",
"sprintf",
"(",
"'file://%s'",
",",
"realpath",
"(",
"$",
"filename",
")",
")",
")",
";",
"return",
"new",
"LocalResource",
"(",
"$",
"filename",
",",
"file_get_contents",
"(",
"$",
"filename",
")",
",",
"$",
"metadata",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Handler/FileHandler.php#L27-L40 |
sensiolabs/melody | src/SensioLabs/Melody/Composer/Composer.php | Composer.guessComposerCommand | private function guessComposerCommand()
{
$candidateNames = array('composer', 'composer.phar');
$executableFinder = new ExecutableFinder();
foreach ($candidateNames as $candidateName) {
if ($composerPath = $executableFinder->find($candidateName, null, array(getcwd()))) {
return array(realpath($composerPath));
}
}
foreach ($candidateNames as $candidateName) {
$composerPath = sprintf('%s/%s', getcwd(), $candidateName);
if (file_exists($composerPath)) {
$phpFinder = new PhpExecutableFinder();
return array_merge(
array(
$phpFinder->find(false),
$composerPath,
),
$phpFinder->findArguments()
);
}
}
return;
} | php | private function guessComposerCommand()
{
$candidateNames = array('composer', 'composer.phar');
$executableFinder = new ExecutableFinder();
foreach ($candidateNames as $candidateName) {
if ($composerPath = $executableFinder->find($candidateName, null, array(getcwd()))) {
return array(realpath($composerPath));
}
}
foreach ($candidateNames as $candidateName) {
$composerPath = sprintf('%s/%s', getcwd(), $candidateName);
if (file_exists($composerPath)) {
$phpFinder = new PhpExecutableFinder();
return array_merge(
array(
$phpFinder->find(false),
$composerPath,
),
$phpFinder->findArguments()
);
}
}
return;
} | [
"private",
"function",
"guessComposerCommand",
"(",
")",
"{",
"$",
"candidateNames",
"=",
"array",
"(",
"'composer'",
",",
"'composer.phar'",
")",
";",
"$",
"executableFinder",
"=",
"new",
"ExecutableFinder",
"(",
")",
";",
"foreach",
"(",
"$",
"candidateNames",
"as",
"$",
"candidateName",
")",
"{",
"if",
"(",
"$",
"composerPath",
"=",
"$",
"executableFinder",
"->",
"find",
"(",
"$",
"candidateName",
",",
"null",
",",
"array",
"(",
"getcwd",
"(",
")",
")",
")",
")",
"{",
"return",
"array",
"(",
"realpath",
"(",
"$",
"composerPath",
")",
")",
";",
"}",
"}",
"foreach",
"(",
"$",
"candidateNames",
"as",
"$",
"candidateName",
")",
"{",
"$",
"composerPath",
"=",
"sprintf",
"(",
"'%s/%s'",
",",
"getcwd",
"(",
")",
",",
"$",
"candidateName",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"composerPath",
")",
")",
"{",
"$",
"phpFinder",
"=",
"new",
"PhpExecutableFinder",
"(",
")",
";",
"return",
"array_merge",
"(",
"array",
"(",
"$",
"phpFinder",
"->",
"find",
"(",
"false",
")",
",",
"$",
"composerPath",
",",
")",
",",
"$",
"phpFinder",
"->",
"findArguments",
"(",
")",
")",
";",
"}",
"}",
"return",
";",
"}"
] | Guess and build the command to call composer.
Search:
- a executable composer (or composer.phar)
- a file composer (or composer.phar) prefixed by php | [
"Guess",
"and",
"build",
"the",
"command",
"to",
"call",
"composer",
"."
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Composer/Composer.php#L106-L133 |
sensiolabs/melody | src/SensioLabs/Melody/Melody.php | Melody.createResource | private function createResource($resourceName)
{
foreach ($this->handlers as $handler) {
if (!$handler->supports($resourceName)) {
continue;
}
return $handler->createResource($resourceName);
}
throw new \LogicException(sprintf('No handler found for resource "%s".', $resourceName));
} | php | private function createResource($resourceName)
{
foreach ($this->handlers as $handler) {
if (!$handler->supports($resourceName)) {
continue;
}
return $handler->createResource($resourceName);
}
throw new \LogicException(sprintf('No handler found for resource "%s".', $resourceName));
} | [
"private",
"function",
"createResource",
"(",
"$",
"resourceName",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"handlers",
"as",
"$",
"handler",
")",
"{",
"if",
"(",
"!",
"$",
"handler",
"->",
"supports",
"(",
"$",
"resourceName",
")",
")",
"{",
"continue",
";",
"}",
"return",
"$",
"handler",
"->",
"createResource",
"(",
"$",
"resourceName",
")",
";",
"}",
"throw",
"new",
"\\",
"LogicException",
"(",
"sprintf",
"(",
"'No handler found for resource \"%s\".'",
",",
"$",
"resourceName",
")",
")",
";",
"}"
] | @param string $resourceName path to the resource
@return Resource | [
"@param",
"string",
"$resourceName",
"path",
"to",
"the",
"resource"
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Melody.php#L95-L106 |
sensiolabs/melody | src/SensioLabs/Melody/WorkingDirectory/GarbageCollector.php | GarbageCollector.run | public function run()
{
$maxATime = time() - self::TTL;
$files = Finder::create()
->in($this->storePath)
->depth(1)
->name(Runner::BOOTSTRAP_FILENAME)
->filter(function (SplFileInfo $d) use ($maxATime) {
return $d->getATime() < $maxATime;
})
;
$directories = array();
foreach ($files as $file) {
$directories[] = dirname($file);
}
$this->filesystem->remove($directories);
} | php | public function run()
{
$maxATime = time() - self::TTL;
$files = Finder::create()
->in($this->storePath)
->depth(1)
->name(Runner::BOOTSTRAP_FILENAME)
->filter(function (SplFileInfo $d) use ($maxATime) {
return $d->getATime() < $maxATime;
})
;
$directories = array();
foreach ($files as $file) {
$directories[] = dirname($file);
}
$this->filesystem->remove($directories);
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"maxATime",
"=",
"time",
"(",
")",
"-",
"self",
"::",
"TTL",
";",
"$",
"files",
"=",
"Finder",
"::",
"create",
"(",
")",
"->",
"in",
"(",
"$",
"this",
"->",
"storePath",
")",
"->",
"depth",
"(",
"1",
")",
"->",
"name",
"(",
"Runner",
"::",
"BOOTSTRAP_FILENAME",
")",
"->",
"filter",
"(",
"function",
"(",
"SplFileInfo",
"$",
"d",
")",
"use",
"(",
"$",
"maxATime",
")",
"{",
"return",
"$",
"d",
"->",
"getATime",
"(",
")",
"<",
"$",
"maxATime",
";",
"}",
")",
";",
"$",
"directories",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file",
")",
"{",
"$",
"directories",
"[",
"]",
"=",
"dirname",
"(",
"$",
"file",
")",
";",
"}",
"$",
"this",
"->",
"filesystem",
"->",
"remove",
"(",
"$",
"directories",
")",
";",
"}"
] | Remove old workingDirectories. | [
"Remove",
"old",
"workingDirectories",
"."
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/WorkingDirectory/GarbageCollector.php#L33-L53 |
sensiolabs/melody | src/SensioLabs/Melody/Configuration/UserConfigurationRepository.php | UserConfigurationRepository.load | public function load()
{
$config = new UserConfiguration();
if (!file_exists($this->storagePath)) {
return $config;
}
try {
$data = Yaml::parse(file_get_contents($this->storagePath));
} catch (ParseException $e) {
throw new ConfigException(sprintf('The config file "%s" is not a valid YAML.', $this->storagePath), 0, $e);
}
if (is_array($data)) {
$config->load($data);
}
return $config;
} | php | public function load()
{
$config = new UserConfiguration();
if (!file_exists($this->storagePath)) {
return $config;
}
try {
$data = Yaml::parse(file_get_contents($this->storagePath));
} catch (ParseException $e) {
throw new ConfigException(sprintf('The config file "%s" is not a valid YAML.', $this->storagePath), 0, $e);
}
if (is_array($data)) {
$config->load($data);
}
return $config;
} | [
"public",
"function",
"load",
"(",
")",
"{",
"$",
"config",
"=",
"new",
"UserConfiguration",
"(",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"storagePath",
")",
")",
"{",
"return",
"$",
"config",
";",
"}",
"try",
"{",
"$",
"data",
"=",
"Yaml",
"::",
"parse",
"(",
"file_get_contents",
"(",
"$",
"this",
"->",
"storagePath",
")",
")",
";",
"}",
"catch",
"(",
"ParseException",
"$",
"e",
")",
"{",
"throw",
"new",
"ConfigException",
"(",
"sprintf",
"(",
"'The config file \"%s\" is not a valid YAML.'",
",",
"$",
"this",
"->",
"storagePath",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"config",
"->",
"load",
"(",
"$",
"data",
")",
";",
"}",
"return",
"$",
"config",
";",
"}"
] | Load stored configuration. Returns an empty UserConfiguration if no previous configuration was stored.
@return UserConfiguration | [
"Load",
"stored",
"configuration",
".",
"Returns",
"an",
"empty",
"UserConfiguration",
"if",
"no",
"previous",
"configuration",
"was",
"stored",
"."
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Configuration/UserConfigurationRepository.php#L26-L44 |
sensiolabs/melody | src/SensioLabs/Melody/Configuration/UserConfigurationRepository.php | UserConfigurationRepository.save | public function save(UserConfiguration $config)
{
file_put_contents($this->storagePath, Yaml::dump($config->toArray(), 3, 2));
return $this;
} | php | public function save(UserConfiguration $config)
{
file_put_contents($this->storagePath, Yaml::dump($config->toArray(), 3, 2));
return $this;
} | [
"public",
"function",
"save",
"(",
"UserConfiguration",
"$",
"config",
")",
"{",
"file_put_contents",
"(",
"$",
"this",
"->",
"storagePath",
",",
"Yaml",
"::",
"dump",
"(",
"$",
"config",
"->",
"toArray",
"(",
")",
",",
"3",
",",
"2",
")",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Save the given configuration.
@param UserConfiguration $config
@return $this | [
"Save",
"the",
"given",
"configuration",
"."
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Configuration/UserConfigurationRepository.php#L53-L58 |
sensiolabs/melody | src/SensioLabs/Melody/Console/Command/SelfUpdateCommand.php | SelfUpdateCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$remoteFilename = 'http://get.sensiolabs.org/melody.phar';
$localFilename = $_SERVER['argv'][0];
if (is_writable(dirname($localFilename))) {
$moveCallback = function ($tempFilename, $localFilename) {
rename($tempFilename, $localFilename);
};
} elseif (is_writable($localFilename)) {
$moveCallback = function ($tempFilename, $localFilename) {
file_put_contents($localFilename, file_get_contents($tempFilename));
unlink($tempFilename);
};
} else {
$output->writeln(sprintf('<error>The file %s could not be written.</error>', $localFilename));
$output->writeln('<error>Please run the self-update command with higher privileges.</error>');
return 1;
}
$tempDirectory = sys_get_temp_dir();
if (!is_writable($tempDirectory)) {
$output->writeln(sprintf('<error>The temporary directory %s could not be written.</error>', $tempDirectory));
$output->writeln('<error>Please run the self-update command with higher privileges.</error>');
return 1;
}
$tempFilename = sprintf('%s/melody-%s.phar', $tempDirectory, uniqid());
@copy($remoteFilename, $tempFilename);
if (!file_exists($tempFilename)) {
$output->writeln('<error>Unable to download new versions from the server.</error>');
return 1;
}
chmod($tempFilename, 0777 & ~umask());
try {
// test the phar validity
$phar = new \Phar($tempFilename);
// free the variable to unlock the file
unset($phar);
} catch (\Exception $e) {
unlink($tempFilename);
$output->writeln(sprintf('<error>The download is corrupt (%s).</error>', $e->getMessage()));
$output->writeln('<error>Please re-run the self-update command to try again.</error>');
return 1;
}
call_user_func($moveCallback, $tempFilename, $localFilename);
$output->writeln('<info>melody updated.</info>');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$remoteFilename = 'http://get.sensiolabs.org/melody.phar';
$localFilename = $_SERVER['argv'][0];
if (is_writable(dirname($localFilename))) {
$moveCallback = function ($tempFilename, $localFilename) {
rename($tempFilename, $localFilename);
};
} elseif (is_writable($localFilename)) {
$moveCallback = function ($tempFilename, $localFilename) {
file_put_contents($localFilename, file_get_contents($tempFilename));
unlink($tempFilename);
};
} else {
$output->writeln(sprintf('<error>The file %s could not be written.</error>', $localFilename));
$output->writeln('<error>Please run the self-update command with higher privileges.</error>');
return 1;
}
$tempDirectory = sys_get_temp_dir();
if (!is_writable($tempDirectory)) {
$output->writeln(sprintf('<error>The temporary directory %s could not be written.</error>', $tempDirectory));
$output->writeln('<error>Please run the self-update command with higher privileges.</error>');
return 1;
}
$tempFilename = sprintf('%s/melody-%s.phar', $tempDirectory, uniqid());
@copy($remoteFilename, $tempFilename);
if (!file_exists($tempFilename)) {
$output->writeln('<error>Unable to download new versions from the server.</error>');
return 1;
}
chmod($tempFilename, 0777 & ~umask());
try {
// test the phar validity
$phar = new \Phar($tempFilename);
// free the variable to unlock the file
unset($phar);
} catch (\Exception $e) {
unlink($tempFilename);
$output->writeln(sprintf('<error>The download is corrupt (%s).</error>', $e->getMessage()));
$output->writeln('<error>Please re-run the self-update command to try again.</error>');
return 1;
}
call_user_func($moveCallback, $tempFilename, $localFilename);
$output->writeln('<info>melody updated.</info>');
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"remoteFilename",
"=",
"'http://get.sensiolabs.org/melody.phar'",
";",
"$",
"localFilename",
"=",
"$",
"_SERVER",
"[",
"'argv'",
"]",
"[",
"0",
"]",
";",
"if",
"(",
"is_writable",
"(",
"dirname",
"(",
"$",
"localFilename",
")",
")",
")",
"{",
"$",
"moveCallback",
"=",
"function",
"(",
"$",
"tempFilename",
",",
"$",
"localFilename",
")",
"{",
"rename",
"(",
"$",
"tempFilename",
",",
"$",
"localFilename",
")",
";",
"}",
";",
"}",
"elseif",
"(",
"is_writable",
"(",
"$",
"localFilename",
")",
")",
"{",
"$",
"moveCallback",
"=",
"function",
"(",
"$",
"tempFilename",
",",
"$",
"localFilename",
")",
"{",
"file_put_contents",
"(",
"$",
"localFilename",
",",
"file_get_contents",
"(",
"$",
"tempFilename",
")",
")",
";",
"unlink",
"(",
"$",
"tempFilename",
")",
";",
"}",
";",
"}",
"else",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>The file %s could not be written.</error>'",
",",
"$",
"localFilename",
")",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"'<error>Please run the self-update command with higher privileges.</error>'",
")",
";",
"return",
"1",
";",
"}",
"$",
"tempDirectory",
"=",
"sys_get_temp_dir",
"(",
")",
";",
"if",
"(",
"!",
"is_writable",
"(",
"$",
"tempDirectory",
")",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>The temporary directory %s could not be written.</error>'",
",",
"$",
"tempDirectory",
")",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"'<error>Please run the self-update command with higher privileges.</error>'",
")",
";",
"return",
"1",
";",
"}",
"$",
"tempFilename",
"=",
"sprintf",
"(",
"'%s/melody-%s.phar'",
",",
"$",
"tempDirectory",
",",
"uniqid",
"(",
")",
")",
";",
"@",
"copy",
"(",
"$",
"remoteFilename",
",",
"$",
"tempFilename",
")",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"tempFilename",
")",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'<error>Unable to download new versions from the server.</error>'",
")",
";",
"return",
"1",
";",
"}",
"chmod",
"(",
"$",
"tempFilename",
",",
"0777",
"&",
"~",
"umask",
"(",
")",
")",
";",
"try",
"{",
"// test the phar validity",
"$",
"phar",
"=",
"new",
"\\",
"Phar",
"(",
"$",
"tempFilename",
")",
";",
"// free the variable to unlock the file",
"unset",
"(",
"$",
"phar",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"unlink",
"(",
"$",
"tempFilename",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>The download is corrupt (%s).</error>'",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"'<error>Please re-run the self-update command to try again.</error>'",
")",
";",
"return",
"1",
";",
"}",
"call_user_func",
"(",
"$",
"moveCallback",
",",
"$",
"tempFilename",
",",
"$",
"localFilename",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"'<info>melody updated.</info>'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Console/Command/SelfUpdateCommand.php#L38-L94 |
sensiolabs/melody | src/SensioLabs/Melody/Handler/StreamHandler.php | StreamHandler.createResource | public function createResource($filename)
{
$metadata = new Metadata(
basename($filename),
null,
new \DateTime(),
new \DateTime(),
1,
$filename
);
return new Resource(file_get_contents($filename), $metadata);
} | php | public function createResource($filename)
{
$metadata = new Metadata(
basename($filename),
null,
new \DateTime(),
new \DateTime(),
1,
$filename
);
return new Resource(file_get_contents($filename), $metadata);
} | [
"public",
"function",
"createResource",
"(",
"$",
"filename",
")",
"{",
"$",
"metadata",
"=",
"new",
"Metadata",
"(",
"basename",
"(",
"$",
"filename",
")",
",",
"null",
",",
"new",
"\\",
"DateTime",
"(",
")",
",",
"new",
"\\",
"DateTime",
"(",
")",
",",
"1",
",",
"$",
"filename",
")",
";",
"return",
"new",
"Resource",
"(",
"file_get_contents",
"(",
"$",
"filename",
")",
",",
"$",
"metadata",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Handler/StreamHandler.php#L28-L40 |
sensiolabs/melody | src/SensioLabs/Melody/Handler/GistHandler.php | GistHandler.createResource | public function createResource($uri)
{
$gist = new Gist($uri);
$data = $gist->get();
if (array_key_exists('message', $data)) {
throw new \InvalidArgumentException('There is an issue with your gist URL: '.$data['message']);
}
$files = $data['files'];
// Throw an error if the gist contains multiple files
if (1 !== count($files)) {
throw new \InvalidArgumentException('The gist should contain a single file');
}
// Fetch the only element in the array
$file = current($files);
$metadata = new Metadata(
$data['id'],
$data['owner']['login'],
new \DateTime($data['created_at']),
new \DateTime($data['updated_at']),
count($data['history']),
$data['html_url']
);
return new Resource($file['content'], $metadata);
} | php | public function createResource($uri)
{
$gist = new Gist($uri);
$data = $gist->get();
if (array_key_exists('message', $data)) {
throw new \InvalidArgumentException('There is an issue with your gist URL: '.$data['message']);
}
$files = $data['files'];
// Throw an error if the gist contains multiple files
if (1 !== count($files)) {
throw new \InvalidArgumentException('The gist should contain a single file');
}
// Fetch the only element in the array
$file = current($files);
$metadata = new Metadata(
$data['id'],
$data['owner']['login'],
new \DateTime($data['created_at']),
new \DateTime($data['updated_at']),
count($data['history']),
$data['html_url']
);
return new Resource($file['content'], $metadata);
} | [
"public",
"function",
"createResource",
"(",
"$",
"uri",
")",
"{",
"$",
"gist",
"=",
"new",
"Gist",
"(",
"$",
"uri",
")",
";",
"$",
"data",
"=",
"$",
"gist",
"->",
"get",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"'message'",
",",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'There is an issue with your gist URL: '",
".",
"$",
"data",
"[",
"'message'",
"]",
")",
";",
"}",
"$",
"files",
"=",
"$",
"data",
"[",
"'files'",
"]",
";",
"// Throw an error if the gist contains multiple files",
"if",
"(",
"1",
"!==",
"count",
"(",
"$",
"files",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The gist should contain a single file'",
")",
";",
"}",
"// Fetch the only element in the array",
"$",
"file",
"=",
"current",
"(",
"$",
"files",
")",
";",
"$",
"metadata",
"=",
"new",
"Metadata",
"(",
"$",
"data",
"[",
"'id'",
"]",
",",
"$",
"data",
"[",
"'owner'",
"]",
"[",
"'login'",
"]",
",",
"new",
"\\",
"DateTime",
"(",
"$",
"data",
"[",
"'created_at'",
"]",
")",
",",
"new",
"\\",
"DateTime",
"(",
"$",
"data",
"[",
"'updated_at'",
"]",
")",
",",
"count",
"(",
"$",
"data",
"[",
"'history'",
"]",
")",
",",
"$",
"data",
"[",
"'html_url'",
"]",
")",
";",
"return",
"new",
"Resource",
"(",
"$",
"file",
"[",
"'content'",
"]",
",",
"$",
"metadata",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Handler/GistHandler.php#L29-L57 |
sensiolabs/melody | src/SensioLabs/Melody/Handler/Github/Gist.php | Gist.download | public function download()
{
$handle = curl_init();
$http_proxy = filter_input(INPUT_ENV, 'HTTPS_PROXY', FILTER_SANITIZE_URL);
curl_setopt_array($handle, array(
CURLOPT_URL => sprintf('https://api.github.com/gists/%s', $this->id),
CURLOPT_HTTPHEADER => array(
'Accept: application/vnd.github.v3+json',
'User-Agent: Melody-Script',
),
CURLOPT_RETURNTRANSFER => 1,
));
if ($http_proxy) {
curl_setopt($handle, CURLOPT_PROXY, $http_proxy);
}
$content = curl_exec($handle);
curl_close($handle);
if (!$content) {
throw new \InvalidArgumentException(sprintf('Gist "%s" not found', $this->id));
}
return json_decode($content, true);
} | php | public function download()
{
$handle = curl_init();
$http_proxy = filter_input(INPUT_ENV, 'HTTPS_PROXY', FILTER_SANITIZE_URL);
curl_setopt_array($handle, array(
CURLOPT_URL => sprintf('https://api.github.com/gists/%s', $this->id),
CURLOPT_HTTPHEADER => array(
'Accept: application/vnd.github.v3+json',
'User-Agent: Melody-Script',
),
CURLOPT_RETURNTRANSFER => 1,
));
if ($http_proxy) {
curl_setopt($handle, CURLOPT_PROXY, $http_proxy);
}
$content = curl_exec($handle);
curl_close($handle);
if (!$content) {
throw new \InvalidArgumentException(sprintf('Gist "%s" not found', $this->id));
}
return json_decode($content, true);
} | [
"public",
"function",
"download",
"(",
")",
"{",
"$",
"handle",
"=",
"curl_init",
"(",
")",
";",
"$",
"http_proxy",
"=",
"filter_input",
"(",
"INPUT_ENV",
",",
"'HTTPS_PROXY'",
",",
"FILTER_SANITIZE_URL",
")",
";",
"curl_setopt_array",
"(",
"$",
"handle",
",",
"array",
"(",
"CURLOPT_URL",
"=>",
"sprintf",
"(",
"'https://api.github.com/gists/%s'",
",",
"$",
"this",
"->",
"id",
")",
",",
"CURLOPT_HTTPHEADER",
"=>",
"array",
"(",
"'Accept: application/vnd.github.v3+json'",
",",
"'User-Agent: Melody-Script'",
",",
")",
",",
"CURLOPT_RETURNTRANSFER",
"=>",
"1",
",",
")",
")",
";",
"if",
"(",
"$",
"http_proxy",
")",
"{",
"curl_setopt",
"(",
"$",
"handle",
",",
"CURLOPT_PROXY",
",",
"$",
"http_proxy",
")",
";",
"}",
"$",
"content",
"=",
"curl_exec",
"(",
"$",
"handle",
")",
";",
"curl_close",
"(",
"$",
"handle",
")",
";",
"if",
"(",
"!",
"$",
"content",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Gist \"%s\" not found'",
",",
"$",
"this",
"->",
"id",
")",
")",
";",
"}",
"return",
"json_decode",
"(",
"$",
"content",
",",
"true",
")",
";",
"}"
] | Call Github and return JSON data.
@return mixed<string> the content of API call to Github | [
"Call",
"Github",
"and",
"return",
"JSON",
"data",
"."
] | train | https://github.com/sensiolabs/melody/blob/9a60775ec774f2a1da33cf5b904223c303bb169f/src/SensioLabs/Melody/Handler/Github/Gist.php#L49-L75 |
mossadal/math-parser | src/MathParser/Lexing/Lexer.php | Lexer.tokenize | public function tokenize($input)
{
// The list of tokens we'll eventually return
$tokens = [];
// The currentIndex indicates where we are inside the input string
$currentIndex = 0;
while ($currentIndex < strlen($input)) {
// We try to match only what is after the currentIndex,
// as the content before is already converted to tokens
$token = $this->findMatchingToken(substr($input, $currentIndex));
// If no tokens were matched, it means that the string has invalid tokens
// for which we did not define a token definition
if (!$token) {
throw new UnknownTokenException(substr($input, $currentIndex));
}
// Add the matched token to our list of token
$tokens[] = $token;
// Increment the string index by the lenght of the matched token,
// so we can now process the rest of the string.
$currentIndex += $token->length();
}
return $tokens;
} | php | public function tokenize($input)
{
// The list of tokens we'll eventually return
$tokens = [];
// The currentIndex indicates where we are inside the input string
$currentIndex = 0;
while ($currentIndex < strlen($input)) {
// We try to match only what is after the currentIndex,
// as the content before is already converted to tokens
$token = $this->findMatchingToken(substr($input, $currentIndex));
// If no tokens were matched, it means that the string has invalid tokens
// for which we did not define a token definition
if (!$token) {
throw new UnknownTokenException(substr($input, $currentIndex));
}
// Add the matched token to our list of token
$tokens[] = $token;
// Increment the string index by the lenght of the matched token,
// so we can now process the rest of the string.
$currentIndex += $token->length();
}
return $tokens;
} | [
"public",
"function",
"tokenize",
"(",
"$",
"input",
")",
"{",
"// The list of tokens we'll eventually return",
"$",
"tokens",
"=",
"[",
"]",
";",
"// The currentIndex indicates where we are inside the input string",
"$",
"currentIndex",
"=",
"0",
";",
"while",
"(",
"$",
"currentIndex",
"<",
"strlen",
"(",
"$",
"input",
")",
")",
"{",
"// We try to match only what is after the currentIndex,",
"// as the content before is already converted to tokens",
"$",
"token",
"=",
"$",
"this",
"->",
"findMatchingToken",
"(",
"substr",
"(",
"$",
"input",
",",
"$",
"currentIndex",
")",
")",
";",
"// If no tokens were matched, it means that the string has invalid tokens",
"// for which we did not define a token definition",
"if",
"(",
"!",
"$",
"token",
")",
"{",
"throw",
"new",
"UnknownTokenException",
"(",
"substr",
"(",
"$",
"input",
",",
"$",
"currentIndex",
")",
")",
";",
"}",
"// Add the matched token to our list of token",
"$",
"tokens",
"[",
"]",
"=",
"$",
"token",
";",
"// Increment the string index by the lenght of the matched token,",
"// so we can now process the rest of the string.",
"$",
"currentIndex",
"+=",
"$",
"token",
"->",
"length",
"(",
")",
";",
"}",
"return",
"$",
"tokens",
";",
"}"
] | Convert an input string to a list of tokens.
Using the list of knowns tokens, sequentially match the input string to
known tokens. Note that the first matching token from the list is chosen,
so if there are tokens sharing parts of the pattern (e.g. `sin` and `sinh`),
care should be taken to add `sinh` before `sin`, otherwise the lexer will
never match a `sinh`.
@retval Token[] sequence of recognized tokens
that doesn't match any knwon token.
@param string $input String to tokenize.
@throws UnknownTokenException throwns when encountering characters in the input string | [
"Convert",
"an",
"input",
"string",
"to",
"a",
"list",
"of",
"tokens",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Lexing/Lexer.php#L74-L102 |
mossadal/math-parser | src/MathParser/Lexing/Lexer.php | Lexer.findMatchingToken | private function findMatchingToken($input)
{
// Check with all tokenDefinitions
foreach ($this->tokenDefinitions as $tokenDefinition) {
$token = $tokenDefinition->match($input);
// Return the first token that was matched.
if ($token) {
return $token;
}
}
// Return null if no tokens were matched.
return null;
} | php | private function findMatchingToken($input)
{
// Check with all tokenDefinitions
foreach ($this->tokenDefinitions as $tokenDefinition) {
$token = $tokenDefinition->match($input);
// Return the first token that was matched.
if ($token) {
return $token;
}
}
// Return null if no tokens were matched.
return null;
} | [
"private",
"function",
"findMatchingToken",
"(",
"$",
"input",
")",
"{",
"// Check with all tokenDefinitions",
"foreach",
"(",
"$",
"this",
"->",
"tokenDefinitions",
"as",
"$",
"tokenDefinition",
")",
"{",
"$",
"token",
"=",
"$",
"tokenDefinition",
"->",
"match",
"(",
"$",
"input",
")",
";",
"// Return the first token that was matched.",
"if",
"(",
"$",
"token",
")",
"{",
"return",
"$",
"token",
";",
"}",
"}",
"// Return null if no tokens were matched.",
"return",
"null",
";",
"}"
] | Find a matching token at the begining of the provided input.
@retval Token|null Matched token
@param string $input | [
"Find",
"a",
"matching",
"token",
"at",
"the",
"begining",
"of",
"the",
"provided",
"input",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Lexing/Lexer.php#L110-L125 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.parseReal | private static function parseReal($value)
{
if ($value == '') return null;
$x = str_replace(',', '.', $value);
if (static::isSignedReal($x)) return floatval($x);
else throw new SyntaxErrorException();
} | php | private static function parseReal($value)
{
if ($value == '') return null;
$x = str_replace(',', '.', $value);
if (static::isSignedReal($x)) return floatval($x);
else throw new SyntaxErrorException();
} | [
"private",
"static",
"function",
"parseReal",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"==",
"''",
")",
"return",
"null",
";",
"$",
"x",
"=",
"str_replace",
"(",
"','",
",",
"'.'",
",",
"$",
"value",
")",
";",
"if",
"(",
"static",
"::",
"isSignedReal",
"(",
"$",
"x",
")",
")",
"return",
"floatval",
"(",
"$",
"x",
")",
";",
"else",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}"
] | convert string to floating point number, if possible
decimal commas accepted
@param string $value
@throws SyntaxErrorException if the string cannot be parsed
@retval float | [
"convert",
"string",
"to",
"floating",
"point",
"number",
"if",
"possible"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L132-L139 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.parse | public static function parse($value)
{
if ($value instanceof Complex) return $value;
if ($value instanceof Rational) return new Complex($value.p/$value.q, 0);
if (is_int($value)) return new Complex($value, 0);
if (is_float($value)) return new Complex($value, 0);
if (!is_string($value)) throw new SyntaxErrorException();
// Match complex numbers with an explicit i
$matches = array();
$valid = \preg_match(
'#^([-,\+])?([0-9/,\.]*?)([-,\+]?)([0-9/,\.]*?)i$#',
\trim($value),
$matches
);
if ($valid == 1) {
$real = $matches[2];
if ($real === '') {
$matches[3] = $matches[1];
$real = '0';
}
$imaginary = $matches[4];
if ($imaginary === '') $imaginary = '1';
if ($matches[1] && $matches[1] == '-') {
$real = '-' . $real;
}
if ($matches[3] && $matches[3] == '-') {
$imaginary = '-' . $imaginary;
}
try {
$a = Rational::parse($real);
$realPart = $a->p/$a->q;
} catch(SyntaxErrorException $e)
{
$realPart = static::parseReal($real);
}
try {
$b = Rational::parse($imaginary);
$imaginaryPart = $b->p/$b->q;
} catch(SyntaxErrorException $e)
{
$imaginaryPart = static::parseReal($imaginary);
}
}
else {
// That failed, try matching a rational number
try {
$a = Rational::parse($value);
$realPart = $a->p/$a->q;
$imaginaryPart = 0;
} catch(SyntaxErrorException $e) {
// Final attempt, try matching a real number
$realPart = static::parseReal($value);
$imaginaryPart = 0;
}
}
$z = new Complex($realPart, $imaginaryPart);
return $z;
} | php | public static function parse($value)
{
if ($value instanceof Complex) return $value;
if ($value instanceof Rational) return new Complex($value.p/$value.q, 0);
if (is_int($value)) return new Complex($value, 0);
if (is_float($value)) return new Complex($value, 0);
if (!is_string($value)) throw new SyntaxErrorException();
// Match complex numbers with an explicit i
$matches = array();
$valid = \preg_match(
'#^([-,\+])?([0-9/,\.]*?)([-,\+]?)([0-9/,\.]*?)i$#',
\trim($value),
$matches
);
if ($valid == 1) {
$real = $matches[2];
if ($real === '') {
$matches[3] = $matches[1];
$real = '0';
}
$imaginary = $matches[4];
if ($imaginary === '') $imaginary = '1';
if ($matches[1] && $matches[1] == '-') {
$real = '-' . $real;
}
if ($matches[3] && $matches[3] == '-') {
$imaginary = '-' . $imaginary;
}
try {
$a = Rational::parse($real);
$realPart = $a->p/$a->q;
} catch(SyntaxErrorException $e)
{
$realPart = static::parseReal($real);
}
try {
$b = Rational::parse($imaginary);
$imaginaryPart = $b->p/$b->q;
} catch(SyntaxErrorException $e)
{
$imaginaryPart = static::parseReal($imaginary);
}
}
else {
// That failed, try matching a rational number
try {
$a = Rational::parse($value);
$realPart = $a->p/$a->q;
$imaginaryPart = 0;
} catch(SyntaxErrorException $e) {
// Final attempt, try matching a real number
$realPart = static::parseReal($value);
$imaginaryPart = 0;
}
}
$z = new Complex($realPart, $imaginaryPart);
return $z;
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"Complex",
")",
"return",
"$",
"value",
";",
"if",
"(",
"$",
"value",
"instanceof",
"Rational",
")",
"return",
"new",
"Complex",
"(",
"$",
"value",
".",
"p",
"/",
"$",
"value",
".",
"q",
",",
"0",
")",
";",
"if",
"(",
"is_int",
"(",
"$",
"value",
")",
")",
"return",
"new",
"Complex",
"(",
"$",
"value",
",",
"0",
")",
";",
"if",
"(",
"is_float",
"(",
"$",
"value",
")",
")",
"return",
"new",
"Complex",
"(",
"$",
"value",
",",
"0",
")",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
")",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"// Match complex numbers with an explicit i",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"$",
"valid",
"=",
"\\",
"preg_match",
"(",
"'#^([-,\\+])?([0-9/,\\.]*?)([-,\\+]?)([0-9/,\\.]*?)i$#'",
",",
"\\",
"trim",
"(",
"$",
"value",
")",
",",
"$",
"matches",
")",
";",
"if",
"(",
"$",
"valid",
"==",
"1",
")",
"{",
"$",
"real",
"=",
"$",
"matches",
"[",
"2",
"]",
";",
"if",
"(",
"$",
"real",
"===",
"''",
")",
"{",
"$",
"matches",
"[",
"3",
"]",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"$",
"real",
"=",
"'0'",
";",
"}",
"$",
"imaginary",
"=",
"$",
"matches",
"[",
"4",
"]",
";",
"if",
"(",
"$",
"imaginary",
"===",
"''",
")",
"$",
"imaginary",
"=",
"'1'",
";",
"if",
"(",
"$",
"matches",
"[",
"1",
"]",
"&&",
"$",
"matches",
"[",
"1",
"]",
"==",
"'-'",
")",
"{",
"$",
"real",
"=",
"'-'",
".",
"$",
"real",
";",
"}",
"if",
"(",
"$",
"matches",
"[",
"3",
"]",
"&&",
"$",
"matches",
"[",
"3",
"]",
"==",
"'-'",
")",
"{",
"$",
"imaginary",
"=",
"'-'",
".",
"$",
"imaginary",
";",
"}",
"try",
"{",
"$",
"a",
"=",
"Rational",
"::",
"parse",
"(",
"$",
"real",
")",
";",
"$",
"realPart",
"=",
"$",
"a",
"->",
"p",
"/",
"$",
"a",
"->",
"q",
";",
"}",
"catch",
"(",
"SyntaxErrorException",
"$",
"e",
")",
"{",
"$",
"realPart",
"=",
"static",
"::",
"parseReal",
"(",
"$",
"real",
")",
";",
"}",
"try",
"{",
"$",
"b",
"=",
"Rational",
"::",
"parse",
"(",
"$",
"imaginary",
")",
";",
"$",
"imaginaryPart",
"=",
"$",
"b",
"->",
"p",
"/",
"$",
"b",
"->",
"q",
";",
"}",
"catch",
"(",
"SyntaxErrorException",
"$",
"e",
")",
"{",
"$",
"imaginaryPart",
"=",
"static",
"::",
"parseReal",
"(",
"$",
"imaginary",
")",
";",
"}",
"}",
"else",
"{",
"// That failed, try matching a rational number",
"try",
"{",
"$",
"a",
"=",
"Rational",
"::",
"parse",
"(",
"$",
"value",
")",
";",
"$",
"realPart",
"=",
"$",
"a",
"->",
"p",
"/",
"$",
"a",
"->",
"q",
";",
"$",
"imaginaryPart",
"=",
"0",
";",
"}",
"catch",
"(",
"SyntaxErrorException",
"$",
"e",
")",
"{",
"// Final attempt, try matching a real number",
"$",
"realPart",
"=",
"static",
"::",
"parseReal",
"(",
"$",
"value",
")",
";",
"$",
"imaginaryPart",
"=",
"0",
";",
"}",
"}",
"$",
"z",
"=",
"new",
"Complex",
"(",
"$",
"realPart",
",",
"$",
"imaginaryPart",
")",
";",
"return",
"$",
"z",
";",
"}"
] | convert data to a complex number, if possible
@param mixed $value (Complex, Rational, int, float and strings accepted)
@throws SyntaxErrorException if the string cannot be parsed
@retval Complex | [
"convert",
"data",
"to",
"a",
"complex",
"number",
"if",
"possible"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L149-L219 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.toFloat | private static function toFloat($x)
{
if (is_float($x)) return $x;
if (is_int($x)) return $x;
if (is_string($x)) {
$r = Rational::parse($x);
return $r->p/$r->q;
}
throw new SyntaxErrorException();
} | php | private static function toFloat($x)
{
if (is_float($x)) return $x;
if (is_int($x)) return $x;
if (is_string($x)) {
$r = Rational::parse($x);
return $r->p/$r->q;
}
throw new SyntaxErrorException();
} | [
"private",
"static",
"function",
"toFloat",
"(",
"$",
"x",
")",
"{",
"if",
"(",
"is_float",
"(",
"$",
"x",
")",
")",
"return",
"$",
"x",
";",
"if",
"(",
"is_int",
"(",
"$",
"x",
")",
")",
"return",
"$",
"x",
";",
"if",
"(",
"is_string",
"(",
"$",
"x",
")",
")",
"{",
"$",
"r",
"=",
"Rational",
"::",
"parse",
"(",
"$",
"x",
")",
";",
"return",
"$",
"r",
"->",
"p",
"/",
"$",
"r",
"->",
"q",
";",
"}",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}"
] | convert data to a floating point number, if possible
@param mixed $value (float, int, Rational)
@throws SyntaxErrorException if the string cannot be parsed
@retval float | [
"convert",
"data",
"to",
"a",
"floating",
"point",
"number",
"if",
"possible"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L229-L238 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.create | public static function create($real, $imag)
{
$x = static::toFloat($real);
$y = static::toFloat($imag);
return new Complex($x, $y);
} | php | public static function create($real, $imag)
{
$x = static::toFloat($real);
$y = static::toFloat($imag);
return new Complex($x, $y);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"real",
",",
"$",
"imag",
")",
"{",
"$",
"x",
"=",
"static",
"::",
"toFloat",
"(",
"$",
"real",
")",
";",
"$",
"y",
"=",
"static",
"::",
"toFloat",
"(",
"$",
"imag",
")",
";",
"return",
"new",
"Complex",
"(",
"$",
"x",
",",
"$",
"y",
")",
";",
"}"
] | create a complex number from its real and imaginary parts
@param mixed $real (float, int, Rational)
@param mixed $imag (float, int, Rational)
@throws SyntaxErrorException if the string cannot be parsed
@retval float | [
"create",
"a",
"complex",
"number",
"from",
"its",
"real",
"and",
"imaginary",
"parts"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L249-L255 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.add | public static function add($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
return static::create($z->x + $w->x, $z->y + $w->y);
} | php | public static function add($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
return static::create($z->x + $w->x, $z->y + $w->y);
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"z",
",",
"$",
"w",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"if",
"(",
"!",
"(",
"$",
"w",
"instanceof",
"Complex",
")",
")",
"$",
"w",
"=",
"static",
"::",
"parse",
"(",
"$",
"w",
")",
";",
"return",
"static",
"::",
"create",
"(",
"$",
"z",
"->",
"x",
"+",
"$",
"w",
"->",
"x",
",",
"$",
"z",
"->",
"y",
"+",
"$",
"w",
"->",
"y",
")",
";",
"}"
] | add two complex numbers
Complex::add($z, $w) computes and returns $z+$w
@param mixed $z (Complex, or parsable to Complex)
@param mixed $w (Complex, or parsable to Complex)
@retval Complex | [
"add",
"two",
"complex",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L268-L273 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.sub | public static function sub($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
return static::create($z->x - $w->x, $z->y - $w->y);
} | php | public static function sub($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
return static::create($z->x - $w->x, $z->y - $w->y);
} | [
"public",
"static",
"function",
"sub",
"(",
"$",
"z",
",",
"$",
"w",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"if",
"(",
"!",
"(",
"$",
"w",
"instanceof",
"Complex",
")",
")",
"$",
"w",
"=",
"static",
"::",
"parse",
"(",
"$",
"w",
")",
";",
"return",
"static",
"::",
"create",
"(",
"$",
"z",
"->",
"x",
"-",
"$",
"w",
"->",
"x",
",",
"$",
"z",
"->",
"y",
"-",
"$",
"w",
"->",
"y",
")",
";",
"}"
] | subtract two complex numbers
Complex::sub($z, $w) computes and returns $z-$w
@param mixed $z (Complex, or parsable to Complex)
@param mixed $w (Complex, or parsable to Complex)
@retval Complex | [
"subtract",
"two",
"complex",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L285-L290 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.mul | public static function mul($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
return static::create($z->x * $w->x - $z->y * $w->y, $z->x * $w->y + $z->y * $w->x);
} | php | public static function mul($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
return static::create($z->x * $w->x - $z->y * $w->y, $z->x * $w->y + $z->y * $w->x);
} | [
"public",
"static",
"function",
"mul",
"(",
"$",
"z",
",",
"$",
"w",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"if",
"(",
"!",
"(",
"$",
"w",
"instanceof",
"Complex",
")",
")",
"$",
"w",
"=",
"static",
"::",
"parse",
"(",
"$",
"w",
")",
";",
"return",
"static",
"::",
"create",
"(",
"$",
"z",
"->",
"x",
"*",
"$",
"w",
"->",
"x",
"-",
"$",
"z",
"->",
"y",
"*",
"$",
"w",
"->",
"y",
",",
"$",
"z",
"->",
"x",
"*",
"$",
"w",
"->",
"y",
"+",
"$",
"z",
"->",
"y",
"*",
"$",
"w",
"->",
"x",
")",
";",
"}"
] | multiply two complex numbers
Complex::mul($z, $w) computes and returns $z*$w
@param mixed $z (Complex, or parsable to Complex)
@param mixed $w (Complex, or parsable to Complex)
@retval Complex | [
"multiply",
"two",
"complex",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L302-L307 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.div | public static function div($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
$d = $w->x * $w->x + $w->y * $w->y;
if ($d == 0) throw new DivisionByZeroException();
return static::create(($z->x * $w->x + $z->y * $w->y)/$d, (-$z->x * $w->y + $z->y * $w->x)/$d);
} | php | public static function div($z, $w) {
if (!($z instanceof Complex)) $z = static::parse($z);
if (!($w instanceof Complex)) $w = static::parse($w);
$d = $w->x * $w->x + $w->y * $w->y;
if ($d == 0) throw new DivisionByZeroException();
return static::create(($z->x * $w->x + $z->y * $w->y)/$d, (-$z->x * $w->y + $z->y * $w->x)/$d);
} | [
"public",
"static",
"function",
"div",
"(",
"$",
"z",
",",
"$",
"w",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"if",
"(",
"!",
"(",
"$",
"w",
"instanceof",
"Complex",
")",
")",
"$",
"w",
"=",
"static",
"::",
"parse",
"(",
"$",
"w",
")",
";",
"$",
"d",
"=",
"$",
"w",
"->",
"x",
"*",
"$",
"w",
"->",
"x",
"+",
"$",
"w",
"->",
"y",
"*",
"$",
"w",
"->",
"y",
";",
"if",
"(",
"$",
"d",
"==",
"0",
")",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"return",
"static",
"::",
"create",
"(",
"(",
"$",
"z",
"->",
"x",
"*",
"$",
"w",
"->",
"x",
"+",
"$",
"z",
"->",
"y",
"*",
"$",
"w",
"->",
"y",
")",
"/",
"$",
"d",
",",
"(",
"-",
"$",
"z",
"->",
"x",
"*",
"$",
"w",
"->",
"y",
"+",
"$",
"z",
"->",
"y",
"*",
"$",
"w",
"->",
"x",
")",
"/",
"$",
"d",
")",
";",
"}"
] | divide two complex numbers
Complex::div($z, $w) computes and returns $z/$w
@param mixed $z (Complex, or parsable to Complex)
@param mixed $w (Complex, or parsable to Complex)
@retval Complex | [
"divide",
"two",
"complex",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L319-L328 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.pow | public static function pow($z, $w) {
// If exponent is an integer, compute the power using a square-and-multiply algorithm
if (is_int($w)) return static::powi($z, $w);
// Otherwise compute the principal branch: z^w = exp(wlog z)
return static::exp(static::mul($w, static::log($z)));
} | php | public static function pow($z, $w) {
// If exponent is an integer, compute the power using a square-and-multiply algorithm
if (is_int($w)) return static::powi($z, $w);
// Otherwise compute the principal branch: z^w = exp(wlog z)
return static::exp(static::mul($w, static::log($z)));
} | [
"public",
"static",
"function",
"pow",
"(",
"$",
"z",
",",
"$",
"w",
")",
"{",
"// If exponent is an integer, compute the power using a square-and-multiply algorithm",
"if",
"(",
"is_int",
"(",
"$",
"w",
")",
")",
"return",
"static",
"::",
"powi",
"(",
"$",
"z",
",",
"$",
"w",
")",
";",
"// Otherwise compute the principal branch: z^w = exp(wlog z)",
"return",
"static",
"::",
"exp",
"(",
"static",
"::",
"mul",
"(",
"$",
"w",
",",
"static",
"::",
"log",
"(",
"$",
"z",
")",
")",
")",
";",
"}"
] | powers of two complex numbers
Complex::pow($z, $w) computes and returns the principal value of $z^$w
@param mixed $z (Complex, or parsable to Complex)
@param mixed $w (Complex, or parsable to Complex)
@retval Complex | [
"powers",
"of",
"two",
"complex",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L340-L346 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.powi | private static function powi($z, $n) {
if ($n < 0) return static::div(1,static::powi($z, -$n));
if ($n == 0) return new Complex(1,0);
$y = new Complex(1,0);
while ($n > 1) {
if ($n % 2 == 0) {
$n = $n / 2;
} else {
$y = static::mul($z, $y);
$n = ($n-1)/2;
}
$z = static::mul($z, $z);
}
return static::mul($z, $y);
} | php | private static function powi($z, $n) {
if ($n < 0) return static::div(1,static::powi($z, -$n));
if ($n == 0) return new Complex(1,0);
$y = new Complex(1,0);
while ($n > 1) {
if ($n % 2 == 0) {
$n = $n / 2;
} else {
$y = static::mul($z, $y);
$n = ($n-1)/2;
}
$z = static::mul($z, $z);
}
return static::mul($z, $y);
} | [
"private",
"static",
"function",
"powi",
"(",
"$",
"z",
",",
"$",
"n",
")",
"{",
"if",
"(",
"$",
"n",
"<",
"0",
")",
"return",
"static",
"::",
"div",
"(",
"1",
",",
"static",
"::",
"powi",
"(",
"$",
"z",
",",
"-",
"$",
"n",
")",
")",
";",
"if",
"(",
"$",
"n",
"==",
"0",
")",
"return",
"new",
"Complex",
"(",
"1",
",",
"0",
")",
";",
"$",
"y",
"=",
"new",
"Complex",
"(",
"1",
",",
"0",
")",
";",
"while",
"(",
"$",
"n",
">",
"1",
")",
"{",
"if",
"(",
"$",
"n",
"%",
"2",
"==",
"0",
")",
"{",
"$",
"n",
"=",
"$",
"n",
"/",
"2",
";",
"}",
"else",
"{",
"$",
"y",
"=",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"y",
")",
";",
"$",
"n",
"=",
"(",
"$",
"n",
"-",
"1",
")",
"/",
"2",
";",
"}",
"$",
"z",
"=",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"z",
")",
";",
"}",
"return",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"y",
")",
";",
"}"
] | integer power of a complex number
Complex::powi($z, $n) computes and returns $z^$n where $n is an integer
@param mixed $z (Complex, or parsable to Complex)
@param int $n
@retval Complex | [
"integer",
"power",
"of",
"a",
"complex",
"number"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L358-L375 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.sin | public static function sin($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::create(sin($z->x)*cosh($z->y), cos($z->x)*sinh($z->y));
} | php | public static function sin($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::create(sin($z->x)*cosh($z->y), cos($z->x)*sinh($z->y));
} | [
"public",
"static",
"function",
"sin",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"return",
"static",
"::",
"create",
"(",
"sin",
"(",
"$",
"z",
"->",
"x",
")",
"*",
"cosh",
"(",
"$",
"z",
"->",
"y",
")",
",",
"cos",
"(",
"$",
"z",
"->",
"x",
")",
"*",
"sinh",
"(",
"$",
"z",
"->",
"y",
")",
")",
";",
"}"
] | complex sine function
Complex::sin($z) computes and returns sin($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"sine",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L388-L392 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.tan | public static function tan($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$d = cos($z->x)*cos($z->x) + sinh($z->y)*sinh($z->y);
return static::create(sin($z->x)*cos($z->x)/$d, sinh($z->y)*cosh($z->y)/$d);
} | php | public static function tan($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$d = cos($z->x)*cos($z->x) + sinh($z->y)*sinh($z->y);
return static::create(sin($z->x)*cos($z->x)/$d, sinh($z->y)*cosh($z->y)/$d);
} | [
"public",
"static",
"function",
"tan",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"d",
"=",
"cos",
"(",
"$",
"z",
"->",
"x",
")",
"*",
"cos",
"(",
"$",
"z",
"->",
"x",
")",
"+",
"sinh",
"(",
"$",
"z",
"->",
"y",
")",
"*",
"sinh",
"(",
"$",
"z",
"->",
"y",
")",
";",
"return",
"static",
"::",
"create",
"(",
"sin",
"(",
"$",
"z",
"->",
"x",
")",
"*",
"cos",
"(",
"$",
"z",
"->",
"x",
")",
"/",
"$",
"d",
",",
"sinh",
"(",
"$",
"z",
"->",
"y",
")",
"*",
"cosh",
"(",
"$",
"z",
"->",
"y",
")",
"/",
"$",
"d",
")",
";",
"}"
] | complex tangent function
Complex::tan($z) computes and returns tan($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"tangent",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L418-L423 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.arcsin | public static function arcsin($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$I = new Complex(0,1);
$iz = static::mul($z, $I); // iz
$temp = static::sqrt(static::sub(1, static::mul($z, $z))); // sqrt(1-z^2)
return static::div(static::log(static::add($iz, $temp)), $I);
} | php | public static function arcsin($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$I = new Complex(0,1);
$iz = static::mul($z, $I); // iz
$temp = static::sqrt(static::sub(1, static::mul($z, $z))); // sqrt(1-z^2)
return static::div(static::log(static::add($iz, $temp)), $I);
} | [
"public",
"static",
"function",
"arcsin",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"I",
"=",
"new",
"Complex",
"(",
"0",
",",
"1",
")",
";",
"$",
"iz",
"=",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"I",
")",
";",
"// iz",
"$",
"temp",
"=",
"static",
"::",
"sqrt",
"(",
"static",
"::",
"sub",
"(",
"1",
",",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"z",
")",
")",
")",
";",
"// sqrt(1-z^2)",
"return",
"static",
"::",
"div",
"(",
"static",
"::",
"log",
"(",
"static",
"::",
"add",
"(",
"$",
"iz",
",",
"$",
"temp",
")",
")",
",",
"$",
"I",
")",
";",
"}"
] | complex inverse sine function
Complex::arcsin($z) computes and returns the principal branch of arcsin($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"sine",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L450-L457 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.arccos | public static function arccos($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$I = new Complex(0,1);
$temp = static::mul(static::sqrt(static::sub(1, static::mul($z, $z))), $I);
return static::div(static::log(static::add($z, $temp)), $I);
} | php | public static function arccos($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$I = new Complex(0,1);
$temp = static::mul(static::sqrt(static::sub(1, static::mul($z, $z))), $I);
return static::div(static::log(static::add($z, $temp)), $I);
} | [
"public",
"static",
"function",
"arccos",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"I",
"=",
"new",
"Complex",
"(",
"0",
",",
"1",
")",
";",
"$",
"temp",
"=",
"static",
"::",
"mul",
"(",
"static",
"::",
"sqrt",
"(",
"static",
"::",
"sub",
"(",
"1",
",",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"z",
")",
")",
")",
",",
"$",
"I",
")",
";",
"return",
"static",
"::",
"div",
"(",
"static",
"::",
"log",
"(",
"static",
"::",
"add",
"(",
"$",
"z",
",",
"$",
"temp",
")",
")",
",",
"$",
"I",
")",
";",
"}"
] | complex inverse cosine function
Complex::arccos($z) computes and returns the principal branch of arccos($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"cosine",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L468-L474 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.arctan | public static function arctan($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$I = new Complex(0,1);
$iz = static::mul($z, $I);
$w = static::div( static::add(1, $iz), static::sub(1, $iz) );
$logw = static::log($w);
return static::div($logw, new Complex(0,2));
} | php | public static function arctan($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$I = new Complex(0,1);
$iz = static::mul($z, $I);
$w = static::div( static::add(1, $iz), static::sub(1, $iz) );
$logw = static::log($w);
return static::div($logw, new Complex(0,2));
} | [
"public",
"static",
"function",
"arctan",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"I",
"=",
"new",
"Complex",
"(",
"0",
",",
"1",
")",
";",
"$",
"iz",
"=",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"I",
")",
";",
"$",
"w",
"=",
"static",
"::",
"div",
"(",
"static",
"::",
"add",
"(",
"1",
",",
"$",
"iz",
")",
",",
"static",
"::",
"sub",
"(",
"1",
",",
"$",
"iz",
")",
")",
";",
"$",
"logw",
"=",
"static",
"::",
"log",
"(",
"$",
"w",
")",
";",
"return",
"static",
"::",
"div",
"(",
"$",
"logw",
",",
"new",
"Complex",
"(",
"0",
",",
"2",
")",
")",
";",
"}"
] | complex inverse tangent function
Complex::arctan($z) computes and returns the principal branch of arctan($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"tangent",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L485-L493 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.arccot | public static function arccot($z)
{
if (!($z instanceof Complex)) $z = static::parse($z);
return static::sub(M_PI/2, static::arctan($z));
} | php | public static function arccot($z)
{
if (!($z instanceof Complex)) $z = static::parse($z);
return static::sub(M_PI/2, static::arctan($z));
} | [
"public",
"static",
"function",
"arccot",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"return",
"static",
"::",
"sub",
"(",
"M_PI",
"/",
"2",
",",
"static",
"::",
"arctan",
"(",
"$",
"z",
")",
")",
";",
"}"
] | complex inverse cotangent function
Complex::arccot($z) computes and returns the principal branch of arccot($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"cotangent",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L504-L509 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.exp | public static function exp($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$r = exp($z->x);
return new Complex($r*cos($z->y), $r*sin($z->y));
} | php | public static function exp($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$r = exp($z->x);
return new Complex($r*cos($z->y), $r*sin($z->y));
} | [
"public",
"static",
"function",
"exp",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"r",
"=",
"exp",
"(",
"$",
"z",
"->",
"x",
")",
";",
"return",
"new",
"Complex",
"(",
"$",
"r",
"*",
"cos",
"(",
"$",
"z",
"->",
"y",
")",
",",
"$",
"r",
"*",
"sin",
"(",
"$",
"z",
"->",
"y",
")",
")",
";",
"}"
] | complex exponential function
Complex::exp($z) computes and returns exp($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"exponential",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L519-L524 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.log | public static function log($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$r = $z->abs();
$theta = $z->arg();
if ($r == 0) return new Complex(NAN, NAN);
return new Complex(log($r), $theta);
} | php | public static function log($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
$r = $z->abs();
$theta = $z->arg();
if ($r == 0) return new Complex(NAN, NAN);
return new Complex(log($r), $theta);
} | [
"public",
"static",
"function",
"log",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"r",
"=",
"$",
"z",
"->",
"abs",
"(",
")",
";",
"$",
"theta",
"=",
"$",
"z",
"->",
"arg",
"(",
")",
";",
"if",
"(",
"$",
"r",
"==",
"0",
")",
"return",
"new",
"Complex",
"(",
"NAN",
",",
"NAN",
")",
";",
"return",
"new",
"Complex",
"(",
"log",
"(",
"$",
"r",
")",
",",
"$",
"theta",
")",
";",
"}"
] | complex logarithm function
Complex::log($z) computes and returns the principal branch of log($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"logarithm",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L534-L543 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.arsinh | public static function arsinh($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::log(static::add($z, static::sqrt(static::add(1, static::mul($z, $z)))));
} | php | public static function arsinh($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::log(static::add($z, static::sqrt(static::add(1, static::mul($z, $z)))));
} | [
"public",
"static",
"function",
"arsinh",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"return",
"static",
"::",
"log",
"(",
"static",
"::",
"add",
"(",
"$",
"z",
",",
"static",
"::",
"sqrt",
"(",
"static",
"::",
"add",
"(",
"1",
",",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"z",
")",
")",
")",
")",
")",
";",
"}"
] | complex inverse hyperbolic sine function
Complex::arsinh($z) computes and returns the principal branch of arsinh($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"hyperbolic",
"sine",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L600-L604 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.arcosh | public static function arcosh($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::log(static::add($z, static::sqrt(static::add(-1, static::mul($z, $z)))));
} | php | public static function arcosh($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::log(static::add($z, static::sqrt(static::add(-1, static::mul($z, $z)))));
} | [
"public",
"static",
"function",
"arcosh",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"return",
"static",
"::",
"log",
"(",
"static",
"::",
"add",
"(",
"$",
"z",
",",
"static",
"::",
"sqrt",
"(",
"static",
"::",
"add",
"(",
"-",
"1",
",",
"static",
"::",
"mul",
"(",
"$",
"z",
",",
"$",
"z",
")",
")",
")",
")",
")",
";",
"}"
] | complex inverse hyperbolic cosine function
Complex::arcosh($z) computes and returns the principal branch of arcosh($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"hyperbolic",
"cosine",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L615-L619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.