repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
indeyets/pake | lib/pake/pakeGlobToRegex.class.php | pakeGlobToRegex.glob_to_regex | public static function glob_to_regex($glob)
{
$first_byte = true;
$escaping = false;
$in_curlies = 0;
$regex = '';
for ($i = 0; $i < strlen($glob); $i++)
{
$car = $glob[$i];
if ($first_byte)
{
if (self::$strict_leading_dot && $car != '.')
{
$regex .= '(?=[^\.])';
}
$first_byte = false;
}
if ($car == '/')
{
$first_byte = true;
}
if ($car == '.' || $car == '(' || $car == ')' || $car == '|' || $car == '+' || $car == '^' || $car == '$')
{
$regex .= "\\$car";
}
else if ($car == '*')
{
$regex .= ($escaping ? "\\*" : (self::$strict_wildcard_slash ? "[^/]*" : ".*"));
}
else if ($car == '?')
{
$regex .= ($escaping ? "\\?" : (self::$strict_wildcard_slash ? "[^/]" : "."));
}
else if ($car == '{')
{
$regex .= ($escaping ? "\\{" : "(");
if (!$escaping) ++$in_curlies;
}
else if ($car == '}' && $in_curlies)
{
$regex .= ($escaping ? "}" : ")");
if (!$escaping) --$in_curlies;
}
else if ($car == ',' && $in_curlies)
{
$regex .= ($escaping ? "," : "|");
}
else if ($car == "\\")
{
if ($escaping)
{
$regex .= "\\\\";
$escaping = false;
}
else
{
$escaping = true;
}
continue;
}
else
{
$regex .= $car;
$escaping = false;
}
$escaping = false;
}
return "#^$regex$#";
} | php | public static function glob_to_regex($glob)
{
$first_byte = true;
$escaping = false;
$in_curlies = 0;
$regex = '';
for ($i = 0; $i < strlen($glob); $i++)
{
$car = $glob[$i];
if ($first_byte)
{
if (self::$strict_leading_dot && $car != '.')
{
$regex .= '(?=[^\.])';
}
$first_byte = false;
}
if ($car == '/')
{
$first_byte = true;
}
if ($car == '.' || $car == '(' || $car == ')' || $car == '|' || $car == '+' || $car == '^' || $car == '$')
{
$regex .= "\\$car";
}
else if ($car == '*')
{
$regex .= ($escaping ? "\\*" : (self::$strict_wildcard_slash ? "[^/]*" : ".*"));
}
else if ($car == '?')
{
$regex .= ($escaping ? "\\?" : (self::$strict_wildcard_slash ? "[^/]" : "."));
}
else if ($car == '{')
{
$regex .= ($escaping ? "\\{" : "(");
if (!$escaping) ++$in_curlies;
}
else if ($car == '}' && $in_curlies)
{
$regex .= ($escaping ? "}" : ")");
if (!$escaping) --$in_curlies;
}
else if ($car == ',' && $in_curlies)
{
$regex .= ($escaping ? "," : "|");
}
else if ($car == "\\")
{
if ($escaping)
{
$regex .= "\\\\";
$escaping = false;
}
else
{
$escaping = true;
}
continue;
}
else
{
$regex .= $car;
$escaping = false;
}
$escaping = false;
}
return "#^$regex$#";
} | [
"public",
"static",
"function",
"glob_to_regex",
"(",
"$",
"glob",
")",
"{",
"$",
"first_byte",
"=",
"true",
";",
"$",
"escaping",
"=",
"false",
";",
"$",
"in_curlies",
"=",
"0",
";",
"$",
"regex",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
... | Returns a compiled regex which is the equiavlent of the globbing pattern.
@param string glob pattern
@return string regex | [
"Returns",
"a",
"compiled",
"regex",
"which",
"is",
"the",
"equiavlent",
"of",
"the",
"globbing",
"pattern",
"."
] | 22b4e1da921c7626bb0e1fd0538a16562129be83 | https://github.com/indeyets/pake/blob/22b4e1da921c7626bb0e1fd0538a16562129be83/lib/pake/pakeGlobToRegex.class.php#L60-L133 | train |
ARCANEDEV/Breadcrumbs | src/Builder.php | Builder.call | public function call($name, array $params = [])
{
$this->checkName($name);
array_unshift($params, $this);
call_user_func_array($this->callbacks[$name], $params);
return $this;
} | php | public function call($name, array $params = [])
{
$this->checkName($name);
array_unshift($params, $this);
call_user_func_array($this->callbacks[$name], $params);
return $this;
} | [
"public",
"function",
"call",
"(",
"$",
"name",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"checkName",
"(",
"$",
"name",
")",
";",
"array_unshift",
"(",
"$",
"params",
",",
"$",
"this",
")",
";",
"call_user_func_array",... | Call breadcrumb.
@param string $name
@param array $params
@return self | [
"Call",
"breadcrumb",
"."
] | ce6a8cd4213cef2ebb978fe7d53850e886735a08 | https://github.com/ARCANEDEV/Breadcrumbs/blob/ce6a8cd4213cef2ebb978fe7d53850e886735a08/src/Builder.php#L96-L104 | train |
ARCANEDEV/Breadcrumbs | src/Builder.php | Builder.push | public function push($title, $url = null, array $data = [])
{
$this->breadcrumbs->addOne($title, $url, $data);
return $this;
} | php | public function push($title, $url = null, array $data = [])
{
$this->breadcrumbs->addOne($title, $url, $data);
return $this;
} | [
"public",
"function",
"push",
"(",
"$",
"title",
",",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"breadcrumbs",
"->",
"addOne",
"(",
"$",
"title",
",",
"$",
"url",
",",
"$",
"data",
")",
";",... | Push a breadcrumb.
@param string $title
@param string|null $url
@param array $data
@return self | [
"Push",
"a",
"breadcrumb",
"."
] | ce6a8cd4213cef2ebb978fe7d53850e886735a08 | https://github.com/ARCANEDEV/Breadcrumbs/blob/ce6a8cd4213cef2ebb978fe7d53850e886735a08/src/Builder.php#L125-L130 | train |
Arara/Process | src/Arara/Process/Control/Signal.php | Signal.handle | protected function handle($signal, $handler, $placement)
{
declare (ticks = 1);
$signalNumber = $this->translateSignal($signal);
if (is_int($handler) && in_array($handler, [SIG_IGN, SIG_DFL])) {
unset($this->handlers[$signalNumber]);
$this->registerHandler($signalNumber, $handler);
return;
}
$this->placeHandler($signalNumber, $handler, $placement);
} | php | protected function handle($signal, $handler, $placement)
{
declare (ticks = 1);
$signalNumber = $this->translateSignal($signal);
if (is_int($handler) && in_array($handler, [SIG_IGN, SIG_DFL])) {
unset($this->handlers[$signalNumber]);
$this->registerHandler($signalNumber, $handler);
return;
}
$this->placeHandler($signalNumber, $handler, $placement);
} | [
"protected",
"function",
"handle",
"(",
"$",
"signal",
",",
"$",
"handler",
",",
"$",
"placement",
")",
"{",
"declare",
"(",
"ticks",
"=",
"1",
")",
";",
"$",
"signalNumber",
"=",
"$",
"this",
"->",
"translateSignal",
"(",
"$",
"signal",
")",
";",
"i... | Define a handler for the given signal.
@param string|int $signal Signal name, PCNTL constant name or PCNTL constant value.
@param callable|int $handler The signal handler.
@param string $placement Placement of handler ("set", "append" or "prepend"). | [
"Define",
"a",
"handler",
"for",
"the",
"given",
"signal",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Signal.php#L98-L112 | train |
Arara/Process | src/Arara/Process/Control/Signal.php | Signal.placeHandler | protected function placeHandler($signalNumber, callable $handler, $placement)
{
if (! isset($this->handlers[$signalNumber])) {
$this->handlers[$signalNumber] = [];
$this->registerHandler($signalNumber, $this);
}
switch ($placement) {
case 'set':
$this->handlers[$signalNumber] = [$handler];
break;
case 'append':
array_push($this->handlers[$signalNumber], $handler);
break;
case 'prepend':
array_unshift($this->handlers[$signalNumber], $handler);
break;
}
} | php | protected function placeHandler($signalNumber, callable $handler, $placement)
{
if (! isset($this->handlers[$signalNumber])) {
$this->handlers[$signalNumber] = [];
$this->registerHandler($signalNumber, $this);
}
switch ($placement) {
case 'set':
$this->handlers[$signalNumber] = [$handler];
break;
case 'append':
array_push($this->handlers[$signalNumber], $handler);
break;
case 'prepend':
array_unshift($this->handlers[$signalNumber], $handler);
break;
}
} | [
"protected",
"function",
"placeHandler",
"(",
"$",
"signalNumber",
",",
"callable",
"$",
"handler",
",",
"$",
"placement",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"handlers",
"[",
"$",
"signalNumber",
"]",
")",
")",
"{",
"$",
"this",... | Define a callback handler for the given signal.
@param int $signalNumber Signal number.
@param callable $handler The signal handler.
@param string $placement Placement of handler ("set", "append" or "prepend"). | [
"Define",
"a",
"callback",
"handler",
"for",
"the",
"given",
"signal",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Signal.php#L121-L141 | train |
Arara/Process | src/Arara/Process/Control/Signal.php | Signal.getHandlers | public function getHandlers($signal)
{
$signalNumber = $this->translateSignal($signal);
$handlers = [];
if (isset($this->handlers[$signalNumber])) {
$handlers = $this->handlers[$signalNumber];
}
return $handlers;
} | php | public function getHandlers($signal)
{
$signalNumber = $this->translateSignal($signal);
$handlers = [];
if (isset($this->handlers[$signalNumber])) {
$handlers = $this->handlers[$signalNumber];
}
return $handlers;
} | [
"public",
"function",
"getHandlers",
"(",
"$",
"signal",
")",
"{",
"$",
"signalNumber",
"=",
"$",
"this",
"->",
"translateSignal",
"(",
"$",
"signal",
")",
";",
"$",
"handlers",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"handler... | Returns handlers of a specific signal.
@param int|string $signal
@return array | [
"Returns",
"handlers",
"of",
"a",
"specific",
"signal",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Signal.php#L150-L159 | train |
Arara/Process | src/Arara/Process/Control/Signal.php | Signal.send | public function send($signal, $processId = null)
{
if (null === $processId) {
$processId = posix_getpid();
}
return posix_kill($processId, $this->translateSignal($signal));
} | php | public function send($signal, $processId = null)
{
if (null === $processId) {
$processId = posix_getpid();
}
return posix_kill($processId, $this->translateSignal($signal));
} | [
"public",
"function",
"send",
"(",
"$",
"signal",
",",
"$",
"processId",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"processId",
")",
"{",
"$",
"processId",
"=",
"posix_getpid",
"(",
")",
";",
"}",
"return",
"posix_kill",
"(",
"$",
"proces... | Send a signal to a process.
@param int|string $signal Signal (code or name) to send.
@param int $processId Process id to send signal, if not defined will use the current one.
@return bool | [
"Send",
"a",
"signal",
"to",
"a",
"process",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Signal.php#L208-L215 | train |
Arara/Process | src/Arara/Process/Control/Signal.php | Signal.translateSignal | protected function translateSignal($signal)
{
if (isset($this->signals[$signal])) {
$signal = $this->signals[$signal];
} elseif (defined($signal)) {
$signal = constant($signal);
}
if (! is_int($signal)) {
throw new InvalidArgumentException('The given value is not a valid signal');
}
return $signal;
} | php | protected function translateSignal($signal)
{
if (isset($this->signals[$signal])) {
$signal = $this->signals[$signal];
} elseif (defined($signal)) {
$signal = constant($signal);
}
if (! is_int($signal)) {
throw new InvalidArgumentException('The given value is not a valid signal');
}
return $signal;
} | [
"protected",
"function",
"translateSignal",
"(",
"$",
"signal",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"signals",
"[",
"$",
"signal",
"]",
")",
")",
"{",
"$",
"signal",
"=",
"$",
"this",
"->",
"signals",
"[",
"$",
"signal",
"]",
";",... | Translate signals names to codes.
@param string|int $signal Signal name, PCNTL constant name or PCNTL constant value.
@throws InvalidArgumentException Then signal is not a valid signal.
@return int | [
"Translate",
"signals",
"names",
"to",
"codes",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Signal.php#L227-L240 | train |
swoft-cloud/swoft-session | src/SessionManager.php | SessionManager.createHandlerByConfig | public function createHandlerByConfig(): \SessionHandlerInterface
{
if (!isset($this->getConfig()['driver'])) {
throw new \InvalidArgumentException('Session driver required');
}
$handler = $this->getHandler($this->getConfig()['driver']);
$handler instanceof LifetimeInterface && $handler->setLifetime($this->getConfig()['lifetime']);
return $handler;
} | php | public function createHandlerByConfig(): \SessionHandlerInterface
{
if (!isset($this->getConfig()['driver'])) {
throw new \InvalidArgumentException('Session driver required');
}
$handler = $this->getHandler($this->getConfig()['driver']);
$handler instanceof LifetimeInterface && $handler->setLifetime($this->getConfig()['lifetime']);
return $handler;
} | [
"public",
"function",
"createHandlerByConfig",
"(",
")",
":",
"\\",
"SessionHandlerInterface",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"getConfig",
"(",
")",
"[",
"'driver'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",... | Create a handler by config
@return \SessionHandlerInterface
@throws \InvalidArgumentException | [
"Create",
"a",
"handler",
"by",
"config"
] | f141f7c0b496ff24709a1f72a25ba22f36dcfb60 | https://github.com/swoft-cloud/swoft-session/blob/f141f7c0b496ff24709a1f72a25ba22f36dcfb60/src/SessionManager.php#L41-L49 | train |
swoft-cloud/swoft-session | src/SessionManager.php | SessionManager.getHandler | public function getHandler(string $name): \SessionHandlerInterface
{
$name = strtolower($name);
$this->isValidate($name);
return App::getBean($this->handlers[$name]);
} | php | public function getHandler(string $name): \SessionHandlerInterface
{
$name = strtolower($name);
$this->isValidate($name);
return App::getBean($this->handlers[$name]);
} | [
"public",
"function",
"getHandler",
"(",
"string",
"$",
"name",
")",
":",
"\\",
"SessionHandlerInterface",
"{",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"$",
"this",
"->",
"isValidate",
"(",
"$",
"name",
")",
";",
"return",
"App",
":... | Get a handler by name
@param string $name
@return \SessionHandlerInterface
@throws \InvalidArgumentException | [
"Get",
"a",
"handler",
"by",
"name"
] | f141f7c0b496ff24709a1f72a25ba22f36dcfb60 | https://github.com/swoft-cloud/swoft-session/blob/f141f7c0b496ff24709a1f72a25ba22f36dcfb60/src/SessionManager.php#L58-L63 | train |
bldr-io/bldr | src/Application.php | Application.buildContainer | private function buildContainer(InputInterface $input, OutputInterface $output)
{
$nonContainerCommands = ['blocks-install', 'blocks-update', 'blocks-dumpautoload', 'help'];
if (in_array($input->getFirstArgument(), $nonContainerCommands)) {
return;
}
$this->container = new ContainerBuilder($this, $input, $output);
$this->container->compile();
} | php | private function buildContainer(InputInterface $input, OutputInterface $output)
{
$nonContainerCommands = ['blocks-install', 'blocks-update', 'blocks-dumpautoload', 'help'];
if (in_array($input->getFirstArgument(), $nonContainerCommands)) {
return;
}
$this->container = new ContainerBuilder($this, $input, $output);
$this->container->compile();
} | [
"private",
"function",
"buildContainer",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"nonContainerCommands",
"=",
"[",
"'blocks-install'",
",",
"'blocks-update'",
",",
"'blocks-dumpautoload'",
",",
"'help'",
"]",
";",
... | Builds the container with extensions
@param InputInterface $input
@param OutputInterface $output
@throws InvalidArgumentException | [
"Builds",
"the",
"container",
"with",
"extensions"
] | 60bc51ff248bd237c13f1811c95a9a33f9d38aab | https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/Application.php#L187-L197 | train |
bldr-io/bldr | src/Application.php | Application.find | public function find($name)
{
try {
return parent::find($name);
} catch (\InvalidArgumentException $e) {
$this->shortcut = true;
return parent::find('run');
}
} | php | public function find($name)
{
try {
return parent::find($name);
} catch (\InvalidArgumentException $e) {
$this->shortcut = true;
return parent::find('run');
}
} | [
"public",
"function",
"find",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"return",
"parent",
"::",
"find",
"(",
"$",
"name",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"shortcut",
"=",
"true",
... | Falls back to "run" for a shortcut
@param string $name
@return Command | [
"Falls",
"back",
"to",
"run",
"for",
"a",
"shortcut"
] | 60bc51ff248bd237c13f1811c95a9a33f9d38aab | https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/Application.php#L206-L215 | train |
bldr-io/bldr | src/Block/Watch/Task/WatchTask.php | WatchTask.getJobs | private function getJobs()
{
if ($this->hasParameter('profile')) {
$this->fetchJobs($this->getParameter('profile'));
return;
}
$this->buildJobs([$this->getParameter('job')]);
} | php | private function getJobs()
{
if ($this->hasParameter('profile')) {
$this->fetchJobs($this->getParameter('profile'));
return;
}
$this->buildJobs([$this->getParameter('job')]);
} | [
"private",
"function",
"getJobs",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasParameter",
"(",
"'profile'",
")",
")",
"{",
"$",
"this",
"->",
"fetchJobs",
"(",
"$",
"this",
"->",
"getParameter",
"(",
"'profile'",
")",
")",
";",
"return",
";",
"}... | Fetches the tasks for either the profile, or the passed task | [
"Fetches",
"the",
"tasks",
"for",
"either",
"the",
"profile",
"or",
"the",
"passed",
"task"
] | 60bc51ff248bd237c13f1811c95a9a33f9d38aab | https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/Block/Watch/Task/WatchTask.php#L136-L145 | train |
titledk/silverstripe-calendar | code/events/Event.php | Event.setEnd | public function setEnd($end, $write=true)
{
$e = $this;
if ($e->TimeFrameType == 'DateTime') {
$e->EndDateTime = $end;
} elseif ($e->TimeFrameType == 'Duration') {
$duration = $this->calcDurationBasedOnEndDateTime($end);
if ($duration) {
$e->Duration = $duration;
} else {
//if duration is more than 1 day, make the time frame "DateTime"
$e->TimeFrameType = 'DateTime';
$e->EndDateTime = $end;
}
}
if ($write) {
$e->write();
}
} | php | public function setEnd($end, $write=true)
{
$e = $this;
if ($e->TimeFrameType == 'DateTime') {
$e->EndDateTime = $end;
} elseif ($e->TimeFrameType == 'Duration') {
$duration = $this->calcDurationBasedOnEndDateTime($end);
if ($duration) {
$e->Duration = $duration;
} else {
//if duration is more than 1 day, make the time frame "DateTime"
$e->TimeFrameType = 'DateTime';
$e->EndDateTime = $end;
}
}
if ($write) {
$e->write();
}
} | [
"public",
"function",
"setEnd",
"(",
"$",
"end",
",",
"$",
"write",
"=",
"true",
")",
"{",
"$",
"e",
"=",
"$",
"this",
";",
"if",
"(",
"$",
"e",
"->",
"TimeFrameType",
"==",
"'DateTime'",
")",
"{",
"$",
"e",
"->",
"EndDateTime",
"=",
"$",
"end",
... | Set new end date
@param string $end Should be SS_Datetime compatible
@param boolean $write If true, write to the db | [
"Set",
"new",
"end",
"date"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/events/Event.php#L206-L226 | train |
titledk/silverstripe-calendar | code/events/Event.php | Event.calcEndDateTimeBasedOnDuration | public function calcEndDateTimeBasedOnDuration()
{
$duration = $this->Duration;
$secs = (substr($duration, 0, 2) * 3600) + (substr($duration, 3, 2) * 60);
$startDate = strtotime($this->StartDateTime);
$endDate = $startDate + $secs;
$formatDate = date("Y-m-d H:i:s", $endDate);
return $formatDate;
} | php | public function calcEndDateTimeBasedOnDuration()
{
$duration = $this->Duration;
$secs = (substr($duration, 0, 2) * 3600) + (substr($duration, 3, 2) * 60);
$startDate = strtotime($this->StartDateTime);
$endDate = $startDate + $secs;
$formatDate = date("Y-m-d H:i:s", $endDate);
return $formatDate;
} | [
"public",
"function",
"calcEndDateTimeBasedOnDuration",
"(",
")",
"{",
"$",
"duration",
"=",
"$",
"this",
"->",
"Duration",
";",
"$",
"secs",
"=",
"(",
"substr",
"(",
"$",
"duration",
",",
"0",
",",
"2",
")",
"*",
"3600",
")",
"+",
"(",
"substr",
"("... | Calculation of end date based on duration
Should only be used in OnBeforeWrite
@return string | [
"Calculation",
"of",
"end",
"date",
"based",
"on",
"duration",
"Should",
"only",
"be",
"used",
"in",
"OnBeforeWrite"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/events/Event.php#L234-L244 | train |
titledk/silverstripe-calendar | code/events/Event.php | Event.calcDurationBasedOnEndDateTime | public function calcDurationBasedOnEndDateTime($end)
{
$startDate = strtotime($this->StartDateTime);
$endDate = strtotime($end);
$duration = $endDate - $startDate;
$secsInDay = 60 * 60 * 24;
if ($duration > $secsInDay) {
//Duration cannot be more than 24h
return false;
}
//info on this calculation here:
//http://stackoverflow.com/questions/3856293/how-to-convert-seconds-to-time-format
$formatDate = gmdate("H:i", $duration);
return $formatDate;
} | php | public function calcDurationBasedOnEndDateTime($end)
{
$startDate = strtotime($this->StartDateTime);
$endDate = strtotime($end);
$duration = $endDate - $startDate;
$secsInDay = 60 * 60 * 24;
if ($duration > $secsInDay) {
//Duration cannot be more than 24h
return false;
}
//info on this calculation here:
//http://stackoverflow.com/questions/3856293/how-to-convert-seconds-to-time-format
$formatDate = gmdate("H:i", $duration);
return $formatDate;
} | [
"public",
"function",
"calcDurationBasedOnEndDateTime",
"(",
"$",
"end",
")",
"{",
"$",
"startDate",
"=",
"strtotime",
"(",
"$",
"this",
"->",
"StartDateTime",
")",
";",
"$",
"endDate",
"=",
"strtotime",
"(",
"$",
"end",
")",
";",
"$",
"duration",
"=",
"... | Calculation of duration based on end datetime
Returns false if there's more than 24h between start and end date
@return string|false | [
"Calculation",
"of",
"duration",
"based",
"on",
"end",
"datetime",
"Returns",
"false",
"if",
"there",
"s",
"more",
"than",
"24h",
"between",
"start",
"and",
"end",
"date"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/events/Event.php#L251-L268 | train |
titledk/silverstripe-calendar | code/events/Event.php | Event.isAllDay | public function isAllDay()
{
if ($this->AllDay) {
return true;
}
$secsInDay = 60 * 60 * 24;
$startTime = strtotime($this->StartDateTime);
$endTime = strtotime($this->EndDateTime);
if (($endTime - $startTime) > $secsInDay) {
return true;
}
} | php | public function isAllDay()
{
if ($this->AllDay) {
return true;
}
$secsInDay = 60 * 60 * 24;
$startTime = strtotime($this->StartDateTime);
$endTime = strtotime($this->EndDateTime);
if (($endTime - $startTime) > $secsInDay) {
return true;
}
} | [
"public",
"function",
"isAllDay",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"AllDay",
")",
"{",
"return",
"true",
";",
"}",
"$",
"secsInDay",
"=",
"60",
"*",
"60",
"*",
"24",
";",
"$",
"startTime",
"=",
"strtotime",
"(",
"$",
"this",
"->",
"St... | All Day getter
Any events that spans more than 24h will be displayed as allday events
Beyond that those events marked as all day events will also be displayed as such
@return boolean | [
"All",
"Day",
"getter",
"Any",
"events",
"that",
"spans",
"more",
"than",
"24h",
"will",
"be",
"displayed",
"as",
"allday",
"events",
"Beyond",
"that",
"those",
"events",
"marked",
"as",
"all",
"day",
"events",
"will",
"also",
"be",
"displayed",
"as",
"suc... | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/events/Event.php#L276-L289 | train |
titledk/silverstripe-calendar | code/events/Event.php | Event.getFrontEndFields | public function getFrontEndFields($params = null)
{
//parent::getFrontEndFields($params);
$timeFrameHeaderText = 'Time Frame';
if (!CalendarConfig::subpackage_setting('events', 'force_end')) {
$timeFrameHeaderText = 'End Date / Time (optional)';
}
$fields = FieldList::create(
TextField::create('Title')
->setAttribute('placeholder', 'Enter a title'),
CheckboxField::create('AllDay', 'All-day'),
$startDateTime = DatetimeField::create('StartDateTime', 'Start'),
//NoEnd field - will only be shown if end dates are not enforced - see below
CheckboxField::create('NoEnd', 'Open End'),
HeaderField::create('TimeFrameHeader', $timeFrameHeaderText, 5),
//LiteralField::create('TimeFrameText','<em class="TimeFrameText">Choose the type of time frame you\'d like to enter</em>'),
SelectionGroup::create('TimeFrameType', array(
"Duration//Duration" => TimeField::create('Duration', '')->setRightTitle('up to 24h')
->setAttribute('placeholder', 'Enter duration'),
"DateTime//Date/Time" => $endDateTime = DateTimeField::create('EndDateTime', '')
)
),
LiteralField::create('Clear', '<div class="clear"></div>')
);
//Date field settings
$timeExpl = 'Time, e.g. 11:15am or 15:30';
//$startDateTime->setConfig('datavalueformat', 'YYYY-MM-dd HH:mm');
//$endDateTime->setConfig('datavalueformat', 'YYYY-MM-dd HH:mm');
$startDateTime->getDateField()
->setConfig('showcalendar', 1)
//->setRightTitle('Date')
->setAttribute('placeholder', 'Enter date')
->setAttribute('readonly', 'true'); //we only want input through the datepicker
$startDateTime->getTimeField()
//->setRightTitle($timeExpl)
//->setConfig('timeformat', 'h:mm') //this is the default, that seems to be giving some troubles: h:mm:ss a
->setConfig('timeformat', 'HH:mm') //24h format
->setAttribute('placeholder', 'Enter time');
$endDateTime->getDateField()
->setConfig('showcalendar', 1)
//->setRightTitle('Date')
->setAttribute('placeholder', 'Enter date')
->setAttribute('readonly', 'true'); //we only want input through the datepicker
$endDateTime->getTimeField()
//->setRightTitle($timeExpl)
->setConfig('timeformat', 'HH:mm') //24h fromat
->setAttribute('placeholder', 'Enter time');
//removing AllDay checkbox if allday events are disabled
if (!CalendarConfig::subpackage_setting('events', 'enable_allday_events')) {
$fields->removeByName('AllDay');
}
//removing NoEnd checkbox if end dates are enforced
if (CalendarConfig::subpackage_setting('events', 'force_end')) {
$fields->removeByName('NoEnd');
} else {
//we don't want the NoEnd checkbox when creating new events
if (!$this->ID) {
//$fields->removeByName('NoEnd');
}
}
$this->extend('updateFrontEndFields', $fields);
return $fields;
} | php | public function getFrontEndFields($params = null)
{
//parent::getFrontEndFields($params);
$timeFrameHeaderText = 'Time Frame';
if (!CalendarConfig::subpackage_setting('events', 'force_end')) {
$timeFrameHeaderText = 'End Date / Time (optional)';
}
$fields = FieldList::create(
TextField::create('Title')
->setAttribute('placeholder', 'Enter a title'),
CheckboxField::create('AllDay', 'All-day'),
$startDateTime = DatetimeField::create('StartDateTime', 'Start'),
//NoEnd field - will only be shown if end dates are not enforced - see below
CheckboxField::create('NoEnd', 'Open End'),
HeaderField::create('TimeFrameHeader', $timeFrameHeaderText, 5),
//LiteralField::create('TimeFrameText','<em class="TimeFrameText">Choose the type of time frame you\'d like to enter</em>'),
SelectionGroup::create('TimeFrameType', array(
"Duration//Duration" => TimeField::create('Duration', '')->setRightTitle('up to 24h')
->setAttribute('placeholder', 'Enter duration'),
"DateTime//Date/Time" => $endDateTime = DateTimeField::create('EndDateTime', '')
)
),
LiteralField::create('Clear', '<div class="clear"></div>')
);
//Date field settings
$timeExpl = 'Time, e.g. 11:15am or 15:30';
//$startDateTime->setConfig('datavalueformat', 'YYYY-MM-dd HH:mm');
//$endDateTime->setConfig('datavalueformat', 'YYYY-MM-dd HH:mm');
$startDateTime->getDateField()
->setConfig('showcalendar', 1)
//->setRightTitle('Date')
->setAttribute('placeholder', 'Enter date')
->setAttribute('readonly', 'true'); //we only want input through the datepicker
$startDateTime->getTimeField()
//->setRightTitle($timeExpl)
//->setConfig('timeformat', 'h:mm') //this is the default, that seems to be giving some troubles: h:mm:ss a
->setConfig('timeformat', 'HH:mm') //24h format
->setAttribute('placeholder', 'Enter time');
$endDateTime->getDateField()
->setConfig('showcalendar', 1)
//->setRightTitle('Date')
->setAttribute('placeholder', 'Enter date')
->setAttribute('readonly', 'true'); //we only want input through the datepicker
$endDateTime->getTimeField()
//->setRightTitle($timeExpl)
->setConfig('timeformat', 'HH:mm') //24h fromat
->setAttribute('placeholder', 'Enter time');
//removing AllDay checkbox if allday events are disabled
if (!CalendarConfig::subpackage_setting('events', 'enable_allday_events')) {
$fields->removeByName('AllDay');
}
//removing NoEnd checkbox if end dates are enforced
if (CalendarConfig::subpackage_setting('events', 'force_end')) {
$fields->removeByName('NoEnd');
} else {
//we don't want the NoEnd checkbox when creating new events
if (!$this->ID) {
//$fields->removeByName('NoEnd');
}
}
$this->extend('updateFrontEndFields', $fields);
return $fields;
} | [
"public",
"function",
"getFrontEndFields",
"(",
"$",
"params",
"=",
"null",
")",
"{",
"//parent::getFrontEndFields($params);",
"$",
"timeFrameHeaderText",
"=",
"'Time Frame'",
";",
"if",
"(",
"!",
"CalendarConfig",
"::",
"subpackage_setting",
"(",
"'events'",
",",
"... | Frontend fields
Simple list of the basic fields - how they're intended to be edited | [
"Frontend",
"fields",
"Simple",
"list",
"of",
"the",
"basic",
"fields",
"-",
"how",
"they",
"re",
"intended",
"to",
"be",
"edited"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/events/Event.php#L296-L369 | train |
titledk/silverstripe-calendar | code/fullcalendar/FullcalendarController.php | FullcalendarController.publicevents | public function publicevents($request, $json=true, $calendars=null, $offset=30)
{
$calendarsSupplied = false;
if ($calendars) {
$calendarsSupplied = true;
}
$events = PublicEvent::get()
->filter(array(
'StartDateTime:GreaterThan' => $this->eventlistOffsetDate('start', $request->postVar('start'), $offset),
'EndDateTime:LessThan' => $this->eventlistOffsetDate('end', $request->postVar('end'), $offset),
));
//If shaded events are enabled we need to filter shaded calendars out
//note that this only takes effect when no calendars have been supplied
//if calendars are supplied, this needs to be taken care of from that method
$sC = CalendarConfig::subpackage_settings('calendars');
if ($sC['shading']) {
if (!$calendars) {
$calendars = PublicCalendar::get();
$calendars = $calendars->filter(array(
'shaded' => false
));
}
}
if ($calendars) {
$calIDList = $calendars->getIdList();
//adding in 0 to allow for showing events without a calendar
if (!$calendarsSupplied) {
$calIDList[0] = 0;
}
//Debug::dump($calIDList);
$events = $events->filter('CalendarID', $calIDList);
}
$result = array();
if ($events) {
foreach ($events as $event) {
$calendar = $event->Calendar();
$bgColor = '#999'; //default
$textColor = '#FFF'; //default
$borderColor = '#555';
if ($calendar->exists()) {
$bgColor = $calendar->getColorWithHash();
$textColor = '#FFF';
$borderColor = $calendar->getColorWithHash();
}
$resultArr = self::format_event_for_fullcalendar($event);
$resultArr = array_merge($resultArr, array(
'backgroundColor' => $bgColor,
'textColor' => '#FFF',
'borderColor' => $borderColor,
));
$result[] = $resultArr;
}
}
if ($json) {
$response = new SS_HTTPResponse(Convert::array2json($result));
$response->addHeader('Content-Type', 'application/json');
return $response;
} else {
return $result;
}
} | php | public function publicevents($request, $json=true, $calendars=null, $offset=30)
{
$calendarsSupplied = false;
if ($calendars) {
$calendarsSupplied = true;
}
$events = PublicEvent::get()
->filter(array(
'StartDateTime:GreaterThan' => $this->eventlistOffsetDate('start', $request->postVar('start'), $offset),
'EndDateTime:LessThan' => $this->eventlistOffsetDate('end', $request->postVar('end'), $offset),
));
//If shaded events are enabled we need to filter shaded calendars out
//note that this only takes effect when no calendars have been supplied
//if calendars are supplied, this needs to be taken care of from that method
$sC = CalendarConfig::subpackage_settings('calendars');
if ($sC['shading']) {
if (!$calendars) {
$calendars = PublicCalendar::get();
$calendars = $calendars->filter(array(
'shaded' => false
));
}
}
if ($calendars) {
$calIDList = $calendars->getIdList();
//adding in 0 to allow for showing events without a calendar
if (!$calendarsSupplied) {
$calIDList[0] = 0;
}
//Debug::dump($calIDList);
$events = $events->filter('CalendarID', $calIDList);
}
$result = array();
if ($events) {
foreach ($events as $event) {
$calendar = $event->Calendar();
$bgColor = '#999'; //default
$textColor = '#FFF'; //default
$borderColor = '#555';
if ($calendar->exists()) {
$bgColor = $calendar->getColorWithHash();
$textColor = '#FFF';
$borderColor = $calendar->getColorWithHash();
}
$resultArr = self::format_event_for_fullcalendar($event);
$resultArr = array_merge($resultArr, array(
'backgroundColor' => $bgColor,
'textColor' => '#FFF',
'borderColor' => $borderColor,
));
$result[] = $resultArr;
}
}
if ($json) {
$response = new SS_HTTPResponse(Convert::array2json($result));
$response->addHeader('Content-Type', 'application/json');
return $response;
} else {
return $result;
}
} | [
"public",
"function",
"publicevents",
"(",
"$",
"request",
",",
"$",
"json",
"=",
"true",
",",
"$",
"calendars",
"=",
"null",
",",
"$",
"offset",
"=",
"30",
")",
"{",
"$",
"calendarsSupplied",
"=",
"false",
";",
"if",
"(",
"$",
"calendars",
")",
"{",... | Handles returning the JSON events data for a time range.
@param SS_HTTPRequest $request
@return SS_HTTPResponse | [
"Handles",
"returning",
"the",
"JSON",
"events",
"data",
"for",
"a",
"time",
"range",
"."
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/fullcalendar/FullcalendarController.php#L111-L181 | train |
titledk/silverstripe-calendar | code/fullcalendar/FullcalendarController.php | FullcalendarController.shadedevents | public function shadedevents($request, $json=true, $calendars = null, $offset=3000)
{
if (!$calendars) {
$calendars = PublicCalendar::get();
}
$calendars = $calendars->filter(array(
'shaded' => true
));
return $this->publicevents($request, $json, $calendars, $offset);
} | php | public function shadedevents($request, $json=true, $calendars = null, $offset=3000)
{
if (!$calendars) {
$calendars = PublicCalendar::get();
}
$calendars = $calendars->filter(array(
'shaded' => true
));
return $this->publicevents($request, $json, $calendars, $offset);
} | [
"public",
"function",
"shadedevents",
"(",
"$",
"request",
",",
"$",
"json",
"=",
"true",
",",
"$",
"calendars",
"=",
"null",
",",
"$",
"offset",
"=",
"3000",
")",
"{",
"if",
"(",
"!",
"$",
"calendars",
")",
"{",
"$",
"calendars",
"=",
"PublicCalenda... | Shaded events controller
Shaded events for the calendar are called once on calendar initialization,
hence the offset of 3000 days | [
"Shaded",
"events",
"controller",
"Shaded",
"events",
"for",
"the",
"calendar",
"are",
"called",
"once",
"on",
"calendar",
"initialization",
"hence",
"the",
"offset",
"of",
"3000",
"days"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/fullcalendar/FullcalendarController.php#L187-L197 | train |
titledk/silverstripe-calendar | code/fullcalendar/FullcalendarController.php | FullcalendarController.handleJsonResponse | public function handleJsonResponse($success = false, $retVars = null)
{
$result = array();
if ($success) {
$result = array(
'success' => $success
);
}
if ($retVars) {
$result = array_merge($retVars, $result);
}
$response = new SS_HTTPResponse(json_encode($result));
$response->addHeader('Content-Type', 'application/json');
return $response;
} | php | public function handleJsonResponse($success = false, $retVars = null)
{
$result = array();
if ($success) {
$result = array(
'success' => $success
);
}
if ($retVars) {
$result = array_merge($retVars, $result);
}
$response = new SS_HTTPResponse(json_encode($result));
$response->addHeader('Content-Type', 'application/json');
return $response;
} | [
"public",
"function",
"handleJsonResponse",
"(",
"$",
"success",
"=",
"false",
",",
"$",
"retVars",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"success",
")",
"{",
"$",
"result",
"=",
"array",
"(",
"'success'",... | AJAX Json Response handler
@param array|null $retVars
@param boolean $success
@return \SS_HTTPResponse | [
"AJAX",
"Json",
"Response",
"handler"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/fullcalendar/FullcalendarController.php#L218-L233 | train |
titledk/silverstripe-calendar | code/fullcalendar/FullcalendarController.php | FullcalendarController.format_event_for_fullcalendar | public static function format_event_for_fullcalendar($event)
{
$bgColor = '#999'; //default
$textColor = '#FFF'; //default
$borderColor = '#555';
$arr = array(
'id' => $event->ID,
'title' => $event->Title,
'start' => self::format_datetime_for_fullcalendar($event->StartDateTime),
'end' => self::format_datetime_for_fullcalendar($event->EndDateTime),
'allDay' => $event->isAllDay(),
'className' => $event->ClassName,
//event calendar
'backgroundColor' => $bgColor,
'textColor' => '#FFFFFF',
'borderColor' => $borderColor,
);
return $arr;
} | php | public static function format_event_for_fullcalendar($event)
{
$bgColor = '#999'; //default
$textColor = '#FFF'; //default
$borderColor = '#555';
$arr = array(
'id' => $event->ID,
'title' => $event->Title,
'start' => self::format_datetime_for_fullcalendar($event->StartDateTime),
'end' => self::format_datetime_for_fullcalendar($event->EndDateTime),
'allDay' => $event->isAllDay(),
'className' => $event->ClassName,
//event calendar
'backgroundColor' => $bgColor,
'textColor' => '#FFFFFF',
'borderColor' => $borderColor,
);
return $arr;
} | [
"public",
"static",
"function",
"format_event_for_fullcalendar",
"(",
"$",
"event",
")",
"{",
"$",
"bgColor",
"=",
"'#999'",
";",
"//default",
"$",
"textColor",
"=",
"'#FFF'",
";",
"//default",
"$",
"borderColor",
"=",
"'#555'",
";",
"$",
"arr",
"=",
"array"... | Format an event to comply with the fullcalendar format
@param Event $event | [
"Format",
"an",
"event",
"to",
"comply",
"with",
"the",
"fullcalendar",
"format"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/fullcalendar/FullcalendarController.php#L239-L258 | train |
sonata-project/SonataCommentBundle | src/Form/Type/CommentType.php | CommentType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($options['add_author']) {
$builder->add('authorName', TextType::class, ['required' => true]);
$this->vars['add_author'] = $options['add_author'];
}
if ($options['show_note']) {
$builder->add('note', ChoiceType::class, [
'required' => false,
'choices' => $this->noteProvider->getValues(),
]);
}
$builder
->add('website', UrlType::class, ['required' => false])
->add('email', EmailType::class, ['required' => false])
;
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
if ($options['add_author']) {
$builder->add('authorName', TextType::class, ['required' => true]);
$this->vars['add_author'] = $options['add_author'];
}
if ($options['show_note']) {
$builder->add('note', ChoiceType::class, [
'required' => false,
'choices' => $this->noteProvider->getValues(),
]);
}
$builder
->add('website', UrlType::class, ['required' => false])
->add('email', EmailType::class, ['required' => false])
;
} | [
"public",
"function",
"buildForm",
"(",
"FormBuilderInterface",
"$",
"builder",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"$",
"options",
"[",
"'add_author'",
"]",
")",
"{",
"$",
"builder",
"->",
"add",
"(",
"'authorName'",
",",
"TextType",
"::",
... | Configures a Comment form.
@param FormBuilderInterface $builder
@param array $options | [
"Configures",
"a",
"Comment",
"form",
"."
] | f78a08e64434242d1d1f0bbd82a7f9e27939d546 | https://github.com/sonata-project/SonataCommentBundle/blob/f78a08e64434242d1d1f0bbd82a7f9e27939d546/src/Form/Type/CommentType.php#L59-L78 | train |
indeyets/pake | lib/pake/pakePHPDoc.class.php | pakePHPDoc.getDescriptions | public static function getDescriptions($function_name)
{
if (is_string($function_name))
$reflection = new ReflectionFunction($function_name);
elseif (is_array($function_name))
$reflection = new ReflectionMethod($function_name[0], $function_name[1]);
else
throw new LogicException();
$comment = $reflection->getDocComment();
$lines = explode("\n", $comment);
$obj = new self($lines);
return array(trim($obj->short_desc), trim($obj->long_desc));
} | php | public static function getDescriptions($function_name)
{
if (is_string($function_name))
$reflection = new ReflectionFunction($function_name);
elseif (is_array($function_name))
$reflection = new ReflectionMethod($function_name[0], $function_name[1]);
else
throw new LogicException();
$comment = $reflection->getDocComment();
$lines = explode("\n", $comment);
$obj = new self($lines);
return array(trim($obj->short_desc), trim($obj->long_desc));
} | [
"public",
"static",
"function",
"getDescriptions",
"(",
"$",
"function_name",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"function_name",
")",
")",
"$",
"reflection",
"=",
"new",
"ReflectionFunction",
"(",
"$",
"function_name",
")",
";",
"elseif",
"(",
"is_... | Returns short and log description of function
@param string $function_name
@return array
@author Alexey Zakhlestin | [
"Returns",
"short",
"and",
"log",
"description",
"of",
"function"
] | 22b4e1da921c7626bb0e1fd0538a16562129be83 | https://github.com/indeyets/pake/blob/22b4e1da921c7626bb0e1fd0538a16562129be83/lib/pake/pakePHPDoc.class.php#L25-L40 | train |
AlfredoRamos/parsedown-extra-laravel | src/HTMLPurifierLaravel.php | HTMLPurifierLaravel.purify | public function purify($html = '', $config = []) {
return $this->purifier->purify(
$html,
$this->getConfig($config)
);
} | php | public function purify($html = '', $config = []) {
return $this->purifier->purify(
$html,
$this->getConfig($config)
);
} | [
"public",
"function",
"purify",
"(",
"$",
"html",
"=",
"''",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"purifier",
"->",
"purify",
"(",
"$",
"html",
",",
"$",
"this",
"->",
"getConfig",
"(",
"$",
"config",
")",
")"... | Filter HTML.
@see \HTMLPurifier::purify()
@param string $html The HTML to be cleaned.
@param array|string $config HTMLPurifier configuration.
@return string Filtered HTML. | [
"Filter",
"HTML",
"."
] | ff2b86306a5e8c5263e941afd4e48311df4f27b2 | https://github.com/AlfredoRamos/parsedown-extra-laravel/blob/ff2b86306a5e8c5263e941afd4e48311df4f27b2/src/HTMLPurifierLaravel.php#L59-L64 | train |
AlfredoRamos/parsedown-extra-laravel | src/HTMLPurifierLaravel.php | HTMLPurifierLaravel.getConfig | protected function getConfig($data = []) {
// HTMLPurifier configuration
$config = HTMLPurifier_Config::createDefault();
$config->autofinalize = false;
// Set default settings, 'default' key must exist
if (empty($data)) {
$data = 'default';
}
// If string given, get the config array
if (is_string($data)) {
$data = config(sprintf(
'parsedownextra.purifier.settings.%s',
$data
));
}
// Merge both global and default settings
$data = array_replace_recursive(
(array) config('parsedownextra.purifier.settings.global'),
(array) $data
);
// At this point $data should be an array
if (is_array($data)) {
$config->loadArray($data);
}
return $config;
} | php | protected function getConfig($data = []) {
// HTMLPurifier configuration
$config = HTMLPurifier_Config::createDefault();
$config->autofinalize = false;
// Set default settings, 'default' key must exist
if (empty($data)) {
$data = 'default';
}
// If string given, get the config array
if (is_string($data)) {
$data = config(sprintf(
'parsedownextra.purifier.settings.%s',
$data
));
}
// Merge both global and default settings
$data = array_replace_recursive(
(array) config('parsedownextra.purifier.settings.global'),
(array) $data
);
// At this point $data should be an array
if (is_array($data)) {
$config->loadArray($data);
}
return $config;
} | [
"protected",
"function",
"getConfig",
"(",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"// HTMLPurifier configuration",
"$",
"config",
"=",
"HTMLPurifier_Config",
"::",
"createDefault",
"(",
")",
";",
"$",
"config",
"->",
"autofinalize",
"=",
"false",
";",
"// Set d... | Get HTMLPurifier config.
@param array|string $data HTMLPurifier configuration.
@return \HTMLPurifier_Config Configuration object. | [
"Get",
"HTMLPurifier",
"config",
"."
] | ff2b86306a5e8c5263e941afd4e48311df4f27b2 | https://github.com/AlfredoRamos/parsedown-extra-laravel/blob/ff2b86306a5e8c5263e941afd4e48311df4f27b2/src/HTMLPurifierLaravel.php#L73-L103 | train |
titledk/silverstripe-calendar | code/registrations/EventRegistrationExtention.php | EventRegistrationExtension.getRegisterLink | public function getRegisterLink()
{
$o = $this->owner;
//$link = $o->getInternalLink() . "/register";
//return $link;
$detailStr = 'register/' . $o->ID;
$calendarPage = CalendarPage::get()->First();
return $calendarPage->Link() . $detailStr;
} | php | public function getRegisterLink()
{
$o = $this->owner;
//$link = $o->getInternalLink() . "/register";
//return $link;
$detailStr = 'register/' . $o->ID;
$calendarPage = CalendarPage::get()->First();
return $calendarPage->Link() . $detailStr;
} | [
"public",
"function",
"getRegisterLink",
"(",
")",
"{",
"$",
"o",
"=",
"$",
"this",
"->",
"owner",
";",
"//$link = $o->getInternalLink() . \"/register\";",
"//return $link;",
"$",
"detailStr",
"=",
"'register/'",
".",
"$",
"o",
"->",
"ID",
";",
"$",
"calendarPag... | Getter for registration link | [
"Getter",
"for",
"registration",
"link"
] | afba392d26f28d6e5c9a44765eab5a3a171cc850 | https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/registrations/EventRegistrationExtention.php#L88-L98 | train |
Arara/Process | src/Arara/Process/Pool.php | Pool.attach | public function attach(Process $process)
{
if ($this->stopped) {
throw new RuntimeException('Could not attach child to non-running pool');
}
$firstProcess = $this->getFirstProcess();
if ($this->isRunning()
&& $firstProcess instanceof Process
&& $this->count() >= $this->processLimit) {
$firstProcess->wait();
$this->detach($firstProcess);
}
$this->process->attach($process);
if ($this->isRunning()) {
$process->start();
}
} | php | public function attach(Process $process)
{
if ($this->stopped) {
throw new RuntimeException('Could not attach child to non-running pool');
}
$firstProcess = $this->getFirstProcess();
if ($this->isRunning()
&& $firstProcess instanceof Process
&& $this->count() >= $this->processLimit) {
$firstProcess->wait();
$this->detach($firstProcess);
}
$this->process->attach($process);
if ($this->isRunning()) {
$process->start();
}
} | [
"public",
"function",
"attach",
"(",
"Process",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"stopped",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Could not attach child to non-running pool'",
")",
";",
"}",
"$",
"firstProcess",
"=",
"$",
... | Attachs a new process to the pool.
Try to detach finished processes from the pool when reaches its limit.
@param Process $process | [
"Attachs",
"a",
"new",
"process",
"to",
"the",
"pool",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pool.php#L74-L92 | train |
Arara/Process | src/Arara/Process/Pool.php | Pool.getFirstProcess | public function getFirstProcess()
{
$firstProcess = null;
foreach ($this->process as $process) {
if ($this->isRunning() && ! $process->isRunning()) {
$this->detach($process);
continue;
}
if (null !== $firstProcess) {
continue;
}
$firstProcess = $process;
}
return $firstProcess;
} | php | public function getFirstProcess()
{
$firstProcess = null;
foreach ($this->process as $process) {
if ($this->isRunning() && ! $process->isRunning()) {
$this->detach($process);
continue;
}
if (null !== $firstProcess) {
continue;
}
$firstProcess = $process;
}
return $firstProcess;
} | [
"public",
"function",
"getFirstProcess",
"(",
")",
"{",
"$",
"firstProcess",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"process",
"as",
"$",
"process",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isRunning",
"(",
")",
"&&",
"!",
"$",
"process... | Returns the fist process in the queue.
Try to detach finished processes from the pool.
@return Process|null | [
"Returns",
"the",
"fist",
"process",
"in",
"the",
"queue",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pool.php#L111-L127 | train |
Arara/Process | src/Arara/Process/Action/Callback.php | Callback.getHandlers | public function getHandlers()
{
$handlers = [];
foreach ($this->handlers as $key => $handler) {
$handlers[$key] = $handler->getCallable();
}
return $handlers;
} | php | public function getHandlers()
{
$handlers = [];
foreach ($this->handlers as $key => $handler) {
$handlers[$key] = $handler->getCallable();
}
return $handlers;
} | [
"public",
"function",
"getHandlers",
"(",
")",
"{",
"$",
"handlers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"handlers",
"as",
"$",
"key",
"=>",
"$",
"handler",
")",
"{",
"$",
"handlers",
"[",
"$",
"key",
"]",
"=",
"$",
"handler",
... | Returns all defined handlers.
@return array | [
"Returns",
"all",
"defined",
"handlers",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Action/Callback.php#L99-L107 | train |
pixers/salesmanago-api | src/Pixers/SalesManagoAPI/Service/EventService.php | EventService.create | public function create($owner, $email, array $data)
{
$data = self::mergeData($data, [
'owner' => $owner,
'email' => $email,
]);
return $this->client->doPost('contact/addContactExtEvent', $data);
} | php | public function create($owner, $email, array $data)
{
$data = self::mergeData($data, [
'owner' => $owner,
'email' => $email,
]);
return $this->client->doPost('contact/addContactExtEvent', $data);
} | [
"public",
"function",
"create",
"(",
"$",
"owner",
",",
"$",
"email",
",",
"array",
"$",
"data",
")",
"{",
"$",
"data",
"=",
"self",
"::",
"mergeData",
"(",
"$",
"data",
",",
"[",
"'owner'",
"=>",
"$",
"owner",
",",
"'email'",
"=>",
"$",
"email",
... | Creating a new external event.
@param string $owner Contact owner e-mail address
@param string $email Contact e-mail address
@param array $data Contact event data
@return array | [
"Creating",
"a",
"new",
"external",
"event",
"."
] | fb0bf9a70cc8c136d4efeb2c710abd3fe8cfbee9 | https://github.com/pixers/salesmanago-api/blob/fb0bf9a70cc8c136d4efeb2c710abd3fe8cfbee9/src/Pixers/SalesManagoAPI/Service/EventService.php#L18-L26 | train |
pixers/salesmanago-api | src/Pixers/SalesManagoAPI/Service/EventService.php | EventService.update | public function update($owner, $eventId, array $data)
{
$data = self::mergeData($data, [
'owner' => $owner,
'contactEvent' => [
'eventId' => $eventId,
],
]);
return $this->client->doPost('contact/updateContactExtEvent', $data);
} | php | public function update($owner, $eventId, array $data)
{
$data = self::mergeData($data, [
'owner' => $owner,
'contactEvent' => [
'eventId' => $eventId,
],
]);
return $this->client->doPost('contact/updateContactExtEvent', $data);
} | [
"public",
"function",
"update",
"(",
"$",
"owner",
",",
"$",
"eventId",
",",
"array",
"$",
"data",
")",
"{",
"$",
"data",
"=",
"self",
"::",
"mergeData",
"(",
"$",
"data",
",",
"[",
"'owner'",
"=>",
"$",
"owner",
",",
"'contactEvent'",
"=>",
"[",
"... | Updating external event.
@param string $owner Contact owner e-mail address
@param string $eventId Ext event identifier
@param array $data New event data
@return array | [
"Updating",
"external",
"event",
"."
] | fb0bf9a70cc8c136d4efeb2c710abd3fe8cfbee9 | https://github.com/pixers/salesmanago-api/blob/fb0bf9a70cc8c136d4efeb2c710abd3fe8cfbee9/src/Pixers/SalesManagoAPI/Service/EventService.php#L36-L46 | train |
adam-boduch/laravel-grid | src/Grid.php | Grid.isFilterable | public function isFilterable()
{
$hasFilters = false;
foreach ($this->columns as $column) {
if ($column->isFilterable()) {
$hasFilters = true;
break;
}
}
return $hasFilters;
} | php | public function isFilterable()
{
$hasFilters = false;
foreach ($this->columns as $column) {
if ($column->isFilterable()) {
$hasFilters = true;
break;
}
}
return $hasFilters;
} | [
"public",
"function",
"isFilterable",
"(",
")",
"{",
"$",
"hasFilters",
"=",
"false",
";",
"foreach",
"(",
"$",
"this",
"->",
"columns",
"as",
"$",
"column",
")",
"{",
"if",
"(",
"$",
"column",
"->",
"isFilterable",
"(",
")",
")",
"{",
"$",
"hasFilte... | Is table filterable?
@return bool | [
"Is",
"table",
"filterable?"
] | 543ffa06e715fe5b6fb6caa0c8d6b5b55f8c18ae | https://github.com/adam-boduch/laravel-grid/blob/543ffa06e715fe5b6fb6caa0c8d6b5b55f8c18ae/src/Grid.php#L316-L328 | train |
Arara/Process | src/Arara/Process/Control.php | Control.execute | public function execute($path, array $args = [], array $envs = [])
{
if (false === @pcntl_exec($path, $args, $envs)) {
throw new RuntimeException('Error when executing command');
}
} | php | public function execute($path, array $args = [], array $envs = [])
{
if (false === @pcntl_exec($path, $args, $envs)) {
throw new RuntimeException('Error when executing command');
}
} | [
"public",
"function",
"execute",
"(",
"$",
"path",
",",
"array",
"$",
"args",
"=",
"[",
"]",
",",
"array",
"$",
"envs",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"false",
"===",
"@",
"pcntl_exec",
"(",
"$",
"path",
",",
"$",
"args",
",",
"$",
"envs",... | Executes specified program in current process space.
@param string $path
@param array $args
@param array $envs
@throws RuntimeException When get an error. | [
"Executes",
"specified",
"program",
"in",
"current",
"process",
"space",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control.php#L64-L69 | train |
Arara/Process | src/Arara/Process/Control.php | Control.flush | public function flush($seconds = 0)
{
if (! (is_float($seconds) || is_int($seconds)) || $seconds < 0) {
throw new InvalidArgumentException('Seconds must be a number greater than or equal to 0');
}
if (is_int($seconds)) {
sleep($seconds);
} else {
usleep($seconds * 1000000);
}
clearstatcache();
gc_collect_cycles();
} | php | public function flush($seconds = 0)
{
if (! (is_float($seconds) || is_int($seconds)) || $seconds < 0) {
throw new InvalidArgumentException('Seconds must be a number greater than or equal to 0');
}
if (is_int($seconds)) {
sleep($seconds);
} else {
usleep($seconds * 1000000);
}
clearstatcache();
gc_collect_cycles();
} | [
"public",
"function",
"flush",
"(",
"$",
"seconds",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"(",
"is_float",
"(",
"$",
"seconds",
")",
"||",
"is_int",
"(",
"$",
"seconds",
")",
")",
"||",
"$",
"seconds",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidAr... | Try to flush current process memory.
- Delays the program execution
- Clears file status cache
- Forces collection of any existing garbage cycles
@param float|int $seconds Seconds to sleep (can be 0.5)
@throws InvalidArgumentException When $seconds is not a valid value. | [
"Try",
"to",
"flush",
"current",
"process",
"memory",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control.php#L97-L111 | train |
Arara/Process | src/Arara/Process/Control/Info.php | Info.setUserName | public function setUserName($userName)
{
$user = posix_getpwnam($userName);
if (! isset($user['uid'])) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid user name', $userName));
}
$this->setUserId($user['uid']);
} | php | public function setUserName($userName)
{
$user = posix_getpwnam($userName);
if (! isset($user['uid'])) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid user name', $userName));
}
$this->setUserId($user['uid']);
} | [
"public",
"function",
"setUserName",
"(",
"$",
"userName",
")",
"{",
"$",
"user",
"=",
"posix_getpwnam",
"(",
"$",
"userName",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"user",
"[",
"'uid'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentExcept... | Defines the current user name.
@param string $userName Unix user name.
@throws RuntimeException When unable to update current user name. | [
"Defines",
"the",
"current",
"user",
"name",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Info.php#L87-L95 | train |
Arara/Process | src/Arara/Process/Control/Info.php | Info.setGroupName | public function setGroupName($groupName)
{
$group = posix_getgrnam($groupName);
if (! isset($group['gid'])) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid group name', $groupName));
}
$this->setGroupId($group['gid']);
} | php | public function setGroupName($groupName)
{
$group = posix_getgrnam($groupName);
if (! isset($group['gid'])) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid group name', $groupName));
}
$this->setGroupId($group['gid']);
} | [
"public",
"function",
"setGroupName",
"(",
"$",
"groupName",
")",
"{",
"$",
"group",
"=",
"posix_getgrnam",
"(",
"$",
"groupName",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"group",
"[",
"'gid'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentE... | Defines the current group name.
@param string $groupName Unix group name.
@throws RuntimeException When unable to update current group name. | [
"Defines",
"the",
"current",
"group",
"name",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Control/Info.php#L147-L155 | train |
sunrise-php/http-server-request | src/ServerRequestFactory.php | ServerRequestFactory.fromGlobals | public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null) : ServerRequestInterface
{
$server = $server ?? $_SERVER ?? [];
$query = $query ?? $_GET ?? [];
$body = $body ?? $_POST ?? [];
$cookies = $cookies ?? $_COOKIE ?? [];
$files = $files ?? $_FILES ?? [];
$request = (new ServerRequest)
->withProtocolVersion(request_http_version($server))
->withBody(request_body())
->withMethod(request_method($server))
->withUri(request_uri($server))
->withServerParams($server)
->withCookieParams($cookies)
->withQueryParams($query)
->withUploadedFiles(request_files($files))
->withParsedBody($body);
foreach (request_headers($server) as $name => $value)
{
$request = $request->withHeader($name, $value);
}
return $request;
} | php | public static function fromGlobals(array $server = null, array $query = null, array $body = null, array $cookies = null, array $files = null) : ServerRequestInterface
{
$server = $server ?? $_SERVER ?? [];
$query = $query ?? $_GET ?? [];
$body = $body ?? $_POST ?? [];
$cookies = $cookies ?? $_COOKIE ?? [];
$files = $files ?? $_FILES ?? [];
$request = (new ServerRequest)
->withProtocolVersion(request_http_version($server))
->withBody(request_body())
->withMethod(request_method($server))
->withUri(request_uri($server))
->withServerParams($server)
->withCookieParams($cookies)
->withQueryParams($query)
->withUploadedFiles(request_files($files))
->withParsedBody($body);
foreach (request_headers($server) as $name => $value)
{
$request = $request->withHeader($name, $value);
}
return $request;
} | [
"public",
"static",
"function",
"fromGlobals",
"(",
"array",
"$",
"server",
"=",
"null",
",",
"array",
"$",
"query",
"=",
"null",
",",
"array",
"$",
"body",
"=",
"null",
",",
"array",
"$",
"cookies",
"=",
"null",
",",
"array",
"$",
"files",
"=",
"nul... | Creates the server request instance from superglobals variables
@param null|array $server
@param null|array $query
@param null|array $body
@param null|array $cookies
@param null|array $files
@return ServerRequestInterface
@link http://php.net/manual/en/language.variables.superglobals.php
@link https://www.php-fig.org/psr/psr-15/meta/ | [
"Creates",
"the",
"server",
"request",
"instance",
"from",
"superglobals",
"variables"
] | 70cc52366cc7ea3c3fc5fc1b6c54bb7a7441d763 | https://github.com/sunrise-php/http-server-request/blob/70cc52366cc7ea3c3fc5fc1b6c54bb7a7441d763/src/ServerRequestFactory.php#L45-L70 | train |
canax/controller | src/Controller/ErrorHandlerController.php | ErrorHandlerController.catchAll | public function catchAll(...$args) : object
{
$title = " | Anax";
$pages = [
"403" => [
"Anax 403: Forbidden",
"You are not permitted to do this."
],
"404" => [
"Anax 404: Not Found",
"The page you are looking for is not here."
],
"500" => [
"Anax 500: Internal Server Error",
"An unexpected condition was encountered."
],
];
$path = $this->di->get("router")->getMatchedPath();
if (!array_key_exists($path, $pages)) {
throw new NotFoundException("Internal route for '$path' is not found.");
}
$page = $this->di->get("page");
$page->add(
"anax/v2/error/default",
[
"header" => $pages[$path][0],
"text" => $pages[$path][1],
]
);
return $page->render([
"title" => $pages[$path][0] . $title
], $path);
} | php | public function catchAll(...$args) : object
{
$title = " | Anax";
$pages = [
"403" => [
"Anax 403: Forbidden",
"You are not permitted to do this."
],
"404" => [
"Anax 404: Not Found",
"The page you are looking for is not here."
],
"500" => [
"Anax 500: Internal Server Error",
"An unexpected condition was encountered."
],
];
$path = $this->di->get("router")->getMatchedPath();
if (!array_key_exists($path, $pages)) {
throw new NotFoundException("Internal route for '$path' is not found.");
}
$page = $this->di->get("page");
$page->add(
"anax/v2/error/default",
[
"header" => $pages[$path][0],
"text" => $pages[$path][1],
]
);
return $page->render([
"title" => $pages[$path][0] . $title
], $path);
} | [
"public",
"function",
"catchAll",
"(",
"...",
"$",
"args",
")",
":",
"object",
"{",
"$",
"title",
"=",
"\" | Anax\"",
";",
"$",
"pages",
"=",
"[",
"\"403\"",
"=>",
"[",
"\"Anax 403: Forbidden\"",
",",
"\"You are not permitted to do this.\"",
"]",
",",
"\"404\"... | Add internal routes for 403, 404 and 500 that provides a page with
error information, using the default page layout.
@param string $message with details.
@throws Anax\Route\Exception\NotFoundException
@return object as the response. | [
"Add",
"internal",
"routes",
"for",
"403",
"404",
"and",
"500",
"that",
"provides",
"a",
"page",
"with",
"error",
"information",
"using",
"the",
"default",
"page",
"layout",
"."
] | 27b7890d630ec8620f07b1b5e46132671a19d6d7 | https://github.com/canax/controller/blob/27b7890d630ec8620f07b1b5e46132671a19d6d7/src/Controller/ErrorHandlerController.php#L28-L63 | train |
bldr-io/bldr | src/Block/Execute/Task/BackgroundTask.php | BackgroundTask.startProcess | private function startProcess(OutputInterface $output)
{
$arguments = $this->resolveProcessArgs();
$name = sha1(serialize($arguments));
if ($this->background->hasProcess($name)) {
throw new \RuntimeException("Service is already running.");
}
$builder = new ProcessBuilder($arguments);
if ($this->hasParameter('cwd')) {
$builder->setWorkingDirectory($this->getParameter('cwd'));
}
$process = $builder->getProcess();
if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln($process->getCommandLine());
}
if ($this->hasParameter('output')) {
$append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w';
$stream = fopen($this->getParameter('output'), $append);
$output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true);
}
$process->start(
function ($type, $buffer) use ($output) {
$output->write($buffer);
}
);
$this->background->addProcess($name, $process);
if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) {
throw new TaskRuntimeException($this->getName(), $process->getErrorOutput());
}
} | php | private function startProcess(OutputInterface $output)
{
$arguments = $this->resolveProcessArgs();
$name = sha1(serialize($arguments));
if ($this->background->hasProcess($name)) {
throw new \RuntimeException("Service is already running.");
}
$builder = new ProcessBuilder($arguments);
if ($this->hasParameter('cwd')) {
$builder->setWorkingDirectory($this->getParameter('cwd'));
}
$process = $builder->getProcess();
if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln($process->getCommandLine());
}
if ($this->hasParameter('output')) {
$append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w';
$stream = fopen($this->getParameter('output'), $append);
$output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true);
}
$process->start(
function ($type, $buffer) use ($output) {
$output->write($buffer);
}
);
$this->background->addProcess($name, $process);
if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) {
throw new TaskRuntimeException($this->getName(), $process->getErrorOutput());
}
} | [
"private",
"function",
"startProcess",
"(",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"arguments",
"=",
"$",
"this",
"->",
"resolveProcessArgs",
"(",
")",
";",
"$",
"name",
"=",
"sha1",
"(",
"serialize",
"(",
"$",
"arguments",
")",
")",
";",
"if",... | Creates the given process
@throws \Exception | [
"Creates",
"the",
"given",
"process"
] | 60bc51ff248bd237c13f1811c95a9a33f9d38aab | https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/Block/Execute/Task/BackgroundTask.php#L76-L113 | train |
bldr-io/bldr | src/Block/Execute/Task/BackgroundTask.php | BackgroundTask.endProcess | private function endProcess()
{
$arguments = $this->resolveProcessArgs();
$name = sha1(serialize($arguments));
if ($this->background->hasProcess($name)) {
$this->background->getProcess($name)->stop();
$this->background->removeProcess($name);
}
} | php | private function endProcess()
{
$arguments = $this->resolveProcessArgs();
$name = sha1(serialize($arguments));
if ($this->background->hasProcess($name)) {
$this->background->getProcess($name)->stop();
$this->background->removeProcess($name);
}
} | [
"private",
"function",
"endProcess",
"(",
")",
"{",
"$",
"arguments",
"=",
"$",
"this",
"->",
"resolveProcessArgs",
"(",
")",
";",
"$",
"name",
"=",
"sha1",
"(",
"serialize",
"(",
"$",
"arguments",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"backgr... | Kills the given process | [
"Kills",
"the",
"given",
"process"
] | 60bc51ff248bd237c13f1811c95a9a33f9d38aab | https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/Block/Execute/Task/BackgroundTask.php#L118-L126 | train |
bldr-io/bldr | src/Block/Core/Task/Traits/FinderAwareTrait.php | FinderAwareTrait.getFiles | protected function getFiles(array $source)
{
$fileSet = [];
foreach ($source as $set) {
if (!array_key_exists('files', $set)) {
throw new \Exception("`src` must have a `files` option");
}
if (!array_key_exists('path', $set)) {
$set['path'] = getcwd();
}
if (!array_key_exists('recursive', $set)) {
$set['recursive'] = false;
}
$paths = is_array($set['path']) ? $set['path'] : [$set['path']];
$files = is_array($set['files']) ? $set['files'] : [$set['files']];
foreach ($paths as $path) {
foreach ($files as $file) {
$finder = new Finder();
$finder->files()->in($path)->name($file);
if (!$set['recursive']) {
$finder->depth('== 0');
}
$fileSet = $this->appendFileSet($finder, $fileSet);
}
}
}
return $fileSet;
} | php | protected function getFiles(array $source)
{
$fileSet = [];
foreach ($source as $set) {
if (!array_key_exists('files', $set)) {
throw new \Exception("`src` must have a `files` option");
}
if (!array_key_exists('path', $set)) {
$set['path'] = getcwd();
}
if (!array_key_exists('recursive', $set)) {
$set['recursive'] = false;
}
$paths = is_array($set['path']) ? $set['path'] : [$set['path']];
$files = is_array($set['files']) ? $set['files'] : [$set['files']];
foreach ($paths as $path) {
foreach ($files as $file) {
$finder = new Finder();
$finder->files()->in($path)->name($file);
if (!$set['recursive']) {
$finder->depth('== 0');
}
$fileSet = $this->appendFileSet($finder, $fileSet);
}
}
}
return $fileSet;
} | [
"protected",
"function",
"getFiles",
"(",
"array",
"$",
"source",
")",
"{",
"$",
"fileSet",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"source",
"as",
"$",
"set",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'files'",
",",
"$",
"set",
")",
")"... | Finds all the files for the given config
@param array $source
@return SplFileInfo[]
@throws \Exception | [
"Finds",
"all",
"the",
"files",
"for",
"the",
"given",
"config"
] | 60bc51ff248bd237c13f1811c95a9a33f9d38aab | https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/Block/Core/Task/Traits/FinderAwareTrait.php#L31-L63 | train |
indeyets/pake | lib/pake/pakeHttp.class.php | pakeHttp.matchRequest | public static function matchRequest($regexp, $method, $url, $query_data = null, $body = null, array $headers = array(), array $options = array())
{
$response = self::request($method, $url, $query_data, $body, $headers, $options);
$result = preg_match($regexp, $response);
if (false === $result) {
throw new pakeException("There's some error with this regular expression: ".$regexp);
}
if (0 === $result) {
throw new pakeException("HTTP Response didn't match against regular expression: ".$regexp);
}
pake_echo_comment('HTTP response matched against '.$regexp);
} | php | public static function matchRequest($regexp, $method, $url, $query_data = null, $body = null, array $headers = array(), array $options = array())
{
$response = self::request($method, $url, $query_data, $body, $headers, $options);
$result = preg_match($regexp, $response);
if (false === $result) {
throw new pakeException("There's some error with this regular expression: ".$regexp);
}
if (0 === $result) {
throw new pakeException("HTTP Response didn't match against regular expression: ".$regexp);
}
pake_echo_comment('HTTP response matched against '.$regexp);
} | [
"public",
"static",
"function",
"matchRequest",
"(",
"$",
"regexp",
",",
"$",
"method",
",",
"$",
"url",
",",
"$",
"query_data",
"=",
"null",
",",
"$",
"body",
"=",
"null",
",",
"array",
"$",
"headers",
"=",
"array",
"(",
")",
",",
"array",
"$",
"o... | execute HTTP Request and match response against PCRE regexp
@param string $regexp PCRE regexp
@param string $method
@param string $url
@param mixed $query_data string or array
@param mixed $body string or array
@param array $headers
@param array $options
@return void | [
"execute",
"HTTP",
"Request",
"and",
"match",
"response",
"against",
"PCRE",
"regexp"
] | 22b4e1da921c7626bb0e1fd0538a16562129be83 | https://github.com/indeyets/pake/blob/22b4e1da921c7626bb0e1fd0538a16562129be83/lib/pake/pakeHttp.class.php#L125-L140 | train |
indeyets/pake | lib/pake/pakeHttp.class.php | pakeHttp.get | public static function get($url, $query_data = null, array $headers = array(), array $options = array())
{
return self::request('GET', $url, $query_data, null, $headers, $options);
} | php | public static function get($url, $query_data = null, array $headers = array(), array $options = array())
{
return self::request('GET', $url, $query_data, null, $headers, $options);
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"url",
",",
"$",
"query_data",
"=",
"null",
",",
"array",
"$",
"headers",
"=",
"array",
"(",
")",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"return",
"self",
"::",
"request",
"(... | Convenience wrappers follow | [
"Convenience",
"wrappers",
"follow"
] | 22b4e1da921c7626bb0e1fd0538a16562129be83 | https://github.com/indeyets/pake/blob/22b4e1da921c7626bb0e1fd0538a16562129be83/lib/pake/pakeHttp.class.php#L144-L147 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.setApplicationName | protected function setApplicationName($applicationName)
{
if ($applicationName != strtolower($applicationName)) {
throw new InvalidArgumentException('Application name should be lowercase');
}
if (preg_match('/[^a-z0-9]/', $applicationName)) {
throw new InvalidArgumentException('Application name should contains only alphanumeric chars');
}
if (strlen($applicationName) > 16) {
$message = 'Application name should be no longer than 16 characters';
throw new InvalidArgumentException($message);
}
$this->applicationName = $applicationName;
} | php | protected function setApplicationName($applicationName)
{
if ($applicationName != strtolower($applicationName)) {
throw new InvalidArgumentException('Application name should be lowercase');
}
if (preg_match('/[^a-z0-9]/', $applicationName)) {
throw new InvalidArgumentException('Application name should contains only alphanumeric chars');
}
if (strlen($applicationName) > 16) {
$message = 'Application name should be no longer than 16 characters';
throw new InvalidArgumentException($message);
}
$this->applicationName = $applicationName;
} | [
"protected",
"function",
"setApplicationName",
"(",
"$",
"applicationName",
")",
"{",
"if",
"(",
"$",
"applicationName",
"!=",
"strtolower",
"(",
"$",
"applicationName",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Application name should be lower... | Defines application name.
@param string $applicationName The application name, used as pidfile basename.
@throws InvalidArgumentException When application name is not valid. | [
"Defines",
"application",
"name",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L83-L98 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.setLockDirectory | protected function setLockDirectory($lockDirectory)
{
if (! is_dir($lockDirectory)) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid directory', $lockDirectory));
}
if (! is_writable($lockDirectory)) {
throw new InvalidArgumentException(sprintf('"%s" is not a writable directory', $lockDirectory));
}
$this->lockDirectory = $lockDirectory;
} | php | protected function setLockDirectory($lockDirectory)
{
if (! is_dir($lockDirectory)) {
throw new InvalidArgumentException(sprintf('"%s" is not a valid directory', $lockDirectory));
}
if (! is_writable($lockDirectory)) {
throw new InvalidArgumentException(sprintf('"%s" is not a writable directory', $lockDirectory));
}
$this->lockDirectory = $lockDirectory;
} | [
"protected",
"function",
"setLockDirectory",
"(",
"$",
"lockDirectory",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"lockDirectory",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'\"%s\" is not a valid directory'",
",",
"$",
... | Defines the lock directory.
@param string $lockDirectory Directory were pidfile should be stored.
@throws InvalidArgumentException When lock directory is not valid. | [
"Defines",
"the",
"lock",
"directory",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L107-L118 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.getFileName | protected function getFileName()
{
if (null === $this->fileName) {
$this->fileName = $this->lockDirectory.'/'.$this->applicationName.'.pid';
}
return $this->fileName;
} | php | protected function getFileName()
{
if (null === $this->fileName) {
$this->fileName = $this->lockDirectory.'/'.$this->applicationName.'.pid';
}
return $this->fileName;
} | [
"protected",
"function",
"getFileName",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"fileName",
")",
"{",
"$",
"this",
"->",
"fileName",
"=",
"$",
"this",
"->",
"lockDirectory",
".",
"'/'",
".",
"$",
"this",
"->",
"applicationName",
"."... | Returns the Pidfile filename.
@return string | [
"Returns",
"the",
"Pidfile",
"filename",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L125-L132 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.getFileResource | protected function getFileResource()
{
if (null === $this->fileResource) {
$fileResource = @fopen($this->getFileName(), 'a+');
if (! $fileResource) {
throw new RuntimeException('Could not open pidfile');
}
$this->fileResource = $fileResource;
}
return $this->fileResource;
} | php | protected function getFileResource()
{
if (null === $this->fileResource) {
$fileResource = @fopen($this->getFileName(), 'a+');
if (! $fileResource) {
throw new RuntimeException('Could not open pidfile');
}
$this->fileResource = $fileResource;
}
return $this->fileResource;
} | [
"protected",
"function",
"getFileResource",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"fileResource",
")",
"{",
"$",
"fileResource",
"=",
"@",
"fopen",
"(",
"$",
"this",
"->",
"getFileName",
"(",
")",
",",
"'a+'",
")",
";",
"if",
"(... | Returns the Pidfile file resource.
@return resource | [
"Returns",
"the",
"Pidfile",
"file",
"resource",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L139-L150 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.isActive | public function isActive()
{
$pid = $this->getProcessId();
if (null === $pid) {
return false;
}
return $this->control->signal()->send(0, $pid);
} | php | public function isActive()
{
$pid = $this->getProcessId();
if (null === $pid) {
return false;
}
return $this->control->signal()->send(0, $pid);
} | [
"public",
"function",
"isActive",
"(",
")",
"{",
"$",
"pid",
"=",
"$",
"this",
"->",
"getProcessId",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"pid",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"control",
"->",
"signal",... | Returns TRUE when pidfile is active or FALSE when is not.
@return bool | [
"Returns",
"TRUE",
"when",
"pidfile",
"is",
"active",
"or",
"FALSE",
"when",
"is",
"not",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L157-L165 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.getProcessId | public function getProcessId()
{
if (null === $this->processId) {
$content = fgets($this->getFileResource());
$pieces = explode(PHP_EOL, trim($content));
$this->processId = reset($pieces) ?: 0;
}
return $this->processId ?: null;
} | php | public function getProcessId()
{
if (null === $this->processId) {
$content = fgets($this->getFileResource());
$pieces = explode(PHP_EOL, trim($content));
$this->processId = reset($pieces) ?: 0;
}
return $this->processId ?: null;
} | [
"public",
"function",
"getProcessId",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"processId",
")",
"{",
"$",
"content",
"=",
"fgets",
"(",
"$",
"this",
"->",
"getFileResource",
"(",
")",
")",
";",
"$",
"pieces",
"=",
"explode",
"(",
... | Returns Pidfile content with the PID or NULL when there is no stored PID.
@return int|null | [
"Returns",
"Pidfile",
"content",
"with",
"the",
"PID",
"or",
"NULL",
"when",
"there",
"is",
"no",
"stored",
"PID",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L172-L181 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.initialize | public function initialize()
{
if ($this->isActive()) {
throw new RuntimeException('Process is already active');
}
$handle = $this->getFileResource();
if (! @flock($handle, (LOCK_EX | LOCK_NB))) {
throw new RuntimeException('Could not lock pidfile');
}
if (-1 === @fseek($handle, 0)) {
throw new RuntimeException('Could not seek pidfile cursor');
}
if (! @ftruncate($handle, 0)) {
throw new RuntimeException('Could not truncate pidfile');
}
if (! @fwrite($handle, $this->control->info()->getId().PHP_EOL)) {
throw new RuntimeException('Could not write on pidfile');
}
} | php | public function initialize()
{
if ($this->isActive()) {
throw new RuntimeException('Process is already active');
}
$handle = $this->getFileResource();
if (! @flock($handle, (LOCK_EX | LOCK_NB))) {
throw new RuntimeException('Could not lock pidfile');
}
if (-1 === @fseek($handle, 0)) {
throw new RuntimeException('Could not seek pidfile cursor');
}
if (! @ftruncate($handle, 0)) {
throw new RuntimeException('Could not truncate pidfile');
}
if (! @fwrite($handle, $this->control->info()->getId().PHP_EOL)) {
throw new RuntimeException('Could not write on pidfile');
}
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isActive",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Process is already active'",
")",
";",
"}",
"$",
"handle",
"=",
"$",
"this",
"->",
"getFileResource"... | Initializes pidfile.
Create an empty file, store the PID into the file and lock it. | [
"Initializes",
"pidfile",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L188-L211 | train |
Arara/Process | src/Arara/Process/Pidfile.php | Pidfile.finalize | public function finalize()
{
@flock($this->getFileResource(), LOCK_UN);
@fclose($this->getFileResource());
@unlink($this->getFileName());
} | php | public function finalize()
{
@flock($this->getFileResource(), LOCK_UN);
@fclose($this->getFileResource());
@unlink($this->getFileName());
} | [
"public",
"function",
"finalize",
"(",
")",
"{",
"@",
"flock",
"(",
"$",
"this",
"->",
"getFileResource",
"(",
")",
",",
"LOCK_UN",
")",
";",
"@",
"fclose",
"(",
"$",
"this",
"->",
"getFileResource",
"(",
")",
")",
";",
"@",
"unlink",
"(",
"$",
"th... | Finalizes pidfile.
Unlock pidfile and removes it. | [
"Finalizes",
"pidfile",
"."
] | 98d42b5b466870f93eb0c85d62b1d7a1241040c3 | https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Pidfile.php#L218-L223 | train |
phpcr/phpcr-shell | src/PHPCR/Shell/Config/ConfigManager.php | ConfigManager.getConfigDir | public function getConfigDir()
{
$home = getenv('PHPCRSH_HOME');
if ($home) {
return $home;
}
// handle windows ..
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
if (!getenv('APPDATA')) {
throw new \RuntimeException(
'The APPDATA or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly'
);
}
$home = strtr(getenv('APPDATA'), '\\', '/').'/phpcrsh';
return $home;
}
if (!getenv('HOME')) {
throw new \RuntimeException(
'The HOME or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly'
);
}
$home = rtrim(getenv('HOME'), '/').'/.phpcrsh';
return $home;
} | php | public function getConfigDir()
{
$home = getenv('PHPCRSH_HOME');
if ($home) {
return $home;
}
// handle windows ..
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
if (!getenv('APPDATA')) {
throw new \RuntimeException(
'The APPDATA or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly'
);
}
$home = strtr(getenv('APPDATA'), '\\', '/').'/phpcrsh';
return $home;
}
if (!getenv('HOME')) {
throw new \RuntimeException(
'The HOME or phpcrsh_HOME environment variable must be set for phpcrsh to run correctly'
);
}
$home = rtrim(getenv('HOME'), '/').'/.phpcrsh';
return $home;
} | [
"public",
"function",
"getConfigDir",
"(",
")",
"{",
"$",
"home",
"=",
"getenv",
"(",
"'PHPCRSH_HOME'",
")",
";",
"if",
"(",
"$",
"home",
")",
"{",
"return",
"$",
"home",
";",
"}",
"// handle windows ..",
"if",
"(",
"defined",
"(",
"'PHP_WINDOWS_VERSION_MA... | Return the configuration directory.
@return string | [
"Return",
"the",
"configuration",
"directory",
"."
] | 360febfaf4760cafcd22d6a0c7503bd8d6e79eea | https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Config/ConfigManager.php#L78-L106 | train |
phpcr/phpcr-shell | src/PHPCR/Shell/Config/ConfigManager.php | ConfigManager.initConfig | public function initConfig(OutputInterface $output = null)
{
$log = function ($message) use ($output) {
if ($output) {
$output->writeln($message);
}
};
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
throw new \RuntimeException('This feature is currently only supported on Linux and OSX (maybe). Please submit a PR to support it on windows.');
}
$configDir = $this->getConfigDir();
$distDir = $this->getDistConfigDir();
if (!$this->filesystem->exists($configDir)) {
$log('<info>[+] Creating directory:</info> '.$configDir);
$this->filesystem->mkdir($configDir);
}
$configFilenames = [
'alias.yml',
'phpcrsh.yml',
];
foreach ($configFilenames as $configFilename) {
$srcFile = $distDir.'/'.$configFilename;
$destFile = $configDir.'/'.$configFilename;
if (!$this->filesystem->exists($srcFile)) {
throw new \Exception('Dist (source) file "'.$srcFile.'" does not exist.');
}
if ($this->filesystem->exists($destFile)) {
$log(sprintf('<info>File</info> %s <info> already exists, not overwriting.', $destFile));
return;
}
$this->filesystem->copy($srcFile, $destFile);
$log('<info>[+] Creating file:</info> '.$destFile);
}
} | php | public function initConfig(OutputInterface $output = null)
{
$log = function ($message) use ($output) {
if ($output) {
$output->writeln($message);
}
};
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
throw new \RuntimeException('This feature is currently only supported on Linux and OSX (maybe). Please submit a PR to support it on windows.');
}
$configDir = $this->getConfigDir();
$distDir = $this->getDistConfigDir();
if (!$this->filesystem->exists($configDir)) {
$log('<info>[+] Creating directory:</info> '.$configDir);
$this->filesystem->mkdir($configDir);
}
$configFilenames = [
'alias.yml',
'phpcrsh.yml',
];
foreach ($configFilenames as $configFilename) {
$srcFile = $distDir.'/'.$configFilename;
$destFile = $configDir.'/'.$configFilename;
if (!$this->filesystem->exists($srcFile)) {
throw new \Exception('Dist (source) file "'.$srcFile.'" does not exist.');
}
if ($this->filesystem->exists($destFile)) {
$log(sprintf('<info>File</info> %s <info> already exists, not overwriting.', $destFile));
return;
}
$this->filesystem->copy($srcFile, $destFile);
$log('<info>[+] Creating file:</info> '.$destFile);
}
} | [
"public",
"function",
"initConfig",
"(",
"OutputInterface",
"$",
"output",
"=",
"null",
")",
"{",
"$",
"log",
"=",
"function",
"(",
"$",
"message",
")",
"use",
"(",
"$",
"output",
")",
"{",
"if",
"(",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"... | Initialize a configuration files. | [
"Initialize",
"a",
"configuration",
"files",
"."
] | 360febfaf4760cafcd22d6a0c7503bd8d6e79eea | https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Config/ConfigManager.php#L177-L219 | train |
sonata-project/SonataCommentBundle | src/DependencyInjection/SonataCommentExtension.php | SonataCommentExtension.hasBundle | protected function hasBundle($name, ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
return isset($bundles[$name]);
} | php | protected function hasBundle($name, ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
return isset($bundles[$name]);
} | [
"protected",
"function",
"hasBundle",
"(",
"$",
"name",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"bundles",
"=",
"$",
"container",
"->",
"getParameter",
"(",
"'kernel.bundles'",
")",
";",
"return",
"isset",
"(",
"$",
"bundles",
"[",
"$",
"... | Returns if a bundle is available.
@param string $name A bundle name
@param ContainerBuilder $container Symfony dependency injection container
@return bool | [
"Returns",
"if",
"a",
"bundle",
"is",
"available",
"."
] | f78a08e64434242d1d1f0bbd82a7f9e27939d546 | https://github.com/sonata-project/SonataCommentBundle/blob/f78a08e64434242d1d1f0bbd82a7f9e27939d546/src/DependencyInjection/SonataCommentExtension.php#L261-L266 | train |
larabros/elogram | src/Repositories/TagsRepository.php | TagsRepository.getRecentMedia | public function getRecentMedia($tag, $count = null, $minTagId = null, $maxTagId = null)
{
$params = ['query' => [
'count' => $count,
'min_tag_id' => $minTagId,
'max_tag_id' => $maxTagId,
]];
return $this->client->request('GET', "tags/$tag/media/recent", $params);
} | php | public function getRecentMedia($tag, $count = null, $minTagId = null, $maxTagId = null)
{
$params = ['query' => [
'count' => $count,
'min_tag_id' => $minTagId,
'max_tag_id' => $maxTagId,
]];
return $this->client->request('GET', "tags/$tag/media/recent", $params);
} | [
"public",
"function",
"getRecentMedia",
"(",
"$",
"tag",
",",
"$",
"count",
"=",
"null",
",",
"$",
"minTagId",
"=",
"null",
",",
"$",
"maxTagId",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"'query'",
"=>",
"[",
"'count'",
"=>",
"$",
"count",
"... | Get a list of recently tagged media.
@param string $tag Name of the tag
@param int|null $count Count of tagged media to return
@param string|null $minTagId Return media before this min_tag_id
@param string|null $maxTagId Return media after this max_tag_id
@return Response
@link https://www.instagram.com/developer/endpoints/tags/#get_tags_media_recent | [
"Get",
"a",
"list",
"of",
"recently",
"tagged",
"media",
"."
] | 89b861d8befaf4f4f0e7c594c9da4eb52a6462c6 | https://github.com/larabros/elogram/blob/89b861d8befaf4f4f0e7c594c9da4eb52a6462c6/src/Repositories/TagsRepository.php#L43-L51 | train |
larabros/elogram | src/Helpers/RedirectLoginHelper.php | RedirectLoginHelper.getLoginUrl | public function getLoginUrl(array $options = [])
{
$url = $this->provider->getAuthorizationUrl($options);
$this->store->set('oauth2state', $this->provider->getState());
return $url;
} | php | public function getLoginUrl(array $options = [])
{
$url = $this->provider->getAuthorizationUrl($options);
$this->store->set('oauth2state', $this->provider->getState());
return $url;
} | [
"public",
"function",
"getLoginUrl",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"provider",
"->",
"getAuthorizationUrl",
"(",
"$",
"options",
")",
";",
"$",
"this",
"->",
"store",
"->",
"set",
"(",
"'oa... | Sets CSRF value and returns the login URL.
@param array $options
@return string
@see League\OAuth2\Client\Provider\AbstractProvider::getAuthorizationUrl() | [
"Sets",
"CSRF",
"value",
"and",
"returns",
"the",
"login",
"URL",
"."
] | 89b861d8befaf4f4f0e7c594c9da4eb52a6462c6 | https://github.com/larabros/elogram/blob/89b861d8befaf4f4f0e7c594c9da4eb52a6462c6/src/Helpers/RedirectLoginHelper.php#L51-L56 | train |
larabros/elogram | src/Helpers/RedirectLoginHelper.php | RedirectLoginHelper.getAccessToken | public function getAccessToken($code, $grant = 'authorization_code')
{
$this->validateCsrf();
return $this->provider->getAccessToken($grant, ['code' => $code]);
} | php | public function getAccessToken($code, $grant = 'authorization_code')
{
$this->validateCsrf();
return $this->provider->getAccessToken($grant, ['code' => $code]);
} | [
"public",
"function",
"getAccessToken",
"(",
"$",
"code",
",",
"$",
"grant",
"=",
"'authorization_code'",
")",
"{",
"$",
"this",
"->",
"validateCsrf",
"(",
")",
";",
"return",
"$",
"this",
"->",
"provider",
"->",
"getAccessToken",
"(",
"$",
"grant",
",",
... | Validates CSRF and returns the access token.
@param string $code
@param string $grant
@return AccessToken
@see League\OAuth2\Client\Provider\AbstractProvider::getAccessToken() | [
"Validates",
"CSRF",
"and",
"returns",
"the",
"access",
"token",
"."
] | 89b861d8befaf4f4f0e7c594c9da4eb52a6462c6 | https://github.com/larabros/elogram/blob/89b861d8befaf4f4f0e7c594c9da4eb52a6462c6/src/Helpers/RedirectLoginHelper.php#L68-L72 | train |
larabros/elogram | src/Helpers/RedirectLoginHelper.php | RedirectLoginHelper.validateCsrf | protected function validateCsrf()
{
if (empty($this->getInput('state'))
|| ($this->getInput('state') !== $this->store->get('oauth2state'))
) {
$this->store->set('oauth2state', null);
throw new CsrfException('Invalid state');
}
return;
} | php | protected function validateCsrf()
{
if (empty($this->getInput('state'))
|| ($this->getInput('state') !== $this->store->get('oauth2state'))
) {
$this->store->set('oauth2state', null);
throw new CsrfException('Invalid state');
}
return;
} | [
"protected",
"function",
"validateCsrf",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"getInput",
"(",
"'state'",
")",
")",
"||",
"(",
"$",
"this",
"->",
"getInput",
"(",
"'state'",
")",
"!==",
"$",
"this",
"->",
"store",
"->",
"get",
... | Validates any CSRF parameters.
@throws CsrfException | [
"Validates",
"any",
"CSRF",
"parameters",
"."
] | 89b861d8befaf4f4f0e7c594c9da4eb52a6462c6 | https://github.com/larabros/elogram/blob/89b861d8befaf4f4f0e7c594c9da4eb52a6462c6/src/Helpers/RedirectLoginHelper.php#L79-L88 | train |
larabros/elogram | src/Client.php | Client.getAccessToken | public function getAccessToken($code, $grant = 'authorization_code')
{
$token = $this->container->get(RedirectLoginHelper::class)
->getAccessToken($code, $grant);
$this->setAccessToken($token);
return $token;
} | php | public function getAccessToken($code, $grant = 'authorization_code')
{
$token = $this->container->get(RedirectLoginHelper::class)
->getAccessToken($code, $grant);
$this->setAccessToken($token);
return $token;
} | [
"public",
"function",
"getAccessToken",
"(",
"$",
"code",
",",
"$",
"grant",
"=",
"'authorization_code'",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"RedirectLoginHelper",
"::",
"class",
")",
"->",
"getAccessToken",
"(",
... | Sets and returns the access token.
@param string $code
@param string $grant
@return AccessToken
@see Elogram\Helpers\RedirectLoginHelper::getAccessToken()
@codeCoverageIgnore | [
"Sets",
"and",
"returns",
"the",
"access",
"token",
"."
] | 89b861d8befaf4f4f0e7c594c9da4eb52a6462c6 | https://github.com/larabros/elogram/blob/89b861d8befaf4f4f0e7c594c9da4eb52a6462c6/src/Client.php#L222-L228 | train |
larabros/elogram | src/Client.php | Client.setAccessToken | public function setAccessToken(AccessToken $token)
{
$this->container->get('config')
->set('access_token', json_encode($token->jsonSerialize()));
} | php | public function setAccessToken(AccessToken $token)
{
$this->container->get('config')
->set('access_token', json_encode($token->jsonSerialize()));
} | [
"public",
"function",
"setAccessToken",
"(",
"AccessToken",
"$",
"token",
")",
"{",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'config'",
")",
"->",
"set",
"(",
"'access_token'",
",",
"json_encode",
"(",
"$",
"token",
"->",
"jsonSerialize",
"(",
")... | Sets an access token and adds it to `AuthMiddleware` so the application
can make authenticated requests.
@param AccessToken $token
@return void
@codeCoverageIgnore | [
"Sets",
"an",
"access",
"token",
"and",
"adds",
"it",
"to",
"AuthMiddleware",
"so",
"the",
"application",
"can",
"make",
"authenticated",
"requests",
"."
] | 89b861d8befaf4f4f0e7c594c9da4eb52a6462c6 | https://github.com/larabros/elogram/blob/89b861d8befaf4f4f0e7c594c9da4eb52a6462c6/src/Client.php#L240-L244 | train |
forxer/gravatar | src/Profile.php | Profile.getData | public function getData($sEmail)
{
$this->sFormat = 'php';
$sProfile = file_get_contents($this->getUrl($sEmail));
$aProfile = unserialize($sProfile);
if (is_array($aProfile) && isset($aProfile['entry'])) {
return $aProfile;
}
} | php | public function getData($sEmail)
{
$this->sFormat = 'php';
$sProfile = file_get_contents($this->getUrl($sEmail));
$aProfile = unserialize($sProfile);
if (is_array($aProfile) && isset($aProfile['entry'])) {
return $aProfile;
}
} | [
"public",
"function",
"getData",
"(",
"$",
"sEmail",
")",
"{",
"$",
"this",
"->",
"sFormat",
"=",
"'php'",
";",
"$",
"sProfile",
"=",
"file_get_contents",
"(",
"$",
"this",
"->",
"getUrl",
"(",
"$",
"sEmail",
")",
")",
";",
"$",
"aProfile",
"=",
"uns... | Return profile data based on the provided email address.
@param string $sEmail The email to get the gravatar profile for
@return array | [
"Return",
"profile",
"data",
"based",
"on",
"the",
"provided",
"email",
"address",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Profile.php#L58-L69 | train |
forxer/gravatar | src/Profile.php | Profile.format | public function format($sFormat= null)
{
if (null === $sFormat) {
return $this->getFormat();
}
return $this->setFormat($sFormat);
} | php | public function format($sFormat= null)
{
if (null === $sFormat) {
return $this->getFormat();
}
return $this->setFormat($sFormat);
} | [
"public",
"function",
"format",
"(",
"$",
"sFormat",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sFormat",
")",
"{",
"return",
"$",
"this",
"->",
"getFormat",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setFormat",
"(",
"$",
"sForm... | Get or set the profile format to use.
@param string $sFormat The profile format to use.
@return string|\forxer\Gravatar\Profile | [
"Get",
"or",
"set",
"the",
"profile",
"format",
"to",
"use",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Profile.php#L77-L84 | train |
forxer/gravatar | src/Profile.php | Profile.setFormat | public function setFormat($sFormat = null)
{
if (null === $sFormat) {
return $this;
}
if (!in_array($sFormat, $this->aValidFormats)) {
$message = sprintf(
'The format "%s" is not a valid one, profile format for Gravatar can be: %s',
$sFormat,
implode(', ', $this->aValidFormats)
);
throw new InvalidProfileFormatException($message);
}
$this->sFormat = $sFormat;
return $this;
} | php | public function setFormat($sFormat = null)
{
if (null === $sFormat) {
return $this;
}
if (!in_array($sFormat, $this->aValidFormats)) {
$message = sprintf(
'The format "%s" is not a valid one, profile format for Gravatar can be: %s',
$sFormat,
implode(', ', $this->aValidFormats)
);
throw new InvalidProfileFormatException($message);
}
$this->sFormat = $sFormat;
return $this;
} | [
"public",
"function",
"setFormat",
"(",
"$",
"sFormat",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sFormat",
")",
"{",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"$",
"sFormat",
",",
"$",
"this",
"->",
"aValidForm... | Set the profile format to use.
@param string $sFormat The profile format to use
@throws \InvalidArgumentException
@return \forxer\Gravatar\Profile The current Profile instance | [
"Set",
"the",
"profile",
"format",
"to",
"use",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Profile.php#L114-L133 | train |
LibreHealthIO/lh-ehr-fhir-api | src/Http/Controllers/Auth/RegisterController.php | RegisterController.createSignup | protected function createSignup(array $data, $userId)
{
return Signup::create([
'user_id' => $userId,
'firstname' => $data['firstname'],
'surname' => $data['surname'],
'gender' => $data['gender'],
'email' => $data['email'],
'mobile_number' => $data['mobile_number'],
]);
} | php | protected function createSignup(array $data, $userId)
{
return Signup::create([
'user_id' => $userId,
'firstname' => $data['firstname'],
'surname' => $data['surname'],
'gender' => $data['gender'],
'email' => $data['email'],
'mobile_number' => $data['mobile_number'],
]);
} | [
"protected",
"function",
"createSignup",
"(",
"array",
"$",
"data",
",",
"$",
"userId",
")",
"{",
"return",
"Signup",
"::",
"create",
"(",
"[",
"'user_id'",
"=>",
"$",
"userId",
",",
"'firstname'",
"=>",
"$",
"data",
"[",
"'firstname'",
"]",
",",
"'surna... | Create a new user profile after a valid registration.
@param array $data
@param int $userId
@return User | [
"Create",
"a",
"new",
"user",
"profile",
"after",
"a",
"valid",
"registration",
"."
] | 3250c17e537ed81030884ff6e7319a91483ccfc6 | https://github.com/LibreHealthIO/lh-ehr-fhir-api/blob/3250c17e537ed81030884ff6e7319a91483ccfc6/src/Http/Controllers/Auth/RegisterController.php#L65-L75 | train |
teamreflex/ChallongePHP | src/Challonge/Helpers/Guzzle.php | Guzzle.handleErrors | private static function handleErrors($response)
{
switch ($response->getStatusCode()) {
case 200:
return json_decode($response->getBody());
break;
case 401:
throw new UnauthorizedException('Unauthorized (Invalid API key or insufficient permissions)');
break;
case 404:
throw new NotFoundException('Object not found within your account scope');
break;
case 406:
throw new InvalidFormatException('Requested format is not supported - request JSON or XML only');
break;
case 422:
throw new ValidationException('Validation error(s) for create or update method');
break;
case 500:
throw new ServerException('Something went wrong on Challonge\'s end');
break;
default:
$decodedResponse = json_decode($response->getBody());
throw new UnexpectedErrorException($decodedResponse);
break;
}
} | php | private static function handleErrors($response)
{
switch ($response->getStatusCode()) {
case 200:
return json_decode($response->getBody());
break;
case 401:
throw new UnauthorizedException('Unauthorized (Invalid API key or insufficient permissions)');
break;
case 404:
throw new NotFoundException('Object not found within your account scope');
break;
case 406:
throw new InvalidFormatException('Requested format is not supported - request JSON or XML only');
break;
case 422:
throw new ValidationException('Validation error(s) for create or update method');
break;
case 500:
throw new ServerException('Something went wrong on Challonge\'s end');
break;
default:
$decodedResponse = json_decode($response->getBody());
throw new UnexpectedErrorException($decodedResponse);
break;
}
} | [
"private",
"static",
"function",
"handleErrors",
"(",
"$",
"response",
")",
"{",
"switch",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
")",
"{",
"case",
"200",
":",
"return",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
")",... | Handles the response and throws errors accordingly.
@param $response GuzzleHttp\Psr7\Response
@return stdClass | [
"Handles",
"the",
"response",
"and",
"throws",
"errors",
"accordingly",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Helpers/Guzzle.php#L68-L94 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator/LatLong.php | LatLong.primeCoordinateParsers | protected function primeCoordinateParsers() {
$this->latitude->getParser()->setDirection(N::LAT);
$this->longitude->getParser()->setDirection(N::LONG);
} | php | protected function primeCoordinateParsers() {
$this->latitude->getParser()->setDirection(N::LAT);
$this->longitude->getParser()->setDirection(N::LONG);
} | [
"protected",
"function",
"primeCoordinateParsers",
"(",
")",
"{",
"$",
"this",
"->",
"latitude",
"->",
"getParser",
"(",
")",
"->",
"setDirection",
"(",
"N",
"::",
"LAT",
")",
";",
"$",
"this",
"->",
"longitude",
"->",
"getParser",
"(",
")",
"->",
"setDi... | Prime the coordinate parser with any additional information
necessary | [
"Prime",
"the",
"coordinate",
"parser",
"with",
"any",
"additional",
"information",
"necessary"
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator/LatLong.php#L47-L50 | train |
novosga/reports-bundle | Controller/DefaultController.php | DefaultController.servicosDisponiveisUnidade | private function servicosDisponiveisUnidade($unidade)
{
$rs = $this
->getDoctrine()
->getManager()
->createQueryBuilder()
->select([
'e',
's',
'sub'
])
->from(ServicoUnidade::class, 'e')
->join('e.servico', 's')
->leftJoin('s.subServicos', 'sub')
->where('s.mestre IS NULL')
->andWhere('e.ativo = TRUE')
->andWhere('e.unidade = :unidade')
->orderBy('s.nome', 'ASC')
->setParameter('unidade', $unidade)
->getQuery()
->getResult();
$dados = [
'unidade' => $unidade->getNome(),
'servicos' => $rs,
];
return $dados;
} | php | private function servicosDisponiveisUnidade($unidade)
{
$rs = $this
->getDoctrine()
->getManager()
->createQueryBuilder()
->select([
'e',
's',
'sub'
])
->from(ServicoUnidade::class, 'e')
->join('e.servico', 's')
->leftJoin('s.subServicos', 'sub')
->where('s.mestre IS NULL')
->andWhere('e.ativo = TRUE')
->andWhere('e.unidade = :unidade')
->orderBy('s.nome', 'ASC')
->setParameter('unidade', $unidade)
->getQuery()
->getResult();
$dados = [
'unidade' => $unidade->getNome(),
'servicos' => $rs,
];
return $dados;
} | [
"private",
"function",
"servicosDisponiveisUnidade",
"(",
"$",
"unidade",
")",
"{",
"$",
"rs",
"=",
"$",
"this",
"->",
"getDoctrine",
"(",
")",
"->",
"getManager",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
"->",
"select",
"(",
"[",
"'e'",
",",
"'s'... | Retorna todos os servicos disponiveis para cada unidade.
@return array | [
"Retorna",
"todos",
"os",
"servicos",
"disponiveis",
"para",
"cada",
"unidade",
"."
] | e390dc9a5f11655307e377da8d4135c2ee24dd06 | https://github.com/novosga/reports-bundle/blob/e390dc9a5f11655307e377da8d4135c2ee24dd06/Controller/DefaultController.php#L337-L365 | train |
Whyounes/laravel-passwordless-auth | src/Providers/PasswordlessProvider.php | PasswordlessProvider.registerEvents | public function registerEvents()
{
// Delete user tokens after login
if (config('passwordless.empty_tokens_after_login') === true) {
Event::listen(
Authenticated::class,
function (Authenticated $event) {
$event->user->tokens()
->delete();
}
);
}
} | php | public function registerEvents()
{
// Delete user tokens after login
if (config('passwordless.empty_tokens_after_login') === true) {
Event::listen(
Authenticated::class,
function (Authenticated $event) {
$event->user->tokens()
->delete();
}
);
}
} | [
"public",
"function",
"registerEvents",
"(",
")",
"{",
"// Delete user tokens after login",
"if",
"(",
"config",
"(",
"'passwordless.empty_tokens_after_login'",
")",
"===",
"true",
")",
"{",
"Event",
"::",
"listen",
"(",
"Authenticated",
"::",
"class",
",",
"functio... | Register application event listeners | [
"Register",
"application",
"event",
"listeners"
] | 0cfbdfede2f2fcca950355e420ff13e51236ed5f | https://github.com/Whyounes/laravel-passwordless-auth/blob/0cfbdfede2f2fcca950355e420ff13e51236ed5f/src/Providers/PasswordlessProvider.php#L37-L49 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.processOne | public function processOne(ObjectId $id): void
{
$this->catchSignal();
$this->logger->debug('process job ['.$id.'] and exit', [
'category' => get_class($this),
]);
try {
$job = $this->scheduler->getJob($id)->toArray();
$this->queueJob($job);
} catch (\Exception $e) {
$this->logger->error('failed process job ['.$id.']', [
'category' => get_class($this),
'exception' => $e,
]);
}
} | php | public function processOne(ObjectId $id): void
{
$this->catchSignal();
$this->logger->debug('process job ['.$id.'] and exit', [
'category' => get_class($this),
]);
try {
$job = $this->scheduler->getJob($id)->toArray();
$this->queueJob($job);
} catch (\Exception $e) {
$this->logger->error('failed process job ['.$id.']', [
'category' => get_class($this),
'exception' => $e,
]);
}
} | [
"public",
"function",
"processOne",
"(",
"ObjectId",
"$",
"id",
")",
":",
"void",
"{",
"$",
"this",
"->",
"catchSignal",
"(",
")",
";",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'process job ['",
".",
"$",
"id",
".",
"'] and exit'",
",",
"[",
... | Process one. | [
"Process",
"one",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L234-L251 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.cleanup | public function cleanup()
{
$this->saveState();
if (null === $this->current_job) {
$this->logger->debug('received cleanup call on worker ['.$this->id.'], no job is currently processing, exit now', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->exit();
return null;
}
$this->logger->debug('received cleanup call on worker ['.$this->id.'], reschedule current processing job ['.$this->current_job['_id'].']', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->updateJob($this->current_job, JobInterface::STATUS_CANCELED);
$this->db->{$this->scheduler->getEventQueue()}->insertOne([
'job' => $this->current_job['_id'],
'worker' => $this->id,
'status' => JobInterface::STATUS_CANCELED,
'timestamp' => new UTCDateTime(),
]);
$options = $this->current_job['options'];
$options['at'] = 0;
$result = $this->scheduler->addJob($this->current_job['class'], $this->current_job['data'], $options)->getId();
$this->exit();
return $result;
} | php | public function cleanup()
{
$this->saveState();
if (null === $this->current_job) {
$this->logger->debug('received cleanup call on worker ['.$this->id.'], no job is currently processing, exit now', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->exit();
return null;
}
$this->logger->debug('received cleanup call on worker ['.$this->id.'], reschedule current processing job ['.$this->current_job['_id'].']', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->updateJob($this->current_job, JobInterface::STATUS_CANCELED);
$this->db->{$this->scheduler->getEventQueue()}->insertOne([
'job' => $this->current_job['_id'],
'worker' => $this->id,
'status' => JobInterface::STATUS_CANCELED,
'timestamp' => new UTCDateTime(),
]);
$options = $this->current_job['options'];
$options['at'] = 0;
$result = $this->scheduler->addJob($this->current_job['class'], $this->current_job['data'], $options)->getId();
$this->exit();
return $result;
} | [
"public",
"function",
"cleanup",
"(",
")",
"{",
"$",
"this",
"->",
"saveState",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"current_job",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'received cleanup call on worker ['",
"... | Cleanup and exit. | [
"Cleanup",
"and",
"exit",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L256-L292 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.saveState | protected function saveState(): self
{
foreach ($this->queue as $key => $job) {
$this->db->selectCollection($this->scheduler->getJobQueue())->updateOne(
['_id' => $job['_id'], '$isolated' => true],
['$setOnInsert' => $job],
['upsert' => true]
);
}
return $this;
} | php | protected function saveState(): self
{
foreach ($this->queue as $key => $job) {
$this->db->selectCollection($this->scheduler->getJobQueue())->updateOne(
['_id' => $job['_id'], '$isolated' => true],
['$setOnInsert' => $job],
['upsert' => true]
);
}
return $this;
} | [
"protected",
"function",
"saveState",
"(",
")",
":",
"self",
"{",
"foreach",
"(",
"$",
"this",
"->",
"queue",
"as",
"$",
"key",
"=>",
"$",
"job",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"selectCollection",
"(",
"$",
"this",
"->",
"scheduler",
"->",
... | Save local queue. | [
"Save",
"local",
"queue",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L297-L308 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.catchSignal | protected function catchSignal(): self
{
pcntl_async_signals(true);
pcntl_signal(SIGTERM, [$this, 'cleanup']);
pcntl_signal(SIGINT, [$this, 'cleanup']);
pcntl_signal(SIGALRM, [$this, 'timeout']);
return $this;
} | php | protected function catchSignal(): self
{
pcntl_async_signals(true);
pcntl_signal(SIGTERM, [$this, 'cleanup']);
pcntl_signal(SIGINT, [$this, 'cleanup']);
pcntl_signal(SIGALRM, [$this, 'timeout']);
return $this;
} | [
"protected",
"function",
"catchSignal",
"(",
")",
":",
"self",
"{",
"pcntl_async_signals",
"(",
"true",
")",
";",
"pcntl_signal",
"(",
"SIGTERM",
",",
"[",
"$",
"this",
",",
"'cleanup'",
"]",
")",
";",
"pcntl_signal",
"(",
"SIGINT",
",",
"[",
"$",
"this"... | Catch signals and cleanup. | [
"Catch",
"signals",
"and",
"cleanup",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L313-L321 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.queueJob | protected function queueJob(array $job): bool
{
if (!isset($job['status'])) {
return false;
}
if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING)) {
$this->processJob($job);
} elseif (JobInterface::STATUS_POSTPONED === $job['status']) {
$this->logger->debug('found postponed job ['.$job['_id'].'] to requeue', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->queue[(string) $job['_id']] = $job;
}
return true;
} | php | protected function queueJob(array $job): bool
{
if (!isset($job['status'])) {
return false;
}
if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING)) {
$this->processJob($job);
} elseif (JobInterface::STATUS_POSTPONED === $job['status']) {
$this->logger->debug('found postponed job ['.$job['_id'].'] to requeue', [
'category' => get_class($this),
'pm' => $this->process,
]);
$this->queue[(string) $job['_id']] = $job;
}
return true;
} | [
"protected",
"function",
"queueJob",
"(",
"array",
"$",
"job",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"job",
"[",
"'status'",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"true",
"===",
"$",
"this",
"->",
"collec... | Queue job. | [
"Queue",
"job",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L326-L344 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.processLocalQueue | protected function processLocalQueue(): bool
{
$now = time();
foreach ($this->queue as $key => $job) {
$this->db->{$this->scheduler->getJobQueue()}->updateOne(
['_id' => $job['_id'], '$isolated' => true],
['$setOnInsert' => $job],
['upsert' => true]
);
if ($job['options']['at'] <= $now) {
$this->logger->info('postponed job ['.$job['_id'].'] ['.$job['class'].'] can now be executed', [
'category' => get_class($this),
'pm' => $this->process,
]);
unset($this->queue[$key]);
$job['options']['at'] = 0;
if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING, JobInterface::STATUS_POSTPONED)) {
$this->processJob($job);
}
}
}
return true;
} | php | protected function processLocalQueue(): bool
{
$now = time();
foreach ($this->queue as $key => $job) {
$this->db->{$this->scheduler->getJobQueue()}->updateOne(
['_id' => $job['_id'], '$isolated' => true],
['$setOnInsert' => $job],
['upsert' => true]
);
if ($job['options']['at'] <= $now) {
$this->logger->info('postponed job ['.$job['_id'].'] ['.$job['class'].'] can now be executed', [
'category' => get_class($this),
'pm' => $this->process,
]);
unset($this->queue[$key]);
$job['options']['at'] = 0;
if (true === $this->collectJob($job, JobInterface::STATUS_PROCESSING, JobInterface::STATUS_POSTPONED)) {
$this->processJob($job);
}
}
}
return true;
} | [
"protected",
"function",
"processLocalQueue",
"(",
")",
":",
"bool",
"{",
"$",
"now",
"=",
"time",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"queue",
"as",
"$",
"key",
"=>",
"$",
"job",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"{",
"$",
... | Check local queue for postponed jobs. | [
"Check",
"local",
"queue",
"for",
"postponed",
"jobs",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L423-L449 | train |
gyselroth/mongodb-php-task-scheduler | src/Worker.php | Worker.executeJob | protected function executeJob(array $job): bool
{
if (!class_exists($job['class'])) {
throw new InvalidJobException('job class does not exists');
}
if (null === $this->container) {
$instance = new $job['class']();
} else {
$instance = $this->container->get($job['class']);
}
if (!($instance instanceof JobInterface)) {
throw new InvalidJobException('job must implement JobInterface');
}
$instance
->setData($job['data'])
->setId($job['_id'])
->start();
$return = $this->updateJob($job, JobInterface::STATUS_DONE);
$this->db->{$this->scheduler->getEventQueue()}->insertOne([
'job' => $job['_id'],
'worker' => $this->id,
'status' => JobInterface::STATUS_DONE,
'timestamp' => new UTCDateTime(),
]);
unset($instance);
return $return;
} | php | protected function executeJob(array $job): bool
{
if (!class_exists($job['class'])) {
throw new InvalidJobException('job class does not exists');
}
if (null === $this->container) {
$instance = new $job['class']();
} else {
$instance = $this->container->get($job['class']);
}
if (!($instance instanceof JobInterface)) {
throw new InvalidJobException('job must implement JobInterface');
}
$instance
->setData($job['data'])
->setId($job['_id'])
->start();
$return = $this->updateJob($job, JobInterface::STATUS_DONE);
$this->db->{$this->scheduler->getEventQueue()}->insertOne([
'job' => $job['_id'],
'worker' => $this->id,
'status' => JobInterface::STATUS_DONE,
'timestamp' => new UTCDateTime(),
]);
unset($instance);
return $return;
} | [
"protected",
"function",
"executeJob",
"(",
"array",
"$",
"job",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"job",
"[",
"'class'",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidJobException",
"(",
"'job class does not exists'",
")",
";"... | Execute job. | [
"Execute",
"job",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Worker.php#L555-L588 | train |
tacowordpress/tacowordpress | src/Frontend/Loader.php | Loader.addToHTML | public static function addToHTML()
{
if (!self::isViewingHTMLPage()) {
return;
}
// js
$paths = self::getAssetFilePaths('js');
echo sprintf(
'<script>%s</script>',
self::getCombinedContents($paths)
);
// css
$paths = self::getAssetFilePaths('css');
echo sprintf(
'<style>%s</style>',
self::getCombinedContents($paths)
);
} | php | public static function addToHTML()
{
if (!self::isViewingHTMLPage()) {
return;
}
// js
$paths = self::getAssetFilePaths('js');
echo sprintf(
'<script>%s</script>',
self::getCombinedContents($paths)
);
// css
$paths = self::getAssetFilePaths('css');
echo sprintf(
'<style>%s</style>',
self::getCombinedContents($paths)
);
} | [
"public",
"static",
"function",
"addToHTML",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"isViewingHTMLPage",
"(",
")",
")",
"{",
"return",
";",
"}",
"// js",
"$",
"paths",
"=",
"self",
"::",
"getAssetFilePaths",
"(",
"'js'",
")",
";",
"echo",
"sprint... | Add HTML to the page for frontend code
This is probably not the right way to do it
but it avoids us needing to reference files from vendor over HTTP requests. | [
"Add",
"HTML",
"to",
"the",
"page",
"for",
"frontend",
"code",
"This",
"is",
"probably",
"not",
"the",
"right",
"way",
"to",
"do",
"it",
"but",
"it",
"avoids",
"us",
"needing",
"to",
"reference",
"files",
"from",
"vendor",
"over",
"HTTP",
"requests",
"."... | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Frontend/Loader.php#L23-L42 | train |
tacowordpress/tacowordpress | src/Frontend/Loader.php | Loader.isViewingHTMLPage | public static function isViewingHTMLPage()
{
if (!is_admin()) {
return false;
}
if (!array_key_exists('SCRIPT_NAME', $_SERVER)) {
return false;
}
$whitelisted_script_names = array(
'wp-admin/post-new.php',
'wp-admin/post.php',
'wp-admin/edit.php',
);
$script_name = strstr($_SERVER['SCRIPT_NAME'], 'wp-admin');
if (!in_array($script_name, $whitelisted_script_names)) {
return false;
}
return true;
} | php | public static function isViewingHTMLPage()
{
if (!is_admin()) {
return false;
}
if (!array_key_exists('SCRIPT_NAME', $_SERVER)) {
return false;
}
$whitelisted_script_names = array(
'wp-admin/post-new.php',
'wp-admin/post.php',
'wp-admin/edit.php',
);
$script_name = strstr($_SERVER['SCRIPT_NAME'], 'wp-admin');
if (!in_array($script_name, $whitelisted_script_names)) {
return false;
}
return true;
} | [
"public",
"static",
"function",
"isViewingHTMLPage",
"(",
")",
"{",
"if",
"(",
"!",
"is_admin",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"'SCRIPT_NAME'",
",",
"$",
"_SERVER",
")",
")",
"{",
"return",
"fa... | Is the user currently viewing a HTML page?
Things that are not HTML would be admin-ajax.php for instance
@return bool | [
"Is",
"the",
"user",
"currently",
"viewing",
"a",
"HTML",
"page?",
"Things",
"that",
"are",
"not",
"HTML",
"would",
"be",
"admin",
"-",
"ajax",
".",
"php",
"for",
"instance"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Frontend/Loader.php#L50-L70 | train |
tacowordpress/tacowordpress | src/Frontend/Loader.php | Loader.getAssetFilePaths | public static function getAssetFilePaths($type)
{
$path = sprintf('%s/assets/%s/', __DIR__, $type);
$filenames = preg_grep('/^[^\.]/', scandir($path));
if (!Arr::iterable($filenames)) {
return array();
}
return array_map(function ($filename) use ($path) {
return $path.$filename;
}, $filenames);
} | php | public static function getAssetFilePaths($type)
{
$path = sprintf('%s/assets/%s/', __DIR__, $type);
$filenames = preg_grep('/^[^\.]/', scandir($path));
if (!Arr::iterable($filenames)) {
return array();
}
return array_map(function ($filename) use ($path) {
return $path.$filename;
}, $filenames);
} | [
"public",
"static",
"function",
"getAssetFilePaths",
"(",
"$",
"type",
")",
"{",
"$",
"path",
"=",
"sprintf",
"(",
"'%s/assets/%s/'",
",",
"__DIR__",
",",
"$",
"type",
")",
";",
"$",
"filenames",
"=",
"preg_grep",
"(",
"'/^[^\\.]/'",
",",
"scandir",
"(",
... | Get file paths for a type of asset
@param string $type Ex: js
@return array | [
"Get",
"file",
"paths",
"for",
"a",
"type",
"of",
"asset"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Frontend/Loader.php#L78-L89 | train |
tacowordpress/tacowordpress | src/Frontend/Loader.php | Loader.getCombinedContents | public static function getCombinedContents($paths)
{
if (!Arr::iterable($paths)) {
return '';
}
$out = array();
foreach ($paths as $path) {
$out[] = file_get_contents($path);
}
return join("\n", $out);
} | php | public static function getCombinedContents($paths)
{
if (!Arr::iterable($paths)) {
return '';
}
$out = array();
foreach ($paths as $path) {
$out[] = file_get_contents($path);
}
return join("\n", $out);
} | [
"public",
"static",
"function",
"getCombinedContents",
"(",
"$",
"paths",
")",
"{",
"if",
"(",
"!",
"Arr",
"::",
"iterable",
"(",
"$",
"paths",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"out",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
... | Get the combined contents of multiple file paths
@param string array
@return string | [
"Get",
"the",
"combined",
"contents",
"of",
"multiple",
"file",
"paths"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Frontend/Loader.php#L97-L108 | train |
tianye/WechatMpSDK | src/Utils/Code/Prpcrypt.php | Prpcrypt.decode | public function decode($decrypted)
{
$pad = ord(substr($decrypted, -1));
if ($pad < 1 || $pad > $this->blockSize) {
$pad = 0;
}
return substr($decrypted, 0, (strlen($decrypted) - $pad));
} | php | public function decode($decrypted)
{
$pad = ord(substr($decrypted, -1));
if ($pad < 1 || $pad > $this->blockSize) {
$pad = 0;
}
return substr($decrypted, 0, (strlen($decrypted) - $pad));
} | [
"public",
"function",
"decode",
"(",
"$",
"decrypted",
")",
"{",
"$",
"pad",
"=",
"ord",
"(",
"substr",
"(",
"$",
"decrypted",
",",
"-",
"1",
")",
")",
";",
"if",
"(",
"$",
"pad",
"<",
"1",
"||",
"$",
"pad",
">",
"$",
"this",
"->",
"blockSize",... | Decode string.
@param string $decrypted
@return string | [
"Decode",
"string",
"."
] | 129ed5d08f1ead44fa773fcc864955794c69276b | https://github.com/tianye/WechatMpSDK/blob/129ed5d08f1ead44fa773fcc864955794c69276b/src/Utils/Code/Prpcrypt.php#L148-L157 | train |
gyselroth/mongodb-php-task-scheduler | src/SchedulerValidator.php | SchedulerValidator.validateOptions | public static function validateOptions(array $options): array
{
foreach ($options as $option => $value) {
switch ($option) {
case Scheduler::OPTION_AT:
case Scheduler::OPTION_INTERVAL:
case Scheduler::OPTION_RETRY:
case Scheduler::OPTION_RETRY_INTERVAL:
case Scheduler::OPTION_TIMEOUT:
if (!is_int($value)) {
throw new InvalidArgumentException('option '.$option.' must be an integer');
}
break;
case Scheduler::OPTION_IGNORE_DATA:
case Scheduler::OPTION_FORCE_SPAWN:
if (!is_bool($value)) {
throw new InvalidArgumentException('option '.$option.' must be a boolean');
}
break;
case Scheduler::OPTION_ID:
if (!$value instanceof ObjectId) {
throw new InvalidArgumentException('option '.$option.' must be a an instance of '.ObjectId::class);
}
break;
default:
throw new InvalidArgumentException('invalid option '.$option.' given');
}
}
return $options;
} | php | public static function validateOptions(array $options): array
{
foreach ($options as $option => $value) {
switch ($option) {
case Scheduler::OPTION_AT:
case Scheduler::OPTION_INTERVAL:
case Scheduler::OPTION_RETRY:
case Scheduler::OPTION_RETRY_INTERVAL:
case Scheduler::OPTION_TIMEOUT:
if (!is_int($value)) {
throw new InvalidArgumentException('option '.$option.' must be an integer');
}
break;
case Scheduler::OPTION_IGNORE_DATA:
case Scheduler::OPTION_FORCE_SPAWN:
if (!is_bool($value)) {
throw new InvalidArgumentException('option '.$option.' must be a boolean');
}
break;
case Scheduler::OPTION_ID:
if (!$value instanceof ObjectId) {
throw new InvalidArgumentException('option '.$option.' must be a an instance of '.ObjectId::class);
}
break;
default:
throw new InvalidArgumentException('invalid option '.$option.' given');
}
}
return $options;
} | [
"public",
"static",
"function",
"validateOptions",
"(",
"array",
"$",
"options",
")",
":",
"array",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"option",
"=>",
"$",
"value",
")",
"{",
"switch",
"(",
"$",
"option",
")",
"{",
"case",
"Scheduler",
"::... | Validate given job options. | [
"Validate",
"given",
"job",
"options",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/SchedulerValidator.php#L23-L56 | train |
bigfork/silverstripe-oauth | src/Helper/Helper.php | Helper.addRedirectUriToServiceConfig | protected static function addRedirectUriToServiceConfig(array $config)
{
if (!empty($config['constructor']) && is_array($config['constructor'])) {
$key = key($config['constructor']); // Key may be non-numeric
if (!isset($config['constructor'][$key]['redirectUri'])) {
$config['constructor'][$key]['redirectUri'] = static::getRedirectUri();
}
}
return $config;
} | php | protected static function addRedirectUriToServiceConfig(array $config)
{
if (!empty($config['constructor']) && is_array($config['constructor'])) {
$key = key($config['constructor']); // Key may be non-numeric
if (!isset($config['constructor'][$key]['redirectUri'])) {
$config['constructor'][$key]['redirectUri'] = static::getRedirectUri();
}
}
return $config;
} | [
"protected",
"static",
"function",
"addRedirectUriToServiceConfig",
"(",
"array",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"config",
"[",
"'constructor'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"config",
"[",
"'constructor'",
"]",
")",
")... | Add in the redirectUri option to this service's constructor options
@param array $config
@return array | [
"Add",
"in",
"the",
"redirectUri",
"option",
"to",
"this",
"service",
"s",
"constructor",
"options"
] | 50dd9728369452788d1951e3d1981b2775c2b81d | https://github.com/bigfork/silverstripe-oauth/blob/50dd9728369452788d1951e3d1981b2775c2b81d/src/Helper/Helper.php#L74-L85 | train |
forxer/gravatar | src/Image.php | Image.getUrl | public function getUrl($sEmail = null)
{
if (null !== $sEmail) {
$this->setEmail($sEmail);
}
return static::URL
.'avatar/'
.$this->getHash($this->getEmail())
.$this->getParams();
} | php | public function getUrl($sEmail = null)
{
if (null !== $sEmail) {
$this->setEmail($sEmail);
}
return static::URL
.'avatar/'
.$this->getHash($this->getEmail())
.$this->getParams();
} | [
"public",
"function",
"getUrl",
"(",
"$",
"sEmail",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"sEmail",
")",
"{",
"$",
"this",
"->",
"setEmail",
"(",
"$",
"sEmail",
")",
";",
"}",
"return",
"static",
"::",
"URL",
".",
"'avatar/'",
".",
... | Build the avatar URL based on the provided email address.
@param string $sEmail The email to get the gravatar for.
@return string The URL to the gravatar. | [
"Build",
"the",
"avatar",
"URL",
"based",
"on",
"the",
"provided",
"email",
"address",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L65-L75 | train |
forxer/gravatar | src/Image.php | Image.size | public function size($iSize = null)
{
if (null === $iSize) {
return $this->getSize();
}
return $this->setSize($iSize);
} | php | public function size($iSize = null)
{
if (null === $iSize) {
return $this->getSize();
}
return $this->setSize($iSize);
} | [
"public",
"function",
"size",
"(",
"$",
"iSize",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"iSize",
")",
"{",
"return",
"$",
"this",
"->",
"getSize",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setSize",
"(",
"$",
"iSize",
")",
... | Get or set the avatar size to use.
@param integer $iSize The avatar size to use, must be less than 2048 and greater than 0.
@return number|\forxer\Gravatar\Image | [
"Get",
"or",
"set",
"the",
"avatar",
"size",
"to",
"use",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L93-L100 | train |
forxer/gravatar | src/Image.php | Image.defaultImage | public function defaultImage($sDefaultImage = null, $bForce = false)
{
if (null === $sDefaultImage) {
return $this->getDefaultImage();
}
return $this->setDefaultImage($sDefaultImage, $bForce);
} | php | public function defaultImage($sDefaultImage = null, $bForce = false)
{
if (null === $sDefaultImage) {
return $this->getDefaultImage();
}
return $this->setDefaultImage($sDefaultImage, $bForce);
} | [
"public",
"function",
"defaultImage",
"(",
"$",
"sDefaultImage",
"=",
"null",
",",
"$",
"bForce",
"=",
"false",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sDefaultImage",
")",
"{",
"return",
"$",
"this",
"->",
"getDefaultImage",
"(",
")",
";",
"}",
"ret... | Get or set the default image to use for avatars.
@param string $sDefaultImage The default image to use. Use a valid image URL, or a recognized gravatar "default".
@param boolean $bForce Force the default image to be always load.
@return number|\forxer\Gravatar\Image | [
"Get",
"or",
"set",
"the",
"default",
"image",
"to",
"use",
"for",
"avatars",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L154-L161 | train |
forxer/gravatar | src/Image.php | Image.forceDefault | public function forceDefault($bForceDefault = null)
{
if (null === $bForceDefault) {
return $this->getForceDefault();
}
return $this->setForceDefault($bForceDefault);
} | php | public function forceDefault($bForceDefault = null)
{
if (null === $bForceDefault) {
return $this->getForceDefault();
}
return $this->setForceDefault($bForceDefault);
} | [
"public",
"function",
"forceDefault",
"(",
"$",
"bForceDefault",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"bForceDefault",
")",
"{",
"return",
"$",
"this",
"->",
"getForceDefault",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setForceDe... | Get or set if we have to force the default image to be always load.
@param boolean $sRating
@return boolean|\forxer\Gravatar\Image | [
"Get",
"or",
"set",
"if",
"we",
"have",
"to",
"force",
"the",
"default",
"image",
"to",
"be",
"always",
"load",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L230-L237 | train |
forxer/gravatar | src/Image.php | Image.rating | public function rating($sRating = null)
{
if (null === $sRating) {
return $this->getMaxRating();
}
return $this->setMaxRating($sRating);
} | php | public function rating($sRating = null)
{
if (null === $sRating) {
return $this->getMaxRating();
}
return $this->setMaxRating($sRating);
} | [
"public",
"function",
"rating",
"(",
"$",
"sRating",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sRating",
")",
"{",
"return",
"$",
"this",
"->",
"getMaxRating",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setMaxRating",
"(",
"$",
... | Get or set the maximum allowed rating for avatars.
@param string $sRating
@return string|\forxer\Gravatar\Image | [
"Get",
"or",
"set",
"the",
"maximum",
"allowed",
"rating",
"for",
"avatars",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L313-L320 | train |
forxer/gravatar | src/Image.php | Image.extension | public function extension($sExtension = null)
{
if (null === $sExtension) {
return $this->getExtension();
}
return $this->setExtension($sExtension);
} | php | public function extension($sExtension = null)
{
if (null === $sExtension) {
return $this->getExtension();
}
return $this->setExtension($sExtension);
} | [
"public",
"function",
"extension",
"(",
"$",
"sExtension",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sExtension",
")",
"{",
"return",
"$",
"this",
"->",
"getExtension",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setExtension",
"(",
... | Get or set the avatar extension to use.
@param string $sExtension The avatar extension to use.
@return string|\forxer\Gravatar\Image | [
"Get",
"or",
"set",
"the",
"avatar",
"extension",
"to",
"use",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L379-L386 | train |
forxer/gravatar | src/Image.php | Image.setExtension | public function setExtension($sExtension = null)
{
if (null === $sExtension) {
return $this;
}
if (!in_array($sExtension, $this->aValidExtensions)) {
$message = sprintf(
'The extension "%s" is not a valid one, extension image for Gravatar can be: %s',
$sExtension,
implode(', ', $this->aValidExtensions)
);
throw new InvalidImageExtensionException($message);
}
$this->sExtension = $sExtension;
return $this;
} | php | public function setExtension($sExtension = null)
{
if (null === $sExtension) {
return $this;
}
if (!in_array($sExtension, $this->aValidExtensions)) {
$message = sprintf(
'The extension "%s" is not a valid one, extension image for Gravatar can be: %s',
$sExtension,
implode(', ', $this->aValidExtensions)
);
throw new InvalidImageExtensionException($message);
}
$this->sExtension = $sExtension;
return $this;
} | [
"public",
"function",
"setExtension",
"(",
"$",
"sExtension",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sExtension",
")",
"{",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"$",
"sExtension",
",",
"$",
"this",
"->",
... | Set the avatar extension to use.
@param string $sExtension The avatar extension to use.
@throws InvalidImageExtensionException
@return \forxer\Gravatar\Image The current Gravatar Image instance. | [
"Set",
"the",
"avatar",
"extension",
"to",
"use",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L416-L435 | train |
forxer/gravatar | src/Image.php | Image.getParams | protected function getParams()
{
$aParams = [];
if (null !== $this->getSize()) {
$aParams['s'] = $this->getSize();
}
if (null !== $this->getDefaultImage()) {
$aParams['d'] = $this->getDefaultImage();
}
if (null !== $this->getMaxRating()) {
$aParams['r'] = $this->getMaxRating();
}
if ($this->forcingDefault()) {
$aParams['f'] = 'y';
}
return (null !== $this->sExtension ? '.'.$this->sExtension : '')
.(empty($aParams) ? '' : '?'.http_build_query($aParams, '', '&'));
} | php | protected function getParams()
{
$aParams = [];
if (null !== $this->getSize()) {
$aParams['s'] = $this->getSize();
}
if (null !== $this->getDefaultImage()) {
$aParams['d'] = $this->getDefaultImage();
}
if (null !== $this->getMaxRating()) {
$aParams['r'] = $this->getMaxRating();
}
if ($this->forcingDefault()) {
$aParams['f'] = 'y';
}
return (null !== $this->sExtension ? '.'.$this->sExtension : '')
.(empty($aParams) ? '' : '?'.http_build_query($aParams, '', '&'));
} | [
"protected",
"function",
"getParams",
"(",
")",
"{",
"$",
"aParams",
"=",
"[",
"]",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"getSize",
"(",
")",
")",
"{",
"$",
"aParams",
"[",
"'s'",
"]",
"=",
"$",
"this",
"->",
"getSize",
"(",
")",
"... | Compute params according to current settings.
@return string | [
"Compute",
"params",
"according",
"to",
"current",
"settings",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Image.php#L442-L464 | train |
codemonkey1988/responsive-images | Classes/Resource/Rendering/ResponsiveImageRenderer.php | ResponsiveImageRenderer.render | public function render(FileInterface $file, $width, $height, array $options = [], $usedPathsRelativeToCurrentScript = false): string
{
if (!array_key_exists(self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY, $options)
&& isset($GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY])
) {
$options[self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY] = (float)$GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY];
}
$view = $this->initializeView();
$view->assignMultiple([
'isAnimatedGif' => $this->isAnimatedGif($file),
'config' => $this->getConfig(),
'data' => $GLOBALS['TSFE']->cObj->data,
'file' => $file,
'options' => $options,
]);
return $view->render('pictureTag');
} | php | public function render(FileInterface $file, $width, $height, array $options = [], $usedPathsRelativeToCurrentScript = false): string
{
if (!array_key_exists(self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY, $options)
&& isset($GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY])
) {
$options[self::OPTIONS_IMAGE_RELATVE_WIDTH_KEY] = (float)$GLOBALS['TSFE']->register[self::REGISTER_IMAGE_RELATVE_WIDTH_KEY];
}
$view = $this->initializeView();
$view->assignMultiple([
'isAnimatedGif' => $this->isAnimatedGif($file),
'config' => $this->getConfig(),
'data' => $GLOBALS['TSFE']->cObj->data,
'file' => $file,
'options' => $options,
]);
return $view->render('pictureTag');
} | [
"public",
"function",
"render",
"(",
"FileInterface",
"$",
"file",
",",
"$",
"width",
",",
"$",
"height",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"usedPathsRelativeToCurrentScript",
"=",
"false",
")",
":",
"string",
"{",
"if",
"(",
"!",
... | Renders a responsive image tag.
@param FileInterface $file
@param int|string $width
@param int|string $height
@param array $options
@param bool $usedPathsRelativeToCurrentScript
@return string | [
"Renders",
"a",
"responsive",
"image",
"tag",
"."
] | 05aaba3a84164f8bbc66e20ed88e00d9eb1aa552 | https://github.com/codemonkey1988/responsive-images/blob/05aaba3a84164f8bbc66e20ed88e00d9eb1aa552/Classes/Resource/Rendering/ResponsiveImageRenderer.php#L72-L90 | train |
davidbarratt/custom-installer | src/Configuration.php | Configuration.getPattern | public function getPattern(PackageInterface $package)
{
if (isset($this->packages[$package->getName()])) {
return $this->packages[$package->getName()];
} elseif (isset($this->packages[$package->getPrettyName()])) {
return $this->packages[$package->getPrettyName()];
} elseif (isset($this->types[$package->getType()])) {
return $this->types[$package->getType()];
}
} | php | public function getPattern(PackageInterface $package)
{
if (isset($this->packages[$package->getName()])) {
return $this->packages[$package->getName()];
} elseif (isset($this->packages[$package->getPrettyName()])) {
return $this->packages[$package->getPrettyName()];
} elseif (isset($this->types[$package->getType()])) {
return $this->types[$package->getType()];
}
} | [
"public",
"function",
"getPattern",
"(",
"PackageInterface",
"$",
"package",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"packages",
"[",
"$",
"package",
"->",
"getName",
"(",
")",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"packages",
... | Retrieve the pattern for the given package.
@param \Composer\Package\PackageInterface $package
@return string | [
"Retrieve",
"the",
"pattern",
"for",
"the",
"given",
"package",
"."
] | 90009113204b8b6257ead91866cc5cddc6876834 | https://github.com/davidbarratt/custom-installer/blob/90009113204b8b6257ead91866cc5cddc6876834/src/Configuration.php#L38-L47 | train |
davidbarratt/custom-installer | src/Configuration.php | Configuration.convert | protected function convert($extra)
{
if (isset($extra['custom-installer'])) {
foreach ($extra['custom-installer'] as $pattern => $specs) {
foreach ($specs as $spec) {
$match = array();
// Type matching
if (preg_match('/^type:(.*)$/', $spec, $match)) {
$this->types[$match[1]] = $pattern;
} // Else it must be the package name.
else {
$this->packages[$spec] = $pattern;
}
}
}
}
} | php | protected function convert($extra)
{
if (isset($extra['custom-installer'])) {
foreach ($extra['custom-installer'] as $pattern => $specs) {
foreach ($specs as $spec) {
$match = array();
// Type matching
if (preg_match('/^type:(.*)$/', $spec, $match)) {
$this->types[$match[1]] = $pattern;
} // Else it must be the package name.
else {
$this->packages[$spec] = $pattern;
}
}
}
}
} | [
"protected",
"function",
"convert",
"(",
"$",
"extra",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"extra",
"[",
"'custom-installer'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"extra",
"[",
"'custom-installer'",
"]",
"as",
"$",
"pattern",
"=>",
"$",
"specs... | Converts the given extra data to relevant configuration values. | [
"Converts",
"the",
"given",
"extra",
"data",
"to",
"relevant",
"configuration",
"values",
"."
] | 90009113204b8b6257ead91866cc5cddc6876834 | https://github.com/davidbarratt/custom-installer/blob/90009113204b8b6257ead91866cc5cddc6876834/src/Configuration.php#L64-L80 | train |
bigfork/silverstripe-oauth | src/Control/Controller.php | Controller.getReturnUrl | protected function getReturnUrl()
{
$backUrl = $this->getRequest()->getSession()->get('oauth2.backurl');
if (!$backUrl || !Director::is_site_url($backUrl)) {
$backUrl = Director::absoluteBaseURL();
}
return $backUrl;
} | php | protected function getReturnUrl()
{
$backUrl = $this->getRequest()->getSession()->get('oauth2.backurl');
if (!$backUrl || !Director::is_site_url($backUrl)) {
$backUrl = Director::absoluteBaseURL();
}
return $backUrl;
} | [
"protected",
"function",
"getReturnUrl",
"(",
")",
"{",
"$",
"backUrl",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getSession",
"(",
")",
"->",
"get",
"(",
"'oauth2.backurl'",
")",
";",
"if",
"(",
"!",
"$",
"backUrl",
"||",
"!",
"Director",... | Get the return URL previously stored in session
@return string | [
"Get",
"the",
"return",
"URL",
"previously",
"stored",
"in",
"session"
] | 50dd9728369452788d1951e3d1981b2775c2b81d | https://github.com/bigfork/silverstripe-oauth/blob/50dd9728369452788d1951e3d1981b2775c2b81d/src/Control/Controller.php#L64-L72 | train |
bigfork/silverstripe-oauth | src/Control/Controller.php | Controller.authenticate | public function authenticate(HTTPRequest $request)
{
$providerName = $request->getVar('provider');
$context = $request->getVar('context');
$scope = $request->getVar('scope');
// Missing or invalid data means we can't proceed
if (!$providerName || !is_array($scope)) {
$this->httpError(404);
return null;
}
/** @var ProviderFactory $providerFactory */
$providerFactory = Injector::inst()->get(ProviderFactory::class);
$provider = $providerFactory->getProvider($providerName);
$url = $provider->getAuthorizationUrl(['scope' => $scope]);
$request->getSession()->set('oauth2', [
'state' => $provider->getState(),
'provider' => $providerName,
'context' => $context,
'scope' => $scope,
'backurl' => $this->findBackUrl($request)
]);
return $this->redirect($url);
} | php | public function authenticate(HTTPRequest $request)
{
$providerName = $request->getVar('provider');
$context = $request->getVar('context');
$scope = $request->getVar('scope');
// Missing or invalid data means we can't proceed
if (!$providerName || !is_array($scope)) {
$this->httpError(404);
return null;
}
/** @var ProviderFactory $providerFactory */
$providerFactory = Injector::inst()->get(ProviderFactory::class);
$provider = $providerFactory->getProvider($providerName);
$url = $provider->getAuthorizationUrl(['scope' => $scope]);
$request->getSession()->set('oauth2', [
'state' => $provider->getState(),
'provider' => $providerName,
'context' => $context,
'scope' => $scope,
'backurl' => $this->findBackUrl($request)
]);
return $this->redirect($url);
} | [
"public",
"function",
"authenticate",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"providerName",
"=",
"$",
"request",
"->",
"getVar",
"(",
"'provider'",
")",
";",
"$",
"context",
"=",
"$",
"request",
"->",
"getVar",
"(",
"'context'",
")",
";",
"$... | This takes parameters like the provider, scopes and callback url, builds an authentication
url with the provider's site and then redirects to it
@todo allow whitelisting of scopes (per provider)?
@param HTTPRequest $request
@return HTTPResponse
@throws HTTPResponse_Exception | [
"This",
"takes",
"parameters",
"like",
"the",
"provider",
"scopes",
"and",
"callback",
"url",
"builds",
"an",
"authentication",
"url",
"with",
"the",
"provider",
"s",
"site",
"and",
"then",
"redirects",
"to",
"it"
] | 50dd9728369452788d1951e3d1981b2775c2b81d | https://github.com/bigfork/silverstripe-oauth/blob/50dd9728369452788d1951e3d1981b2775c2b81d/src/Control/Controller.php#L91-L117 | train |
bigfork/silverstripe-oauth | src/Control/Controller.php | Controller.callback | public function callback(HTTPRequest $request)
{
$session = $request->getSession();
if (!$this->validateState($request)) {
$session->clear('oauth2');
$this->httpError(400, 'Invalid session state.');
return null;
}
$providerName = $session->get('oauth2.provider');
/** @var ProviderFactory $providerFactory */
$providerFactory = Injector::inst()->get(ProviderFactory::class);
$provider = $providerFactory->getProvider($providerName);
$returnUrl = $this->getReturnUrl();
try {
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $request->getVar('code')
]);
$handlers = $this->getHandlersForContext($session->get('oauth2.context'));
// Run handlers to process the token
$results = [];
foreach ($handlers as $handlerConfig) {
$handler = Injector::inst()->create($handlerConfig['class']);
$results[] = $handler->handleToken($accessToken, $provider);
}
// Handlers may return response objects
foreach ($results as $result) {
if ($result instanceof HTTPResponse) {
$session->clear('oauth2');
// If the response is redirecting to the login page (e.g. on Security::permissionFailure()),
// update the BackURL so it doesn't point to /oauth/callback/
if ($result->isRedirect()) {
$location = $result->getHeader('location');
$relativeLocation = Director::makeRelative($location);
// If the URL begins Security/login and a BackURL parameter is set...
if (
strpos($relativeLocation, Security::config()->uninherited('login_url')) === 0
&& strpos($relativeLocation, 'BackURL') !== -1
) {
$session->set('BackURL', $returnUrl);
$location = HTTP::setGetVar('BackURL', $returnUrl, $location);
$result->addHeader('location', $location);
}
}
return $result;
}
}
} catch (IdentityProviderException $e) {
/** @var LoggerInterface $logger */
$logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
$logger->error('OAuth IdentityProviderException: ' . $e->getMessage());
$this->httpError(400, 'Invalid access token.');
return null;
} catch (Exception $e) {
/** @var LoggerInterface $logger */
$logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
$logger->error('OAuth Exception: ' . $e->getMessage());
$this->httpError(400, $e->getMessage());
return null;
} finally {
$session->clear('oauth2');
}
return $this->redirect($returnUrl);
} | php | public function callback(HTTPRequest $request)
{
$session = $request->getSession();
if (!$this->validateState($request)) {
$session->clear('oauth2');
$this->httpError(400, 'Invalid session state.');
return null;
}
$providerName = $session->get('oauth2.provider');
/** @var ProviderFactory $providerFactory */
$providerFactory = Injector::inst()->get(ProviderFactory::class);
$provider = $providerFactory->getProvider($providerName);
$returnUrl = $this->getReturnUrl();
try {
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $request->getVar('code')
]);
$handlers = $this->getHandlersForContext($session->get('oauth2.context'));
// Run handlers to process the token
$results = [];
foreach ($handlers as $handlerConfig) {
$handler = Injector::inst()->create($handlerConfig['class']);
$results[] = $handler->handleToken($accessToken, $provider);
}
// Handlers may return response objects
foreach ($results as $result) {
if ($result instanceof HTTPResponse) {
$session->clear('oauth2');
// If the response is redirecting to the login page (e.g. on Security::permissionFailure()),
// update the BackURL so it doesn't point to /oauth/callback/
if ($result->isRedirect()) {
$location = $result->getHeader('location');
$relativeLocation = Director::makeRelative($location);
// If the URL begins Security/login and a BackURL parameter is set...
if (
strpos($relativeLocation, Security::config()->uninherited('login_url')) === 0
&& strpos($relativeLocation, 'BackURL') !== -1
) {
$session->set('BackURL', $returnUrl);
$location = HTTP::setGetVar('BackURL', $returnUrl, $location);
$result->addHeader('location', $location);
}
}
return $result;
}
}
} catch (IdentityProviderException $e) {
/** @var LoggerInterface $logger */
$logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
$logger->error('OAuth IdentityProviderException: ' . $e->getMessage());
$this->httpError(400, 'Invalid access token.');
return null;
} catch (Exception $e) {
/** @var LoggerInterface $logger */
$logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
$logger->error('OAuth Exception: ' . $e->getMessage());
$this->httpError(400, $e->getMessage());
return null;
} finally {
$session->clear('oauth2');
}
return $this->redirect($returnUrl);
} | [
"public",
"function",
"callback",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"session",
"=",
"$",
"request",
"->",
"getSession",
"(",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"validateState",
"(",
"$",
"request",
")",
")",
"{",
"$",
"sess... | The return endpoint after the user has authenticated with a provider
@param HTTPRequest $request
@return HTTPResponse
@throws HTTPResponse_Exception | [
"The",
"return",
"endpoint",
"after",
"the",
"user",
"has",
"authenticated",
"with",
"a",
"provider"
] | 50dd9728369452788d1951e3d1981b2775c2b81d | https://github.com/bigfork/silverstripe-oauth/blob/50dd9728369452788d1951e3d1981b2775c2b81d/src/Control/Controller.php#L126-L198 | train |
bigfork/silverstripe-oauth | src/Control/Controller.php | Controller.getHandlersForContext | protected function getHandlersForContext($context = null)
{
$handlers = $this->config()->get('token_handlers');
if (empty($handlers)) {
throw new Exception('No token handlers were registered');
}
// If we've been given a context, limit to that context + global handlers.
// Otherwise only allow global handlers (i.e. exclude named ones)
$allowedContexts = ['*'];
if ($context) {
$allowedContexts[] = $context;
}
// Filter handlers by context
$handlers = array_filter($handlers, function ($handler) use ($allowedContexts) {
return in_array($handler['context'], $allowedContexts);
});
// Sort handlers by priority
uasort($handlers, function ($a, $b) {
if (!array_key_exists('priority', $a) || !array_key_exists('priority', $b)) {
return 0;
}
return ($a['priority'] < $b['priority']) ? -1 : 1;
});
return $handlers;
} | php | protected function getHandlersForContext($context = null)
{
$handlers = $this->config()->get('token_handlers');
if (empty($handlers)) {
throw new Exception('No token handlers were registered');
}
// If we've been given a context, limit to that context + global handlers.
// Otherwise only allow global handlers (i.e. exclude named ones)
$allowedContexts = ['*'];
if ($context) {
$allowedContexts[] = $context;
}
// Filter handlers by context
$handlers = array_filter($handlers, function ($handler) use ($allowedContexts) {
return in_array($handler['context'], $allowedContexts);
});
// Sort handlers by priority
uasort($handlers, function ($a, $b) {
if (!array_key_exists('priority', $a) || !array_key_exists('priority', $b)) {
return 0;
}
return ($a['priority'] < $b['priority']) ? -1 : 1;
});
return $handlers;
} | [
"protected",
"function",
"getHandlersForContext",
"(",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"handlers",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'token_handlers'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"handlers",
")",
")... | Get a list of token handlers for the given context
@param string|null $context
@return array
@throws Exception | [
"Get",
"a",
"list",
"of",
"token",
"handlers",
"for",
"the",
"given",
"context"
] | 50dd9728369452788d1951e3d1981b2775c2b81d | https://github.com/bigfork/silverstripe-oauth/blob/50dd9728369452788d1951e3d1981b2775c2b81d/src/Control/Controller.php#L207-L236 | train |
bigfork/silverstripe-oauth | src/Control/Controller.php | Controller.validateState | public function validateState(HTTPRequest $request)
{
$state = $request->getVar('state');
$session = $request->getSession();
$data = $session->get('oauth2');
// If we're lacking any required data, or the session state doesn't match
// the one the provider returned, the request is invalid
if (empty($data['state']) || empty($data['provider']) || empty($data['scope']) || $state !== $data['state']) {
$session->clear('oauth2');
return false;
}
return true;
} | php | public function validateState(HTTPRequest $request)
{
$state = $request->getVar('state');
$session = $request->getSession();
$data = $session->get('oauth2');
// If we're lacking any required data, or the session state doesn't match
// the one the provider returned, the request is invalid
if (empty($data['state']) || empty($data['provider']) || empty($data['scope']) || $state !== $data['state']) {
$session->clear('oauth2');
return false;
}
return true;
} | [
"public",
"function",
"validateState",
"(",
"HTTPRequest",
"$",
"request",
")",
"{",
"$",
"state",
"=",
"$",
"request",
"->",
"getVar",
"(",
"'state'",
")",
";",
"$",
"session",
"=",
"$",
"request",
"->",
"getSession",
"(",
")",
";",
"$",
"data",
"=",
... | Validate the request's state against the one stored in session
@param HTTPRequest $request
@return boolean | [
"Validate",
"the",
"request",
"s",
"state",
"against",
"the",
"one",
"stored",
"in",
"session"
] | 50dd9728369452788d1951e3d1981b2775c2b81d | https://github.com/bigfork/silverstripe-oauth/blob/50dd9728369452788d1951e3d1981b2775c2b81d/src/Control/Controller.php#L244-L258 | train |
teamreflex/ChallongePHP | src/Challonge/Challonge.php | Challonge.getTournaments | public function getTournaments() {
$response = Guzzle::get('tournaments');
$tournaments = [];
foreach ($response as $tourney) {
$tournaments[] = new Tournament($tourney->tournament);
}
return $tournaments;
} | php | public function getTournaments() {
$response = Guzzle::get('tournaments');
$tournaments = [];
foreach ($response as $tourney) {
$tournaments[] = new Tournament($tourney->tournament);
}
return $tournaments;
} | [
"public",
"function",
"getTournaments",
"(",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"get",
"(",
"'tournaments'",
")",
";",
"$",
"tournaments",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"response",
"as",
"$",
"tourney",
")",
"{",
"$",
"tournamen... | Retrieve a set of tournaments created with your account.
@return array | [
"Retrieve",
"a",
"set",
"of",
"tournaments",
"created",
"with",
"your",
"account",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Challonge.php#L46-L55 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.