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 |
|---|---|---|---|---|---|---|---|---|---|---|
mjphaynes/php-resque | src/Resque/Worker.php | Worker.toArray | public function toArray()
{
$packet = $this->getPacket();
return array(
'id' => (string)$this->id,
'hostname' => (string)$packet['hostname'],
'pid' => (int)$packet['pid'],
'queues' => array(
'selected' => (array)explode(',', $packet['queues']),
'resolved' => (array)$this->resolveQueues()
),
'shutdown' => (bool)$packet['shutdown'],
'blocking' => (bool)$packet['blocking'],
'status' => (int)$packet['status'],
'interval' => (int)$packet['interval'],
'timeout' => (int)$packet['timeout'],
'memory' => (int)$packet['memory'],
'memory_limit' => (int)$packet['memory_limit'] * 1024 * 1024,
'started' => (float)$packet['started'],
'processed' => (int)$packet['processed'],
'cancelled' => (int)$packet['cancelled'],
'failed' => (int)$packet['failed'],
'job_id' => (string)$packet['job_id'],
'job_pid' => (int)$packet['job_pid'],
'job_started' => (float)$packet['job_started'],
);
} | php | public function toArray()
{
$packet = $this->getPacket();
return array(
'id' => (string)$this->id,
'hostname' => (string)$packet['hostname'],
'pid' => (int)$packet['pid'],
'queues' => array(
'selected' => (array)explode(',', $packet['queues']),
'resolved' => (array)$this->resolveQueues()
),
'shutdown' => (bool)$packet['shutdown'],
'blocking' => (bool)$packet['blocking'],
'status' => (int)$packet['status'],
'interval' => (int)$packet['interval'],
'timeout' => (int)$packet['timeout'],
'memory' => (int)$packet['memory'],
'memory_limit' => (int)$packet['memory_limit'] * 1024 * 1024,
'started' => (float)$packet['started'],
'processed' => (int)$packet['processed'],
'cancelled' => (int)$packet['cancelled'],
'failed' => (int)$packet['failed'],
'job_id' => (string)$packet['job_id'],
'job_pid' => (int)$packet['job_pid'],
'job_started' => (float)$packet['job_started'],
);
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"packet",
"=",
"$",
"this",
"->",
"getPacket",
"(",
")",
";",
"return",
"array",
"(",
"'id'",
"=>",
"(",
"string",
")",
"$",
"this",
"->",
"id",
",",
"'hostname'",
"=>",
"(",
"string",
")",
"$",
... | Return array representation of this job
@return array | [
"Return",
"array",
"representation",
"of",
"this",
"job"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1215-L1245 |
mjphaynes/php-resque | src/Resque/Worker.php | Worker.updateProcLine | protected function updateProcLine($status)
{
$status = $this->getProcessTitle($status);
if (function_exists('cli_set_process_title') && PHP_OS !== 'Darwin') {
cli_set_process_title($status);
return;
}
if (function_exists('setproctitle')) {
setproctitle($status);
}
} | php | protected function updateProcLine($status)
{
$status = $this->getProcessTitle($status);
if (function_exists('cli_set_process_title') && PHP_OS !== 'Darwin') {
cli_set_process_title($status);
return;
}
if (function_exists('setproctitle')) {
setproctitle($status);
}
} | [
"protected",
"function",
"updateProcLine",
"(",
"$",
"status",
")",
"{",
"$",
"status",
"=",
"$",
"this",
"->",
"getProcessTitle",
"(",
"$",
"status",
")",
";",
"if",
"(",
"function_exists",
"(",
"'cli_set_process_title'",
")",
"&&",
"PHP_OS",
"!==",
"'Darwi... | On supported systems, update the name of the currently running process
to indicate the current state of a worker.
supported systems are
- PHP Version < 5.5.0 with the PECL proctitle module installed
- PHP Version >= 5.5.0 using built in method
@param string $status The updated process title. | [
"On",
"supported",
"systems",
"update",
"the",
"name",
"of",
"the",
"currently",
"running",
"process",
"to",
"indicate",
"the",
"current",
"state",
"of",
"a",
"worker",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1257-L1268 |
mjphaynes/php-resque | src/Resque/Worker.php | Worker.memoryExceeded | protected function memoryExceeded()
{
static $warning_percent = 0.5;
$percent = (memory_get_usage() / 1024 / 1024) / $this->memoryLimit;
if ($percent >= $warning_percent) {
$this->log(sprintf('Memory usage at %d%% (Max %s MB)', round($percent * 100, 1), $this->memoryLimit), Logger::DEBUG);
$warning_percent = ceil(($percent * 100) / 10) * 10 / 100;
}
return $percent > 0.999;
} | php | protected function memoryExceeded()
{
static $warning_percent = 0.5;
$percent = (memory_get_usage() / 1024 / 1024) / $this->memoryLimit;
if ($percent >= $warning_percent) {
$this->log(sprintf('Memory usage at %d%% (Max %s MB)', round($percent * 100, 1), $this->memoryLimit), Logger::DEBUG);
$warning_percent = ceil(($percent * 100) / 10) * 10 / 100;
}
return $percent > 0.999;
} | [
"protected",
"function",
"memoryExceeded",
"(",
")",
"{",
"static",
"$",
"warning_percent",
"=",
"0.5",
";",
"$",
"percent",
"=",
"(",
"memory_get_usage",
"(",
")",
"/",
"1024",
"/",
"1024",
")",
"/",
"$",
"this",
"->",
"memoryLimit",
";",
"if",
"(",
"... | Determine if the memory limit has been exceeded.
@return bool | [
"Determine",
"if",
"the",
"memory",
"limit",
"has",
"been",
"exceeded",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1286-L1298 |
mjphaynes/php-resque | src/Resque/Helpers/Stats.php | Stats.get | public static function get($stat, $key = Stats::DEFAULT_KEY)
{
return (int)Redis::instance()->hget($key, $stat);
} | php | public static function get($stat, $key = Stats::DEFAULT_KEY)
{
return (int)Redis::instance()->hget($key, $stat);
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"stat",
",",
"$",
"key",
"=",
"Stats",
"::",
"DEFAULT_KEY",
")",
"{",
"return",
"(",
"int",
")",
"Redis",
"::",
"instance",
"(",
")",
"->",
"hget",
"(",
"$",
"key",
",",
"$",
"stat",
")",
";",
"}"
... | Get the value of the supplied statistic counter for the specified statistic
@param string $stat The name of the statistic to get the stats for
@param string $key The stat key to use
@return mixed Value of the statistic. | [
"Get",
"the",
"value",
"of",
"the",
"supplied",
"statistic",
"counter",
"for",
"the",
"specified",
"statistic"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/Stats.php#L32-L35 |
mjphaynes/php-resque | src/Resque/Helpers/Stats.php | Stats.incr | public static function incr($stat, $by = 1, $key = Stats::DEFAULT_KEY)
{
return (bool)Redis::instance()->hincrby($key, $stat, $by);
} | php | public static function incr($stat, $by = 1, $key = Stats::DEFAULT_KEY)
{
return (bool)Redis::instance()->hincrby($key, $stat, $by);
} | [
"public",
"static",
"function",
"incr",
"(",
"$",
"stat",
",",
"$",
"by",
"=",
"1",
",",
"$",
"key",
"=",
"Stats",
"::",
"DEFAULT_KEY",
")",
"{",
"return",
"(",
"bool",
")",
"Redis",
"::",
"instance",
"(",
")",
"->",
"hincrby",
"(",
"$",
"key",
"... | Increment the value of the specified statistic by a certain amount (default is 1)
@param string $stat The name of the statistic to increment
@param int $by The amount to increment the statistic by
@param string $key The stat key to use
@return bool True if successful, false if not. | [
"Increment",
"the",
"value",
"of",
"the",
"specified",
"statistic",
"by",
"a",
"certain",
"amount",
"(",
"default",
"is",
"1",
")"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/Stats.php#L45-L48 |
mjphaynes/php-resque | src/Resque/Helpers/Stats.php | Stats.clear | public static function clear($stat, $key = Stats::DEFAULT_KEY)
{
return (bool)Redis::instance()->hdel($key, $stat);
} | php | public static function clear($stat, $key = Stats::DEFAULT_KEY)
{
return (bool)Redis::instance()->hdel($key, $stat);
} | [
"public",
"static",
"function",
"clear",
"(",
"$",
"stat",
",",
"$",
"key",
"=",
"Stats",
"::",
"DEFAULT_KEY",
")",
"{",
"return",
"(",
"bool",
")",
"Redis",
"::",
"instance",
"(",
")",
"->",
"hdel",
"(",
"$",
"key",
",",
"$",
"stat",
")",
";",
"... | Delete a statistic with the given name.
@param string $stat The name of the statistic to delete.
@param string $key The stat key to use
@return bool True if successful, false if not. | [
"Delete",
"a",
"statistic",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/Stats.php#L70-L73 |
mjphaynes/php-resque | src/Resque/Logger/Formatter/ConsoleFormatter.php | ConsoleFormatter.format | public function format(array $record)
{
$tag = strtolower($record['level_name']);
$record['start_tag'] = '<'.$tag.'>';
$record['end_tag'] = '</'.$tag.'>';
return parent::format($record);
} | php | public function format(array $record)
{
$tag = strtolower($record['level_name']);
$record['start_tag'] = '<'.$tag.'>';
$record['end_tag'] = '</'.$tag.'>';
return parent::format($record);
} | [
"public",
"function",
"format",
"(",
"array",
"$",
"record",
")",
"{",
"$",
"tag",
"=",
"strtolower",
"(",
"$",
"record",
"[",
"'level_name'",
"]",
")",
";",
"$",
"record",
"[",
"'start_tag'",
"]",
"=",
"'<'",
".",
"$",
"tag",
".",
"'>'",
";",
"$",... | {@inheritdoc} | [
"{"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Formatter/ConsoleFormatter.php#L28-L36 |
mjphaynes/php-resque | src/Resque/Logger/Handler/ConsoleHandler.php | ConsoleHandler.write | protected function write(array $record)
{
if (
null === $this->output or
OutputInterface::VERBOSITY_QUIET === ($verbosity = $this->output->getVerbosity()) or
$verbosity < $this->verbosityLevelMap[$record['level']]
) {
return false;
}
if ($record['level'] >= Logger::ERROR and $this->output instanceof ConsoleOutputInterface) {
$this->output->getErrorOutput()->write((string)$record['formatted']);
} else {
$this->output->write((string)$record['formatted']);
}
} | php | protected function write(array $record)
{
if (
null === $this->output or
OutputInterface::VERBOSITY_QUIET === ($verbosity = $this->output->getVerbosity()) or
$verbosity < $this->verbosityLevelMap[$record['level']]
) {
return false;
}
if ($record['level'] >= Logger::ERROR and $this->output instanceof ConsoleOutputInterface) {
$this->output->getErrorOutput()->write((string)$record['formatted']);
} else {
$this->output->write((string)$record['formatted']);
}
} | [
"protected",
"function",
"write",
"(",
"array",
"$",
"record",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"output",
"or",
"OutputInterface",
"::",
"VERBOSITY_QUIET",
"===",
"(",
"$",
"verbosity",
"=",
"$",
"this",
"->",
"output",
"->",
"getVe... | {@inheritdoc} | [
"{"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/ConsoleHandler.php#L111-L126 |
mjphaynes/php-resque | src/Resque/Logger/Handler/ConsoleHandler.php | ConsoleHandler.getDefaultFormatter | protected function getDefaultFormatter()
{
$formatter = new Logger\Formatter\ConsoleFormatter;
if (method_exists($formatter, 'allowInlineLineBreaks')) {
$formatter->allowInlineLineBreaks(true);
}
return $formatter;
} | php | protected function getDefaultFormatter()
{
$formatter = new Logger\Formatter\ConsoleFormatter;
if (method_exists($formatter, 'allowInlineLineBreaks')) {
$formatter->allowInlineLineBreaks(true);
}
return $formatter;
} | [
"protected",
"function",
"getDefaultFormatter",
"(",
")",
"{",
"$",
"formatter",
"=",
"new",
"Logger",
"\\",
"Formatter",
"\\",
"ConsoleFormatter",
";",
"if",
"(",
"method_exists",
"(",
"$",
"formatter",
",",
"'allowInlineLineBreaks'",
")",
")",
"{",
"$",
"for... | {@inheritdoc} | [
"{"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/ConsoleHandler.php#L131-L138 |
mjphaynes/php-resque | src/Resque/Logger/Handler/ConsoleHandler.php | ConsoleHandler.updateLevel | private function updateLevel()
{
if (null === $this->output or OutputInterface::VERBOSITY_QUIET === ($verbosity = $this->output->getVerbosity())) {
return false;
}
$this->setLevel(Logger::DEBUG);
return true;
} | php | private function updateLevel()
{
if (null === $this->output or OutputInterface::VERBOSITY_QUIET === ($verbosity = $this->output->getVerbosity())) {
return false;
}
$this->setLevel(Logger::DEBUG);
return true;
} | [
"private",
"function",
"updateLevel",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"output",
"or",
"OutputInterface",
"::",
"VERBOSITY_QUIET",
"===",
"(",
"$",
"verbosity",
"=",
"$",
"this",
"->",
"output",
"->",
"getVerbosity",
"(",
")",
... | Updates the logging level based on the verbosity setting of the console output.
@return bool Whether the handler is enabled and verbosity is not set to quiet. | [
"Updates",
"the",
"logging",
"level",
"based",
"on",
"the",
"verbosity",
"setting",
"of",
"the",
"console",
"output",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/ConsoleHandler.php#L145-L153 |
mjphaynes/php-resque | src/Resque/Logger/Handler/Connector/AbstractConnector.php | AbstractConnector.processor | public function processor(Command $command, InputInterface $input, OutputInterface $output, array $args)
{
return new StripFormatProcessor($command, $input, $output);
} | php | public function processor(Command $command, InputInterface $input, OutputInterface $output, array $args)
{
return new StripFormatProcessor($command, $input, $output);
} | [
"public",
"function",
"processor",
"(",
"Command",
"$",
"command",
",",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
",",
"array",
"$",
"args",
")",
"{",
"return",
"new",
"StripFormatProcessor",
"(",
"$",
"command",
",",
"$",
"input... | The default processor is the StripFormatProcessor which
removes all the console colour formatting from the string
@param Command $command
@param InputInterface $input
@param OutputInterface $output
@param array $args
@return StripProcessor | [
"The",
"default",
"processor",
"is",
"the",
"StripFormatProcessor",
"which",
"removes",
"all",
"the",
"console",
"colour",
"formatting",
"from",
"the",
"string"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/Connector/AbstractConnector.php#L38-L41 |
mjphaynes/php-resque | src/Resque/Logger/Handler/Connector/AbstractConnector.php | AbstractConnector.replacePlaceholders | public function replacePlaceholders($string)
{
$placeholders = array(
'%host%' => new Resque\Host,
'%worker%' => new Resque\Worker,
'%pid%' => getmypid(),
'%date%' => date('Y-m-d'),
'%time%' => date('H:i')
);
return strtr($string, $placeholders);
} | php | public function replacePlaceholders($string)
{
$placeholders = array(
'%host%' => new Resque\Host,
'%worker%' => new Resque\Worker,
'%pid%' => getmypid(),
'%date%' => date('Y-m-d'),
'%time%' => date('H:i')
);
return strtr($string, $placeholders);
} | [
"public",
"function",
"replacePlaceholders",
"(",
"$",
"string",
")",
"{",
"$",
"placeholders",
"=",
"array",
"(",
"'%host%'",
"=>",
"new",
"Resque",
"\\",
"Host",
",",
"'%worker%'",
"=>",
"new",
"Resque",
"\\",
"Worker",
",",
"'%pid%'",
"=>",
"getmypid",
... | Replaces all instances of [%host%, %worker%, %pid%, %date%, %time%]
in logger target key so can be unique log per worker
@param string $string Input string
@return string | [
"Replaces",
"all",
"instances",
"of",
"[",
"%host%",
"%worker%",
"%pid%",
"%date%",
"%time%",
"]",
"in",
"logger",
"target",
"key",
"so",
"can",
"be",
"unique",
"log",
"per",
"worker"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/Connector/AbstractConnector.php#L50-L61 |
mjphaynes/php-resque | src/Resque/Queue.php | Queue.redisKey | public static function redisKey($queue = null, $suffix = null)
{
if (is_null($queue)) {
return 'queues';
}
return (strpos($queue, 'queue:') !== 0 ? 'queue:' : '').$queue.($suffix ? ':'.$suffix : '');
} | php | public static function redisKey($queue = null, $suffix = null)
{
if (is_null($queue)) {
return 'queues';
}
return (strpos($queue, 'queue:') !== 0 ? 'queue:' : '').$queue.($suffix ? ':'.$suffix : '');
} | [
"public",
"static",
"function",
"redisKey",
"(",
"$",
"queue",
"=",
"null",
",",
"$",
"suffix",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"queue",
")",
")",
"{",
"return",
"'queues'",
";",
"}",
"return",
"(",
"strpos",
"(",
"$",
"queue... | Get the Queue key
@param Queue|null $queue the worker to get the key for
@param string|null $suffix to be appended to key
@return string | [
"Get",
"the",
"Queue",
"key"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Queue.php#L41-L48 |
mjphaynes/php-resque | src/Resque/Queue.php | Queue.push | public function push($job, array $data = null, $queue = null)
{
if (false !== ($delay = \Resque::getConfig('default.jobs.delay', false))) {
return $this->later($delay, $job, $data, $queue);
}
return Job::create($this->getQueue($queue), $job, $data);
} | php | public function push($job, array $data = null, $queue = null)
{
if (false !== ($delay = \Resque::getConfig('default.jobs.delay', false))) {
return $this->later($delay, $job, $data, $queue);
}
return Job::create($this->getQueue($queue), $job, $data);
} | [
"public",
"function",
"push",
"(",
"$",
"job",
",",
"array",
"$",
"data",
"=",
"null",
",",
"$",
"queue",
"=",
"null",
")",
"{",
"if",
"(",
"false",
"!==",
"(",
"$",
"delay",
"=",
"\\",
"Resque",
"::",
"getConfig",
"(",
"'default.jobs.delay'",
",",
... | Push a new job onto the queue
@param string $job The job class
@param mixed $data The job data
@param string $queue The queue to add the job to
@return Job job instance | [
"Push",
"a",
"new",
"job",
"onto",
"the",
"queue"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Queue.php#L81-L88 |
mjphaynes/php-resque | src/Resque/Queue.php | Queue.later | public function later($delay, $job, array $data = array(), $queue = null)
{
// If it's a datetime object conver to unix time
if ($delay instanceof \DateTime) {
$delay = $delay->getTimestamp();
}
if (!is_numeric($delay)) {
throw new \InvalidArgumentException('The delay "'.$delay.'" must be an integer or DateTime object.');
}
// If the delay is smaller than 3 years then assume that an interval
// has been passed i.e. 600 seconds, otherwise it's a unix timestamp
if ($delay < 94608000) {
$delay += time();
}
return Job::create($this->getQueue($queue), $job, $data, $delay);
} | php | public function later($delay, $job, array $data = array(), $queue = null)
{
// If it's a datetime object conver to unix time
if ($delay instanceof \DateTime) {
$delay = $delay->getTimestamp();
}
if (!is_numeric($delay)) {
throw new \InvalidArgumentException('The delay "'.$delay.'" must be an integer or DateTime object.');
}
// If the delay is smaller than 3 years then assume that an interval
// has been passed i.e. 600 seconds, otherwise it's a unix timestamp
if ($delay < 94608000) {
$delay += time();
}
return Job::create($this->getQueue($queue), $job, $data, $delay);
} | [
"public",
"function",
"later",
"(",
"$",
"delay",
",",
"$",
"job",
",",
"array",
"$",
"data",
"=",
"array",
"(",
")",
",",
"$",
"queue",
"=",
"null",
")",
"{",
"// If it's a datetime object conver to unix time",
"if",
"(",
"$",
"delay",
"instanceof",
"\\",... | Queue a job for later retrieval. Jobs are unique per queue and
are deleted upon retrieval. If a given job (payload) already exists,
it is updated with the new delay.
@param int $delay This can be number of seconds or unix timestamp
@param string $job The job class
@param mixed $data The job data
@param string $queue The queue to add the job to
@return Job job instance | [
"Queue",
"a",
"job",
"for",
"later",
"retrieval",
".",
"Jobs",
"are",
"unique",
"per",
"queue",
"and",
"are",
"deleted",
"upon",
"retrieval",
".",
"If",
"a",
"given",
"job",
"(",
"payload",
")",
"already",
"exists",
"it",
"is",
"updated",
"with",
"the",
... | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Queue.php#L101-L119 |
mjphaynes/php-resque | src/Resque/Queue.php | Queue.pop | public function pop(array $queues, $timeout = 10, $blocking = true)
{
$queue = $payload = null;
foreach ($queues as $key => $queue) {
$queues[$key] = self::redisKey($queue);
}
if ($blocking) {
list($queue, $payload) = $this->redis->blpop($queues, $timeout);
$queue = $this->redis->removeNamespace($queue);
} else {
foreach ($queues as $queue) {
if ($payload = $this->redis->lpop($queue)) {
break;
}
}
}
if (!$queue or !$payload) {
return false;
}
$queue = substr($queue, strlen('queue:'));
return Job::loadPayload($queue, $payload);
} | php | public function pop(array $queues, $timeout = 10, $blocking = true)
{
$queue = $payload = null;
foreach ($queues as $key => $queue) {
$queues[$key] = self::redisKey($queue);
}
if ($blocking) {
list($queue, $payload) = $this->redis->blpop($queues, $timeout);
$queue = $this->redis->removeNamespace($queue);
} else {
foreach ($queues as $queue) {
if ($payload = $this->redis->lpop($queue)) {
break;
}
}
}
if (!$queue or !$payload) {
return false;
}
$queue = substr($queue, strlen('queue:'));
return Job::loadPayload($queue, $payload);
} | [
"public",
"function",
"pop",
"(",
"array",
"$",
"queues",
",",
"$",
"timeout",
"=",
"10",
",",
"$",
"blocking",
"=",
"true",
")",
"{",
"$",
"queue",
"=",
"$",
"payload",
"=",
"null",
";",
"foreach",
"(",
"$",
"queues",
"as",
"$",
"key",
"=>",
"$"... | Pop the next job off of the queue.
@param array $queues Queues to watch for new jobs
@param int $timeout Timeout if blocking
@param bool $blocking Should Redis use blocking
@return Job|false | [
"Pop",
"the",
"next",
"job",
"off",
"of",
"the",
"queue",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Queue.php#L129-L155 |
mjphaynes/php-resque | src/Resque/Queue.php | Queue.size | public function size($queue)
{
return $this->redis->llen(self::redisKey($this->getQueue($queue)));
} | php | public function size($queue)
{
return $this->redis->llen(self::redisKey($this->getQueue($queue)));
} | [
"public",
"function",
"size",
"(",
"$",
"queue",
")",
"{",
"return",
"$",
"this",
"->",
"redis",
"->",
"llen",
"(",
"self",
"::",
"redisKey",
"(",
"$",
"this",
"->",
"getQueue",
"(",
"$",
"queue",
")",
")",
")",
";",
"}"
] | Return the size (number of pending jobs) of the specified queue.
@param string $queue name of the queue to be checked for pending jobs
@return int The size of the queue. | [
"Return",
"the",
"size",
"(",
"number",
"of",
"pending",
"jobs",
")",
"of",
"the",
"specified",
"queue",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Queue.php#L163-L166 |
mjphaynes/php-resque | src/Resque/Queue.php | Queue.sizeDelayed | public function sizeDelayed($queue)
{
return $this->redis->zcard(self::redisKey($this->getQueue($queue), 'delayed'));
} | php | public function sizeDelayed($queue)
{
return $this->redis->zcard(self::redisKey($this->getQueue($queue), 'delayed'));
} | [
"public",
"function",
"sizeDelayed",
"(",
"$",
"queue",
")",
"{",
"return",
"$",
"this",
"->",
"redis",
"->",
"zcard",
"(",
"self",
"::",
"redisKey",
"(",
"$",
"this",
"->",
"getQueue",
"(",
"$",
"queue",
")",
",",
"'delayed'",
")",
")",
";",
"}"
] | Return the size (number of delayed jobs) of the specified queue.
@param string $queue name of the queue to be checked for delayed jobs
@return int The size of the delayed queue. | [
"Return",
"the",
"size",
"(",
"number",
"of",
"delayed",
"jobs",
")",
"of",
"the",
"specified",
"queue",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Queue.php#L174-L177 |
mjphaynes/php-resque | src/Resque/Helpers/SerializableClosure.php | SerializableClosure.getCodeFromFile | protected function getCodeFromFile()
{
$file = $this->getFile();
$code = '';
// Next, we will just loop through the lines of the file until we get to the end
// of the Closure. Then, we will return the complete contents of this Closure
// so it can be serialized with these variables and stored for later usage.
while ($file->key() < $this->reflection->getEndLine()) {
$code .= $file->current();
$file->next();
}
preg_match('/function\s*\(/', $code, $matches, PREG_OFFSET_CAPTURE);
$begin = isset($matches[0][1]) ? $matches[0][1] : 0;
return substr($code, $begin, strrpos($code, '}') - $begin + 1);
} | php | protected function getCodeFromFile()
{
$file = $this->getFile();
$code = '';
// Next, we will just loop through the lines of the file until we get to the end
// of the Closure. Then, we will return the complete contents of this Closure
// so it can be serialized with these variables and stored for later usage.
while ($file->key() < $this->reflection->getEndLine()) {
$code .= $file->current();
$file->next();
}
preg_match('/function\s*\(/', $code, $matches, PREG_OFFSET_CAPTURE);
$begin = isset($matches[0][1]) ? $matches[0][1] : 0;
return substr($code, $begin, strrpos($code, '}') - $begin + 1);
} | [
"protected",
"function",
"getCodeFromFile",
"(",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getFile",
"(",
")",
";",
"$",
"code",
"=",
"''",
";",
"// Next, we will just loop through the lines of the file until we get to the end",
"// of the Closure. Then, we will ret... | Extract the code from the Closure's file.
@return string | [
"Extract",
"the",
"code",
"from",
"the",
"Closure",
"s",
"file",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/SerializableClosure.php#L76-L94 |
mjphaynes/php-resque | src/Resque/Helpers/SerializableClosure.php | SerializableClosure.getFile | protected function getFile()
{
$file = new SplFileObject($this->reflection->getFileName());
$file->seek($this->reflection->getStartLine() - 1);
return $file;
} | php | protected function getFile()
{
$file = new SplFileObject($this->reflection->getFileName());
$file->seek($this->reflection->getStartLine() - 1);
return $file;
} | [
"protected",
"function",
"getFile",
"(",
")",
"{",
"$",
"file",
"=",
"new",
"SplFileObject",
"(",
"$",
"this",
"->",
"reflection",
"->",
"getFileName",
"(",
")",
")",
";",
"$",
"file",
"->",
"seek",
"(",
"$",
"this",
"->",
"reflection",
"->",
"getStart... | Get an SplObjectFile object at the starting line of the Closure.
@return \SplFileObject | [
"Get",
"an",
"SplObjectFile",
"object",
"at",
"the",
"starting",
"line",
"of",
"the",
"Closure",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/SerializableClosure.php#L101-L108 |
mjphaynes/php-resque | src/Resque/Helpers/SerializableClosure.php | SerializableClosure.getVariables | public function getVariables()
{
if (!$this->getUseIndex()) {
return array();
}
$staticVariables = $this->reflection->getStaticVariables();
// When looping through the variables, we will only take the variables that are
// specified in the use clause, and will not take any other static variables
// that may be used by the Closures, allowing this to re-create its state.
$usedVariables = array();
foreach ($this->getUseClauseVariables() as $variable) {
$variable = trim($variable, ' $&');
$usedVariables[$variable] = $staticVariables[$variable];
}
return $usedVariables;
} | php | public function getVariables()
{
if (!$this->getUseIndex()) {
return array();
}
$staticVariables = $this->reflection->getStaticVariables();
// When looping through the variables, we will only take the variables that are
// specified in the use clause, and will not take any other static variables
// that may be used by the Closures, allowing this to re-create its state.
$usedVariables = array();
foreach ($this->getUseClauseVariables() as $variable) {
$variable = trim($variable, ' $&');
$usedVariables[$variable] = $staticVariables[$variable];
}
return $usedVariables;
} | [
"public",
"function",
"getVariables",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getUseIndex",
"(",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"$",
"staticVariables",
"=",
"$",
"this",
"->",
"reflection",
"->",
"getStaticVariables",
... | Get the variables used by the Closure.
@return array | [
"Get",
"the",
"variables",
"used",
"by",
"the",
"Closure",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/SerializableClosure.php#L115-L135 |
mjphaynes/php-resque | src/Resque/Helpers/SerializableClosure.php | SerializableClosure.getUseClauseVariables | protected function getUseClauseVariables()
{
$begin = strpos($code = $this->getCode(), '(', $this->getUseIndex()) + 1;
return explode(',', substr($code, $begin, strpos($code, ')', $begin) - $begin));
} | php | protected function getUseClauseVariables()
{
$begin = strpos($code = $this->getCode(), '(', $this->getUseIndex()) + 1;
return explode(',', substr($code, $begin, strpos($code, ')', $begin) - $begin));
} | [
"protected",
"function",
"getUseClauseVariables",
"(",
")",
"{",
"$",
"begin",
"=",
"strpos",
"(",
"$",
"code",
"=",
"$",
"this",
"->",
"getCode",
"(",
")",
",",
"'('",
",",
"$",
"this",
"->",
"getUseIndex",
"(",
")",
")",
"+",
"1",
";",
"return",
... | Get the variables from the "use" clause.
@return array | [
"Get",
"the",
"variables",
"from",
"the",
"use",
"clause",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/SerializableClosure.php#L142-L147 |
mjphaynes/php-resque | src/Resque/Helpers/SerializableClosure.php | SerializableClosure.unserialize | public function unserialize($serialized)
{
$payload = unserialize($serialized);
// We will extract the variables into the current scope so that as the Closure
// is built it will inherit the scope it had before it was serialized which
// will emulate the Closures existing in that scope instead of right now.
extract($payload['variables']);
eval('$this->closure = '.$payload['code'].';');
$this->reflection = new ReflectionFunction($this->closure);
} | php | public function unserialize($serialized)
{
$payload = unserialize($serialized);
// We will extract the variables into the current scope so that as the Closure
// is built it will inherit the scope it had before it was serialized which
// will emulate the Closures existing in that scope instead of right now.
extract($payload['variables']);
eval('$this->closure = '.$payload['code'].';');
$this->reflection = new ReflectionFunction($this->closure);
} | [
"public",
"function",
"unserialize",
"(",
"$",
"serialized",
")",
"{",
"$",
"payload",
"=",
"unserialize",
"(",
"$",
"serialized",
")",
";",
"// We will extract the variables into the current scope so that as the Closure",
"// is built it will inherit the scope it had before it w... | Unserialize the Closure instance.
@param string $serialized
@return void | [
"Unserialize",
"the",
"Closure",
"instance",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/SerializableClosure.php#L177-L189 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.start | public function start()
{
if (false === ($this->socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname($this->config['protocol'])))) {
throw new Exception(sprintf('socket_create(AF_INET, SOCK_STREAM, <%s>) failed: [%d] %s',
$this->config['protocol'], $code = socket_last_error(), socket_strerror($code)));
}
if (false === @socket_bind($this->socket, $this->config['ip'], $this->config['port'])) {
throw new Exception(sprintf('socket_bind($socket, "%s", %d) failed: [%d] %s',
$this->config['ip'], $this->config['port'], $code = socket_last_error(), socket_strerror($code)));
}
if (false === @socket_getsockname($this->socket, $this->config['ip'], $this->config['port'])) {
throw new Exception(sprintf('socket_getsockname($socket, "%s", %d) failed: [%d] %s',
$this->config['ip'], $this->config['port'], $code = socket_last_error(), socket_strerror($code)));
}
if (false === @socket_listen($this->socket)) {
throw new Exception(sprintf('socket_listen($socket) failed: [%d] %s', $code = socket_last_error(), socket_strerror($code)));
}
$this->started = true;
$this->log('Listening for connections on <pop>'.$this.'</pop>', Logger::INFO);
} | php | public function start()
{
if (false === ($this->socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname($this->config['protocol'])))) {
throw new Exception(sprintf('socket_create(AF_INET, SOCK_STREAM, <%s>) failed: [%d] %s',
$this->config['protocol'], $code = socket_last_error(), socket_strerror($code)));
}
if (false === @socket_bind($this->socket, $this->config['ip'], $this->config['port'])) {
throw new Exception(sprintf('socket_bind($socket, "%s", %d) failed: [%d] %s',
$this->config['ip'], $this->config['port'], $code = socket_last_error(), socket_strerror($code)));
}
if (false === @socket_getsockname($this->socket, $this->config['ip'], $this->config['port'])) {
throw new Exception(sprintf('socket_getsockname($socket, "%s", %d) failed: [%d] %s',
$this->config['ip'], $this->config['port'], $code = socket_last_error(), socket_strerror($code)));
}
if (false === @socket_listen($this->socket)) {
throw new Exception(sprintf('socket_listen($socket) failed: [%d] %s', $code = socket_last_error(), socket_strerror($code)));
}
$this->started = true;
$this->log('Listening for connections on <pop>'.$this.'</pop>', Logger::INFO);
} | [
"public",
"function",
"start",
"(",
")",
"{",
"if",
"(",
"false",
"===",
"(",
"$",
"this",
"->",
"socket",
"=",
"@",
"socket_create",
"(",
"AF_INET",
",",
"SOCK_STREAM",
",",
"getprotobyname",
"(",
"$",
"this",
"->",
"config",
"[",
"'protocol'",
"]",
"... | Starts the server | [
"Starts",
"the",
"server"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L136-L160 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.close | public function close()
{
foreach ($this->clients as &$client) {
$this->disconnect($client, 'Receiver shutting down... Goodbye.');
}
socket_close($this->socket);
} | php | public function close()
{
foreach ($this->clients as &$client) {
$this->disconnect($client, 'Receiver shutting down... Goodbye.');
}
socket_close($this->socket);
} | [
"public",
"function",
"close",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"clients",
"as",
"&",
"$",
"client",
")",
"{",
"$",
"this",
"->",
"disconnect",
"(",
"$",
"client",
",",
"'Receiver shutting down... Goodbye.'",
")",
";",
"}",
"socket_close",... | Closes the socket on shutdown | [
"Closes",
"the",
"socket",
"on",
"shutdown"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L173-L180 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.run | public function run()
{
if (!$this->started) {
$this->start();
}
if (function_exists('pcntl_signal')) {
// PHP 7.1 allows async signals
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 1);
}
pcntl_signal(SIGTERM, array($this, 'shutdown'));
pcntl_signal(SIGINT, array($this, 'shutdown'));
pcntl_signal(SIGQUIT, array($this, 'shutdown'));
}
register_shutdown_function(array($this, 'close'));
while (true) {
if ($this->shutdown) {
$this->log('Shutting down listener on <pop>'.$this.'</pop>', Logger::INFO);
break;
}
$read = array($this->socket);
foreach ($this->clients as &$client) {
$read[] = $client->getSocket();
}
// Set up a blocking call to socket_select
$write = $except = null;
if (($changed_sockets = @socket_select($read, $write, $except, $this->tv_sec)) < 1) {
// $this->log('Waiting for socket update', self::LOG_VERBOSE);
continue;
}
// Handle new Connections
if (in_array($this->socket, $read)) {
if (count($this->clients) >= $this->max_clients) {
$this->log('New client trying to connect but maximum <pop>'.$this->max_clients.'</pop> clients already connected', Logger::INFO);
$client = new Client($this->socket);
$this->send($client, '{"ok":0,"message":"Could not connect, hit max number of connections"}');
$client->disconnect();
continue;
} else {
$this->clients[] = $client = new Client($this->socket);
$this->log('New client connected: <pop>'.$client.'</pop>', Logger::INFO);
$this->fire(self::CLIENT_CONNECT, $client);
}
}
// Handle input for each client
foreach ($this->clients as $i => $client) {
if (in_array($client->getSocket(), $read)) {
$data = @socket_read($client->getSocket(), $this->max_read);
if ($data === false) {
$this->disconnect($client);
continue;
}
// Remove any control characters
$data = preg_replace('/[\x00-\x1F\x7F]/', '', trim($data));
if (empty($data)) {
// Send a null byte to flush
$this->send($client, "\0");
} else {
$this->log(sprintf('Received "<comment>%s</comment>" from <pop>%s</pop>', $data, $client), Logger::INFO);
$this->fire(self::CLIENT_RECEIVE, $client, $data);
}
}
}
}
} | php | public function run()
{
if (!$this->started) {
$this->start();
}
if (function_exists('pcntl_signal')) {
// PHP 7.1 allows async signals
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
} else {
declare(ticks = 1);
}
pcntl_signal(SIGTERM, array($this, 'shutdown'));
pcntl_signal(SIGINT, array($this, 'shutdown'));
pcntl_signal(SIGQUIT, array($this, 'shutdown'));
}
register_shutdown_function(array($this, 'close'));
while (true) {
if ($this->shutdown) {
$this->log('Shutting down listener on <pop>'.$this.'</pop>', Logger::INFO);
break;
}
$read = array($this->socket);
foreach ($this->clients as &$client) {
$read[] = $client->getSocket();
}
// Set up a blocking call to socket_select
$write = $except = null;
if (($changed_sockets = @socket_select($read, $write, $except, $this->tv_sec)) < 1) {
// $this->log('Waiting for socket update', self::LOG_VERBOSE);
continue;
}
// Handle new Connections
if (in_array($this->socket, $read)) {
if (count($this->clients) >= $this->max_clients) {
$this->log('New client trying to connect but maximum <pop>'.$this->max_clients.'</pop> clients already connected', Logger::INFO);
$client = new Client($this->socket);
$this->send($client, '{"ok":0,"message":"Could not connect, hit max number of connections"}');
$client->disconnect();
continue;
} else {
$this->clients[] = $client = new Client($this->socket);
$this->log('New client connected: <pop>'.$client.'</pop>', Logger::INFO);
$this->fire(self::CLIENT_CONNECT, $client);
}
}
// Handle input for each client
foreach ($this->clients as $i => $client) {
if (in_array($client->getSocket(), $read)) {
$data = @socket_read($client->getSocket(), $this->max_read);
if ($data === false) {
$this->disconnect($client);
continue;
}
// Remove any control characters
$data = preg_replace('/[\x00-\x1F\x7F]/', '', trim($data));
if (empty($data)) {
// Send a null byte to flush
$this->send($client, "\0");
} else {
$this->log(sprintf('Received "<comment>%s</comment>" from <pop>%s</pop>', $data, $client), Logger::INFO);
$this->fire(self::CLIENT_RECEIVE, $client, $data);
}
}
}
}
} | [
"public",
"function",
"run",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"started",
")",
"{",
"$",
"this",
"->",
"start",
"(",
")",
";",
"}",
"if",
"(",
"function_exists",
"(",
"'pcntl_signal'",
")",
")",
"{",
"// PHP 7.1 allows async signals",
"... | Runs the server code until the server is shut down. | [
"Runs",
"the",
"server",
"code",
"until",
"the",
"server",
"is",
"shut",
"down",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L185-L264 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.send | public function send(&$client, $message, $end = true)
{
$this->log('Messaging client <pop>'.$client.'</pop> with "<comment>'.str_replace("\n", '\n', $message).'</comment>"');
$end and $message = "$message\n";
$length = strlen($message);
$sent = 0;
while (true) {
$attempt = @socket_write($client->getSocket(), $message, $length);
if ($attempt === false) {
return false;
}
$sent += $attempt;
if ($attempt < $length) {
$message = substr($message, $attempt);
$length -= $attempt;
} else {
return $attempt;
}
}
return false;
} | php | public function send(&$client, $message, $end = true)
{
$this->log('Messaging client <pop>'.$client.'</pop> with "<comment>'.str_replace("\n", '\n', $message).'</comment>"');
$end and $message = "$message\n";
$length = strlen($message);
$sent = 0;
while (true) {
$attempt = @socket_write($client->getSocket(), $message, $length);
if ($attempt === false) {
return false;
}
$sent += $attempt;
if ($attempt < $length) {
$message = substr($message, $attempt);
$length -= $attempt;
} else {
return $attempt;
}
}
return false;
} | [
"public",
"function",
"send",
"(",
"&",
"$",
"client",
",",
"$",
"message",
",",
"$",
"end",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"log",
"(",
"'Messaging client <pop>'",
".",
"$",
"client",
".",
"'</pop> with \"<comment>'",
".",
"str_replace",
"(",
... | Writes data to the socket, including the length of the data, and ends it with a CRLF unless specified.
It is perfectly valid for socket_write to return zero which means no bytes have been written.
Be sure to use the === operator to check for FALSE in case of an error.
@param Client $client Connected client to write to
@param string $message Data to write to the socket.
@param string $end Data to end the line with. Specify false if you don't want a line end sent.
@return mixed Returns the number of bytes successfully written to the socket or FALSE on failure.
The error code can be retrieved with socket_last_error(). This code may be passed to
socket_strerror() to get a textual explanation of the error. | [
"Writes",
"data",
"to",
"the",
"socket",
"including",
"the",
"length",
"of",
"the",
"data",
"and",
"ends",
"it",
"with",
"a",
"CRLF",
"unless",
"specified",
".",
"It",
"is",
"perfectly",
"valid",
"for",
"socket_write",
"to",
"return",
"zero",
"which",
"mea... | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L278-L304 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.disconnect | public function disconnect(Client $client, $message = 'Goodbye.')
{
$this->fire(self::CLIENT_DISCONNECT, $client, $message);
$this->log('Client disconnected: <pop>'.$client.'</pop>', Logger::INFO);
$client->disconnect();
$i = array_search($client, $this->clients);
unset($this->clients[$i]);
} | php | public function disconnect(Client $client, $message = 'Goodbye.')
{
$this->fire(self::CLIENT_DISCONNECT, $client, $message);
$this->log('Client disconnected: <pop>'.$client.'</pop>', Logger::INFO);
$client->disconnect();
$i = array_search($client, $this->clients);
unset($this->clients[$i]);
} | [
"public",
"function",
"disconnect",
"(",
"Client",
"$",
"client",
",",
"$",
"message",
"=",
"'Goodbye.'",
")",
"{",
"$",
"this",
"->",
"fire",
"(",
"self",
"::",
"CLIENT_DISCONNECT",
",",
"$",
"client",
",",
"$",
"message",
")",
";",
"$",
"this",
"->",... | Disconnect a client
@param Client $client The client to disconnect
@param string $message Data to write to the socket.
@return mixed | [
"Disconnect",
"a",
"client"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L313-L323 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.fire | public function fire($event, &$client, $data = null)
{
$retval = true;
if (!array_key_exists($event, $this->events)) {
return;
}
foreach ($this->events[$event] as $callback) {
if (!is_callable($callback)) {
continue;
}
if (($retval = call_user_func($callback, $this, $client, $data)) === false) {
break;
}
}
return $retval !== false;
} | php | public function fire($event, &$client, $data = null)
{
$retval = true;
if (!array_key_exists($event, $this->events)) {
return;
}
foreach ($this->events[$event] as $callback) {
if (!is_callable($callback)) {
continue;
}
if (($retval = call_user_func($callback, $this, $client, $data)) === false) {
break;
}
}
return $retval !== false;
} | [
"public",
"function",
"fire",
"(",
"$",
"event",
",",
"&",
"$",
"client",
",",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"retval",
"=",
"true",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"event",
",",
"$",
"this",
"->",
"events",
")",
")",... | Raise a given event with the supplied data.
@param string $event Name of event to be raised.
@param Client $client Connected client
@param mixed $data Optional, any data that should be passed to each callback.
@return true | [
"Raise",
"a",
"given",
"event",
"with",
"the",
"supplied",
"data",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L406-L425 |
mjphaynes/php-resque | src/Resque/Socket/Server.php | Server.fwrite | public static function fwrite($fh, $string)
{
for ($written = 0; $written < strlen($string); $written += $fwrite) {
if (($fwrite = fwrite($fh, substr($string, $written))) === false) {
return $written;
}
}
return $written;
} | php | public static function fwrite($fh, $string)
{
for ($written = 0; $written < strlen($string); $written += $fwrite) {
if (($fwrite = fwrite($fh, substr($string, $written))) === false) {
return $written;
}
}
return $written;
} | [
"public",
"static",
"function",
"fwrite",
"(",
"$",
"fh",
",",
"$",
"string",
")",
"{",
"for",
"(",
"$",
"written",
"=",
"0",
";",
"$",
"written",
"<",
"strlen",
"(",
"$",
"string",
")",
";",
"$",
"written",
"+=",
"$",
"fwrite",
")",
"{",
"if",
... | Write a string to a resource
@param resource $fh The resource to write to
@param string $string The string to write | [
"Write",
"a",
"string",
"to",
"a",
"resource"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Server.php#L441-L450 |
mjphaynes/php-resque | src/Resque/Logger/Handler/Connector.php | Connector.resolve | public function resolve($logFormat)
{
// Loop over connectionMap and see if the log format matches any of them
foreach ($this->connectionMap as $connection => $match) {
// Because the last connection stream is an effective catch all i.e. just specifying a
// path to a file, lets make sure the user wasn't trying to use another handler but got
// the format wrong. If they did then show them the correct format
if ($connection == 'Stream' and stripos($logFormat, 'stream') !== 0) {
$pattern = '~^(?P<handler>'.implode('|', array_keys($this->connectionMap)).')(.*)$~i';
if ($possible = $this->matches($pattern, $logFormat)) {
// Map to correct key case
$handler = str_replace(
array_map('strtolower', array_keys($this->connectionMap)),
array_keys($this->connectionMap),
strtolower($possible['handler'])
);
// Tell them the error of their ways
$format = str_replace(array('(?:', ')?', '\)'), '', $this->connectionMap[$handler]);
$cb = function ($m) {
return ($m[1] == 'ignore') ? '' : '<'.$m[1].'>';
};
$format = preg_replace_callback('/\(\?P<([a-z_]+)>(?:.+?)\)/', $cb, $format);
throw new \InvalidArgumentException('Invalid format "'.$logFormat.'" for "'.$handler.'" handler. Should be of format "'.$format.'"');
}
}
if ($args = $this->matches('~^'.$match.'$~i', $logFormat)) {
$connectorClass = new \ReflectionClass('Resque\Logger\Handler\Connector\\'.$connection.'Connector');
$connectorClass = $connectorClass->newInstance();
$handler = $connectorClass->resolve($this->command, $this->input, $this->output, $args);
$handler->pushProcessor($connectorClass->processor($this->command, $this->input, $this->output, $args));
return $handler;
}
}
throw new \InvalidArgumentException('Log format "'.$logFormat.'" is invalid');
} | php | public function resolve($logFormat)
{
// Loop over connectionMap and see if the log format matches any of them
foreach ($this->connectionMap as $connection => $match) {
// Because the last connection stream is an effective catch all i.e. just specifying a
// path to a file, lets make sure the user wasn't trying to use another handler but got
// the format wrong. If they did then show them the correct format
if ($connection == 'Stream' and stripos($logFormat, 'stream') !== 0) {
$pattern = '~^(?P<handler>'.implode('|', array_keys($this->connectionMap)).')(.*)$~i';
if ($possible = $this->matches($pattern, $logFormat)) {
// Map to correct key case
$handler = str_replace(
array_map('strtolower', array_keys($this->connectionMap)),
array_keys($this->connectionMap),
strtolower($possible['handler'])
);
// Tell them the error of their ways
$format = str_replace(array('(?:', ')?', '\)'), '', $this->connectionMap[$handler]);
$cb = function ($m) {
return ($m[1] == 'ignore') ? '' : '<'.$m[1].'>';
};
$format = preg_replace_callback('/\(\?P<([a-z_]+)>(?:.+?)\)/', $cb, $format);
throw new \InvalidArgumentException('Invalid format "'.$logFormat.'" for "'.$handler.'" handler. Should be of format "'.$format.'"');
}
}
if ($args = $this->matches('~^'.$match.'$~i', $logFormat)) {
$connectorClass = new \ReflectionClass('Resque\Logger\Handler\Connector\\'.$connection.'Connector');
$connectorClass = $connectorClass->newInstance();
$handler = $connectorClass->resolve($this->command, $this->input, $this->output, $args);
$handler->pushProcessor($connectorClass->processor($this->command, $this->input, $this->output, $args));
return $handler;
}
}
throw new \InvalidArgumentException('Log format "'.$logFormat.'" is invalid');
} | [
"public",
"function",
"resolve",
"(",
"$",
"logFormat",
")",
"{",
"// Loop over connectionMap and see if the log format matches any of them",
"foreach",
"(",
"$",
"this",
"->",
"connectionMap",
"as",
"$",
"connection",
"=>",
"$",
"match",
")",
"{",
"// Because the last ... | Resolves a Monolog handler from string input
@param mixed $logFormat
@throws InvalidArgumentException
@return Monolog\Handler\HandlerInterface | [
"Resolves",
"a",
"Monolog",
"handler",
"from",
"string",
"input"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/Connector.php#L78-L120 |
mjphaynes/php-resque | src/Resque/Logger/Handler/Connector.php | Connector.matches | private function matches($pattern, $subject)
{
if (preg_match($pattern, $subject, $matches)) {
$args = array();
foreach ($matches as $key => $value) {
if (!is_int($key)) {
$args[$key] = $value;
}
}
return $args;
}
return false;
} | php | private function matches($pattern, $subject)
{
if (preg_match($pattern, $subject, $matches)) {
$args = array();
foreach ($matches as $key => $value) {
if (!is_int($key)) {
$args[$key] = $value;
}
}
return $args;
}
return false;
} | [
"private",
"function",
"matches",
"(",
"$",
"pattern",
",",
"$",
"subject",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"subject",
",",
"$",
"matches",
")",
")",
"{",
"$",
"args",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
... | Performs a pattern match on a string and returns just
the named matches or false if no match
@param mixed $pattern
@param mixed $subject
@return array|false | [
"Performs",
"a",
"pattern",
"match",
"on",
"a",
"string",
"and",
"returns",
"just",
"the",
"named",
"matches",
"or",
"false",
"if",
"no",
"match"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger/Handler/Connector.php#L130-L145 |
mjphaynes/php-resque | src/Resque/Redis.php | Redis.addNamespace | public function addNamespace($string)
{
if (is_array($string)) {
foreach ($string as &$str) {
$str = $this->addNamespace($str);
}
return $string;
}
if (strpos($string, $this->namespace) !== 0) {
$string = $this->namespace . $string;
}
return $string;
} | php | public function addNamespace($string)
{
if (is_array($string)) {
foreach ($string as &$str) {
$str = $this->addNamespace($str);
}
return $string;
}
if (strpos($string, $this->namespace) !== 0) {
$string = $this->namespace . $string;
}
return $string;
} | [
"public",
"function",
"addNamespace",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"string",
")",
")",
"{",
"foreach",
"(",
"$",
"string",
"as",
"&",
"$",
"str",
")",
"{",
"$",
"str",
"=",
"$",
"this",
"->",
"addNamespace",
"(",
... | Add Redis namespace to a string
@param string $string String to namespace
@return string | [
"Add",
"Redis",
"namespace",
"to",
"a",
"string"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Redis.php#L292-L307 |
mjphaynes/php-resque | src/Resque/Redis.php | Redis.removeNamespace | public function removeNamespace($string)
{
$prefix = $this->namespace;
if (substr($string, 0, strlen($prefix)) == $prefix) {
$string = substr($string, strlen($prefix), strlen($string));
}
return $string;
} | php | public function removeNamespace($string)
{
$prefix = $this->namespace;
if (substr($string, 0, strlen($prefix)) == $prefix) {
$string = substr($string, strlen($prefix), strlen($string));
}
return $string;
} | [
"public",
"function",
"removeNamespace",
"(",
"$",
"string",
")",
"{",
"$",
"prefix",
"=",
"$",
"this",
"->",
"namespace",
";",
"if",
"(",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"strlen",
"(",
"$",
"prefix",
")",
")",
"==",
"$",
"prefix",
")"... | Remove Redis namespace from string
@param string $string String to de-namespace
@return string | [
"Remove",
"Redis",
"namespace",
"from",
"string"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Redis.php#L315-L324 |
mjphaynes/php-resque | src/Resque/Event.php | Event.listen | public static function listen($event, $callback)
{
if (is_array($event)) {
foreach ($event as $e) {
self::listen($e, $callback);
}
return;
}
if ($event !== '*' and !self::eventName($event)) {
throw new \InvalidArgumentException('Event "'.$event.'" is not a valid event');
}
if (!isset(self::$events[$event])) {
self::$events[$event] = array();
}
self::$events[$event][] = $callback;
} | php | public static function listen($event, $callback)
{
if (is_array($event)) {
foreach ($event as $e) {
self::listen($e, $callback);
}
return;
}
if ($event !== '*' and !self::eventName($event)) {
throw new \InvalidArgumentException('Event "'.$event.'" is not a valid event');
}
if (!isset(self::$events[$event])) {
self::$events[$event] = array();
}
self::$events[$event][] = $callback;
} | [
"public",
"static",
"function",
"listen",
"(",
"$",
"event",
",",
"$",
"callback",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"event",
")",
")",
"{",
"foreach",
"(",
"$",
"event",
"as",
"$",
"e",
")",
"{",
"self",
"::",
"listen",
"(",
"$",
"e",
... | Listen in on a given event to have a specified callback fired.
@param string $event Name of event to listen on.
@param mixed $callback Any callback callable by call_user_func_array
@return true | [
"Listen",
"in",
"on",
"a",
"given",
"event",
"to",
"have",
"a",
"specified",
"callback",
"fired",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Event.php#L73-L91 |
mjphaynes/php-resque | src/Resque/Event.php | Event.fire | public static function fire($event, $data = null)
{
if (!is_array($data)) {
$data = array($data);
}
array_unshift($data, $event);
$retval = true;
foreach (array('*', $event) as $e) {
if (!array_key_exists($e, self::$events)) {
continue;
}
foreach (self::$events[$e] as $callback) {
if (!is_callable($callback)) {
continue;
}
if (($retval = call_user_func_array($callback, $data)) === false) {
break 2;
}
}
}
return $retval !== false;
} | php | public static function fire($event, $data = null)
{
if (!is_array($data)) {
$data = array($data);
}
array_unshift($data, $event);
$retval = true;
foreach (array('*', $event) as $e) {
if (!array_key_exists($e, self::$events)) {
continue;
}
foreach (self::$events[$e] as $callback) {
if (!is_callable($callback)) {
continue;
}
if (($retval = call_user_func_array($callback, $data)) === false) {
break 2;
}
}
}
return $retval !== false;
} | [
"public",
"static",
"function",
"fire",
"(",
"$",
"event",
",",
"$",
"data",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"$",
"data",
")",
";",
"}",
"array_unshift",
"(",
"... | Raise a given event with the supplied data.
@param string $event Name of event to be raised
@param mixed $data Data that should be passed to each callback (optional)
@return true | [
"Raise",
"a",
"given",
"event",
"with",
"the",
"supplied",
"data",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Event.php#L100-L126 |
mjphaynes/php-resque | src/Resque/Event.php | Event.eventName | public static function eventName($event)
{
static $constants = null;
if (is_null($constants)) {
$class = new \ReflectionClass('Resque\Event');
$constants = array();
foreach ($class->getConstants() as $name => $value) {
$constants[$value] = strtolower($name);
}
}
return isset($constants[$event]) ? $constants[$event] : false;
} | php | public static function eventName($event)
{
static $constants = null;
if (is_null($constants)) {
$class = new \ReflectionClass('Resque\Event');
$constants = array();
foreach ($class->getConstants() as $name => $value) {
$constants[$value] = strtolower($name);
}
}
return isset($constants[$event]) ? $constants[$event] : false;
} | [
"public",
"static",
"function",
"eventName",
"(",
"$",
"event",
")",
"{",
"static",
"$",
"constants",
"=",
"null",
";",
"if",
"(",
"is_null",
"(",
"$",
"constants",
")",
")",
"{",
"$",
"class",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"'Resque\\Event'",... | Returns the name of the given event from constant
@param int $event Event constant
@return string|false | [
"Returns",
"the",
"name",
"of",
"the",
"given",
"event",
"from",
"constant"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Event.php#L164-L178 |
mjphaynes/php-resque | examples/autoload.php | ExampleAutoloader.registerEvents | public function registerEvents()
{
$job = & $this->job;
Event::listen(Event::JOB_PERFORM, function ($event, $_job) use (&$job) {
$job = $_job;
});
} | php | public function registerEvents()
{
$job = & $this->job;
Event::listen(Event::JOB_PERFORM, function ($event, $_job) use (&$job) {
$job = $_job;
});
} | [
"public",
"function",
"registerEvents",
"(",
")",
"{",
"$",
"job",
"=",
"&",
"$",
"this",
"->",
"job",
";",
"Event",
"::",
"listen",
"(",
"Event",
"::",
"JOB_PERFORM",
",",
"function",
"(",
"$",
"event",
",",
"$",
"_job",
")",
"use",
"(",
"&",
"$",... | which outputs all the debugging logs | [
"which",
"outputs",
"all",
"the",
"debugging",
"logs"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/examples/autoload.php#L44-L51 |
mjphaynes/php-resque | src/Resque/Logger.php | Logger.log | public function log($message, $context = null, $logType = null)
{
if (is_int($context) and is_null($logType)) {
$logType = $context;
$context = array();
}
if (!is_array($context)) {
$context = is_null($context) ? array() : array($context);
}
if (!is_int($logType)) {
$logType = self::INFO;
}
return call_user_func(array($this->instance, $this->logTypes[$logType]), $message, $context);
} | php | public function log($message, $context = null, $logType = null)
{
if (is_int($context) and is_null($logType)) {
$logType = $context;
$context = array();
}
if (!is_array($context)) {
$context = is_null($context) ? array() : array($context);
}
if (!is_int($logType)) {
$logType = self::INFO;
}
return call_user_func(array($this->instance, $this->logTypes[$logType]), $message, $context);
} | [
"public",
"function",
"log",
"(",
"$",
"message",
",",
"$",
"context",
"=",
"null",
",",
"$",
"logType",
"=",
"null",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"context",
")",
"and",
"is_null",
"(",
"$",
"logType",
")",
")",
"{",
"$",
"logType",
"... | Send log message to output interface
@param string $message Message to output
@param int $context Some context around the log
@param int $logType The log type
@reutrn mixed | [
"Send",
"log",
"message",
"to",
"output",
"interface"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Logger.php#L116-L132 |
mjphaynes/php-resque | src/Resque.php | Resque.loadConfig | public static function loadConfig($file = self::DEFAULT_CONFIG_FILE)
{
self::readConfigFile($file);
Redis::setConfig(array(
'scheme' => static::getConfig('redis.scheme', Redis::DEFAULT_SCHEME),
'host' => static::getConfig('redis.host', Redis::DEFAULT_HOST),
'port' => static::getConfig('redis.port', Redis::DEFAULT_PORT),
'namespace' => static::getConfig('redis.namespace', Redis::DEFAULT_NS),
'password' => static::getConfig('redis.password', Redis::DEFAULT_PASSWORD),
'rw_timeout' => static::getConfig('redis.rw_timeout', Redis::DEFAULT_RW_TIMEOUT),
'phpiredis' => static::getConfig('redis.phpiredis', Redis::DEFAULT_PHPIREDIS),
'predis' => static::getConfig('predis'),
));
return true;
} | php | public static function loadConfig($file = self::DEFAULT_CONFIG_FILE)
{
self::readConfigFile($file);
Redis::setConfig(array(
'scheme' => static::getConfig('redis.scheme', Redis::DEFAULT_SCHEME),
'host' => static::getConfig('redis.host', Redis::DEFAULT_HOST),
'port' => static::getConfig('redis.port', Redis::DEFAULT_PORT),
'namespace' => static::getConfig('redis.namespace', Redis::DEFAULT_NS),
'password' => static::getConfig('redis.password', Redis::DEFAULT_PASSWORD),
'rw_timeout' => static::getConfig('redis.rw_timeout', Redis::DEFAULT_RW_TIMEOUT),
'phpiredis' => static::getConfig('redis.phpiredis', Redis::DEFAULT_PHPIREDIS),
'predis' => static::getConfig('predis'),
));
return true;
} | [
"public",
"static",
"function",
"loadConfig",
"(",
"$",
"file",
"=",
"self",
"::",
"DEFAULT_CONFIG_FILE",
")",
"{",
"self",
"::",
"readConfigFile",
"(",
"$",
"file",
")",
";",
"Redis",
"::",
"setConfig",
"(",
"array",
"(",
"'scheme'",
"=>",
"static",
"::",... | Reads and loads data from a config file
@param string $file The config file path
@return bool | [
"Reads",
"and",
"loads",
"data",
"from",
"a",
"config",
"file"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque.php#L84-L100 |
mjphaynes/php-resque | src/Resque.php | Resque.readConfigFile | public static function readConfigFile($file = self::DEFAULT_CONFIG_FILE)
{
if (!is_string($file)) {
throw new InvalidArgumentException('The config file path must be a string, type passed "'.gettype($file).'".');
}
$baseDir = realpath(dirname($file));
$searchDirs = array(
$baseDir.'/',
$baseDir.'/../',
$baseDir.'/../../',
$baseDir.'/config/',
$baseDir.'/../config/',
$baseDir.'/../../config/'
);
$filename = basename($file);
$configFile = null;
foreach ($searchDirs as $dir) {
if (realpath($dir.$filename) and is_readable($dir.$filename)) {
$configFile = realpath($dir.$filename);
break;
}
}
if (is_null($configFile) and $file !== self::DEFAULT_CONFIG_FILE) {
throw new InvalidArgumentException('The config file "'.$file.'" cannot be found or read.');
}
if (!$configFile) {
return static::$config;
}
// Try to parse the contents
try {
$yaml = Yaml\Yaml::parse(file_get_contents($configFile));
} catch (Yaml\Exception\ParseException $e) {
throw new Exception('Unable to parse the config file: '.$e->getMessage());
}
return static::$config = $yaml;
} | php | public static function readConfigFile($file = self::DEFAULT_CONFIG_FILE)
{
if (!is_string($file)) {
throw new InvalidArgumentException('The config file path must be a string, type passed "'.gettype($file).'".');
}
$baseDir = realpath(dirname($file));
$searchDirs = array(
$baseDir.'/',
$baseDir.'/../',
$baseDir.'/../../',
$baseDir.'/config/',
$baseDir.'/../config/',
$baseDir.'/../../config/'
);
$filename = basename($file);
$configFile = null;
foreach ($searchDirs as $dir) {
if (realpath($dir.$filename) and is_readable($dir.$filename)) {
$configFile = realpath($dir.$filename);
break;
}
}
if (is_null($configFile) and $file !== self::DEFAULT_CONFIG_FILE) {
throw new InvalidArgumentException('The config file "'.$file.'" cannot be found or read.');
}
if (!$configFile) {
return static::$config;
}
// Try to parse the contents
try {
$yaml = Yaml\Yaml::parse(file_get_contents($configFile));
} catch (Yaml\Exception\ParseException $e) {
throw new Exception('Unable to parse the config file: '.$e->getMessage());
}
return static::$config = $yaml;
} | [
"public",
"static",
"function",
"readConfigFile",
"(",
"$",
"file",
"=",
"self",
"::",
"DEFAULT_CONFIG_FILE",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The config file path must be ... | Reads data from a config file
@param string $file The config file path
@return array | [
"Reads",
"data",
"from",
"a",
"config",
"file"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque.php#L108-L150 |
mjphaynes/php-resque | src/Resque.php | Resque.getConfig | public static function getConfig($key = null, $default = null)
{
if (!is_null($key)) {
if (false !== Util::path(static::$config, $key, $found)) {
return $found;
} else {
return $default;
}
}
return static::$config;
} | php | public static function getConfig($key = null, $default = null)
{
if (!is_null($key)) {
if (false !== Util::path(static::$config, $key, $found)) {
return $found;
} else {
return $default;
}
}
return static::$config;
} | [
"public",
"static",
"function",
"getConfig",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"if",
"(",
"false",
"!==",
"Util",
"::",
"path",
"(",
"static",
"::"... | Gets Resque config variable
@param string $key The key to search for (optional)
@param mixed $default If key not found returns this (optional)
@return mixed | [
"Gets",
"Resque",
"config",
"variable"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque.php#L159-L170 |
mjphaynes/php-resque | src/Resque/Helpers/CatchOutput.php | CatchOutput.write | public function write($messages, $newline = false, $type = self::OUTPUT_RAW)
{
parent::write($messages, $newline, $type);
} | php | public function write($messages, $newline = false, $type = self::OUTPUT_RAW)
{
parent::write($messages, $newline, $type);
} | [
"public",
"function",
"write",
"(",
"$",
"messages",
",",
"$",
"newline",
"=",
"false",
",",
"$",
"type",
"=",
"self",
"::",
"OUTPUT_RAW",
")",
"{",
"parent",
"::",
"write",
"(",
"$",
"messages",
",",
"$",
"newline",
",",
"$",
"type",
")",
";",
"}"... | Writes a message to the output.
@param string|array $messages The message as an array of lines or a single string
@param bool $newline Whether to add a newline
@param int $type The type of output (one of the OUTPUT constants)
@throws \InvalidArgumentException When unknown output type is given | [
"Writes",
"a",
"message",
"to",
"the",
"output",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/CatchOutput.php#L53-L56 |
mjphaynes/php-resque | src/Resque/Host.php | Host.redisKey | public static function redisKey($host = null, $suffix = null)
{
if (is_null($host)) {
return 'hosts';
}
$hostname = $host instanceof Host ? $host->hostname : $host;
return 'host:'.$hostname.($suffix ? ':'.$suffix : '');
} | php | public static function redisKey($host = null, $suffix = null)
{
if (is_null($host)) {
return 'hosts';
}
$hostname = $host instanceof Host ? $host->hostname : $host;
return 'host:'.$hostname.($suffix ? ':'.$suffix : '');
} | [
"public",
"static",
"function",
"redisKey",
"(",
"$",
"host",
"=",
"null",
",",
"$",
"suffix",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"host",
")",
")",
"{",
"return",
"'hosts'",
";",
"}",
"$",
"hostname",
"=",
"$",
"host",
"instance... | Get the Redis key
@param Host $host The host to get the key for
@param string $suffix To be appended to key
@return string | [
"Get",
"the",
"Redis",
"key"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Host.php#L47-L55 |
mjphaynes/php-resque | src/Resque/Host.php | Host.working | public function working(Worker $worker)
{
$this->redis->sadd(self::redisKey(), $this->hostname);
$this->redis->sadd(self::redisKey($this), (string)$worker);
$this->redis->expire(self::redisKey($this), $this->timeout);
} | php | public function working(Worker $worker)
{
$this->redis->sadd(self::redisKey(), $this->hostname);
$this->redis->sadd(self::redisKey($this), (string)$worker);
$this->redis->expire(self::redisKey($this), $this->timeout);
} | [
"public",
"function",
"working",
"(",
"Worker",
"$",
"worker",
")",
"{",
"$",
"this",
"->",
"redis",
"->",
"sadd",
"(",
"self",
"::",
"redisKey",
"(",
")",
",",
"$",
"this",
"->",
"hostname",
")",
";",
"$",
"this",
"->",
"redis",
"->",
"sadd",
"(",... | Mark host as having an active worker
@param Worker $worker the worker instance | [
"Mark",
"host",
"as",
"having",
"an",
"active",
"worker"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Host.php#L82-L88 |
mjphaynes/php-resque | src/Resque/Host.php | Host.finished | public function finished(Worker $worker)
{
$this->redis->srem(self::redisKey($this), (string)$worker);
} | php | public function finished(Worker $worker)
{
$this->redis->srem(self::redisKey($this), (string)$worker);
} | [
"public",
"function",
"finished",
"(",
"Worker",
"$",
"worker",
")",
"{",
"$",
"this",
"->",
"redis",
"->",
"srem",
"(",
"self",
"::",
"redisKey",
"(",
"$",
"this",
")",
",",
"(",
"string",
")",
"$",
"worker",
")",
";",
"}"
] | Mark host as having a finished worker
@param Worker $worker The worker instance | [
"Mark",
"host",
"as",
"having",
"a",
"finished",
"worker"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Host.php#L95-L98 |
mjphaynes/php-resque | src/Resque/Host.php | Host.cleanup | public function cleanup()
{
$hosts = $this->redis->smembers(self::redisKey());
$workers = $this->redis->smembers(Worker::redisKey());
$cleaned = array('hosts' => array(), 'workers' => array());
foreach ($hosts as $hostname) {
$host = new static($hostname);
if (!$this->redis->exists(self::redisKey($host))) {
$this->redis->srem(self::redisKey(), (string)$host);
$cleaned['hosts'][] = (string)$host;
} else {
$host_workers = $this->redis->smembers(self::redisKey($host));
foreach ($host_workers as $host_worker) {
if (!in_array($host_worker, $workers)) {
$cleaned['workers'][] = $host_worker;
$this->redis->srem(self::redisKey($host), $host_worker);
}
}
}
}
return $cleaned;
} | php | public function cleanup()
{
$hosts = $this->redis->smembers(self::redisKey());
$workers = $this->redis->smembers(Worker::redisKey());
$cleaned = array('hosts' => array(), 'workers' => array());
foreach ($hosts as $hostname) {
$host = new static($hostname);
if (!$this->redis->exists(self::redisKey($host))) {
$this->redis->srem(self::redisKey(), (string)$host);
$cleaned['hosts'][] = (string)$host;
} else {
$host_workers = $this->redis->smembers(self::redisKey($host));
foreach ($host_workers as $host_worker) {
if (!in_array($host_worker, $workers)) {
$cleaned['workers'][] = $host_worker;
$this->redis->srem(self::redisKey($host), $host_worker);
}
}
}
}
return $cleaned;
} | [
"public",
"function",
"cleanup",
"(",
")",
"{",
"$",
"hosts",
"=",
"$",
"this",
"->",
"redis",
"->",
"smembers",
"(",
"self",
"::",
"redisKey",
"(",
")",
")",
";",
"$",
"workers",
"=",
"$",
"this",
"->",
"redis",
"->",
"smembers",
"(",
"Worker",
":... | Cleans up any dead hosts
@return array List of cleaned hosts | [
"Cleans",
"up",
"any",
"dead",
"hosts"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Host.php#L105-L131 |
mjphaynes/php-resque | src/Resque/Commands/Command.php | Command.mergeDefinitions | protected function mergeDefinitions(array $definitions)
{
return array_merge(
$definitions,
array(
new InputOption('config', 'c', InputOption::VALUE_OPTIONAL, 'Path to config file. Inline options override.', Resque::DEFAULT_CONFIG_FILE),
new InputOption('include', 'I', InputOption::VALUE_OPTIONAL, 'Path to include php file'),
new InputOption('host', 'H', InputOption::VALUE_OPTIONAL, 'The Redis hostname.', Resque\Redis::DEFAULT_HOST),
new InputOption('port', 'p', InputOption::VALUE_OPTIONAL, 'The Redis port.', Resque\Redis::DEFAULT_PORT),
new InputOption('scheme', null, InputOption::VALUE_REQUIRED, 'The Redis scheme to use.', Resque\Redis::DEFAULT_SCHEME),
new InputOption('namespace', null, InputOption::VALUE_REQUIRED, 'The Redis namespace to use. This is prefixed to all keys.', Resque\Redis::DEFAULT_NS),
new InputOption('password', null, InputOption::VALUE_OPTIONAL, 'The Redis AUTH password.'),
new InputOption('log', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Specify the handler(s) to use for logging.'),
new InputOption('events', 'e', InputOption::VALUE_NONE, 'Outputs all events to the console, for debugging.'),
)
);
} | php | protected function mergeDefinitions(array $definitions)
{
return array_merge(
$definitions,
array(
new InputOption('config', 'c', InputOption::VALUE_OPTIONAL, 'Path to config file. Inline options override.', Resque::DEFAULT_CONFIG_FILE),
new InputOption('include', 'I', InputOption::VALUE_OPTIONAL, 'Path to include php file'),
new InputOption('host', 'H', InputOption::VALUE_OPTIONAL, 'The Redis hostname.', Resque\Redis::DEFAULT_HOST),
new InputOption('port', 'p', InputOption::VALUE_OPTIONAL, 'The Redis port.', Resque\Redis::DEFAULT_PORT),
new InputOption('scheme', null, InputOption::VALUE_REQUIRED, 'The Redis scheme to use.', Resque\Redis::DEFAULT_SCHEME),
new InputOption('namespace', null, InputOption::VALUE_REQUIRED, 'The Redis namespace to use. This is prefixed to all keys.', Resque\Redis::DEFAULT_NS),
new InputOption('password', null, InputOption::VALUE_OPTIONAL, 'The Redis AUTH password.'),
new InputOption('log', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Specify the handler(s) to use for logging.'),
new InputOption('events', 'e', InputOption::VALUE_NONE, 'Outputs all events to the console, for debugging.'),
)
);
} | [
"protected",
"function",
"mergeDefinitions",
"(",
"array",
"$",
"definitions",
")",
"{",
"return",
"array_merge",
"(",
"$",
"definitions",
",",
"array",
"(",
"new",
"InputOption",
"(",
"'config'",
",",
"'c'",
",",
"InputOption",
"::",
"VALUE_OPTIONAL",
",",
"'... | Globally sets some input options that are available for all commands
@param array $definitions List of command definitions
@return array | [
"Globally",
"sets",
"some",
"input",
"options",
"that",
"are",
"available",
"for",
"all",
"commands"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Commands/Command.php#L75-L91 |
mjphaynes/php-resque | src/Resque/Commands/Command.php | Command.initialize | protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->parseConfig($input->getOptions(), $this->getNativeDefinition()->getOptionDefaults());
$config = $this->getConfig();
// Configure Redis
Resque\Redis::setConfig(array(
'scheme' => $config['scheme'],
'host' => $config['host'],
'port' => $config['port'],
'namespace' => $config['namespace'],
'password' => $config['password']
));
// Set the verbosity
if (array_key_exists('verbose', $config)) {
if (!$input->getOption('verbose') and !$input->getOption('quiet') and is_int($config['verbose'])) {
$output->setVerbosity($config['verbose']);
} else {
$this->config['verbose'] = $output->getVerbosity();
}
}
// Set the monolog loggers, it's possible to speficfy multiple handlers
$logs = array_key_exists('log', $config) ? array_unique($config['log']) : array();
empty($logs) and $logs[] = 'console';
$handlerConnector = new Resque\Logger\Handler\Connector($this, $input, $output);
$handlers = array();
foreach ($logs as $log) {
$handlers[] = $handlerConnector->resolve($log);
}
$this->logger = $logger = new Resque\Logger($handlers);
// Unset some variables so as not to pass to include file
unset($logs, $handlerConnector, $handlers);
// Include file?
if (array_key_exists('include', $config) and strlen($include = $config['include'])) {
if (
!($includeFile = realpath(dirname($include).'/'.basename($include))) or
!is_readable($includeFile) or !is_file($includeFile) or
substr($includeFile, -4) !== '.php'
) {
throw new \InvalidArgumentException('The include file "'.$include.'" is not a readable php file.');
}
try {
require_once $includeFile;
} catch (\Exception $e) {
throw new \RuntimeException('The include file "'.$include.'" threw an exception: "'.$e->getMessage().'" on line '.$e->getLine());
}
}
// This outputs all the events that are fired, useful for learning
// about when events are fired in the command flow
if (array_key_exists('events', $config) and $config['events'] === true) {
Resque\Event::listen('*', function ($event) use ($output) {
$data = array_map(
function ($d) {
$d instanceof \Exception and ($d = '"'.$d->getMessage().'"');
is_array($d) and ($d = '['.implode(',', $d).']');
return (string)$d;
},
array_slice(func_get_args(), 1)
);
$output->writeln('<comment>-> event:'.Resque\Event::eventName($event).'('.implode(',', $data).')</comment>');
});
}
} | php | protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->parseConfig($input->getOptions(), $this->getNativeDefinition()->getOptionDefaults());
$config = $this->getConfig();
// Configure Redis
Resque\Redis::setConfig(array(
'scheme' => $config['scheme'],
'host' => $config['host'],
'port' => $config['port'],
'namespace' => $config['namespace'],
'password' => $config['password']
));
// Set the verbosity
if (array_key_exists('verbose', $config)) {
if (!$input->getOption('verbose') and !$input->getOption('quiet') and is_int($config['verbose'])) {
$output->setVerbosity($config['verbose']);
} else {
$this->config['verbose'] = $output->getVerbosity();
}
}
// Set the monolog loggers, it's possible to speficfy multiple handlers
$logs = array_key_exists('log', $config) ? array_unique($config['log']) : array();
empty($logs) and $logs[] = 'console';
$handlerConnector = new Resque\Logger\Handler\Connector($this, $input, $output);
$handlers = array();
foreach ($logs as $log) {
$handlers[] = $handlerConnector->resolve($log);
}
$this->logger = $logger = new Resque\Logger($handlers);
// Unset some variables so as not to pass to include file
unset($logs, $handlerConnector, $handlers);
// Include file?
if (array_key_exists('include', $config) and strlen($include = $config['include'])) {
if (
!($includeFile = realpath(dirname($include).'/'.basename($include))) or
!is_readable($includeFile) or !is_file($includeFile) or
substr($includeFile, -4) !== '.php'
) {
throw new \InvalidArgumentException('The include file "'.$include.'" is not a readable php file.');
}
try {
require_once $includeFile;
} catch (\Exception $e) {
throw new \RuntimeException('The include file "'.$include.'" threw an exception: "'.$e->getMessage().'" on line '.$e->getLine());
}
}
// This outputs all the events that are fired, useful for learning
// about when events are fired in the command flow
if (array_key_exists('events', $config) and $config['events'] === true) {
Resque\Event::listen('*', function ($event) use ($output) {
$data = array_map(
function ($d) {
$d instanceof \Exception and ($d = '"'.$d->getMessage().'"');
is_array($d) and ($d = '['.implode(',', $d).']');
return (string)$d;
},
array_slice(func_get_args(), 1)
);
$output->writeln('<comment>-> event:'.Resque\Event::eventName($event).'('.implode(',', $data).')</comment>');
});
}
} | [
"protected",
"function",
"initialize",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"parseConfig",
"(",
"$",
"input",
"->",
"getOptions",
"(",
")",
",",
"$",
"this",
"->",
"getNativeDefinition",
"("... | Initialises the command just after the input has been validated.
This is mainly useful when a lot of commands extends one main command
where some things need to be initialised based on the input arguments and options.
@param InputInterface $input An InputInterface instance
@param OutputInterface $output An OutputInterface instance
@return void | [
"Initialises",
"the",
"command",
"just",
"after",
"the",
"input",
"has",
"been",
"validated",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Commands/Command.php#L103-L176 |
mjphaynes/php-resque | src/Resque/Commands/Command.php | Command.parseConfig | protected function parseConfig($config, $defaults)
{
if (array_key_exists('config', $config)) {
$configFileData = Resque::readConfigFile($config['config']);
foreach ($config as $key => &$value) {
// If the config value is equal to the default value set in the command then
// have a look at the config file. This is so that the config options can be
// over-ridden in the command line.
if (
isset($this->configOptionMap[$key]) and
(
($key === 'verbose' or $value === $defaults[$key]) and
(false !== Util::path($configFileData, $this->configOptionMap[$key], $found))
)
) {
switch ($key) {
// Need to make sure the log handlers are in the correct format
case 'log':
$value = array();
foreach ((array)$found as $handler => $target) {
$handler = strtolower($handler);
if ($target !== true) {
$handler .= ':';
if (in_array($handler, array('redis:', 'mongodb:', 'couchdb:', 'amqp:'))) {
$handler .= '//';
}
$handler .= $target;
}
$value[] = $handler;
}
break;
default:
$value = $found;
break;
}
}
}
$this->config = $config;
return true;
}
return false;
} | php | protected function parseConfig($config, $defaults)
{
if (array_key_exists('config', $config)) {
$configFileData = Resque::readConfigFile($config['config']);
foreach ($config as $key => &$value) {
// If the config value is equal to the default value set in the command then
// have a look at the config file. This is so that the config options can be
// over-ridden in the command line.
if (
isset($this->configOptionMap[$key]) and
(
($key === 'verbose' or $value === $defaults[$key]) and
(false !== Util::path($configFileData, $this->configOptionMap[$key], $found))
)
) {
switch ($key) {
// Need to make sure the log handlers are in the correct format
case 'log':
$value = array();
foreach ((array)$found as $handler => $target) {
$handler = strtolower($handler);
if ($target !== true) {
$handler .= ':';
if (in_array($handler, array('redis:', 'mongodb:', 'couchdb:', 'amqp:'))) {
$handler .= '//';
}
$handler .= $target;
}
$value[] = $handler;
}
break;
default:
$value = $found;
break;
}
}
}
$this->config = $config;
return true;
}
return false;
} | [
"protected",
"function",
"parseConfig",
"(",
"$",
"config",
",",
"$",
"defaults",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"'config'",
",",
"$",
"config",
")",
")",
"{",
"$",
"configFileData",
"=",
"Resque",
"::",
"readConfigFile",
"(",
"$",
"config",... | Parses the configuration file
@param mixed $config
@param mixed $defaults
@return bool | [
"Parses",
"the",
"configuration",
"file"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Commands/Command.php#L206-L256 |
mjphaynes/php-resque | src/Resque/Commands/Command.php | Command.getConfig | protected function getConfig($key = null)
{
if (!is_null($key)) {
if (!array_key_exists($key, $this->config)) {
throw new \InvalidArgumentException('Config key "'.$key.'" does not exist. Valid keys are: "'.implode(', ', array_keys($this->config)).'"');
}
return $this->config[$key];
}
return $this->config;
} | php | protected function getConfig($key = null)
{
if (!is_null($key)) {
if (!array_key_exists($key, $this->config)) {
throw new \InvalidArgumentException('Config key "'.$key.'" does not exist. Valid keys are: "'.implode(', ', array_keys($this->config)).'"');
}
return $this->config[$key];
}
return $this->config;
} | [
"protected",
"function",
"getConfig",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"config",
")",
")",
"{",
"throw"... | Returns all config items or a specific one
@param null|mixed $key
@return mixed | [
"Returns",
"all",
"config",
"items",
"or",
"a",
"specific",
"one"
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Commands/Command.php#L264-L275 |
mjphaynes/php-resque | src/Resque/Helpers/Util.php | Util.bytes | public static function bytes($bytes, $force_unit = null, $format = null, $si = true)
{
$format = ($format === null) ? '%01.2f %s' : (string) $format;
// IEC prefixes (binary)
if ($si == false or strpos($force_unit, 'i') !== false) {
$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
$mod = 1024;
// SI prefixes (decimal)
} else {
$units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
$mod = 1000;
}
if (($power = array_search((string) $force_unit, $units)) === false) {
$power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
}
return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
} | php | public static function bytes($bytes, $force_unit = null, $format = null, $si = true)
{
$format = ($format === null) ? '%01.2f %s' : (string) $format;
// IEC prefixes (binary)
if ($si == false or strpos($force_unit, 'i') !== false) {
$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
$mod = 1024;
// SI prefixes (decimal)
} else {
$units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
$mod = 1000;
}
if (($power = array_search((string) $force_unit, $units)) === false) {
$power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
}
return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
} | [
"public",
"static",
"function",
"bytes",
"(",
"$",
"bytes",
",",
"$",
"force_unit",
"=",
"null",
",",
"$",
"format",
"=",
"null",
",",
"$",
"si",
"=",
"true",
")",
"{",
"$",
"format",
"=",
"(",
"$",
"format",
"===",
"null",
")",
"?",
"'%01.2f %s'",... | Returns human readable sizes. Based on original functions written by
[Aidan Lister](http://aidanlister.com/repos/v/function.size_readable.php)
and [Quentin Zervaas](http://www.phpriot.com/d/code/strings/filesize-format/).
@param int $bytes size in bytes
@param string $force_unit a definitive unit
@param string $format the return string format
@param bool $si whether to use SI prefixes or IEC
@return string | [
"Returns",
"human",
"readable",
"sizes",
".",
"Based",
"on",
"original",
"functions",
"written",
"by",
"[",
"Aidan",
"Lister",
"]",
"(",
"http",
":",
"//",
"aidanlister",
".",
"com",
"/",
"repos",
"/",
"v",
"/",
"function",
".",
"size_readable",
".",
"ph... | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/Util.php#L33-L53 |
mjphaynes/php-resque | src/Resque/Helpers/Util.php | Util.human_time_diff | public static function human_time_diff($from, $to = null)
{
$to = $to ?: time();
$diff = (int)abs($to - $from);
if ($diff < self::MINUTE_IN_SECONDS) {
$since = array($diff, 'sec');
} elseif ($diff < self::HOUR_IN_SECONDS) {
$since = array(round($diff / self::MINUTE_IN_SECONDS), 'min');
} elseif ($diff < self::DAY_IN_SECONDS and $diff >= self::HOUR_IN_SECONDS) {
$since = array(round($diff / self::HOUR_IN_SECONDS), 'hour');
} elseif ($diff < self::WEEK_IN_SECONDS and $diff >= self::DAY_IN_SECONDS) {
$since = array(round($diff / self::DAY_IN_SECONDS), 'day');
} elseif ($diff < 30 * self::DAY_IN_SECONDS and $diff >= self::WEEK_IN_SECONDS) {
$since = array(round($diff / self::WEEK_IN_SECONDS), 'week');
} elseif ($diff < self::YEAR_IN_SECONDS and $diff >= 30 * self::DAY_IN_SECONDS) {
$since = array(round($diff / (30 * self::DAY_IN_SECONDS)), 'month');
} elseif ($diff >= self::YEAR_IN_SECONDS) {
$since = array(round($diff / self::YEAR_IN_SECONDS), 'year');
}
if ($since[0] <= 1) {
$since[0] = 1;
}
return $since[0].' '.$since[1].($since[0] == 1 ? '' : 's');
} | php | public static function human_time_diff($from, $to = null)
{
$to = $to ?: time();
$diff = (int)abs($to - $from);
if ($diff < self::MINUTE_IN_SECONDS) {
$since = array($diff, 'sec');
} elseif ($diff < self::HOUR_IN_SECONDS) {
$since = array(round($diff / self::MINUTE_IN_SECONDS), 'min');
} elseif ($diff < self::DAY_IN_SECONDS and $diff >= self::HOUR_IN_SECONDS) {
$since = array(round($diff / self::HOUR_IN_SECONDS), 'hour');
} elseif ($diff < self::WEEK_IN_SECONDS and $diff >= self::DAY_IN_SECONDS) {
$since = array(round($diff / self::DAY_IN_SECONDS), 'day');
} elseif ($diff < 30 * self::DAY_IN_SECONDS and $diff >= self::WEEK_IN_SECONDS) {
$since = array(round($diff / self::WEEK_IN_SECONDS), 'week');
} elseif ($diff < self::YEAR_IN_SECONDS and $diff >= 30 * self::DAY_IN_SECONDS) {
$since = array(round($diff / (30 * self::DAY_IN_SECONDS)), 'month');
} elseif ($diff >= self::YEAR_IN_SECONDS) {
$since = array(round($diff / self::YEAR_IN_SECONDS), 'year');
}
if ($since[0] <= 1) {
$since[0] = 1;
}
return $since[0].' '.$since[1].($since[0] == 1 ? '' : 's');
} | [
"public",
"static",
"function",
"human_time_diff",
"(",
"$",
"from",
",",
"$",
"to",
"=",
"null",
")",
"{",
"$",
"to",
"=",
"$",
"to",
"?",
":",
"time",
"(",
")",
";",
"$",
"diff",
"=",
"(",
"int",
")",
"abs",
"(",
"$",
"to",
"-",
"$",
"from"... | Determines the difference between two timestamps.
The difference is returned in a human readable format such as "1 hour",
"5 mins", "2 days".
@param int $from Unix timestamp from which the difference begins.
@param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
@return string Human readable time difference. | [
"Determines",
"the",
"difference",
"between",
"two",
"timestamps",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/Util.php#L74-L101 |
mjphaynes/php-resque | src/Resque/Helpers/Util.php | Util.path | public static function path($array, $path, &$found, $delimiter = '.')
{
if (!is_array($array)) {
return false;
}
if (is_array($path)) {
$keys = $path;
} else {
if (array_key_exists($path, $array)) {
$found = $array[$path]; // No need to do extra processing
return true;
}
$keys = explode($delimiter, trim($path, "{$delimiter} "));
}
do {
$key = array_shift($keys);
if (ctype_digit($key)) {
$key = (int)$key;
}
if (isset($array[$key])) {
if ($keys) {
if (is_array($array[$key])) {
$array = $array[$key];
} else {
break;
}
} else {
$found = $array[$key];
return true;
}
} else {
break;
}
} while ($keys);
// Unable to find the value requested
return false;
} | php | public static function path($array, $path, &$found, $delimiter = '.')
{
if (!is_array($array)) {
return false;
}
if (is_array($path)) {
$keys = $path;
} else {
if (array_key_exists($path, $array)) {
$found = $array[$path]; // No need to do extra processing
return true;
}
$keys = explode($delimiter, trim($path, "{$delimiter} "));
}
do {
$key = array_shift($keys);
if (ctype_digit($key)) {
$key = (int)$key;
}
if (isset($array[$key])) {
if ($keys) {
if (is_array($array[$key])) {
$array = $array[$key];
} else {
break;
}
} else {
$found = $array[$key];
return true;
}
} else {
break;
}
} while ($keys);
// Unable to find the value requested
return false;
} | [
"public",
"static",
"function",
"path",
"(",
"$",
"array",
",",
"$",
"path",
",",
"&",
"$",
"found",
",",
"$",
"delimiter",
"=",
"'.'",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"array",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"... | Gets a value from an array using a dot separated path.
Returns true if found and false if not.
@param array $array array to search
@param mixed $path key path string (delimiter separated) or array of keys
@param mixed $found value that was found
@param string $delimiter key path delimiter
@return bool | [
"Gets",
"a",
"value",
"from",
"an",
"array",
"using",
"a",
"dot",
"separated",
"path",
".",
"Returns",
"true",
"if",
"found",
"and",
"false",
"if",
"not",
"."
] | train | https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Helpers/Util.php#L113-L155 |
prooph/event-store | src/StreamMetadataBuilder.php | StreamMetadataBuilder.setMaxCount | public function setMaxCount(int $maxCount): StreamMetadataBuilder
{
if ($maxCount < 0) {
throw new InvalidArgumentException('Max count must be positive');
}
$this->maxCount = $maxCount;
return $this;
} | php | public function setMaxCount(int $maxCount): StreamMetadataBuilder
{
if ($maxCount < 0) {
throw new InvalidArgumentException('Max count must be positive');
}
$this->maxCount = $maxCount;
return $this;
} | [
"public",
"function",
"setMaxCount",
"(",
"int",
"$",
"maxCount",
")",
":",
"StreamMetadataBuilder",
"{",
"if",
"(",
"$",
"maxCount",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Max count must be positive'",
")",
";",
"}",
"$",
"this... | Sets the maximum number of events allowed in the stream | [
"Sets",
"the",
"maximum",
"number",
"of",
"events",
"allowed",
"in",
"the",
"stream"
] | train | https://github.com/prooph/event-store/blob/0cbd53e4a521ab883daf45fe1fe67c435deeb8f7/src/StreamMetadataBuilder.php#L86-L95 |
prooph/event-store | src/StreamMetadataBuilder.php | StreamMetadataBuilder.setMaxAge | public function setMaxAge(int $maxAge): StreamMetadataBuilder
{
if ($maxAge < 0) {
throw new InvalidArgumentException('Max age must be positive');
}
$this->maxAge = $maxAge;
return $this;
} | php | public function setMaxAge(int $maxAge): StreamMetadataBuilder
{
if ($maxAge < 0) {
throw new InvalidArgumentException('Max age must be positive');
}
$this->maxAge = $maxAge;
return $this;
} | [
"public",
"function",
"setMaxAge",
"(",
"int",
"$",
"maxAge",
")",
":",
"StreamMetadataBuilder",
"{",
"if",
"(",
"$",
"maxAge",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Max age must be positive'",
")",
";",
"}",
"$",
"this",
"->... | Sets the event number from which previous events can be scavenged | [
"Sets",
"the",
"event",
"number",
"from",
"which",
"previous",
"events",
"can",
"be",
"scavenged"
] | train | https://github.com/prooph/event-store/blob/0cbd53e4a521ab883daf45fe1fe67c435deeb8f7/src/StreamMetadataBuilder.php#L98-L107 |
prooph/event-store | src/StreamMetadataBuilder.php | StreamMetadataBuilder.setTruncateBefore | public function setTruncateBefore(int $truncateBefore): StreamMetadataBuilder
{
if ($truncateBefore < 0) {
throw new InvalidArgumentException('Truncate before must be positive');
}
$this->truncateBefore = $truncateBefore;
return $this;
} | php | public function setTruncateBefore(int $truncateBefore): StreamMetadataBuilder
{
if ($truncateBefore < 0) {
throw new InvalidArgumentException('Truncate before must be positive');
}
$this->truncateBefore = $truncateBefore;
return $this;
} | [
"public",
"function",
"setTruncateBefore",
"(",
"int",
"$",
"truncateBefore",
")",
":",
"StreamMetadataBuilder",
"{",
"if",
"(",
"$",
"truncateBefore",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Truncate before must be positive'",
")",
";... | Sets the event number from which previous events can be scavenged | [
"Sets",
"the",
"event",
"number",
"from",
"which",
"previous",
"events",
"can",
"be",
"scavenged"
] | train | https://github.com/prooph/event-store/blob/0cbd53e4a521ab883daf45fe1fe67c435deeb8f7/src/StreamMetadataBuilder.php#L110-L119 |
prooph/event-store | src/StreamMetadataBuilder.php | StreamMetadataBuilder.setCacheControl | public function setCacheControl(int $cacheControl): StreamMetadataBuilder
{
if ($cacheControl < 0) {
throw new InvalidArgumentException('CacheControl must be positive');
}
$this->cacheControl = $cacheControl;
return $this;
} | php | public function setCacheControl(int $cacheControl): StreamMetadataBuilder
{
if ($cacheControl < 0) {
throw new InvalidArgumentException('CacheControl must be positive');
}
$this->cacheControl = $cacheControl;
return $this;
} | [
"public",
"function",
"setCacheControl",
"(",
"int",
"$",
"cacheControl",
")",
":",
"StreamMetadataBuilder",
"{",
"if",
"(",
"$",
"cacheControl",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'CacheControl must be positive'",
")",
";",
"}",... | Sets the amount of time for which the stream head is cachable | [
"Sets",
"the",
"amount",
"of",
"time",
"for",
"which",
"the",
"stream",
"head",
"is",
"cachable"
] | train | https://github.com/prooph/event-store/blob/0cbd53e4a521ab883daf45fe1fe67c435deeb8f7/src/StreamMetadataBuilder.php#L122-L131 |
prooph/event-store | src/Async/EventStoreTransaction.php | EventStoreTransaction.writeAsync | public function writeAsync(array $events = []): Promise
{
if ($this->isRolledBack) {
throw new \RuntimeException('Cannot commit a rolledback transaction');
}
if ($this->isCommitted) {
throw new \RuntimeException('Transaction is already committed');
}
return $this->connection->transactionalWriteAsync($this, $events, $this->userCredentials);
} | php | public function writeAsync(array $events = []): Promise
{
if ($this->isRolledBack) {
throw new \RuntimeException('Cannot commit a rolledback transaction');
}
if ($this->isCommitted) {
throw new \RuntimeException('Transaction is already committed');
}
return $this->connection->transactionalWriteAsync($this, $events, $this->userCredentials);
} | [
"public",
"function",
"writeAsync",
"(",
"array",
"$",
"events",
"=",
"[",
"]",
")",
":",
"Promise",
"{",
"if",
"(",
"$",
"this",
"->",
"isRolledBack",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Cannot commit a rolledback transaction'",
")",
... | @param EventData[] $events
@return Promise<void> | [
"@param",
"EventData",
"[]",
"$events"
] | train | https://github.com/prooph/event-store/blob/0cbd53e4a521ab883daf45fe1fe67c435deeb8f7/src/Async/EventStoreTransaction.php#L69-L80 |
prooph/event-store | src/EventStoreTransaction.php | EventStoreTransaction.write | public function write(array $events = []): void
{
if ($this->isRolledBack) {
throw new \RuntimeException('Cannot commit a rolledback transaction');
}
if ($this->isCommitted) {
throw new \RuntimeException('Transaction is already committed');
}
$this->connection->transactionalWrite($this, $events, $this->userCredentials);
} | php | public function write(array $events = []): void
{
if ($this->isRolledBack) {
throw new \RuntimeException('Cannot commit a rolledback transaction');
}
if ($this->isCommitted) {
throw new \RuntimeException('Transaction is already committed');
}
$this->connection->transactionalWrite($this, $events, $this->userCredentials);
} | [
"public",
"function",
"write",
"(",
"array",
"$",
"events",
"=",
"[",
"]",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"isRolledBack",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Cannot commit a rolledback transaction'",
")",
";",
"... | @param EventData[] $events
@return void | [
"@param",
"EventData",
"[]",
"$events"
] | train | https://github.com/prooph/event-store/blob/0cbd53e4a521ab883daf45fe1fe67c435deeb8f7/src/EventStoreTransaction.php#L64-L75 |
adbario/php-dot-notation | src/Dot.php | Dot.add | public function add($keys, $value = null)
{
if (is_array($keys)) {
foreach ($keys as $key => $value) {
$this->add($key, $value);
}
} elseif (is_null($this->get($keys))) {
$this->set($keys, $value);
}
} | php | public function add($keys, $value = null)
{
if (is_array($keys)) {
foreach ($keys as $key => $value) {
$this->add($key, $value);
}
} elseif (is_null($this->get($keys))) {
$this->set($keys, $value);
}
} | [
"public",
"function",
"add",
"(",
"$",
"keys",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"keys",
")",
")",
"{",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"... | Set a given key / value pair or pairs
if the key doesn't exist already
@param array|int|string $keys
@param mixed $value | [
"Set",
"a",
"given",
"key",
"/",
"value",
"pair",
"or",
"pairs",
"if",
"the",
"key",
"doesn",
"t",
"exist",
"already"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L49-L58 |
adbario/php-dot-notation | src/Dot.php | Dot.clear | public function clear($keys = null)
{
if (is_null($keys)) {
$this->items = [];
return;
}
$keys = (array) $keys;
foreach ($keys as $key) {
$this->set($key, []);
}
} | php | public function clear($keys = null)
{
if (is_null($keys)) {
$this->items = [];
return;
}
$keys = (array) $keys;
foreach ($keys as $key) {
$this->set($key, []);
}
} | [
"public",
"function",
"clear",
"(",
"$",
"keys",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"keys",
")",
")",
"{",
"$",
"this",
"->",
"items",
"=",
"[",
"]",
";",
"return",
";",
"}",
"$",
"keys",
"=",
"(",
"array",
")",
"$",
"keys... | Delete the contents of a given key or keys
@param array|int|string|null $keys | [
"Delete",
"the",
"contents",
"of",
"a",
"given",
"key",
"or",
"keys"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L75-L88 |
adbario/php-dot-notation | src/Dot.php | Dot.delete | public function delete($keys)
{
$keys = (array) $keys;
foreach ($keys as $key) {
if ($this->exists($this->items, $key)) {
unset($this->items[$key]);
continue;
}
$items = &$this->items;
$segments = explode('.', $key);
$lastSegment = array_pop($segments);
foreach ($segments as $segment) {
if (!isset($items[$segment]) || !is_array($items[$segment])) {
continue 2;
}
$items = &$items[$segment];
}
unset($items[$lastSegment]);
}
} | php | public function delete($keys)
{
$keys = (array) $keys;
foreach ($keys as $key) {
if ($this->exists($this->items, $key)) {
unset($this->items[$key]);
continue;
}
$items = &$this->items;
$segments = explode('.', $key);
$lastSegment = array_pop($segments);
foreach ($segments as $segment) {
if (!isset($items[$segment]) || !is_array($items[$segment])) {
continue 2;
}
$items = &$items[$segment];
}
unset($items[$lastSegment]);
}
} | [
"public",
"function",
"delete",
"(",
"$",
"keys",
")",
"{",
"$",
"keys",
"=",
"(",
"array",
")",
"$",
"keys",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"exists",
"(",
"$",
"this",
"->",
"items",... | Delete the given key or keys
@param array|int|string $keys | [
"Delete",
"the",
"given",
"key",
"or",
"keys"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L95-L120 |
adbario/php-dot-notation | src/Dot.php | Dot.flatten | public function flatten($delimiter = '.', $items = null, $prepend = '')
{
$flatten = [];
if (is_null($items)) {
$items = $this->items;
}
foreach ($items as $key => $value) {
if (is_array($value) && !empty($value)) {
$flatten = array_merge(
$flatten,
$this->flatten($delimiter, $value, $prepend.$key.$delimiter)
);
} else {
$flatten[$prepend.$key] = $value;
}
}
return $flatten;
} | php | public function flatten($delimiter = '.', $items = null, $prepend = '')
{
$flatten = [];
if (is_null($items)) {
$items = $this->items;
}
foreach ($items as $key => $value) {
if (is_array($value) && !empty($value)) {
$flatten = array_merge(
$flatten,
$this->flatten($delimiter, $value, $prepend.$key.$delimiter)
);
} else {
$flatten[$prepend.$key] = $value;
}
}
return $flatten;
} | [
"public",
"function",
"flatten",
"(",
"$",
"delimiter",
"=",
"'.'",
",",
"$",
"items",
"=",
"null",
",",
"$",
"prepend",
"=",
"''",
")",
"{",
"$",
"flatten",
"=",
"[",
"]",
";",
"if",
"(",
"is_null",
"(",
"$",
"items",
")",
")",
"{",
"$",
"item... | Flatten an array with the given character as a key delimiter
@param string $delimiter
@param array|null $items
@param string $prepend
@return array | [
"Flatten",
"an",
"array",
"with",
"the",
"given",
"character",
"as",
"a",
"key",
"delimiter"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L143-L163 |
adbario/php-dot-notation | src/Dot.php | Dot.getArrayItems | protected function getArrayItems($items)
{
if (is_array($items)) {
return $items;
} elseif ($items instanceof self) {
return $items->all();
}
return (array) $items;
} | php | protected function getArrayItems($items)
{
if (is_array($items)) {
return $items;
} elseif ($items instanceof self) {
return $items->all();
}
return (array) $items;
} | [
"protected",
"function",
"getArrayItems",
"(",
"$",
"items",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"items",
")",
")",
"{",
"return",
"$",
"items",
";",
"}",
"elseif",
"(",
"$",
"items",
"instanceof",
"self",
")",
"{",
"return",
"$",
"items",
"->... | Return the given items as an array
@param mixed $items
@return array | [
"Return",
"the",
"given",
"items",
"as",
"an",
"array"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L205-L214 |
adbario/php-dot-notation | src/Dot.php | Dot.mergeRecursive | public function mergeRecursive($key, $value = [])
{
if (is_array($key)) {
$this->items = array_merge_recursive($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_merge_recursive($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_merge_recursive($this->items, $key->all());
}
} | php | public function mergeRecursive($key, $value = [])
{
if (is_array($key)) {
$this->items = array_merge_recursive($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_merge_recursive($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_merge_recursive($this->items, $key->all());
}
} | [
"public",
"function",
"mergeRecursive",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"key",
")",
")",
"{",
"$",
"this",
"->",
"items",
"=",
"array_merge_recursive",
"(",
"$",
"this",
"->",
"items",
"... | Recursively merge a given array or a Dot object with the given key
or with the whole Dot object.
Duplicate keys are converted to arrays.
@param array|string|self $key
@param array|self $value | [
"Recursively",
"merge",
"a",
"given",
"array",
"or",
"a",
"Dot",
"object",
"with",
"the",
"given",
"key",
"or",
"with",
"the",
"whole",
"Dot",
"object",
"."
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L302-L314 |
adbario/php-dot-notation | src/Dot.php | Dot.mergeRecursiveDistinct | public function mergeRecursiveDistinct($key, $value = [])
{
if (is_array($key)) {
$this->items = $this->arrayMergeRecursiveDistinct($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = $this->arrayMergeRecursiveDistinct($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = $this->arrayMergeRecursiveDistinct($this->items, $key->all());
}
} | php | public function mergeRecursiveDistinct($key, $value = [])
{
if (is_array($key)) {
$this->items = $this->arrayMergeRecursiveDistinct($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = $this->arrayMergeRecursiveDistinct($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = $this->arrayMergeRecursiveDistinct($this->items, $key->all());
}
} | [
"public",
"function",
"mergeRecursiveDistinct",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"key",
")",
")",
"{",
"$",
"this",
"->",
"items",
"=",
"$",
"this",
"->",
"arrayMergeRecursiveDistinct",
"(",
... | Recursively merge a given array or a Dot object with the given key
or with the whole Dot object.
Instead of converting duplicate keys to arrays, the value from
given array will replace the value in Dot object.
@param array|string|self $key
@param array|self $value | [
"Recursively",
"merge",
"a",
"given",
"array",
"or",
"a",
"Dot",
"object",
"with",
"the",
"given",
"key",
"or",
"with",
"the",
"whole",
"Dot",
"object",
"."
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L326-L338 |
adbario/php-dot-notation | src/Dot.php | Dot.pull | public function pull($key = null, $default = null)
{
if (is_null($key)) {
$value = $this->all();
$this->clear();
return $value;
}
$value = $this->get($key, $default);
$this->delete($key);
return $value;
} | php | public function pull($key = null, $default = null)
{
if (is_null($key)) {
$value = $this->all();
$this->clear();
return $value;
}
$value = $this->get($key, $default);
$this->delete($key);
return $value;
} | [
"public",
"function",
"pull",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"all",
"(",
")",
";",
"$",
"this",
"->",
"clea... | Return the value of a given key and
delete the key
@param int|string|null $key
@param mixed $default
@return mixed | [
"Return",
"the",
"value",
"of",
"a",
"given",
"key",
"and",
"delete",
"the",
"key"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L372-L385 |
adbario/php-dot-notation | src/Dot.php | Dot.push | public function push($key, $value = null)
{
if (is_null($value)) {
$this->items[] = $key;
return;
}
$items = $this->get($key);
if (is_array($items) || is_null($items)) {
$items[] = $value;
$this->set($key, $items);
}
} | php | public function push($key, $value = null)
{
if (is_null($value)) {
$this->items[] = $key;
return;
}
$items = $this->get($key);
if (is_array($items) || is_null($items)) {
$items[] = $value;
$this->set($key, $items);
}
} | [
"public",
"function",
"push",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"value",
")",
")",
"{",
"$",
"this",
"->",
"items",
"[",
"]",
"=",
"$",
"key",
";",
"return",
";",
"}",
"$",
"items",
"="... | Push a given value to the end of the array
in a given key
@param mixed $key
@param mixed $value | [
"Push",
"a",
"given",
"value",
"to",
"the",
"end",
"of",
"the",
"array",
"in",
"a",
"given",
"key"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L394-L408 |
adbario/php-dot-notation | src/Dot.php | Dot.replace | public function replace($key, $value = [])
{
if (is_array($key)) {
$this->items = array_replace($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_replace($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_replace($this->items, $key->all());
}
} | php | public function replace($key, $value = [])
{
if (is_array($key)) {
$this->items = array_replace($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_replace($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_replace($this->items, $key->all());
}
} | [
"public",
"function",
"replace",
"(",
"$",
"key",
",",
"$",
"value",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"key",
")",
")",
"{",
"$",
"this",
"->",
"items",
"=",
"array_replace",
"(",
"$",
"this",
"->",
"items",
",",
"$",
"k... | Replace all values or values within the given key
with an array or Dot object
@param array|string|self $key
@param array|self $value | [
"Replace",
"all",
"values",
"or",
"values",
"within",
"the",
"given",
"key",
"with",
"an",
"array",
"or",
"Dot",
"object"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L417-L429 |
adbario/php-dot-notation | src/Dot.php | Dot.set | public function set($keys, $value = null)
{
if (is_array($keys)) {
foreach ($keys as $key => $value) {
$this->set($key, $value);
}
return;
}
$items = &$this->items;
foreach (explode('.', $keys) as $key) {
if (!isset($items[$key]) || !is_array($items[$key])) {
$items[$key] = [];
}
$items = &$items[$key];
}
$items = $value;
} | php | public function set($keys, $value = null)
{
if (is_array($keys)) {
foreach ($keys as $key => $value) {
$this->set($key, $value);
}
return;
}
$items = &$this->items;
foreach (explode('.', $keys) as $key) {
if (!isset($items[$key]) || !is_array($items[$key])) {
$items[$key] = [];
}
$items = &$items[$key];
}
$items = $value;
} | [
"public",
"function",
"set",
"(",
"$",
"keys",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"keys",
")",
")",
"{",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"... | Set a given key / value pair or pairs
@param array|int|string $keys
@param mixed $value | [
"Set",
"a",
"given",
"key",
"/",
"value",
"pair",
"or",
"pairs"
] | train | https://github.com/adbario/php-dot-notation/blob/eee4fc81296531e6aafba4c2bbccfc5adab1676e/src/Dot.php#L437-L458 |
calinrada/php-apidoc | Extractor.php | Extractor.getClassAnnotations | public static function getClassAnnotations($className)
{
if (!isset(self::$annotationCache[$className])) {
$class = new \ReflectionClass($className);
self::$annotationCache[$className] = self::parseAnnotations($class->getDocComment());
}
return self::$annotationCache[$className];
} | php | public static function getClassAnnotations($className)
{
if (!isset(self::$annotationCache[$className])) {
$class = new \ReflectionClass($className);
self::$annotationCache[$className] = self::parseAnnotations($class->getDocComment());
}
return self::$annotationCache[$className];
} | [
"public",
"static",
"function",
"getClassAnnotations",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"annotationCache",
"[",
"$",
"className",
"]",
")",
")",
"{",
"$",
"class",
"=",
"new",
"\\",
"ReflectionClass",
"(",... | Gets all anotations with pattern @SomeAnnotation() from a given class
@param string $className class name to get annotations
@return array self::$annotationCache all annotated elements | [
"Gets",
"all",
"anotations",
"with",
"pattern",
"@SomeAnnotation",
"()",
"from",
"a",
"given",
"class"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Extractor.php#L69-L77 |
calinrada/php-apidoc | Extractor.php | Extractor.getMethodAnnotations | public static function getMethodAnnotations($className, $methodName)
{
if (!isset(self::$annotationCache[$className . '::' . $methodName])) {
try {
$method = new \ReflectionMethod($className, $methodName);
$class = new \ReflectionClass($className);
$annotations = self::consolidateAnnotations($method->getDocComment(), $class->getDocComment());
} catch (\ReflectionException $e) {
$annotations = array();
}
self::$annotationCache[$className . '::' . $methodName] = $annotations;
}
return self::$annotationCache[$className . '::' . $methodName];
} | php | public static function getMethodAnnotations($className, $methodName)
{
if (!isset(self::$annotationCache[$className . '::' . $methodName])) {
try {
$method = new \ReflectionMethod($className, $methodName);
$class = new \ReflectionClass($className);
$annotations = self::consolidateAnnotations($method->getDocComment(), $class->getDocComment());
} catch (\ReflectionException $e) {
$annotations = array();
}
self::$annotationCache[$className . '::' . $methodName] = $annotations;
}
return self::$annotationCache[$className . '::' . $methodName];
} | [
"public",
"static",
"function",
"getMethodAnnotations",
"(",
"$",
"className",
",",
"$",
"methodName",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"annotationCache",
"[",
"$",
"className",
".",
"'::'",
".",
"$",
"methodName",
"]",
")",
")"... | Gets all anotations with pattern @SomeAnnotation() from a determinated method of a given class
@param string $className class name
@param string $methodName method name to get annotations
@return array self::$annotationCache all annotated elements of a method given | [
"Gets",
"all",
"anotations",
"with",
"pattern",
"@SomeAnnotation",
"()",
"from",
"a",
"determinated",
"method",
"of",
"a",
"given",
"class"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Extractor.php#L97-L112 |
calinrada/php-apidoc | Extractor.php | Extractor.getMethodAnnotationsObjects | public function getMethodAnnotationsObjects($className, $methodName)
{
$annotations = $this->getMethodAnnotations($className, $methodName);
$objects = array();
$i = 0;
foreach ($annotations as $annotationClass => $listParams) {
$annotationClass = ucfirst($annotationClass);
$class = $this->defaultNamespace . $annotationClass . 'Annotation';
// verify is the annotation class exists, depending if Annotations::strict is true
// if not, just skip the annotation instance creation.
if (! class_exists($class)) {
if ($this->strict) {
throw new Exception(sprintf('Runtime Error: Annotation Class Not Found: %s', $class));
} else {
// silent skip & continue
continue;
}
}
if (empty($objects[$annotationClass])) {
$objects[$annotationClass] = new $class();
}
foreach ($listParams as $params) {
if (is_array($params)) {
foreach ($params as $key => $value) {
$objects[$annotationClass]->set($key, $value);
}
} else {
$objects[$annotationClass]->set($i++, $params);
}
}
}
return $objects;
} | php | public function getMethodAnnotationsObjects($className, $methodName)
{
$annotations = $this->getMethodAnnotations($className, $methodName);
$objects = array();
$i = 0;
foreach ($annotations as $annotationClass => $listParams) {
$annotationClass = ucfirst($annotationClass);
$class = $this->defaultNamespace . $annotationClass . 'Annotation';
// verify is the annotation class exists, depending if Annotations::strict is true
// if not, just skip the annotation instance creation.
if (! class_exists($class)) {
if ($this->strict) {
throw new Exception(sprintf('Runtime Error: Annotation Class Not Found: %s', $class));
} else {
// silent skip & continue
continue;
}
}
if (empty($objects[$annotationClass])) {
$objects[$annotationClass] = new $class();
}
foreach ($listParams as $params) {
if (is_array($params)) {
foreach ($params as $key => $value) {
$objects[$annotationClass]->set($key, $value);
}
} else {
$objects[$annotationClass]->set($i++, $params);
}
}
}
return $objects;
} | [
"public",
"function",
"getMethodAnnotationsObjects",
"(",
"$",
"className",
",",
"$",
"methodName",
")",
"{",
"$",
"annotations",
"=",
"$",
"this",
"->",
"getMethodAnnotations",
"(",
"$",
"className",
",",
"$",
"methodName",
")",
";",
"$",
"objects",
"=",
"a... | Gets all anotations with pattern @SomeAnnotation() from a determinated method of a given class
and instance its abcAnnotation class
@param string $className class name
@param string $methodName method name to get annotations
@return array self::$annotationCache all annotated objects of a method given | [
"Gets",
"all",
"anotations",
"with",
"pattern",
"@SomeAnnotation",
"()",
"from",
"a",
"determinated",
"method",
"of",
"a",
"given",
"class",
"and",
"instance",
"its",
"abcAnnotation",
"class"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Extractor.php#L122-L160 |
calinrada/php-apidoc | Extractor.php | Extractor.parseAnnotations | private static function parseAnnotations($docblock)
{
$annotations = array();
// Strip away the docblock header and footer to ease parsing of one line annotations
$docblock = substr($docblock, 3, -2);
if (preg_match_all('/@(?<name>[A-Za-z_-]+)[\s\t]*\((?<args>(?:(?!\)).)*)\)\r?/s', $docblock, $matches)) {
$numMatches = count($matches[0]);
for ($i = 0; $i < $numMatches; ++$i) {
// annotations has arguments
if (isset($matches['args'][$i])) {
$argsParts = trim($matches['args'][$i]);
$name = $matches['name'][$i];
$value = self::parseArgs($argsParts);
} else {
$value = array();
}
$annotations[$name][] = $value;
}
}
return $annotations;
} | php | private static function parseAnnotations($docblock)
{
$annotations = array();
// Strip away the docblock header and footer to ease parsing of one line annotations
$docblock = substr($docblock, 3, -2);
if (preg_match_all('/@(?<name>[A-Za-z_-]+)[\s\t]*\((?<args>(?:(?!\)).)*)\)\r?/s', $docblock, $matches)) {
$numMatches = count($matches[0]);
for ($i = 0; $i < $numMatches; ++$i) {
// annotations has arguments
if (isset($matches['args'][$i])) {
$argsParts = trim($matches['args'][$i]);
$name = $matches['name'][$i];
$value = self::parseArgs($argsParts);
} else {
$value = array();
}
$annotations[$name][] = $value;
}
}
return $annotations;
} | [
"private",
"static",
"function",
"parseAnnotations",
"(",
"$",
"docblock",
")",
"{",
"$",
"annotations",
"=",
"array",
"(",
")",
";",
"// Strip away the docblock header and footer to ease parsing of one line annotations",
"$",
"docblock",
"=",
"substr",
"(",
"$",
"docbl... | Parse annotations
@param string $docblock
@return array parsed annotations params | [
"Parse",
"annotations"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Extractor.php#L200-L225 |
calinrada/php-apidoc | Extractor.php | Extractor.parseArgs | private static function parseArgs($content)
{
// Replace initial stars
$content = preg_replace('/^\s*\*/m', '', $content);
$data = array();
$len = strlen($content);
$i = 0;
$var = '';
$val = '';
$level = 1;
$prevDelimiter = '';
$nextDelimiter = '';
$nextToken = '';
$composing = false;
$type = 'plain';
$delimiter = null;
$quoted = false;
$tokens = array('"', '"', '{', '}', ',', '=');
while ($i <= $len) {
$prev_c = substr($content, $i -1, 1);
$c = substr($content, $i++, 1);
if ($c === '"' && $prev_c !== "\\") {
$delimiter = $c;
//open delimiter
if (!$composing && empty($prevDelimiter) && empty($nextDelimiter)) {
$prevDelimiter = $nextDelimiter = $delimiter;
$val = '';
$composing = true;
$quoted = true;
} else {
// close delimiter
if ($c !== $nextDelimiter) {
throw new Exception(sprintf(
"Parse Error: enclosing error -> expected: [%s], given: [%s]",
$nextDelimiter, $c
));
}
// validating syntax
if ($i < $len) {
if (',' !== substr($content, $i, 1) && '\\' !== $prev_c) {
throw new Exception(sprintf(
"Parse Error: missing comma separator near: ...%s<--",
substr($content, ($i-10), $i)
));
}
}
$prevDelimiter = $nextDelimiter = '';
$composing = false;
$delimiter = null;
}
} elseif (!$composing && in_array($c, $tokens)) {
switch ($c) {
case '=':
$prevDelimiter = $nextDelimiter = '';
$level = 2;
$composing = false;
$type = 'assoc';
$quoted = false;
break;
case ',':
$level = 3;
// If composing flag is true yet,
// it means that the string was not enclosed, so it is parsing error.
if ($composing === true && !empty($prevDelimiter) && !empty($nextDelimiter)) {
throw new Exception(sprintf(
"Parse Error: enclosing error -> expected: [%s], given: [%s]",
$nextDelimiter, $c
));
}
$prevDelimiter = $nextDelimiter = '';
break;
case '{':
$subc = '';
$subComposing = true;
while ($i <= $len) {
$c = substr($content, $i++, 1);
if (isset($delimiter) && $c === $delimiter) {
throw new Exception(sprintf(
"Parse Error: Composite variable is not enclosed correctly."
));
}
if ($c === '}') {
$subComposing = false;
break;
}
$subc .= $c;
}
// if the string is composing yet means that the structure of var. never was enclosed with '}'
if ($subComposing) {
throw new Exception(sprintf(
"Parse Error: Composite variable is not enclosed correctly. near: ...%s'",
$subc
));
}
$val = self::parseArgs($subc);
break;
}
} else {
if ($level == 1) {
$var .= $c;
} elseif ($level == 2) {
$val .= $c;
}
}
if ($level === 3 || $i === $len) {
if ($type == 'plain' && $i === $len) {
$data = self::castValue($var);
} else {
$data[trim($var)] = self::castValue($val, !$quoted);
}
$level = 1;
$var = $val = '';
$composing = false;
$quoted = false;
}
}
return $data;
} | php | private static function parseArgs($content)
{
// Replace initial stars
$content = preg_replace('/^\s*\*/m', '', $content);
$data = array();
$len = strlen($content);
$i = 0;
$var = '';
$val = '';
$level = 1;
$prevDelimiter = '';
$nextDelimiter = '';
$nextToken = '';
$composing = false;
$type = 'plain';
$delimiter = null;
$quoted = false;
$tokens = array('"', '"', '{', '}', ',', '=');
while ($i <= $len) {
$prev_c = substr($content, $i -1, 1);
$c = substr($content, $i++, 1);
if ($c === '"' && $prev_c !== "\\") {
$delimiter = $c;
//open delimiter
if (!$composing && empty($prevDelimiter) && empty($nextDelimiter)) {
$prevDelimiter = $nextDelimiter = $delimiter;
$val = '';
$composing = true;
$quoted = true;
} else {
// close delimiter
if ($c !== $nextDelimiter) {
throw new Exception(sprintf(
"Parse Error: enclosing error -> expected: [%s], given: [%s]",
$nextDelimiter, $c
));
}
// validating syntax
if ($i < $len) {
if (',' !== substr($content, $i, 1) && '\\' !== $prev_c) {
throw new Exception(sprintf(
"Parse Error: missing comma separator near: ...%s<--",
substr($content, ($i-10), $i)
));
}
}
$prevDelimiter = $nextDelimiter = '';
$composing = false;
$delimiter = null;
}
} elseif (!$composing && in_array($c, $tokens)) {
switch ($c) {
case '=':
$prevDelimiter = $nextDelimiter = '';
$level = 2;
$composing = false;
$type = 'assoc';
$quoted = false;
break;
case ',':
$level = 3;
// If composing flag is true yet,
// it means that the string was not enclosed, so it is parsing error.
if ($composing === true && !empty($prevDelimiter) && !empty($nextDelimiter)) {
throw new Exception(sprintf(
"Parse Error: enclosing error -> expected: [%s], given: [%s]",
$nextDelimiter, $c
));
}
$prevDelimiter = $nextDelimiter = '';
break;
case '{':
$subc = '';
$subComposing = true;
while ($i <= $len) {
$c = substr($content, $i++, 1);
if (isset($delimiter) && $c === $delimiter) {
throw new Exception(sprintf(
"Parse Error: Composite variable is not enclosed correctly."
));
}
if ($c === '}') {
$subComposing = false;
break;
}
$subc .= $c;
}
// if the string is composing yet means that the structure of var. never was enclosed with '}'
if ($subComposing) {
throw new Exception(sprintf(
"Parse Error: Composite variable is not enclosed correctly. near: ...%s'",
$subc
));
}
$val = self::parseArgs($subc);
break;
}
} else {
if ($level == 1) {
$var .= $c;
} elseif ($level == 2) {
$val .= $c;
}
}
if ($level === 3 || $i === $len) {
if ($type == 'plain' && $i === $len) {
$data = self::castValue($var);
} else {
$data[trim($var)] = self::castValue($val, !$quoted);
}
$level = 1;
$var = $val = '';
$composing = false;
$quoted = false;
}
}
return $data;
} | [
"private",
"static",
"function",
"parseArgs",
"(",
"$",
"content",
")",
"{",
"// Replace initial stars",
"$",
"content",
"=",
"preg_replace",
"(",
"'/^\\s*\\*/m'",
",",
"''",
",",
"$",
"content",
")",
";",
"$",
"data",
"=",
"array",
"(",
")",
";",
"$",
"... | Parse individual annotation arguments
@param string $content arguments string
@return array annotated arguments | [
"Parse",
"individual",
"annotation",
"arguments"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Extractor.php#L233-L366 |
calinrada/php-apidoc | Extractor.php | Extractor.castValue | private static function castValue($val, $trim = false)
{
if (is_array($val)) {
foreach ($val as $key => $value) {
$val[$key] = self::castValue($value);
}
} elseif (is_string($val)) {
if ($trim) {
$val = trim($val);
}
$val = stripslashes($val);
$tmp = strtolower($val);
if ($tmp === 'false' || $tmp === 'true') {
$val = $tmp === 'true';
} elseif (is_numeric($val)) {
return $val + 0;
}
unset($tmp);
}
return $val;
} | php | private static function castValue($val, $trim = false)
{
if (is_array($val)) {
foreach ($val as $key => $value) {
$val[$key] = self::castValue($value);
}
} elseif (is_string($val)) {
if ($trim) {
$val = trim($val);
}
$val = stripslashes($val);
$tmp = strtolower($val);
if ($tmp === 'false' || $tmp === 'true') {
$val = $tmp === 'true';
} elseif (is_numeric($val)) {
return $val + 0;
}
unset($tmp);
}
return $val;
} | [
"private",
"static",
"function",
"castValue",
"(",
"$",
"val",
",",
"$",
"trim",
"=",
"false",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"val",
")",
")",
"{",
"foreach",
"(",
"$",
"val",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"va... | Try determinate the original type variable of a string
@param string $val string containing possibles variables that can be cast to bool or int
@param boolean $trim indicate if the value passed should be trimmed after to try cast
@return mixed returns the value converted to original type if was possible | [
"Try",
"determinate",
"the",
"original",
"type",
"variable",
"of",
"a",
"string"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Extractor.php#L375-L398 |
calinrada/php-apidoc | View/JsonView.php | JsonView.render | public function render()
{
$data = json_encode($this->st_data, JSON_FORCE_OBJECT);
$response = new \Crada\Apidoc\Response();
$response->setContentType('application/json');
$response->closeConection();
$response->send($data);
} | php | public function render()
{
$data = json_encode($this->st_data, JSON_FORCE_OBJECT);
$response = new \Crada\Apidoc\Response();
$response->setContentType('application/json');
$response->closeConection();
$response->send($data);
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"data",
"=",
"json_encode",
"(",
"$",
"this",
"->",
"st_data",
",",
"JSON_FORCE_OBJECT",
")",
";",
"$",
"response",
"=",
"new",
"\\",
"Crada",
"\\",
"Apidoc",
"\\",
"Response",
"(",
")",
";",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/View/JsonView.php#L16-L24 |
calinrada/php-apidoc | Template.php | Template.parse | public function parse( $template_file )
{
if ( file_exists( $template_file ) ) {
$content = file_get_contents($template_file);
foreach ( $this->vars as $key => $value ) {
if ( is_array( $value ) ) {
$content = $this->parsePair($key, $value, $content);
} else {
$content = $this->parseSingle($key, (string) $value, $content);
}
}
return $content;
} else {
exit( '<h1>Template error</h1>' );
}
} | php | public function parse( $template_file )
{
if ( file_exists( $template_file ) ) {
$content = file_get_contents($template_file);
foreach ( $this->vars as $key => $value ) {
if ( is_array( $value ) ) {
$content = $this->parsePair($key, $value, $content);
} else {
$content = $this->parseSingle($key, (string) $value, $content);
}
}
return $content;
} else {
exit( '<h1>Template error</h1>' );
}
} | [
"public",
"function",
"parse",
"(",
"$",
"template_file",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"template_file",
")",
")",
"{",
"$",
"content",
"=",
"file_get_contents",
"(",
"$",
"template_file",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"var... | Parse template file
@access public
@param string $template_file | [
"Parse",
"template",
"file"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Template.php#L46-L63 |
calinrada/php-apidoc | Template.php | Template.parseSingle | private function parseSingle( $key, $value, $string, $index = null )
{
if ( isset( $index ) ) {
$string = str_replace( $this->l_delim . '%index%' . $this->r_delim, $index, $string );
}
return str_replace( $this->l_delim . $key . $this->r_delim, $value, $string );
} | php | private function parseSingle( $key, $value, $string, $index = null )
{
if ( isset( $index ) ) {
$string = str_replace( $this->l_delim . '%index%' . $this->r_delim, $index, $string );
}
return str_replace( $this->l_delim . $key . $this->r_delim, $value, $string );
} | [
"private",
"function",
"parseSingle",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"string",
",",
"$",
"index",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"index",
")",
")",
"{",
"$",
"string",
"=",
"str_replace",
"(",
"$",
"this",
"->... | Parsing content for single varliable
@access private
@param string $key property name
@param string $value property value
@param string $string content to replace
@param integer $index index of loop item
@return string replaced content | [
"Parsing",
"content",
"for",
"single",
"varliable"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Template.php#L74-L80 |
calinrada/php-apidoc | Template.php | Template.parsePair | private function parsePair( $variable, $data, $string )
{
$match = $this->matchPair($string, $variable);
if( $match == false ) return $string;
$str = '';
foreach ( $data as $k_row => $row ) {
$temp = $match['1'];
foreach( $row as $key => $val ) {
if( !is_array( $val ) ) {
$index = array_search( $k_row, array_keys( $data ) );
$temp = $this->parseSingle( $key, $val, $temp, $index );
} else {
$temp = $this->parsePair( $key, $val, $temp );
}
}
$str .= $temp;
}
return str_replace( $match['0'], $str, $string );
} | php | private function parsePair( $variable, $data, $string )
{
$match = $this->matchPair($string, $variable);
if( $match == false ) return $string;
$str = '';
foreach ( $data as $k_row => $row ) {
$temp = $match['1'];
foreach( $row as $key => $val ) {
if( !is_array( $val ) ) {
$index = array_search( $k_row, array_keys( $data ) );
$temp = $this->parseSingle( $key, $val, $temp, $index );
} else {
$temp = $this->parsePair( $key, $val, $temp );
}
}
$str .= $temp;
}
return str_replace( $match['0'], $str, $string );
} | [
"private",
"function",
"parsePair",
"(",
"$",
"variable",
",",
"$",
"data",
",",
"$",
"string",
")",
"{",
"$",
"match",
"=",
"$",
"this",
"->",
"matchPair",
"(",
"$",
"string",
",",
"$",
"variable",
")",
";",
"if",
"(",
"$",
"match",
"==",
"false",... | Parsing content for loop varliable
@access private
@param string $variable loop name
@param string $value loop data
@param string $string content to replace
@return string replaced content | [
"Parsing",
"content",
"for",
"loop",
"varliable"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Template.php#L90-L110 |
calinrada/php-apidoc | Template.php | Template.matchPair | private function matchPair( $string, $variable )
{
if ( !preg_match("|" . preg_quote($this->l_delim) . 'loop ' . $variable . preg_quote($this->r_delim) . "(.+?)". preg_quote($this->l_delim) . 'end loop' . preg_quote($this->r_delim) . "|s", $string, $match ) ) {
return false;
}
return $match;
} | php | private function matchPair( $string, $variable )
{
if ( !preg_match("|" . preg_quote($this->l_delim) . 'loop ' . $variable . preg_quote($this->r_delim) . "(.+?)". preg_quote($this->l_delim) . 'end loop' . preg_quote($this->r_delim) . "|s", $string, $match ) ) {
return false;
}
return $match;
} | [
"private",
"function",
"matchPair",
"(",
"$",
"string",
",",
"$",
"variable",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"\"|\"",
".",
"preg_quote",
"(",
"$",
"this",
"->",
"l_delim",
")",
".",
"'loop '",
".",
"$",
"variable",
".",
"preg_quote",
"(",... | Match loop pair
@access private
@param string $string content with loop
@param string $variable loop name
@return string matched content | [
"Match",
"loop",
"pair"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Template.php#L119-L126 |
calinrada/php-apidoc | Builder.php | Builder.generateTemplate | protected function generateTemplate()
{
$st_annotations = $this->extractAnnotations();
$template = array();
$counter = 0;
$section = null;
$partial_template = $this->loadPartialTemplate('main');
foreach ($st_annotations as $class => $methods) {
foreach ($methods as $name => $docs) {
if (isset($docs['ApiDescription'][0]['section'])) {
$section = $docs['ApiDescription'][0]['section'];
}elseif(isset($docs['ApiSector'][0]['name'])){
$section = $docs['ApiSector'][0]['name'];
}else{
$section = $class;
}
if (0 === count($docs)) {
continue;
}
$sampleOutput = $this->generateSampleOutput($docs, $counter);
$tr = array(
'{{ elt_id }}' => $counter,
'{{ method }}' => $this->generateBadgeForMethod($docs),
'{{ route }}' => $docs['ApiRoute'][0]['name'],
'{{ description }}' => $docs['ApiDescription'][0]['description'],
'{{ headers }}' => $this->generateHeadersTemplate($counter, $docs),
'{{ parameters }}' => $this->generateParamsTemplate($counter, $docs),
'{{ body }}' => $this->generateBodyTemplate($counter, $docs),
'{{ sandbox_form }}' => $this->generateSandboxForm($docs, $counter),
'{{ sample_response_headers }}' => $sampleOutput[0],
'{{ sample_response_body }}' => $sampleOutput[1]
);
$template[$section][] = strtr($partial_template, $tr);
$counter++;
}
}
$output = '';
foreach ($template as $key => $value) {
array_unshift($value, '<h2>' . $key . '</h2>');
$output .= implode(PHP_EOL, $value);
}
$this->saveTemplate($output, $this->_output_file);
return true;
} | php | protected function generateTemplate()
{
$st_annotations = $this->extractAnnotations();
$template = array();
$counter = 0;
$section = null;
$partial_template = $this->loadPartialTemplate('main');
foreach ($st_annotations as $class => $methods) {
foreach ($methods as $name => $docs) {
if (isset($docs['ApiDescription'][0]['section'])) {
$section = $docs['ApiDescription'][0]['section'];
}elseif(isset($docs['ApiSector'][0]['name'])){
$section = $docs['ApiSector'][0]['name'];
}else{
$section = $class;
}
if (0 === count($docs)) {
continue;
}
$sampleOutput = $this->generateSampleOutput($docs, $counter);
$tr = array(
'{{ elt_id }}' => $counter,
'{{ method }}' => $this->generateBadgeForMethod($docs),
'{{ route }}' => $docs['ApiRoute'][0]['name'],
'{{ description }}' => $docs['ApiDescription'][0]['description'],
'{{ headers }}' => $this->generateHeadersTemplate($counter, $docs),
'{{ parameters }}' => $this->generateParamsTemplate($counter, $docs),
'{{ body }}' => $this->generateBodyTemplate($counter, $docs),
'{{ sandbox_form }}' => $this->generateSandboxForm($docs, $counter),
'{{ sample_response_headers }}' => $sampleOutput[0],
'{{ sample_response_body }}' => $sampleOutput[1]
);
$template[$section][] = strtr($partial_template, $tr);
$counter++;
}
}
$output = '';
foreach ($template as $key => $value) {
array_unshift($value, '<h2>' . $key . '</h2>');
$output .= implode(PHP_EOL, $value);
}
$this->saveTemplate($output, $this->_output_file);
return true;
} | [
"protected",
"function",
"generateTemplate",
"(",
")",
"{",
"$",
"st_annotations",
"=",
"$",
"this",
"->",
"extractAnnotations",
"(",
")",
";",
"$",
"template",
"=",
"array",
"(",
")",
";",
"$",
"counter",
"=",
"0",
";",
"$",
"section",
"=",
"null",
";... | Generate the content of the documentation
@return boolean | [
"Generate",
"the",
"content",
"of",
"the",
"documentation"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L121-L173 |
calinrada/php-apidoc | Builder.php | Builder.generateSampleOutput | protected function generateSampleOutput($st_params, $counter)
{
if (!isset($st_params['ApiReturn'])) {
$responseBody = '';
} else {
$ret = [];
$partial_template = $this->loadPartialTemplate('sampleReponseTpl');
foreach ($st_params['ApiReturn'] as $params) {
if (in_array($params['type'], array('object', 'array(object) ', 'array', 'string', 'boolean', 'integer', 'number')) && isset($params['sample'])) {
$tr = array(
'{{ elt_id }}' => $counter,
'{{ response }}' => $params['sample'],
'{{ description }}' => '',
);
if (isset($params['description'])) {
$tr['{{ description }}'] = $params['description'];
}
$ret[] = strtr($partial_template, $tr);
}
}
$responseBody = implode(PHP_EOL, $ret);
}
if(!isset($st_params['ApiReturnHeaders'])) {
$responseHeaders = '';
} else {
$ret = [];
$partial_template = $this->loadPartialTemplate('sampleReponseHeaderTpl');
foreach ($st_params['ApiReturnHeaders'] as $headers) {
if(isset($headers['sample'])) {
$tr = array(
'{{ elt_id }}' => $counter,
'{{ response }}' => $headers['sample'],
'{{ description }}' => ''
);
$ret[] = strtr($partial_template, $tr);
}
}
$responseHeaders = implode(PHP_EOL, $ret);
}
return array($responseHeaders, $responseBody);
} | php | protected function generateSampleOutput($st_params, $counter)
{
if (!isset($st_params['ApiReturn'])) {
$responseBody = '';
} else {
$ret = [];
$partial_template = $this->loadPartialTemplate('sampleReponseTpl');
foreach ($st_params['ApiReturn'] as $params) {
if (in_array($params['type'], array('object', 'array(object) ', 'array', 'string', 'boolean', 'integer', 'number')) && isset($params['sample'])) {
$tr = array(
'{{ elt_id }}' => $counter,
'{{ response }}' => $params['sample'],
'{{ description }}' => '',
);
if (isset($params['description'])) {
$tr['{{ description }}'] = $params['description'];
}
$ret[] = strtr($partial_template, $tr);
}
}
$responseBody = implode(PHP_EOL, $ret);
}
if(!isset($st_params['ApiReturnHeaders'])) {
$responseHeaders = '';
} else {
$ret = [];
$partial_template = $this->loadPartialTemplate('sampleReponseHeaderTpl');
foreach ($st_params['ApiReturnHeaders'] as $headers) {
if(isset($headers['sample'])) {
$tr = array(
'{{ elt_id }}' => $counter,
'{{ response }}' => $headers['sample'],
'{{ description }}' => ''
);
$ret[] = strtr($partial_template, $tr);
}
}
$responseHeaders = implode(PHP_EOL, $ret);
}
return array($responseHeaders, $responseBody);
} | [
"protected",
"function",
"generateSampleOutput",
"(",
"$",
"st_params",
",",
"$",
"counter",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"st_params",
"[",
"'ApiReturn'",
"]",
")",
")",
"{",
"$",
"responseBody",
"=",
"''",
";",
"}",
"else",
"{",
"$",
... | Generate the sample output
@param array $st_params
@param integer $counter
@return string | [
"Generate",
"the",
"sample",
"output"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L182-L228 |
calinrada/php-apidoc | Builder.php | Builder.generateHeadersTemplate | protected function generateHeadersTemplate($id, $st_params)
{
if (!isset($st_params['ApiHeaders']))
{
return;
}
$body = [];
$partial_template = $this->loadPartialTemplate('paramContentTpl');
foreach ($st_params['ApiHeaders'] as $params) {
$tr = array(
'{{ name }}' => $params['name'],
'{{ type }}' => $params['type'],
'{{ nullable }}' => @$params['nullable'] == '1' ? 'No' : 'Yes',
'{{ description }}' => @$params['description'],
);
$body[] = strtr($partial_template, $tr);
}
return strtr($this->loadPartialTemplate('paramTableTpl'), array('{{ tbody }}' => implode(PHP_EOL, $body)));
} | php | protected function generateHeadersTemplate($id, $st_params)
{
if (!isset($st_params['ApiHeaders']))
{
return;
}
$body = [];
$partial_template = $this->loadPartialTemplate('paramContentTpl');
foreach ($st_params['ApiHeaders'] as $params) {
$tr = array(
'{{ name }}' => $params['name'],
'{{ type }}' => $params['type'],
'{{ nullable }}' => @$params['nullable'] == '1' ? 'No' : 'Yes',
'{{ description }}' => @$params['description'],
);
$body[] = strtr($partial_template, $tr);
}
return strtr($this->loadPartialTemplate('paramTableTpl'), array('{{ tbody }}' => implode(PHP_EOL, $body)));
} | [
"protected",
"function",
"generateHeadersTemplate",
"(",
"$",
"id",
",",
"$",
"st_params",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"st_params",
"[",
"'ApiHeaders'",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"body",
"=",
"[",
"]",
";",
"$",
... | Generates the template for headers
@param int $id
@param array $st_params
@return void|string | [
"Generates",
"the",
"template",
"for",
"headers"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L236-L258 |
calinrada/php-apidoc | Builder.php | Builder.generateParamsTemplate | protected function generateParamsTemplate($id, $st_params)
{
if (!isset($st_params['ApiParams']))
{
return;
}
$body = [];
$paramSampleBtnTpl = $this->loadPartialTemplate('paramSampleBtnTpl');
$paramContentTpl = $this->loadPartialTemplate('paramContentTpl');
foreach ($st_params['ApiParams'] as $params) {
$tr = array(
'{{ name }}' => $params['name'],
'{{ type }}' => $params['type'],
'{{ nullable }}' => @$params['nullable'] == '1' ? 'No' : 'Yes',
'{{ description }}' => @$params['description'],
);
if (isset($params['sample'])) {
$tr['{{ type }}'].= ' '.strtr($paramSampleBtnTpl, array('{{ sample }}' => $params['sample']));
}
$body[] = strtr($paramContentTpl, $tr);
}
return strtr($this->loadPartialTemplate('paramTableTpl'), array('{{ tbody }}' => implode(PHP_EOL, $body)));
} | php | protected function generateParamsTemplate($id, $st_params)
{
if (!isset($st_params['ApiParams']))
{
return;
}
$body = [];
$paramSampleBtnTpl = $this->loadPartialTemplate('paramSampleBtnTpl');
$paramContentTpl = $this->loadPartialTemplate('paramContentTpl');
foreach ($st_params['ApiParams'] as $params) {
$tr = array(
'{{ name }}' => $params['name'],
'{{ type }}' => $params['type'],
'{{ nullable }}' => @$params['nullable'] == '1' ? 'No' : 'Yes',
'{{ description }}' => @$params['description'],
);
if (isset($params['sample'])) {
$tr['{{ type }}'].= ' '.strtr($paramSampleBtnTpl, array('{{ sample }}' => $params['sample']));
}
$body[] = strtr($paramContentTpl, $tr);
}
return strtr($this->loadPartialTemplate('paramTableTpl'), array('{{ tbody }}' => implode(PHP_EOL, $body)));
} | [
"protected",
"function",
"generateParamsTemplate",
"(",
"$",
"id",
",",
"$",
"st_params",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"st_params",
"[",
"'ApiParams'",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"body",
"=",
"[",
"]",
";",
"$",
"p... | Generates the template for parameters
@param int $id
@param array $st_params
@return void|string | [
"Generates",
"the",
"template",
"for",
"parameters"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L267-L294 |
calinrada/php-apidoc | Builder.php | Builder.generateBodyTemplate | private function generateBodyTemplate($id, $docs)
{
if (!isset($docs['ApiBody']))
{
return;
}
$body = $docs['ApiBody'][0];
return strtr($this->loadPartialTemplate('samplePostBodyTpl'), array(
'{{ elt_id }}' => $id,
'{{ body }}' => $body['sample']
));
} | php | private function generateBodyTemplate($id, $docs)
{
if (!isset($docs['ApiBody']))
{
return;
}
$body = $docs['ApiBody'][0];
return strtr($this->loadPartialTemplate('samplePostBodyTpl'), array(
'{{ elt_id }}' => $id,
'{{ body }}' => $body['sample']
));
} | [
"private",
"function",
"generateBodyTemplate",
"(",
"$",
"id",
",",
"$",
"docs",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"docs",
"[",
"'ApiBody'",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"body",
"=",
"$",
"docs",
"[",
"'ApiBody'",
"]",
... | Generate POST body template
@param int $id
@param array $body
@return void|string | [
"Generate",
"POST",
"body",
"template"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L303-L317 |
calinrada/php-apidoc | Builder.php | Builder.generateSandboxForm | protected function generateSandboxForm($st_params, $counter)
{
$headers = [];
$params = [];
$sandboxFormInputTpl = $this->loadPartialTemplate('sandboxFormInputTpl');
if (isset($st_params['ApiParams']) && is_array($st_params['ApiParams']))
{
foreach ($st_params['ApiParams'] as $param)
{
$params[] = strtr($sandboxFormInputTpl, [
'{{ type }}' => $param['type'],
'{{ name }}' => $param['name'],
'{{ description }}' => $param['description'],
'{{ sample }}' => $param['sample']
]);
}
}
if (isset($st_params['ApiHeaders']) && is_array($st_params['ApiHeaders']))
{
foreach ($st_params['ApiHeaders'] as $header)
{
$headers[] = strtr($sandboxFormInputTpl, [
'{{ type }}' => 'text',
'{{ name }}' => $header['name'],
'{{ description }}' => $header['description'],
'{{ sample }}' => $header['sample']
]);
}
}
$tr = array(
'{{ elt_id }}' => $counter,
'{{ method }}' => $st_params['ApiMethod'][0]['type'],
'{{ route }}' => $st_params['ApiRoute'][0]['name'],
'{{ headers }}' => implode(PHP_EOL, $headers),
'{{ params }}' => implode(PHP_EOL, $params),
);
return strtr($this->loadPartialTemplate('sandboxFormTpl'), $tr);
} | php | protected function generateSandboxForm($st_params, $counter)
{
$headers = [];
$params = [];
$sandboxFormInputTpl = $this->loadPartialTemplate('sandboxFormInputTpl');
if (isset($st_params['ApiParams']) && is_array($st_params['ApiParams']))
{
foreach ($st_params['ApiParams'] as $param)
{
$params[] = strtr($sandboxFormInputTpl, [
'{{ type }}' => $param['type'],
'{{ name }}' => $param['name'],
'{{ description }}' => $param['description'],
'{{ sample }}' => $param['sample']
]);
}
}
if (isset($st_params['ApiHeaders']) && is_array($st_params['ApiHeaders']))
{
foreach ($st_params['ApiHeaders'] as $header)
{
$headers[] = strtr($sandboxFormInputTpl, [
'{{ type }}' => 'text',
'{{ name }}' => $header['name'],
'{{ description }}' => $header['description'],
'{{ sample }}' => $header['sample']
]);
}
}
$tr = array(
'{{ elt_id }}' => $counter,
'{{ method }}' => $st_params['ApiMethod'][0]['type'],
'{{ route }}' => $st_params['ApiRoute'][0]['name'],
'{{ headers }}' => implode(PHP_EOL, $headers),
'{{ params }}' => implode(PHP_EOL, $params),
);
return strtr($this->loadPartialTemplate('sandboxFormTpl'), $tr);
} | [
"protected",
"function",
"generateSandboxForm",
"(",
"$",
"st_params",
",",
"$",
"counter",
")",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"$",
"params",
"=",
"[",
"]",
";",
"$",
"sandboxFormInputTpl",
"=",
"$",
"this",
"->",
"loadPartialTemplate",
"(",
"... | Generate route paramteres form
@param array $st_params
@param integer $counter
@return void|mixed | [
"Generate",
"route",
"paramteres",
"form"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L326-L368 |
calinrada/php-apidoc | Builder.php | Builder.renderJson | public function renderJson()
{
$st_annotations = $this->extractAnnotations();
$o_view = new JsonView();
$o_view->set('annotations', $st_annotations);
$o_view->render();
} | php | public function renderJson()
{
$st_annotations = $this->extractAnnotations();
$o_view = new JsonView();
$o_view->set('annotations', $st_annotations);
$o_view->render();
} | [
"public",
"function",
"renderJson",
"(",
")",
"{",
"$",
"st_annotations",
"=",
"$",
"this",
"->",
"extractAnnotations",
"(",
")",
";",
"$",
"o_view",
"=",
"new",
"JsonView",
"(",
")",
";",
"$",
"o_view",
"->",
"set",
"(",
"'annotations'",
",",
"$",
"st... | Output the annotations in json format
@return json | [
"Output",
"the",
"annotations",
"in",
"json",
"format"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Builder.php#L410-L417 |
calinrada/php-apidoc | Response.php | Response.setHeader | public function setHeader($key, $value, $http_response_code = null)
{
header($key.': '.$value, null, $http_response_code);
} | php | public function setHeader($key, $value, $http_response_code = null)
{
header($key.': '.$value, null, $http_response_code);
} | [
"public",
"function",
"setHeader",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"http_response_code",
"=",
"null",
")",
"{",
"header",
"(",
"$",
"key",
".",
"': '",
".",
"$",
"value",
",",
"null",
",",
"$",
"http_response_code",
")",
";",
"}"
] | Set header
@param string $key
@param string $value
@param integer $http_response_code Optional
@example $response->setHeader('Content-type','application/json') | [
"Set",
"header"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/Response.php#L21-L24 |
calinrada/php-apidoc | View/BaseView.php | BaseView.getConfig | public function getConfig($s_key = null)
{
if ($s_key) {
if (isset($this->st_viewConfig[$s_key])) {
return $this->st_viewConfig[$s_key];
}
return false;
}
return $this->st_viewConfig;
} | php | public function getConfig($s_key = null)
{
if ($s_key) {
if (isset($this->st_viewConfig[$s_key])) {
return $this->st_viewConfig[$s_key];
}
return false;
}
return $this->st_viewConfig;
} | [
"public",
"function",
"getConfig",
"(",
"$",
"s_key",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"s_key",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"st_viewConfig",
"[",
"$",
"s_key",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"st_v... | Get config param(s)
@param string $s_key
@return string|array|boolean | [
"Get",
"config",
"param",
"(",
"s",
")"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/View/BaseView.php#L64-L75 |
calinrada/php-apidoc | View/BaseView.php | BaseView.set | public function set($key, $value, $b_skipKey = false)
{
if (true === $b_skipKey) {
$this->st_data = $value;
} else {
$this->st_data[$key] = $value;
}
} | php | public function set($key, $value, $b_skipKey = false)
{
if (true === $b_skipKey) {
$this->st_data = $value;
} else {
$this->st_data[$key] = $value;
}
} | [
"public",
"function",
"set",
"(",
"$",
"key",
",",
"$",
"value",
",",
"$",
"b_skipKey",
"=",
"false",
")",
"{",
"if",
"(",
"true",
"===",
"$",
"b_skipKey",
")",
"{",
"$",
"this",
"->",
"st_data",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
"... | Set parameters to render
@param string $key
@param mixed $value Value - can be string / array
@param boolean $b_skipKey If true, the value will be assign directly to $this->st_data | [
"Set",
"parameters",
"to",
"render"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/View/BaseView.php#L100-L107 |
calinrada/php-apidoc | View/BaseView.php | BaseView.render | public function render()
{
$file = str_replace('\\','/',$this->getTemplate()).'.php';
if (!file_exists($file)) {
throw new Exception('Template ' . $file . ' does not exist.');
}
extract($this->st_data);
ob_start();
include($file);
$output = ob_get_contents();
ob_end_clean();
echo $output;
} | php | public function render()
{
$file = str_replace('\\','/',$this->getTemplate()).'.php';
if (!file_exists($file)) {
throw new Exception('Template ' . $file . ' does not exist.');
}
extract($this->st_data);
ob_start();
include($file);
$output = ob_get_contents();
ob_end_clean();
echo $output;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"file",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"this",
"->",
"getTemplate",
"(",
")",
")",
".",
"'.php'",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/calinrada/php-apidoc/blob/e5c6f46cfbf3b6c20e7f55c02cc8345b65ed873f/View/BaseView.php#L129-L141 |
orchidsoftware/widget | src/Widget/WidgetServiceProvider.php | WidgetServiceProvider.boot | public function boot()
{
$this->publishes([
__DIR__ . '/../../config/widget.php' => config_path('widget.php'),
], 'config');
Blade::directive('widget', function ($expression) {
$segments = explode(',', preg_replace("/[\(\)\\\]/", '', $expression));
if (!array_key_exists(1, $segments)) {
return '<?php echo (new \Orchid\Widget\Widget)->get(' . $segments[0] . '); ?>';
}
return '<?php echo (new \Orchid\Widget\Widget)->get(' . $segments[0] . ',' . $segments[1] . '); ?>';
});
} | php | public function boot()
{
$this->publishes([
__DIR__ . '/../../config/widget.php' => config_path('widget.php'),
], 'config');
Blade::directive('widget', function ($expression) {
$segments = explode(',', preg_replace("/[\(\)\\\]/", '', $expression));
if (!array_key_exists(1, $segments)) {
return '<?php echo (new \Orchid\Widget\Widget)->get(' . $segments[0] . '); ?>';
}
return '<?php echo (new \Orchid\Widget\Widget)->get(' . $segments[0] . ',' . $segments[1] . '); ?>';
});
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/../../config/widget.php'",
"=>",
"config_path",
"(",
"'widget.php'",
")",
",",
"]",
",",
"'config'",
")",
";",
"Blade",
"::",
"directive",
"(",
"'widg... | Boot the application events. | [
"Boot",
"the",
"application",
"events",
"."
] | train | https://github.com/orchidsoftware/widget/blob/11e91d2fdbb91a97b8ea38bc72fb05d9d3ea7bc7/src/Widget/WidgetServiceProvider.php#L18-L35 |
orchidsoftware/widget | src/Widget/Widget.php | Widget.get | public function get(string $key, $arg = null)
{
$widget = $this->getWidgetFromConfig($key);
return $widget->handler($arg);
} | php | public function get(string $key, $arg = null)
{
$widget = $this->getWidgetFromConfig($key);
return $widget->handler($arg);
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"key",
",",
"$",
"arg",
"=",
"null",
")",
"{",
"$",
"widget",
"=",
"$",
"this",
"->",
"getWidgetFromConfig",
"(",
"$",
"key",
")",
";",
"return",
"$",
"widget",
"->",
"handler",
"(",
"$",
"arg",
")",... | @param $key
@param null $arg
@return mixed | [
"@param",
"$key",
"@param",
"null",
"$arg"
] | train | https://github.com/orchidsoftware/widget/blob/11e91d2fdbb91a97b8ea38bc72fb05d9d3ea7bc7/src/Widget/Widget.php#L18-L23 |
cartalyst/stripe-laravel | src/StripeServiceProvider.php | StripeServiceProvider.registerStripe | protected function registerStripe()
{
$this->app->singleton('stripe', function ($app) {
$config = $app['config']->get('services.stripe');
$secret = isset($config['secret']) ? $config['secret'] : null;
$version = isset($config['version']) ? $config['version'] : null;
return new Stripe($secret, $version);
});
$this->app->alias('stripe', 'Cartalyst\Stripe\Stripe');
} | php | protected function registerStripe()
{
$this->app->singleton('stripe', function ($app) {
$config = $app['config']->get('services.stripe');
$secret = isset($config['secret']) ? $config['secret'] : null;
$version = isset($config['version']) ? $config['version'] : null;
return new Stripe($secret, $version);
});
$this->app->alias('stripe', 'Cartalyst\Stripe\Stripe');
} | [
"protected",
"function",
"registerStripe",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"singleton",
"(",
"'stripe'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"$",
"config",
"=",
"$",
"app",
"[",
"'config'",
"]",
"->",
"get",
"(",
"'services.strip... | Register the Stripe API class.
@return void | [
"Register",
"the",
"Stripe",
"API",
"class",
"."
] | train | https://github.com/cartalyst/stripe-laravel/blob/52188fe02d12b5e7451f71bc485c036c19763a0b/src/StripeServiceProvider.php#L53-L66 |
cartalyst/stripe-laravel | src/StripeServiceProvider.php | StripeServiceProvider.registerConfig | protected function registerConfig()
{
$this->app->singleton('stripe.config', function ($app) {
return $app['stripe']->getConfig();
});
$this->app->alias('stripe.config', 'Cartalyst\Stripe\Config');
$this->app->alias('stripe.config', 'Cartalyst\Stripe\ConfigInterface');
} | php | protected function registerConfig()
{
$this->app->singleton('stripe.config', function ($app) {
return $app['stripe']->getConfig();
});
$this->app->alias('stripe.config', 'Cartalyst\Stripe\Config');
$this->app->alias('stripe.config', 'Cartalyst\Stripe\ConfigInterface');
} | [
"protected",
"function",
"registerConfig",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"singleton",
"(",
"'stripe.config'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"$",
"app",
"[",
"'stripe'",
"]",
"->",
"getConfig",
"(",
")",
";",
"}"... | Register the config class.
@return void | [
"Register",
"the",
"config",
"class",
"."
] | train | https://github.com/cartalyst/stripe-laravel/blob/52188fe02d12b5e7451f71bc485c036c19763a0b/src/StripeServiceProvider.php#L73-L82 |
Dealerdirect/phpcodesniffer-composer-installer | src/Plugin.php | Plugin.run | public static function run(Event $event)
{
$io = $event->getIO();
$composer = $event->getComposer();
$instance = new static();
$instance->io = $io;
$instance->composer = $composer;
$instance->init();
$instance->onDependenciesChangedEvent();
} | php | public static function run(Event $event)
{
$io = $event->getIO();
$composer = $event->getComposer();
$instance = new static();
$instance->io = $io;
$instance->composer = $composer;
$instance->init();
$instance->onDependenciesChangedEvent();
} | [
"public",
"static",
"function",
"run",
"(",
"Event",
"$",
"event",
")",
"{",
"$",
"io",
"=",
"$",
"event",
"->",
"getIO",
"(",
")",
";",
"$",
"composer",
"=",
"$",
"event",
"->",
"getComposer",
"(",
")",
";",
"$",
"instance",
"=",
"new",
"static",
... | Triggers the plugin's main functionality.
Makes it possible to run the plugin as a custom command.
@param Event $event
@throws \InvalidArgumentException
@throws \RuntimeException
@throws LogicException
@throws ProcessFailedException
@throws RuntimeException | [
"Triggers",
"the",
"plugin",
"s",
"main",
"functionality",
"."
] | train | https://github.com/Dealerdirect/phpcodesniffer-composer-installer/blob/e749410375ff6fb7a040a68878c656c2e610b132/src/Plugin.php#L93-L104 |
Dealerdirect/phpcodesniffer-composer-installer | src/Plugin.php | Plugin.init | private function init()
{
$this->cwd = getcwd();
$this->installedPaths = array();
$this->processExecutor = new ProcessExecutor($this->io);
$this->filesystem = new Filesystem($this->processExecutor);
} | php | private function init()
{
$this->cwd = getcwd();
$this->installedPaths = array();
$this->processExecutor = new ProcessExecutor($this->io);
$this->filesystem = new Filesystem($this->processExecutor);
} | [
"private",
"function",
"init",
"(",
")",
"{",
"$",
"this",
"->",
"cwd",
"=",
"getcwd",
"(",
")",
";",
"$",
"this",
"->",
"installedPaths",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"processExecutor",
"=",
"new",
"ProcessExecutor",
"(",
"$",
"th... | Prepares the plugin so it's main functionality can be run.
@throws \RuntimeException
@throws LogicException
@throws ProcessFailedException
@throws RuntimeException | [
"Prepares",
"the",
"plugin",
"so",
"it",
"s",
"main",
"functionality",
"can",
"be",
"run",
"."
] | train | https://github.com/Dealerdirect/phpcodesniffer-composer-installer/blob/e749410375ff6fb7a040a68878c656c2e610b132/src/Plugin.php#L130-L137 |
Dealerdirect/phpcodesniffer-composer-installer | src/Plugin.php | Plugin.onDependenciesChangedEvent | public function onDependenciesChangedEvent()
{
$io = $this->io;
$isVerbose = $io->isVerbose();
if ($isVerbose) {
$io->write(sprintf('<info>%s</info>', self::MESSAGE_RUNNING_INSTALLER));
}
if ($this->isPHPCodeSnifferInstalled() === true) {
$this->loadInstalledPaths();
$installPathCleaned = $this->cleanInstalledPaths();
$installPathUpdated = $this->updateInstalledPaths();
if ($installPathCleaned === true || $installPathUpdated === true) {
$this->saveInstalledPaths();
} elseif ($isVerbose) {
$io->write(sprintf('<info>%s</info>', self::MESSAGE_NOTHING_TO_INSTALL));
}
} elseif ($isVerbose) {
$io->write(sprintf('<info>%s</info>', self::MESSAGE_NOT_INSTALLED));
}
} | php | public function onDependenciesChangedEvent()
{
$io = $this->io;
$isVerbose = $io->isVerbose();
if ($isVerbose) {
$io->write(sprintf('<info>%s</info>', self::MESSAGE_RUNNING_INSTALLER));
}
if ($this->isPHPCodeSnifferInstalled() === true) {
$this->loadInstalledPaths();
$installPathCleaned = $this->cleanInstalledPaths();
$installPathUpdated = $this->updateInstalledPaths();
if ($installPathCleaned === true || $installPathUpdated === true) {
$this->saveInstalledPaths();
} elseif ($isVerbose) {
$io->write(sprintf('<info>%s</info>', self::MESSAGE_NOTHING_TO_INSTALL));
}
} elseif ($isVerbose) {
$io->write(sprintf('<info>%s</info>', self::MESSAGE_NOT_INSTALLED));
}
} | [
"public",
"function",
"onDependenciesChangedEvent",
"(",
")",
"{",
"$",
"io",
"=",
"$",
"this",
"->",
"io",
";",
"$",
"isVerbose",
"=",
"$",
"io",
"->",
"isVerbose",
"(",
")",
";",
"if",
"(",
"$",
"isVerbose",
")",
"{",
"$",
"io",
"->",
"write",
"(... | Entry point for post install and post update events.
@throws \InvalidArgumentException
@throws LogicException
@throws ProcessFailedException
@throws RuntimeException | [
"Entry",
"point",
"for",
"post",
"install",
"and",
"post",
"update",
"events",
"."
] | train | https://github.com/Dealerdirect/phpcodesniffer-composer-installer/blob/e749410375ff6fb7a040a68878c656c2e610b132/src/Plugin.php#L162-L184 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.