repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
UnionOfRAD/lithium | template/View.php | View.render | public function render($process, array $data = [], array $options = []) {
$defaults = [
'type' => 'html',
'layout' => null,
'template' => null,
'context' => [],
'paths' => [],
'data' => []
];
$options += $defaults;
$data += $options['data'];
$paths = $options['paths'];
unset($options['data'], $options['paths']);
$params = array_filter($options, function($val) { return $val && is_string($val); });
$result = null;
foreach ($this->_process($process, $params) as $name => $step) {
if (isset($paths[$name]) && $paths[$name] === false) {
continue;
}
if (!$this->_conditions($step, $params, $data, $options)) {
continue;
}
if ($step['multi'] && isset($options[$name])) {
foreach ((array) $options[$name] as $value) {
$params[$name] = $value;
$result = $this->_step($step, $params, $data, $options);
}
continue;
}
$result = $this->_step((array) $step, $params, $data, $options);
}
return $result;
} | php | public function render($process, array $data = [], array $options = []) {
$defaults = [
'type' => 'html',
'layout' => null,
'template' => null,
'context' => [],
'paths' => [],
'data' => []
];
$options += $defaults;
$data += $options['data'];
$paths = $options['paths'];
unset($options['data'], $options['paths']);
$params = array_filter($options, function($val) { return $val && is_string($val); });
$result = null;
foreach ($this->_process($process, $params) as $name => $step) {
if (isset($paths[$name]) && $paths[$name] === false) {
continue;
}
if (!$this->_conditions($step, $params, $data, $options)) {
continue;
}
if ($step['multi'] && isset($options[$name])) {
foreach ((array) $options[$name] as $value) {
$params[$name] = $value;
$result = $this->_step($step, $params, $data, $options);
}
continue;
}
$result = $this->_step((array) $step, $params, $data, $options);
}
return $result;
} | [
"public",
"function",
"render",
"(",
"$",
"process",
",",
"array",
"$",
"data",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'type'",
"=>",
"'html'",
",",
"'layout'",
"=>",
"null",
",",
"'templat... | Executes a named rendering process by running each process step in sequence and aggregating
the results. The `View` class comes with 3 built-in processes: `'all'`, `'template'`, and
`'element'`. The `'all'` process is the default two-step rendered view, where a template is
wrapped in a layout containing a header and footer.
@see lithium\template\View::_conditions()
@see lithium\template\View::$_processes
@see lithium\template\View::$_steps
@param string $process A named set of rendering steps defined in the `$_processes` array.
@param array $data An associative array of data to be rendered in the set of templates.
@param array $options Options used when rendering. Available keys are as follows:
- `'type'` _string_: The type of content to render. Defaults to `'html'`.
- `'layout'` _string_: The name of the layout to use in the default two-step
rendering process. Defaults to `null`.
- `'template'` _string_: The name of the template to render. Defaults to `null`.
- `'context'` _array_: An associative array of information to inject into the
rendering context.
- `'paths'` _array_: A nested array of paths to use for rendering steps. The
top-level keys should match the `'path'` key in a step configuration (i.e.:
`'template'`, `'layout'`, or `'element'`), and the second level is an array
of path template strings to search (can be a string if there's only one path).
These path strings generally take the following form:
`'{:library}/views/{:controller}/{:template}.{:type}.php'`. These template
strings are specific to the `File` loader, but can take any form useful to the
template loader being used.
@return string Returns the result of the rendering process, typically by rendering a template
first, then rendering a layout (using the default configuration of the `'all'`
process). | [
"Executes",
"a",
"named",
"rendering",
"process",
"by",
"running",
"each",
"process",
"step",
"in",
"sequence",
"and",
"aggregating",
"the",
"results",
".",
"The",
"View",
"class",
"comes",
"with",
"3",
"built",
"-",
"in",
"processes",
":",
"all",
"template"... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/View.php#L300-L334 |
UnionOfRAD/lithium | template/View.php | View._conditions | protected function _conditions(array $step, array $params, array $data, array $options) {
if (!$conditions = $step['conditions']) {
return true;
}
$isCallable = is_callable($conditions) && !is_string($conditions);
if ($isCallable && !$conditions($params, $data, $options)) {
return false;
}
if (is_string($conditions) && !(isset($options[$conditions]) && $options[$conditions])) {
return false;
}
return true;
} | php | protected function _conditions(array $step, array $params, array $data, array $options) {
if (!$conditions = $step['conditions']) {
return true;
}
$isCallable = is_callable($conditions) && !is_string($conditions);
if ($isCallable && !$conditions($params, $data, $options)) {
return false;
}
if (is_string($conditions) && !(isset($options[$conditions]) && $options[$conditions])) {
return false;
}
return true;
} | [
"protected",
"function",
"_conditions",
"(",
"array",
"$",
"step",
",",
"array",
"$",
"params",
",",
"array",
"$",
"data",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"$",
"conditions",
"=",
"$",
"step",
"[",
"'conditions'",
"]",
")",
"{"... | Evaluates a step condition to determine if the step should be executed.
@see lithium\template\View::$_steps
@param array $step The array of instructions that define a rendering step.
@param array $params The parameters associated with this rendering operation, as passed to
`render()` (filtered from the `$options` parameter).
@param array $data The associative array of template variables passed to `render()`.
@param array $options The `$options` parameter, as passed to `render()`.
@return boolean Returns `true` if the step should be executed, or `false` if the step should
be skipped. If the step array has a `'conditions'` key which is a string, it checks
to see if the rendering options (`$options`) contain a key of the same name, and if
that key evaluates to `true`. If `'conditions'` is a closure, that closure is
executed with the rendering parameters (`$params`, `$data`, and `$options`), and the
result is determined by the return value of the closure. If a step definition has no
`'conditions'` key, it is always executed. | [
"Evaluates",
"a",
"step",
"condition",
"to",
"determine",
"if",
"the",
"step",
"should",
"be",
"executed",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/View.php#L353-L366 |
UnionOfRAD/lithium | template/View.php | View._step | protected function _step(array $step, array $params, array &$data, array &$options = []) {
$step += ['path' => null, 'capture' => null];
$_renderer = $this->_renderer;
$_loader = $this->_loader;
$filters = $this->outputFilters;
$params = compact('step', 'params', 'options') + [
'data' => $data + $filters,
'loader' => $_loader,
'renderer' => $_renderer
];
$result = Filters::run($this, __FUNCTION__, $params, function($params) {
$template = $params['loader']->template($params['step']['path'], $params['params']);
return $params['renderer']->render($template, $params['data'], $params['options']);
});
if (is_array($step['capture'])) {
switch (key($step['capture'])) {
case 'context':
$options['context'][current($step['capture'])] = $result;
break;
case 'data':
$data[current($step['capture'])] = $result;
break;
}
}
return $result;
} | php | protected function _step(array $step, array $params, array &$data, array &$options = []) {
$step += ['path' => null, 'capture' => null];
$_renderer = $this->_renderer;
$_loader = $this->_loader;
$filters = $this->outputFilters;
$params = compact('step', 'params', 'options') + [
'data' => $data + $filters,
'loader' => $_loader,
'renderer' => $_renderer
];
$result = Filters::run($this, __FUNCTION__, $params, function($params) {
$template = $params['loader']->template($params['step']['path'], $params['params']);
return $params['renderer']->render($template, $params['data'], $params['options']);
});
if (is_array($step['capture'])) {
switch (key($step['capture'])) {
case 'context':
$options['context'][current($step['capture'])] = $result;
break;
case 'data':
$data[current($step['capture'])] = $result;
break;
}
}
return $result;
} | [
"protected",
"function",
"_step",
"(",
"array",
"$",
"step",
",",
"array",
"$",
"params",
",",
"array",
"&",
"$",
"data",
",",
"array",
"&",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"step",
"+=",
"[",
"'path'",
"=>",
"null",
",",
"'capture'",
... | Performs a rendering step.
@see lithium\template\view\adapter\File::template()
@see lithium\template\view\Renderer::render()
@see lithium\template\view\adapter\File::render()
@param array $step The array defining the step configuration to render.
@param array $params An associative array of string values used in the template lookup
process. See the `$params` argument of `File::template()`.
@param array $data associative array for template data.
@param array $options An associative array of options to pass to the renderer. See the
`$options` parameter of `Renderer::render()` or `File::render()`.
@return string
@filter | [
"Performs",
"a",
"rendering",
"step",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/View.php#L383-L410 |
UnionOfRAD/lithium | template/View.php | View._process | protected function _process($process, &$params) {
$defaults = ['conditions' => null, 'multi' => false];
if (!is_array($process)) {
if (!isset($this->_processes[$process])) {
throw new TemplateException("Undefined rendering process '{$process}'.");
}
$process = $this->_processes[$process];
}
if (is_string(key($process))) {
return $this->_convertSteps($process, $params, $defaults);
}
$result = [];
foreach ($process as $step) {
if (is_array($step)) {
$result[] = $step + $defaults;
continue;
}
if (!isset($this->_steps[$step])) {
throw new TemplateException("Undefined rendering step '{$step}'.");
}
$result[$step] = $this->_steps[$step] + $defaults;
}
return $result;
} | php | protected function _process($process, &$params) {
$defaults = ['conditions' => null, 'multi' => false];
if (!is_array($process)) {
if (!isset($this->_processes[$process])) {
throw new TemplateException("Undefined rendering process '{$process}'.");
}
$process = $this->_processes[$process];
}
if (is_string(key($process))) {
return $this->_convertSteps($process, $params, $defaults);
}
$result = [];
foreach ($process as $step) {
if (is_array($step)) {
$result[] = $step + $defaults;
continue;
}
if (!isset($this->_steps[$step])) {
throw new TemplateException("Undefined rendering step '{$step}'.");
}
$result[$step] = $this->_steps[$step] + $defaults;
}
return $result;
} | [
"protected",
"function",
"_process",
"(",
"$",
"process",
",",
"&",
"$",
"params",
")",
"{",
"$",
"defaults",
"=",
"[",
"'conditions'",
"=>",
"null",
",",
"'multi'",
"=>",
"false",
"]",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"process",
")",
")",
... | Converts a process name to an array containing the rendering steps to be executed for each
process.
@param string $process A named set of rendering steps.
@param array $params
@return array A 2-dimensional array that defines the rendering process. The first dimension
is a numerically-indexed array containing each rendering step. The second dimension
represents the parameters for each step. | [
"Converts",
"a",
"process",
"name",
"to",
"an",
"array",
"containing",
"the",
"rendering",
"steps",
"to",
"be",
"executed",
"for",
"each",
"process",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/View.php#L422-L447 |
UnionOfRAD/lithium | template/View.php | View._convertSteps | protected function _convertSteps(array $command, array &$params, $defaults) {
if (count($command) === 1) {
$params['template'] = current($command);
return [['path' => key($command)] + $defaults];
}
return $command;
} | php | protected function _convertSteps(array $command, array &$params, $defaults) {
if (count($command) === 1) {
$params['template'] = current($command);
return [['path' => key($command)] + $defaults];
}
return $command;
} | [
"protected",
"function",
"_convertSteps",
"(",
"array",
"$",
"command",
",",
"array",
"&",
"$",
"params",
",",
"$",
"defaults",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"command",
")",
"===",
"1",
")",
"{",
"$",
"params",
"[",
"'template'",
"]",
"=",
... | Handles API backward compatibility by converting an array-based rendering instruction passed
to `render()` as a process, to a set of rendering steps, rewriting any associated rendering
parameters as necessary.
@param array $command A deprecated rendering instruction, i.e.
`array('template' => '/path/to/template')`.
@param array $params The array of associated rendering parameters, passed by reference.
@param array $defaults Default step rendering options to be merged with the passed rendering
instruction information.
@return array Returns a converted set of rendering steps, to be executed in `render()`. | [
"Handles",
"API",
"backward",
"compatibility",
"by",
"converting",
"an",
"array",
"-",
"based",
"rendering",
"instruction",
"passed",
"to",
"render",
"()",
"as",
"a",
"process",
"to",
"a",
"set",
"of",
"rendering",
"steps",
"rewriting",
"any",
"associated",
"r... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/View.php#L461-L467 |
UnionOfRAD/lithium | net/socket/Context.php | Context.open | public function open(array $options = []) {
parent::open($options);
$config = $this->_config;
if (!$config['scheme'] || !$config['host']) {
return false;
}
$url = "{$config['scheme']}://{$config['host']}:{$config['port']}";
$context = [$config['scheme'] => ['timeout' => $this->_timeout]];
if (is_object($config['message'])) {
$url = $config['message']->to('url');
$context = $config['message']->to('context', ['timeout' => $this->_timeout]);
}
$this->_resource = fopen($url, $config['mode'], false, stream_context_create($context));
return $this->_resource;
} | php | public function open(array $options = []) {
parent::open($options);
$config = $this->_config;
if (!$config['scheme'] || !$config['host']) {
return false;
}
$url = "{$config['scheme']}://{$config['host']}:{$config['port']}";
$context = [$config['scheme'] => ['timeout' => $this->_timeout]];
if (is_object($config['message'])) {
$url = $config['message']->to('url');
$context = $config['message']->to('context', ['timeout' => $this->_timeout]);
}
$this->_resource = fopen($url, $config['mode'], false, stream_context_create($context));
return $this->_resource;
} | [
"public",
"function",
"open",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"parent",
"::",
"open",
"(",
"$",
"options",
")",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"_config",
";",
"if",
"(",
"!",
"$",
"config",
"[",
"'scheme'",
"]"... | Opens the socket and sets its timeout value.
@param array $options Update the config settings.
@return mixed Returns `false` if the socket configuration does not contain the
`'scheme'` or `'host'` settings, or if configuration fails, otherwise returns a
resource stream. | [
"Opens",
"the",
"socket",
"and",
"sets",
"its",
"timeout",
"value",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/socket/Context.php#L56-L72 |
UnionOfRAD/lithium | net/socket/Context.php | Context.read | public function read() {
if (!is_resource($this->_resource)) {
return false;
}
$meta = stream_get_meta_data($this->_resource);
if (isset($meta['wrapper_data'])) {
$headers = join("\r\n", $meta['wrapper_data']) . "\r\n\r\n";
} else {
$headers = null;
}
return $headers . stream_get_contents($this->_resource);
} | php | public function read() {
if (!is_resource($this->_resource)) {
return false;
}
$meta = stream_get_meta_data($this->_resource);
if (isset($meta['wrapper_data'])) {
$headers = join("\r\n", $meta['wrapper_data']) . "\r\n\r\n";
} else {
$headers = null;
}
return $headers . stream_get_contents($this->_resource);
} | [
"public",
"function",
"read",
"(",
")",
"{",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"this",
"->",
"_resource",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"meta",
"=",
"stream_get_meta_data",
"(",
"$",
"this",
"->",
"_resource",
")",
";",
"if"... | Reads from the socket. Does not apply to this implementation.
@return boolean|string | [
"Reads",
"from",
"the",
"socket",
".",
"Does",
"not",
"apply",
"to",
"this",
"implementation",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/socket/Context.php#L100-L111 |
UnionOfRAD/lithium | net/socket/Context.php | Context.write | public function write($data = null) {
if (!is_resource($this->_resource)) {
return false;
}
if (!is_object($data)) {
$data = $this->_instance($this->_classes['request'], (array) $data + $this->_config);
}
return stream_context_set_option(
$this->_resource, $data->to('context', ['timeout' => $this->_timeout])
);
} | php | public function write($data = null) {
if (!is_resource($this->_resource)) {
return false;
}
if (!is_object($data)) {
$data = $this->_instance($this->_classes['request'], (array) $data + $this->_config);
}
return stream_context_set_option(
$this->_resource, $data->to('context', ['timeout' => $this->_timeout])
);
} | [
"public",
"function",
"write",
"(",
"$",
"data",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"this",
"->",
"_resource",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
... | Writes to the socket.
@param string $data Data to write.
@return boolean Success | [
"Writes",
"to",
"the",
"socket",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/socket/Context.php#L119-L129 |
UnionOfRAD/lithium | net/socket/Context.php | Context.timeout | public function timeout($time = null) {
if ($time !== null) {
$this->_timeout = $time;
}
return $this->_timeout;
} | php | public function timeout($time = null) {
if ($time !== null) {
$this->_timeout = $time;
}
return $this->_timeout;
} | [
"public",
"function",
"timeout",
"(",
"$",
"time",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"time",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"_timeout",
"=",
"$",
"time",
";",
"}",
"return",
"$",
"this",
"->",
"_timeout",
";",
"}"
] | Sets the timeout on the socket *connection*.
@param integer $time Seconds after the connection times out.
@return booelan `true` if timeout has been set, `false` otherwise. | [
"Sets",
"the",
"timeout",
"on",
"the",
"socket",
"*",
"connection",
"*",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/net/socket/Context.php#L137-L142 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable.config | public static function config($config = null) {
if ($config && is_array($config)) {
static::$_configurations = $config;
return;
}
if ($config) {
return static::_config($config);
}
$result = [];
static::$_configurations = array_filter(static::$_configurations);
foreach (array_keys(static::$_configurations) as $key) {
$result[$key] = static::_config($key);
}
return $result;
} | php | public static function config($config = null) {
if ($config && is_array($config)) {
static::$_configurations = $config;
return;
}
if ($config) {
return static::_config($config);
}
$result = [];
static::$_configurations = array_filter(static::$_configurations);
foreach (array_keys(static::$_configurations) as $key) {
$result[$key] = static::_config($key);
}
return $result;
} | [
"public",
"static",
"function",
"config",
"(",
"$",
"config",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"config",
"&&",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"static",
"::",
"$",
"_configurations",
"=",
"$",
"config",
";",
"return",
";",
"}",
... | Sets configurations for a particular adaptable implementation, or returns the current
configuration settings.
@param array|string $config An array of configurations, indexed by name to set
configurations in one go or a name for which to return the configuration.
@return array|void Configuration or void if setting configurations. | [
"Sets",
"configurations",
"for",
"a",
"particular",
"adaptable",
"implementation",
"or",
"returns",
"the",
"current",
"configuration",
"settings",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L78-L93 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable.adapter | public static function adapter($name = null) {
$config = static::_config($name);
if ($config === null) {
throw new ConfigException("Configuration `{$name}` has not been defined.");
}
if (isset($config['object'])) {
return $config['object'];
}
$class = static::_class($config, static::$_adapters);
$settings = static::$_configurations[$name];
$settings[0]['object'] = static::_initAdapter($class, $config);
static::$_configurations[$name] = $settings;
return static::$_configurations[$name][0]['object'];
} | php | public static function adapter($name = null) {
$config = static::_config($name);
if ($config === null) {
throw new ConfigException("Configuration `{$name}` has not been defined.");
}
if (isset($config['object'])) {
return $config['object'];
}
$class = static::_class($config, static::$_adapters);
$settings = static::$_configurations[$name];
$settings[0]['object'] = static::_initAdapter($class, $config);
static::$_configurations[$name] = $settings;
return static::$_configurations[$name][0]['object'];
} | [
"public",
"static",
"function",
"adapter",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"config",
"=",
"static",
"::",
"_config",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"config",
"===",
"null",
")",
"{",
"throw",
"new",
"ConfigException",
"(",
... | Returns adapter class name for given `$name` configuration, using
the `$_adapter` path defined in Adaptable subclasses.
@param string|null $name Class name of adapter to load.
@return object Adapter object. | [
"Returns",
"adapter",
"class",
"name",
"for",
"given",
"$name",
"configuration",
"using",
"the",
"$_adapter",
"path",
"defined",
"in",
"Adaptable",
"subclasses",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L111-L126 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable.strategies | public static function strategies($name) {
$config = static::_config($name);
if ($config === null) {
throw new ConfigException("Configuration `{$name}` has not been defined.");
}
if (!isset($config['strategies'])) {
return null;
}
$stack = new SplDoublyLinkedList();
foreach ($config['strategies'] as $key => $strategy) {
if (!is_array($strategy)) {
$name = $strategy;
$class = static::_strategy($name, static::$_strategies);
$stack->push(new $class());
continue;
}
$class = static::_strategy($key, static::$_strategies);
$index = (isset($config['strategies'][$key])) ? $key : $class;
$stack->push(new $class($config['strategies'][$index]));
}
return $stack;
} | php | public static function strategies($name) {
$config = static::_config($name);
if ($config === null) {
throw new ConfigException("Configuration `{$name}` has not been defined.");
}
if (!isset($config['strategies'])) {
return null;
}
$stack = new SplDoublyLinkedList();
foreach ($config['strategies'] as $key => $strategy) {
if (!is_array($strategy)) {
$name = $strategy;
$class = static::_strategy($name, static::$_strategies);
$stack->push(new $class());
continue;
}
$class = static::_strategy($key, static::$_strategies);
$index = (isset($config['strategies'][$key])) ? $key : $class;
$stack->push(new $class($config['strategies'][$index]));
}
return $stack;
} | [
"public",
"static",
"function",
"strategies",
"(",
"$",
"name",
")",
"{",
"$",
"config",
"=",
"static",
"::",
"_config",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$",
"config",
"===",
"null",
")",
"{",
"throw",
"new",
"ConfigException",
"(",
"\"Configura... | Obtain an `SplDoublyLinkedList` of the strategies for the given `$name` configuration, using
the `$_strategies` path defined in `Adaptable` subclasses.
@param string $name Class name of adapter to load.
@return object `SplDoublyLinkedList` of strategies, or `null` if none are defined. | [
"Obtain",
"an",
"SplDoublyLinkedList",
"of",
"the",
"strategies",
"for",
"the",
"given",
"$name",
"configuration",
"using",
"the",
"$_strategies",
"path",
"defined",
"in",
"Adaptable",
"subclasses",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L135-L158 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable.applyStrategies | public static function applyStrategies($method, $name, $data, array $options = []) {
$options += ['mode' => null];
if (!$strategies = static::strategies($name)) {
return $data;
}
if (!count($strategies)) {
return $data;
}
if (isset($options['mode']) && ($options['mode'] === 'LIFO')) {
$strategies->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
unset($options['mode']);
}
foreach ($strategies as $strategy) {
if (method_exists($strategy, $method)) {
$data = $strategy->{$method}($data, $options);
}
}
return $data;
} | php | public static function applyStrategies($method, $name, $data, array $options = []) {
$options += ['mode' => null];
if (!$strategies = static::strategies($name)) {
return $data;
}
if (!count($strategies)) {
return $data;
}
if (isset($options['mode']) && ($options['mode'] === 'LIFO')) {
$strategies->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
unset($options['mode']);
}
foreach ($strategies as $strategy) {
if (method_exists($strategy, $method)) {
$data = $strategy->{$method}($data, $options);
}
}
return $data;
} | [
"public",
"static",
"function",
"applyStrategies",
"(",
"$",
"method",
",",
"$",
"name",
",",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"[",
"'mode'",
"=>",
"null",
"]",
";",
"if",
"(",
"!",
"$",
"s... | Applies strategies configured in `$name` for `$method` on `$data`.
@param string $method The strategy method to be applied.
@param string $name The named configuration
@param mixed $data The data to which the strategies will be applied.
@param array $options If `mode` is set to 'LIFO', the strategies are applied in reverse.
order of their definition.
@return mixed Result of application of strategies to data. If no strategies
have been configured, this method will simply return the original data. | [
"Applies",
"strategies",
"configured",
"in",
"$name",
"for",
"$method",
"on",
"$data",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L171-L192 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable._initAdapter | protected static function _initAdapter($class, array $config) {
$params = compact('class', 'config');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
return new $params['class']($params['config']);
});
} | php | protected static function _initAdapter($class, array $config) {
$params = compact('class', 'config');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
return new $params['class']($params['config']);
});
} | [
"protected",
"static",
"function",
"_initAdapter",
"(",
"$",
"class",
",",
"array",
"$",
"config",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'class'",
",",
"'config'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
"get_called_class",
"(",
")",
",... | Provides an extension point for modifying how adapters are instantiated.
@see lithium\core\Object::__construct()
@param string $class The fully-namespaced class name of the adapter to instantiate.
@param array $config The configuration array to be passed to the adapter instance. See the
`$config` parameter of `Object::__construct()`.
@return object The adapter's class.
@filter | [
"Provides",
"an",
"extension",
"point",
"for",
"modifying",
"how",
"adapters",
"are",
"instantiated",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L219-L225 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable._class | protected static function _class($config, $paths = []) {
if (!$name = $config['adapter']) {
$self = get_called_class();
throw new ConfigException("No adapter set for configuration in class `{$self}`.");
}
if (!$class = static::_locate($paths, $name)) {
$self = get_called_class();
throw new ConfigException("Could not find adapter `{$name}` in class `{$self}`.");
}
return $class;
} | php | protected static function _class($config, $paths = []) {
if (!$name = $config['adapter']) {
$self = get_called_class();
throw new ConfigException("No adapter set for configuration in class `{$self}`.");
}
if (!$class = static::_locate($paths, $name)) {
$self = get_called_class();
throw new ConfigException("Could not find adapter `{$name}` in class `{$self}`.");
}
return $class;
} | [
"protected",
"static",
"function",
"_class",
"(",
"$",
"config",
",",
"$",
"paths",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"name",
"=",
"$",
"config",
"[",
"'adapter'",
"]",
")",
"{",
"$",
"self",
"=",
"get_called_class",
"(",
")",
";",
"t... | Looks up an adapter by class by name.
@see lithium\core\libraries::locate()
@param array $config Configuration array of class to be found.
@param array $paths Optional array of search paths that will be checked.
@return string Returns a fully-namespaced class reference to the adapter class. | [
"Looks",
"up",
"an",
"adapter",
"by",
"class",
"by",
"name",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L235-L245 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable._strategy | protected static function _strategy($name, $paths = []) {
if (!$name) {
$self = get_called_class();
throw new ConfigException("No strategy set for configuration in class `{$self}`.");
}
if (!$class = static::_locate($paths, $name)) {
$self = get_called_class();
throw new ConfigException("Could not find strategy `{$name}` in class `{$self}`.");
}
return $class;
} | php | protected static function _strategy($name, $paths = []) {
if (!$name) {
$self = get_called_class();
throw new ConfigException("No strategy set for configuration in class `{$self}`.");
}
if (!$class = static::_locate($paths, $name)) {
$self = get_called_class();
throw new ConfigException("Could not find strategy `{$name}` in class `{$self}`.");
}
return $class;
} | [
"protected",
"static",
"function",
"_strategy",
"(",
"$",
"name",
",",
"$",
"paths",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"name",
")",
"{",
"$",
"self",
"=",
"get_called_class",
"(",
")",
";",
"throw",
"new",
"ConfigException",
"(",
"\"No st... | Looks up a strategy by class by name.
@see lithium\core\libraries::locate()
@param string $name The strategy to locate.
@param array $paths Optional array of search paths that will be checked.
@return string Returns a fully-namespaced class reference to the adapter class. | [
"Looks",
"up",
"a",
"strategy",
"by",
"class",
"by",
"name",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L255-L265 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable._locate | protected static function _locate($paths, $name) {
foreach ((array) $paths as $path) {
if ($class = Libraries::locate($path, $name)) {
return $class;
}
}
return null;
} | php | protected static function _locate($paths, $name) {
foreach ((array) $paths as $path) {
if ($class = Libraries::locate($path, $name)) {
return $class;
}
}
return null;
} | [
"protected",
"static",
"function",
"_locate",
"(",
"$",
"paths",
",",
"$",
"name",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"paths",
"as",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"class",
"=",
"Libraries",
"::",
"locate",
"(",
"$",
"path",
... | Perform library location for an array of paths or a single string-based path.
@param string|array $paths Paths that Libraries::locate() will utilize.
@param string $name The name of the class to be located.
@return string Fully-namespaced path to the class, or null if not found. | [
"Perform",
"library",
"location",
"for",
"an",
"array",
"of",
"paths",
"or",
"a",
"single",
"string",
"-",
"based",
"path",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L274-L281 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable._config | protected static function _config($name) {
if (!isset(static::$_configurations[$name])) {
return null;
}
$settings = static::$_configurations[$name];
if (isset($settings[0])) {
return $settings[0];
}
$env = Environment::get();
$config = isset($settings[$env]) ? $settings[$env] : $settings;
if (isset($settings[$env]) && isset($settings[true])) {
$config += $settings[true];
}
static::$_configurations[$name] += [static::_initConfig($name, $config)];
return static::$_configurations[$name][0];
} | php | protected static function _config($name) {
if (!isset(static::$_configurations[$name])) {
return null;
}
$settings = static::$_configurations[$name];
if (isset($settings[0])) {
return $settings[0];
}
$env = Environment::get();
$config = isset($settings[$env]) ? $settings[$env] : $settings;
if (isset($settings[$env]) && isset($settings[true])) {
$config += $settings[true];
}
static::$_configurations[$name] += [static::_initConfig($name, $config)];
return static::$_configurations[$name][0];
} | [
"protected",
"static",
"function",
"_config",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"static",
"::",
"$",
"_configurations",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"settings",
"=",
"static",
"::",
... | Gets an array of settings for the given named configuration in the current
environment. Each configuration will at least contain an `'adapter'` option.
@see lithium\core\Environment
@param string $name Named configuration.
@return array|null Settings for the named configuration. | [
"Gets",
"an",
"array",
"of",
"settings",
"for",
"the",
"given",
"named",
"configuration",
"in",
"the",
"current",
"environment",
".",
"Each",
"configuration",
"will",
"at",
"least",
"contain",
"an",
"adapter",
"option",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L291-L308 |
UnionOfRAD/lithium | core/Adaptable.php | Adaptable._initConfig | protected static function _initConfig($name, $config) {
if (!empty($config['filters'])) {
trigger_error('Per adapter filters have been deprecated.', E_USER_DEPRECATED);
}
$defaults = ['adapter' => null, 'filters' => []];
return (array) $config + $defaults;
} | php | protected static function _initConfig($name, $config) {
if (!empty($config['filters'])) {
trigger_error('Per adapter filters have been deprecated.', E_USER_DEPRECATED);
}
$defaults = ['adapter' => null, 'filters' => []];
return (array) $config + $defaults;
} | [
"protected",
"static",
"function",
"_initConfig",
"(",
"$",
"name",
",",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"config",
"[",
"'filters'",
"]",
")",
")",
"{",
"trigger_error",
"(",
"'Per adapter filters have been deprecated.'",
",",
"E_... | A stub method called by `_config()` which allows `Adaptable` subclasses to automatically
assign or auto-generate additional configuration data, once a configuration is first
accessed. This allows configuration data to be lazy-loaded from adapters or other data
sources.
@deprecated Per adapter filters have been deprecated, future versions will not add the
`'filters'` option to the initial configuration anymore.
@param string $name The name of the configuration which is being accessed. This is the key
name containing the specific set of configuration passed into `config()`.
@param array $config Contains the configuration assigned to `$name`. If this configuration is
segregated by environment, then this will contain the configuration for the
current environment.
@return array Returns the final array of settings for the given named configuration. | [
"A",
"stub",
"method",
"called",
"by",
"_config",
"()",
"which",
"allows",
"Adaptable",
"subclasses",
"to",
"automatically",
"assign",
"or",
"auto",
"-",
"generate",
"additional",
"configuration",
"data",
"once",
"a",
"configuration",
"is",
"first",
"accessed",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Adaptable.php#L325-L331 |
UnionOfRAD/lithium | analysis/Docblock.php | Docblock.comment | public static function comment($comment) {
$text = null;
$tags = [];
$description = null;
$comment = trim(preg_replace('/^(\s*\/\*\*|\s*\*{1,2}\/|\s*\* ?)/m', '', $comment));
$comment = str_replace("\r\n", "\n", $comment);
if ($items = preg_split('/\n@/ms', $comment, 2)) {
list($description, $tags) = $items + ['', ''];
$tags = $tags ? static::tags("@{$tags}") : [];
}
if (strpos($description, "\n\n")) {
list($description, $text) = explode("\n\n", $description, 2);
}
$text = trim($text);
$description = trim($description);
return compact('description', 'text', 'tags');
} | php | public static function comment($comment) {
$text = null;
$tags = [];
$description = null;
$comment = trim(preg_replace('/^(\s*\/\*\*|\s*\*{1,2}\/|\s*\* ?)/m', '', $comment));
$comment = str_replace("\r\n", "\n", $comment);
if ($items = preg_split('/\n@/ms', $comment, 2)) {
list($description, $tags) = $items + ['', ''];
$tags = $tags ? static::tags("@{$tags}") : [];
}
if (strpos($description, "\n\n")) {
list($description, $text) = explode("\n\n", $description, 2);
}
$text = trim($text);
$description = trim($description);
return compact('description', 'text', 'tags');
} | [
"public",
"static",
"function",
"comment",
"(",
"$",
"comment",
")",
"{",
"$",
"text",
"=",
"null",
";",
"$",
"tags",
"=",
"[",
"]",
";",
"$",
"description",
"=",
"null",
";",
"$",
"comment",
"=",
"trim",
"(",
"preg_replace",
"(",
"'/^(\\s*\\/\\*\\*|\\... | Parses a doc block into its major components of `description`, `text` and `tags`.
@param string $comment The doc block string to be parsed
@return array An associative array of the parsed comment, whose keys are `description`,
`text` and `tags`. | [
"Parses",
"a",
"doc",
"block",
"into",
"its",
"major",
"components",
"of",
"description",
"text",
"and",
"tags",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Docblock.php#L39-L57 |
UnionOfRAD/lithium | analysis/Docblock.php | Docblock.tags | public static function tags($string) {
$regex = '/\n@(?P<type>' . join('|', static::$tags) . ")/msi";
$string = trim($string);
$result = preg_split($regex, "\n$string", -1, PREG_SPLIT_DELIM_CAPTURE);
$tags = [];
for ($i = 1; $i < count($result) - 1; $i += 2) {
$type = trim(strtolower($result[$i]));
$text = trim($result[$i + 1]);
if (isset($tags[$type])) {
$tags[$type] = is_array($tags[$type]) ? $tags[$type] : (array) $tags[$type];
$tags[$type][] = $text;
} else {
$tags[$type] = $text;
}
}
if (isset($tags['param'])) {
$tags['params'] = static::_params((array) $tags['param']);
unset($tags['param']);
}
return $tags;
} | php | public static function tags($string) {
$regex = '/\n@(?P<type>' . join('|', static::$tags) . ")/msi";
$string = trim($string);
$result = preg_split($regex, "\n$string", -1, PREG_SPLIT_DELIM_CAPTURE);
$tags = [];
for ($i = 1; $i < count($result) - 1; $i += 2) {
$type = trim(strtolower($result[$i]));
$text = trim($result[$i + 1]);
if (isset($tags[$type])) {
$tags[$type] = is_array($tags[$type]) ? $tags[$type] : (array) $tags[$type];
$tags[$type][] = $text;
} else {
$tags[$type] = $text;
}
}
if (isset($tags['param'])) {
$tags['params'] = static::_params((array) $tags['param']);
unset($tags['param']);
}
return $tags;
} | [
"public",
"static",
"function",
"tags",
"(",
"$",
"string",
")",
"{",
"$",
"regex",
"=",
"'/\\n@(?P<type>'",
".",
"join",
"(",
"'|'",
",",
"static",
"::",
"$",
"tags",
")",
".",
"\")/msi\"",
";",
"$",
"string",
"=",
"trim",
"(",
"$",
"string",
")",
... | Parses `@<tagname>` docblock tags and their descriptions from a docblock.
See the `$tags` property for the list of supported tags.
@param string $string The string to be parsed for tags
@return array Returns an array where each docblock tag is a key name, and the corresponding
values are either strings (if one of each tag), or arrays (if multiple of the same
tag). | [
"Parses",
"@<tagname",
">",
"docblock",
"tags",
"and",
"their",
"descriptions",
"from",
"a",
"docblock",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Docblock.php#L69-L93 |
UnionOfRAD/lithium | analysis/Docblock.php | Docblock._params | protected static function _params(array $params) {
$result = [];
foreach ($params as $param) {
$param = explode(' ', $param, 3);
$type = $name = $text = null;
foreach (['type', 'name', 'text'] as $i => $key) {
if (!isset($param[$i])) {
break;
}
${$key} = $param[$i];
}
if ($name) {
$result[$name] = compact('type', 'text');
}
}
return $result;
} | php | protected static function _params(array $params) {
$result = [];
foreach ($params as $param) {
$param = explode(' ', $param, 3);
$type = $name = $text = null;
foreach (['type', 'name', 'text'] as $i => $key) {
if (!isset($param[$i])) {
break;
}
${$key} = $param[$i];
}
if ($name) {
$result[$name] = compact('type', 'text');
}
}
return $result;
} | [
"protected",
"static",
"function",
"_params",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"params",
"as",
"$",
"param",
")",
"{",
"$",
"param",
"=",
"explode",
"(",
"' '",
",",
"$",
"param",
",",
... | Parses `@param` docblock tags to separate out the parameter type from the description.
@param array $params An array of `@param` tags, as parsed from the `tags()` method.
@return array Returns an array where each key is a parameter name, and each value is an
associative array containing `'type'` and `'text'` keys. | [
"Parses",
"@param",
"docblock",
"tags",
"to",
"separate",
"out",
"the",
"parameter",
"type",
"from",
"the",
"description",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/analysis/Docblock.php#L102-L119 |
UnionOfRAD/lithium | console/Dispatcher.php | Dispatcher.config | public static function config($config = []) {
if (!$config) {
return ['rules' => static::$_rules];
}
foreach ($config as $key => $val) {
if (isset(static::${'_' . $key})) {
static::${'_' . $key} = $val + static::${'_' . $key};
}
}
} | php | public static function config($config = []) {
if (!$config) {
return ['rules' => static::$_rules];
}
foreach ($config as $key => $val) {
if (isset(static::${'_' . $key})) {
static::${'_' . $key} = $val + static::${'_' . $key};
}
}
} | [
"public",
"static",
"function",
"config",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"config",
")",
"{",
"return",
"[",
"'rules'",
"=>",
"static",
"::",
"$",
"_rules",
"]",
";",
"}",
"foreach",
"(",
"$",
"config",
"as",
"$"... | Used to set configuration parameters for the Dispatcher.
@param array $config Optional configuration params.
@return array If no parameters are passed, returns an associative array with the
current configuration, otherwise returns null. | [
"Used",
"to",
"set",
"configuration",
"parameters",
"for",
"the",
"Dispatcher",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Dispatcher.php#L68-L77 |
UnionOfRAD/lithium | console/Dispatcher.php | Dispatcher.run | public static function run($request = null, $options = []) {
$defaults = ['request' => []];
$options += $defaults;
$params = compact('request', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$classes = static::$_classes;
$request = $params['request'];
$options = $params['options'];
$router = $classes['router'];
$request = $request ?: new $classes['request']($options['request']);
$request->params = $router::parse($request);
$params = static::applyRules($request->params);
Environment::set($request);
try {
$callable = static::_callable($request, $params, $options);
return static::_call($callable, $request, $params);
} catch (UnexpectedValueException $e) {
return (object) ['status' => $e->getMessage() . "\n"];
}
});
} | php | public static function run($request = null, $options = []) {
$defaults = ['request' => []];
$options += $defaults;
$params = compact('request', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$classes = static::$_classes;
$request = $params['request'];
$options = $params['options'];
$router = $classes['router'];
$request = $request ?: new $classes['request']($options['request']);
$request->params = $router::parse($request);
$params = static::applyRules($request->params);
Environment::set($request);
try {
$callable = static::_callable($request, $params, $options);
return static::_call($callable, $request, $params);
} catch (UnexpectedValueException $e) {
return (object) ['status' => $e->getMessage() . "\n"];
}
});
} | [
"public",
"static",
"function",
"run",
"(",
"$",
"request",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'request'",
"=>",
"[",
"]",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",
"params",
"=... | Dispatches a request based on a request object (an instance of `lithium\console\Request`).
If `$request` is `null`, a new request object is instantiated based on the value of the
`'request'` key in the `$_classes` array.
@param object $request An instance of a request object with console request information. If
`null`, an instance will be created.
@param array $options
@return object The command action result which is an instance of `lithium\console\Response`.
@filter Allows to execute very early or very late in the command request. | [
"Dispatches",
"a",
"request",
"based",
"on",
"a",
"request",
"object",
"(",
"an",
"instance",
"of",
"lithium",
"\\",
"console",
"\\",
"Request",
")",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Dispatcher.php#L91-L114 |
UnionOfRAD/lithium | console/Dispatcher.php | Dispatcher._callable | protected static function _callable($request, $params, $options) {
$params = compact('request', 'params', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$request = $params['request'];
$params = $params['params'];
$name = $params['command'];
if (!$name) {
$request->params['args'][0] = $name;
$name = 'lithium\console\command\Help';
}
if (class_exists($class = Libraries::locate('command', $name))) {
return new $class(compact('request'));
}
throw new UnexpectedValueException("Command `{$name}` not found.");
});
} | php | protected static function _callable($request, $params, $options) {
$params = compact('request', 'params', 'options');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
$request = $params['request'];
$params = $params['params'];
$name = $params['command'];
if (!$name) {
$request->params['args'][0] = $name;
$name = 'lithium\console\command\Help';
}
if (class_exists($class = Libraries::locate('command', $name))) {
return new $class(compact('request'));
}
throw new UnexpectedValueException("Command `{$name}` not found.");
});
} | [
"protected",
"static",
"function",
"_callable",
"(",
"$",
"request",
",",
"$",
"params",
",",
"$",
"options",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'request'",
",",
"'params'",
",",
"'options'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
... | Determines which command to use for current request.
@param object $request An instance of a `Request` object.
@param array $params Request params that can be accessed inside the filter.
@param array $options
@return class lithium\console\Command Returns the instantiated command object.
@filter | [
"Determines",
"which",
"command",
"to",
"use",
"for",
"current",
"request",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Dispatcher.php#L125-L141 |
UnionOfRAD/lithium | console/Dispatcher.php | Dispatcher.applyRules | public static function applyRules($params) {
$result = [];
if (!$params) {
return false;
}
foreach (static::$_rules as $name => $rules) {
foreach ($rules as $rule) {
if (!empty($params[$name]) && isset($rule[0])) {
$options = array_merge(
[$params[$name]], isset($rule[2]) ? (array) $rule[2] : []
);
$result[$name] = call_user_func_array([$rule[0], $rule[1]], $options);
}
}
}
return $result + array_diff_key($params, $result);
} | php | public static function applyRules($params) {
$result = [];
if (!$params) {
return false;
}
foreach (static::$_rules as $name => $rules) {
foreach ($rules as $rule) {
if (!empty($params[$name]) && isset($rule[0])) {
$options = array_merge(
[$params[$name]], isset($rule[2]) ? (array) $rule[2] : []
);
$result[$name] = call_user_func_array([$rule[0], $rule[1]], $options);
}
}
}
return $result + array_diff_key($params, $result);
} | [
"public",
"static",
"function",
"applyRules",
"(",
"$",
"params",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"params",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"static",
"::",
"$",
"_rules",
"as",
"$",
"name",
... | Attempts to apply a set of formatting rules from `$_rules` to a `$params` array.
Each formatting rule is applied if the key of the rule in `$_rules` is present and not empty
in `$params`. Also performs sanity checking against `$params` to ensure that no value
matching a rule is present unless the rule check passes.
@param array $params An array of route parameters to which rules will be applied.
@return array Returns the `$params` array with formatting rules applied to array values. | [
"Attempts",
"to",
"apply",
"a",
"set",
"of",
"formatting",
"rules",
"from",
"$_rules",
"to",
"a",
"$params",
"array",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Dispatcher.php#L153-L171 |
UnionOfRAD/lithium | console/Dispatcher.php | Dispatcher._call | protected static function _call($callable, $request, $params) {
$params = compact('callable', 'request', 'params');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
if (is_callable($callable = $params['callable'])) {
$request = $params['request'];
$params = $params['params'];
if (!method_exists($callable, $params['action'])) {
array_unshift($params['args'], $request->params['action']);
$params['action'] = 'run';
}
$isHelp = (
!empty($params['help']) || !empty($params['h']) ||
!method_exists($callable, $params['action'])
);
if ($isHelp) {
$params['action'] = '_help';
}
return $callable($params['action'], $params['args']);
}
throw new UnexpectedValueException("Callable `{$callable}` is actually not callable.");
});
} | php | protected static function _call($callable, $request, $params) {
$params = compact('callable', 'request', 'params');
return Filters::run(get_called_class(), __FUNCTION__, $params, function($params) {
if (is_callable($callable = $params['callable'])) {
$request = $params['request'];
$params = $params['params'];
if (!method_exists($callable, $params['action'])) {
array_unshift($params['args'], $request->params['action']);
$params['action'] = 'run';
}
$isHelp = (
!empty($params['help']) || !empty($params['h']) ||
!method_exists($callable, $params['action'])
);
if ($isHelp) {
$params['action'] = '_help';
}
return $callable($params['action'], $params['args']);
}
throw new UnexpectedValueException("Callable `{$callable}` is actually not callable.");
});
} | [
"protected",
"static",
"function",
"_call",
"(",
"$",
"callable",
",",
"$",
"request",
",",
"$",
"params",
")",
"{",
"$",
"params",
"=",
"compact",
"(",
"'callable'",
",",
"'request'",
",",
"'params'",
")",
";",
"return",
"Filters",
"::",
"run",
"(",
"... | Calls a given command with the appropriate action.
This method is responsible for calling a `$callable` command and returning its result.
@param string $callable The callable command.
@param string $request The associated `Request` object.
@param string $params Additional params that should be passed along.
@return mixed Returns the result of the called action, typically `true` or `false`.
@filter | [
"Calls",
"a",
"given",
"command",
"with",
"the",
"appropriate",
"action",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/console/Dispatcher.php#L184-L206 |
UnionOfRAD/lithium | template/helper/Html.php | Html.charset | public function charset($encoding = null) {
if ($response = $this->_context->response()) {
$encoding = $encoding ?: $response->encoding;
}
return $this->_render(__METHOD__, 'charset', compact('encoding'));
} | php | public function charset($encoding = null) {
if ($response = $this->_context->response()) {
$encoding = $encoding ?: $response->encoding;
}
return $this->_render(__METHOD__, 'charset', compact('encoding'));
} | [
"public",
"function",
"charset",
"(",
"$",
"encoding",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"response",
"=",
"$",
"this",
"->",
"_context",
"->",
"response",
"(",
")",
")",
"{",
"$",
"encoding",
"=",
"$",
"encoding",
"?",
":",
"$",
"response",
"-... | Returns a charset meta-tag for declaring the encoding of the document.
The terms character set (here: charset) and character encoding (here:
encoding) were historically synonymous. The terms now have related but
distinct meanings. Whenever possible Lithium tries to use precise
terminology. Since HTML uses the term `charset` we expose this method
under the exact same name. This caters to the expectation towards a HTML
helper. However the rest of the framework will use the term `encoding`
when talking about character encoding.
It is suggested that uppercase letters should be used when specifying
the encoding. HTML specs don't require it to be uppercase and sites in
the wild most often use the lowercase variant. On the other hand must
XML parsers (those may not be relevant in this context anyway) not
support lowercase encodings. This and the fact that IANA lists only
encodings with uppercase characters led to the above suggestion.
@see lithium\net\http\Response::$encoding
@link http://www.iana.org/assignments/character-sets
@param string $encoding The character encoding to be used in the meta tag.
Defaults to the encoding of the `Response` object attached to the
current context. The default encoding of that object is `UTF-8`.
The string given here is not manipulated in any way, so that
values are rendered literally. Also see above note about casing.
@return string A meta tag containing the specified encoding (literally). | [
"Returns",
"a",
"charset",
"meta",
"-",
"tag",
"for",
"declaring",
"the",
"encoding",
"of",
"the",
"document",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L115-L120 |
UnionOfRAD/lithium | template/helper/Html.php | Html.link | public function link($title, $url = null, array $options = []) {
$defaults = ['escape' => true, 'type' => null];
list($scope, $options) = $this->_options($defaults, $options);
if (isset($scope['type']) && $type = $scope['type']) {
$options += compact('title');
return $this->_metaLink($type, $url, $options);
}
$url = $url === null ? $title : $url;
return $this->_render(__METHOD__, 'link', compact('title', 'url', 'options'), $scope);
} | php | public function link($title, $url = null, array $options = []) {
$defaults = ['escape' => true, 'type' => null];
list($scope, $options) = $this->_options($defaults, $options);
if (isset($scope['type']) && $type = $scope['type']) {
$options += compact('title');
return $this->_metaLink($type, $url, $options);
}
$url = $url === null ? $title : $url;
return $this->_render(__METHOD__, 'link', compact('title', 'url', 'options'), $scope);
} | [
"public",
"function",
"link",
"(",
"$",
"title",
",",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'escape'",
"=>",
"true",
",",
"'type'",
"=>",
"null",
"]",
";",
"list",
"(",
"$",
... | Creates an HTML link (`<a />`) or a document meta-link (`<link />`).
If `$url` starts with `'http://'` or `'https://'`, this is treated as an external link.
Otherwise, it is treated as a path to controller/action and parsed using
the `Router::match()` method (where `Router` is the routing class dependency specified by
the rendering context, i.e. `lithium\template\view\Renderer::$_classes`).
If `$url` is empty, `$title` is used in its place.
@param string $title The content to be wrapped by an `<a />` tag,
or the `title` attribute of a meta-link `<link />`.
@param mixed $url Can be a string representing a URL relative to the base of your Lithium
application, an external URL (starts with `'http://'` or `'https://'`), an
anchor name starting with `'#'` (i.e. `'#top'`), or an array defining a set
of request parameters that should be matched against a route in `Router`.
@param array $options The available options are:
- `'escape'` _boolean_: Whether or not the title content should be escaped.
Defaults to `true`.
- `'type'` _string_: The meta-link type, which is looked up in
`Html::$_metaLinks`. By default it accepts `atom`, `rss` and `icon`. If a `type`
is specified, this method will render a document meta-link (`<link />`),
instead of an HTML link (`<a />`).
- any other options specified are rendered as HTML attributes of the element.
@return string Returns an `<a />` or `<link />` element. | [
"Creates",
"an",
"HTML",
"link",
"(",
"<a",
"/",
">",
")",
"or",
"a",
"document",
"meta",
"-",
"link",
"(",
"<link",
"/",
">",
")",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L148-L159 |
UnionOfRAD/lithium | template/helper/Html.php | Html.script | public function script($path, array $options = []) {
$defaults = ['inline' => true];
list($scope, $options) = $this->_options($defaults, $options);
if (is_array($path)) {
foreach ($path as $i => $item) {
$path[$i] = $this->script($item, $scope);
}
return ($scope['inline']) ? join("\n\t", $path) . "\n" : null;
}
$m = __METHOD__;
$params = compact('path', 'options');
$script = Filters::run($this, __FUNCTION__, $params, function($params) use ($m) {
return $this->_render($m, 'script', $params);
});
if ($scope['inline']) {
return $script;
}
if ($this->_context) {
$this->_context->scripts($script);
}
} | php | public function script($path, array $options = []) {
$defaults = ['inline' => true];
list($scope, $options) = $this->_options($defaults, $options);
if (is_array($path)) {
foreach ($path as $i => $item) {
$path[$i] = $this->script($item, $scope);
}
return ($scope['inline']) ? join("\n\t", $path) . "\n" : null;
}
$m = __METHOD__;
$params = compact('path', 'options');
$script = Filters::run($this, __FUNCTION__, $params, function($params) use ($m) {
return $this->_render($m, 'script', $params);
});
if ($scope['inline']) {
return $script;
}
if ($this->_context) {
$this->_context->scripts($script);
}
} | [
"public",
"function",
"script",
"(",
"$",
"path",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'inline'",
"=>",
"true",
"]",
";",
"list",
"(",
"$",
"scope",
",",
"$",
"options",
")",
"=",
"$",
"this",
"->",
... | Returns a JavaScript include tag (`<script />` element). If the filename is prefixed with
`'/'`, the path will be relative to the base path of your application. Otherwise, the path
will be relative to your JavaScript path, usually `webroot/js`.
@link http://li3.me/docs/book/manual/1.x/views/
@param mixed $path String The name of a JavaScript file, or an array of names.
@param array $options Available options are:
- `'inline'` _boolean_: Whether or not the `<script />` element should be output
inline. When set to false, the `scripts()` handler prints out the script, and
other specified scripts to be included in the layout. Defaults to `true`.
This is useful when page-specific scripts are created inline in the page, and
you'd like to place them in the `<head />` along with your other scripts.
- any other options specified are rendered as HTML attributes of the element.
@return string
@filter | [
"Returns",
"a",
"JavaScript",
"include",
"tag",
"(",
"<script",
"/",
">",
"element",
")",
".",
"If",
"the",
"filename",
"is",
"prefixed",
"with",
"/",
"the",
"path",
"will",
"be",
"relative",
"to",
"the",
"base",
"path",
"of",
"your",
"application",
".",... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L178-L200 |
UnionOfRAD/lithium | template/helper/Html.php | Html.style | public function style($path, array $options = []) {
$defaults = ['type' => 'stylesheet', 'inline' => true];
list($scope, $options) = $this->_options($defaults, $options);
if (is_array($path)) {
foreach ($path as $i => $item) {
$path[$i] = $this->style($item, $scope);
}
return ($scope['inline']) ? join("\n\t", $path) . "\n" : null;
}
$m = __METHOD__;
$type = $scope['type'];
$params = compact('type', 'path', 'options');
$style = Filters::run($this, __FUNCTION__, $params, function($params) use ($m) {
$template = ($params['type'] === 'import') ? 'style-import' : 'style-link';
return $this->_render($m, $template, $params);
});
if ($scope['inline']) {
return $style;
}
if ($this->_context) {
$this->_context->styles($style);
}
} | php | public function style($path, array $options = []) {
$defaults = ['type' => 'stylesheet', 'inline' => true];
list($scope, $options) = $this->_options($defaults, $options);
if (is_array($path)) {
foreach ($path as $i => $item) {
$path[$i] = $this->style($item, $scope);
}
return ($scope['inline']) ? join("\n\t", $path) . "\n" : null;
}
$m = __METHOD__;
$type = $scope['type'];
$params = compact('type', 'path', 'options');
$style = Filters::run($this, __FUNCTION__, $params, function($params) use ($m) {
$template = ($params['type'] === 'import') ? 'style-import' : 'style-link';
return $this->_render($m, $template, $params);
});
if ($scope['inline']) {
return $style;
}
if ($this->_context) {
$this->_context->styles($style);
}
} | [
"public",
"function",
"style",
"(",
"$",
"path",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'type'",
"=>",
"'stylesheet'",
",",
"'inline'",
"=>",
"true",
"]",
";",
"list",
"(",
"$",
"scope",
",",
"$",
"option... | Creates a `<link />` element for CSS stylesheets or a `<style />` tag. If the filename is
prefixed with `'/'`, the path will be relative to the base path of your application.
Otherwise, the path will be relative to your stylesheets path, usually `webroot/css`.
@param mixed $path The name of a CSS stylesheet in `/app/webroot/css`, or an array
containing names of CSS stylesheets in that directory.
@param array $options Available options are:
- `'inline'` _boolean_: Whether or not the `<style />` element should be output
inline. When set to `false`, the `styles()` handler prints out the styles,
and other specified styles to be included in the layout. Defaults to `true`.
This is useful when page-specific styles are created inline in the page, and
you'd like to place them in the `<head />` along with your other styles.
- `'type'` _string_: By default, accepts `stylesheet` or `import`, which
respectively correspond to `style-link` and `style-import` strings templates
defined in `Html::$_strings`.
- any other options specified are rendered as HTML attributes of the element.
@return string CSS <link /> or <style /> tag, depending on the type of link.
@filter | [
"Creates",
"a",
"<link",
"/",
">",
"element",
"for",
"CSS",
"stylesheets",
"or",
"a",
"<style",
"/",
">",
"tag",
".",
"If",
"the",
"filename",
"is",
"prefixed",
"with",
"/",
"the",
"path",
"will",
"be",
"relative",
"to",
"the",
"base",
"path",
"of",
... | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L222-L247 |
UnionOfRAD/lithium | template/helper/Html.php | Html.head | public function head($tag, array $options) {
if (!isset($this->_strings[$tag])) {
return null;
}
$m = __METHOD__;
$head = Filters::run($this, __FUNCTION__, $options, function($params) use ($m, $tag) {
return $this->_render($m, $tag, $params);
});
if ($this->_context) {
$this->_context->head($head);
}
return $head;
} | php | public function head($tag, array $options) {
if (!isset($this->_strings[$tag])) {
return null;
}
$m = __METHOD__;
$head = Filters::run($this, __FUNCTION__, $options, function($params) use ($m, $tag) {
return $this->_render($m, $tag, $params);
});
if ($this->_context) {
$this->_context->head($head);
}
return $head;
} | [
"public",
"function",
"head",
"(",
"$",
"tag",
",",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_strings",
"[",
"$",
"tag",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"m",
"=",
"__METHOD__",
";... | Creates a tag for the `<head>` section of your document.
If there is a rendering context, then it also pushes the resulting tag to it.
The `$options` must match the named parameters from `$_strings` for the
given `$tag`.
@param string $tag the name of a key in `$_strings`
@param array $options the options required by `$_strings[$tag]`
@return mixed a string if successful, otherwise `null`
@filter | [
"Creates",
"a",
"tag",
"for",
"the",
"<head",
">",
"section",
"of",
"your",
"document",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L262-L275 |
UnionOfRAD/lithium | template/helper/Html.php | Html.image | public function image($path, array $options = []) {
$defaults = ['alt' => ''];
$options += $defaults;
$path = is_array($path) ? $this->_context->url($path) : $path;
$params = compact('path', 'options');
$m = __METHOD__;
return Filters::run($this, __FUNCTION__, $params, function($params) use ($m) {
return $this->_render($m, 'image', $params);
});
} | php | public function image($path, array $options = []) {
$defaults = ['alt' => ''];
$options += $defaults;
$path = is_array($path) ? $this->_context->url($path) : $path;
$params = compact('path', 'options');
$m = __METHOD__;
return Filters::run($this, __FUNCTION__, $params, function($params) use ($m) {
return $this->_render($m, 'image', $params);
});
} | [
"public",
"function",
"image",
"(",
"$",
"path",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'alt'",
"=>",
"''",
"]",
";",
"$",
"options",
"+=",
"$",
"defaults",
";",
"$",
"path",
"=",
"is_array",
"(",
"$",
... | Creates a formatted `<img />` element.
@param string $path Path to the image file. If the filename is prefixed with
`'/'`, the path will be relative to the base path of your application.
Otherwise the path will be relative to the images directory, usually
`app/webroot/img/`. If the name starts with `'http://'`, this is treated
as an external url used as the `src` attribute.
@param array $options Array of HTML attributes.
@return string Returns a formatted `<img />` tag.
@filter | [
"Creates",
"a",
"formatted",
"<img",
"/",
">",
"element",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L289-L300 |
UnionOfRAD/lithium | template/helper/Html.php | Html._metaLink | protected function _metaLink($type, $url = null, array $options = []) {
$options += isset($this->_metaLinks[$type]) ? $this->_metaLinks[$type] : [];
if ($type === 'icon') {
$url = $url ?: 'favicon.ico';
$standard = $this->_render(__METHOD__, 'meta-link', compact('url', 'options'), [
'handlers' => ['url' => 'path']
]);
$options['rel'] = 'shortcut icon';
$ieFix = $this->_render(__METHOD__, 'meta-link', compact('url', 'options'), [
'handlers' => ['url' => 'path']
]);
return "{$standard}\n\t{$ieFix}";
}
return $this->_render(__METHOD__, 'meta-link', compact('url', 'options'), [
'handlers' => []
]);
} | php | protected function _metaLink($type, $url = null, array $options = []) {
$options += isset($this->_metaLinks[$type]) ? $this->_metaLinks[$type] : [];
if ($type === 'icon') {
$url = $url ?: 'favicon.ico';
$standard = $this->_render(__METHOD__, 'meta-link', compact('url', 'options'), [
'handlers' => ['url' => 'path']
]);
$options['rel'] = 'shortcut icon';
$ieFix = $this->_render(__METHOD__, 'meta-link', compact('url', 'options'), [
'handlers' => ['url' => 'path']
]);
return "{$standard}\n\t{$ieFix}";
}
return $this->_render(__METHOD__, 'meta-link', compact('url', 'options'), [
'handlers' => []
]);
} | [
"protected",
"function",
"_metaLink",
"(",
"$",
"type",
",",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"isset",
"(",
"$",
"this",
"->",
"_metaLinks",
"[",
"$",
"type",
"]",
")",
"?",
"$"... | Creates a link to an external resource.
@param string $type The title of the external resource
@param mixed $url The address of the external resource or string for content attribute
@param array $options Other attributes for the generated tag. If the type attribute
is 'html', 'rss', 'atom', or 'icon', the mime-type is returned.
@return string | [
"Creates",
"a",
"link",
"to",
"an",
"external",
"resource",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/template/helper/Html.php#L311-L328 |
UnionOfRAD/lithium | core/Configuration.php | Configuration.set | public function set($name = null, $config = null) {
if (is_array($config)) {
$this->_configurations[$name] = $config;
return;
}
if ($config === false) {
unset($this->_configurations[$name]);
}
} | php | public function set($name = null, $config = null) {
if (is_array($config)) {
$this->_configurations[$name] = $config;
return;
}
if ($config === false) {
unset($this->_configurations[$name]);
}
} | [
"public",
"function",
"set",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"config",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"$",
"this",
"->",
"_configurations",
"[",
"$",
"name",
"]",
"=",
"$",
"config",
";",... | Sets configurations for a particular adaptable implementation, or returns the current
configuration settings.
@param string $name Name of the scope.
@param array $config Configuration to set. | [
"Sets",
"configurations",
"for",
"a",
"particular",
"adaptable",
"implementation",
"or",
"returns",
"the",
"current",
"configuration",
"settings",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Configuration.php#L51-L59 |
UnionOfRAD/lithium | core/Configuration.php | Configuration.get | public function get($name = null) {
if ($name === null) {
$result = [];
$this->_configurations = array_filter($this->_configurations);
foreach ($this->_configurations as $key => $value) {
$result[$key] = $this->get($key);
}
return $result;
}
$settings = &$this->_configurations;
if (!isset($settings[$name])) {
return null;
}
if (isset($settings[$name][0])) {
return $settings[$name][0];
}
$env = Environment::get();
$config = isset($settings[$name][$env]) ? $settings[$name][$env] : $settings[$name];
$method = is_callable($this->initConfig) ? $this->initConfig : null;
$settings[$name][0] = $method ? $method($name, $config) : $config;
return $settings[$name][0];
} | php | public function get($name = null) {
if ($name === null) {
$result = [];
$this->_configurations = array_filter($this->_configurations);
foreach ($this->_configurations as $key => $value) {
$result[$key] = $this->get($key);
}
return $result;
}
$settings = &$this->_configurations;
if (!isset($settings[$name])) {
return null;
}
if (isset($settings[$name][0])) {
return $settings[$name][0];
}
$env = Environment::get();
$config = isset($settings[$name][$env]) ? $settings[$name][$env] : $settings[$name];
$method = is_callable($this->initConfig) ? $this->initConfig : null;
$settings[$name][0] = $method ? $method($name, $config) : $config;
return $settings[$name][0];
} | [
"public",
"function",
"get",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"name",
"===",
"null",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"_configurations",
"=",
"array_filter",
"(",
"$",
"this",
"->",
"_configura... | Gets an array of settings for the given named configuration in the current
environment.
@see lithium\core\Environment
@param string $name Name of the configuration.
@return array Settings of the named configuration. | [
"Gets",
"an",
"array",
"of",
"settings",
"for",
"the",
"given",
"named",
"configuration",
"in",
"the",
"current",
"environment",
"."
] | train | https://github.com/UnionOfRAD/lithium/blob/bec3f4fdf61ea5002904754f43941ad1430ecec7/core/Configuration.php#L69-L96 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.export | public function export(string $fingerprint): string
{
$gnupg = new \Crypt_GPG($this->options);
try {
$gnupg->addEncryptKey($fingerprint);
return $gnupg->exportPublicKey($fingerprint, true);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not export fingerprint "' . $fingerprint . '": ' .
$ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | php | public function export(string $fingerprint): string
{
$gnupg = new \Crypt_GPG($this->options);
try {
$gnupg->addEncryptKey($fingerprint);
return $gnupg->exportPublicKey($fingerprint, true);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not export fingerprint "' . $fingerprint . '": ' .
$ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | [
"public",
"function",
"export",
"(",
"string",
"$",
"fingerprint",
")",
":",
"string",
"{",
"$",
"gnupg",
"=",
"new",
"\\",
"Crypt_GPG",
"(",
"$",
"this",
"->",
"options",
")",
";",
"try",
"{",
"$",
"gnupg",
"->",
"addEncryptKey",
"(",
"$",
"fingerprin... | Get the public key corresponding to a fingerprint.
@param string $fingerprint
@return string
@throws \Crypt_GPG_Exception
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception | [
"Get",
"the",
"public",
"key",
"corresponding",
"to",
"a",
"fingerprint",
"."
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L63-L77 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.decrypt | public function decrypt(Message $message): Message
{
$gnupg = new \Crypt_GPG($this->options);
try {
$gnupg->addDecryptKey($this->serverKeyFingerprint);
// Replace the message with its encrypted counterpart
$decrypted = $gnupg->decrypt($message->getBodyText());
return (clone $message)->setBody($decrypted);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not decrypt message: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | php | public function decrypt(Message $message): Message
{
$gnupg = new \Crypt_GPG($this->options);
try {
$gnupg->addDecryptKey($this->serverKeyFingerprint);
// Replace the message with its encrypted counterpart
$decrypted = $gnupg->decrypt($message->getBodyText());
return (clone $message)->setBody($decrypted);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not decrypt message: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | [
"public",
"function",
"decrypt",
"(",
"Message",
"$",
"message",
")",
":",
"Message",
"{",
"$",
"gnupg",
"=",
"new",
"\\",
"Crypt_GPG",
"(",
"$",
"this",
"->",
"options",
")",
";",
"try",
"{",
"$",
"gnupg",
"->",
"addDecryptKey",
"(",
"$",
"this",
"-... | Encrypt the body of an email.
@param Message $message
@return Message
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception | [
"Encrypt",
"the",
"body",
"of",
"an",
"email",
"."
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L88-L104 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.encrypt | public function encrypt(Message $message, string $fingerprint): Message
{
$gnupg = new \Crypt_GPG($this->options);
try {
$gnupg->addEncryptKey($fingerprint);
// Replace the message with its encrypted counterpart
$encrypted = $gnupg->encrypt($message->getBodyText(), true);
return (clone $message)->setBody($encrypted);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not encrypt message: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | php | public function encrypt(Message $message, string $fingerprint): Message
{
$gnupg = new \Crypt_GPG($this->options);
try {
$gnupg->addEncryptKey($fingerprint);
// Replace the message with its encrypted counterpart
$encrypted = $gnupg->encrypt($message->getBodyText(), true);
return (clone $message)->setBody($encrypted);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not encrypt message: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | [
"public",
"function",
"encrypt",
"(",
"Message",
"$",
"message",
",",
"string",
"$",
"fingerprint",
")",
":",
"Message",
"{",
"$",
"gnupg",
"=",
"new",
"\\",
"Crypt_GPG",
"(",
"$",
"this",
"->",
"options",
")",
";",
"try",
"{",
"$",
"gnupg",
"->",
"a... | Encrypt the body of an email.
@param Message $message
@param string $fingerprint
@return Message
@throws \Crypt_GPG_Exception
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception | [
"Encrypt",
"the",
"body",
"of",
"an",
"email",
"."
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L117-L134 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.import | public function import(string $gpgKey): string
{
try {
$gnupg = new \Crypt_GPG($this->options);
/** @var array<string, string> $data */
$data = $gnupg->importKey($gpgKey);
return $data['fingerprint'];
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not import public key: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | php | public function import(string $gpgKey): string
{
try {
$gnupg = new \Crypt_GPG($this->options);
/** @var array<string, string> $data */
$data = $gnupg->importKey($gpgKey);
return $data['fingerprint'];
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not import public key: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | [
"public",
"function",
"import",
"(",
"string",
"$",
"gpgKey",
")",
":",
"string",
"{",
"try",
"{",
"$",
"gnupg",
"=",
"new",
"\\",
"Crypt_GPG",
"(",
"$",
"this",
"->",
"options",
")",
";",
"/** @var array<string, string> $data */",
"$",
"data",
"=",
"$",
... | Import a public key, return the fingerprint
@param string $gpgKey An ASCII armored public key
@return string The GPG fingerprint for this key
@throws GPGMailerException | [
"Import",
"a",
"public",
"key",
"return",
"the",
"fingerprint"
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L187-L202 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.send | public function send(Message $message, string $fingerprint)
{
if ($this->serverKeyFingerprint) {
$this->mailer->send(
// Encrypted, signed
$this->encryptAndSign($message, $fingerprint)
);
} else {
$this->mailer->send(
// Encrypted, unsigned
$this->encrypt($message, $fingerprint)
);
}
} | php | public function send(Message $message, string $fingerprint)
{
if ($this->serverKeyFingerprint) {
$this->mailer->send(
// Encrypted, signed
$this->encryptAndSign($message, $fingerprint)
);
} else {
$this->mailer->send(
// Encrypted, unsigned
$this->encrypt($message, $fingerprint)
);
}
} | [
"public",
"function",
"send",
"(",
"Message",
"$",
"message",
",",
"string",
"$",
"fingerprint",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"serverKeyFingerprint",
")",
"{",
"$",
"this",
"->",
"mailer",
"->",
"send",
"(",
"// Encrypted, signed",
"$",
"this",
... | Encrypt then email a message
@param Message $message The message data
@param string $fingerprint Which public key fingerprint to use
@return void
@throws \Crypt_GPG_Exception
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception | [
"Encrypt",
"then",
"email",
"a",
"message"
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L216-L229 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.sendUnencrypted | public function sendUnencrypted(Message $message, bool $force = false)
{
if (!$this->serverKeyFingerprint) {
if ($force) {
// Unencrypted, unsigned
$message->setBody($message->getBodyText());
}
return;
}
$this->mailer->send(
// Unencrypted, signed:
$this->sign($message)
);
} | php | public function sendUnencrypted(Message $message, bool $force = false)
{
if (!$this->serverKeyFingerprint) {
if ($force) {
// Unencrypted, unsigned
$message->setBody($message->getBodyText());
}
return;
}
$this->mailer->send(
// Unencrypted, signed:
$this->sign($message)
);
} | [
"public",
"function",
"sendUnencrypted",
"(",
"Message",
"$",
"message",
",",
"bool",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"serverKeyFingerprint",
")",
"{",
"if",
"(",
"$",
"force",
")",
"{",
"// Unencrypted, unsigned",
... | Email a message without encrypting it.
@param Message $message The message data
@param bool $force Send even if we don't have a private key?
@return void
@throws GPGMailerException
@throws \Crypt_GPG_FileException
@throws \PEAR_Exception | [
"Email",
"a",
"message",
"without",
"encrypting",
"it",
"."
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L242-L255 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.getOption | public function getOption(string $key)
{
if (!\array_key_exists($key, $this->options)) {
throw new GPGMailerException('Key ' . $key . ' not defined');
}
return $this->options[$key];
} | php | public function getOption(string $key)
{
if (!\array_key_exists($key, $this->options)) {
throw new GPGMailerException('Key ' . $key . ' not defined');
}
return $this->options[$key];
} | [
"public",
"function",
"getOption",
"(",
"string",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"\\",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"options",
")",
")",
"{",
"throw",
"new",
"GPGMailerException",
"(",
"'Key '",
".",
"$",
"key",
... | @param string $key
@return string|int|float|bool|null|array
@throws GPGMailerException | [
"@param",
"string",
"$key",
"@return",
"string|int|float|bool|null|array"
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L263-L269 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.setOption | public function setOption(string $key, $value): self
{
$options = $this->options;
$options[$key] = $value;
// Try to set this, so it will throw an exception
try {
(new \Crypt_GPG($options));
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not set option "' . $key . '": ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
$this->options = $options;
return $this;
} | php | public function setOption(string $key, $value): self
{
$options = $this->options;
$options[$key] = $value;
// Try to set this, so it will throw an exception
try {
(new \Crypt_GPG($options));
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not set option "' . $key . '": ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
$this->options = $options;
return $this;
} | [
"public",
"function",
"setOption",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"options",
";",
"$",
"options",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"// Try to set this, so it wil... | Override an option at runtime
@param string $key
@param string|int|float|bool|null|array $value
@return self
@throws GPGMailerException | [
"Override",
"an",
"option",
"at",
"runtime"
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L288-L304 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.setPrivateKey | public function setPrivateKey(string $serverKey): self
{
$this->serverKeyFingerprint = $this->import($serverKey);
return $this;
} | php | public function setPrivateKey(string $serverKey): self
{
$this->serverKeyFingerprint = $this->import($serverKey);
return $this;
} | [
"public",
"function",
"setPrivateKey",
"(",
"string",
"$",
"serverKey",
")",
":",
"self",
"{",
"$",
"this",
"->",
"serverKeyFingerprint",
"=",
"$",
"this",
"->",
"import",
"(",
"$",
"serverKey",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Sets the private key for signing.
@param string $serverKey
@return self
@throws GPGMailerException | [
"Sets",
"the",
"private",
"key",
"for",
"signing",
"."
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L313-L317 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.sign | public function sign(Message $message): Message
{
if (!$this->serverKeyFingerprint) {
throw new GPGMailerException('No signing key provided');
}
$gnupg = new \Crypt_GPG($this->options);
$gnupg->addSignKey($this->serverKeyFingerprint);
try {
return (clone $message)->setBody(
$gnupg->sign(
$message->getBodyText(),
\Crypt_GPG::SIGN_MODE_CLEAR,
true
)
);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not sign message: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | php | public function sign(Message $message): Message
{
if (!$this->serverKeyFingerprint) {
throw new GPGMailerException('No signing key provided');
}
$gnupg = new \Crypt_GPG($this->options);
$gnupg->addSignKey($this->serverKeyFingerprint);
try {
return (clone $message)->setBody(
$gnupg->sign(
$message->getBodyText(),
\Crypt_GPG::SIGN_MODE_CLEAR,
true
)
);
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'Could not sign message: ' . $ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | [
"public",
"function",
"sign",
"(",
"Message",
"$",
"message",
")",
":",
"Message",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"serverKeyFingerprint",
")",
"{",
"throw",
"new",
"GPGMailerException",
"(",
"'No signing key provided'",
")",
";",
"}",
"$",
"gnupg",
... | Sign a message (but don't encrypt)
@param Message $message
@return Message
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception | [
"Sign",
"a",
"message",
"(",
"but",
"don",
"t",
"encrypt",
")"
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L340-L363 |
paragonie/gpg-mailer | src/GPGMailer.php | GPGMailer.verify | public function verify(Message $message, string $fingerprint): bool
{
$gnupg = new \Crypt_GPG($this->options);
$gnupg->addSignKey($fingerprint);
/**
* @var \Crypt_GPG_Signature[] $verified
*/
try {
$verified = $gnupg->verify($message->getBodyText());
/**
* @var \Crypt_GPG_Signature $sig
*/
foreach ($verified as $sig) {
if ($sig->isValid()) {
return true;
}
}
return false;
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'An error occurred trying to verify this message: ' .
$ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | php | public function verify(Message $message, string $fingerprint): bool
{
$gnupg = new \Crypt_GPG($this->options);
$gnupg->addSignKey($fingerprint);
/**
* @var \Crypt_GPG_Signature[] $verified
*/
try {
$verified = $gnupg->verify($message->getBodyText());
/**
* @var \Crypt_GPG_Signature $sig
*/
foreach ($verified as $sig) {
if ($sig->isValid()) {
return true;
}
}
return false;
} catch (\PEAR_Exception $ex) {
throw new GPGMailerException(
'An error occurred trying to verify this message: ' .
$ex->getMessage(),
$ex->getCode(),
$ex
);
}
} | [
"public",
"function",
"verify",
"(",
"Message",
"$",
"message",
",",
"string",
"$",
"fingerprint",
")",
":",
"bool",
"{",
"$",
"gnupg",
"=",
"new",
"\\",
"Crypt_GPG",
"(",
"$",
"this",
"->",
"options",
")",
";",
"$",
"gnupg",
"->",
"addSignKey",
"(",
... | Verify a message
@param Message $message
@param string $fingerprint
@return bool
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception | [
"Verify",
"a",
"message"
] | train | https://github.com/paragonie/gpg-mailer/blob/7fbaf43e0b04888a0b6240b974425cbceb122df7/src/GPGMailer.php#L376-L403 |
kodeine/laravel-acl | src/Kodeine/Acl/Helper/Helper.php | Helper.toDotPermissions | protected function toDotPermissions(array $permissions)
{
$data = [];
//$permissions = $this->permissions->lists('slug', 'name');
foreach ($permissions as $alias => $perm) {
if ( ! is_array($perm) ) continue;
foreach ($perm as $key => $value) {
//if ( (bool) $value == false ) continue;
$slug = $key . '.' . $alias;
$data[$slug] = $value;
//$data[] = $slug;
}
}
return $data;
} | php | protected function toDotPermissions(array $permissions)
{
$data = [];
//$permissions = $this->permissions->lists('slug', 'name');
foreach ($permissions as $alias => $perm) {
if ( ! is_array($perm) ) continue;
foreach ($perm as $key => $value) {
//if ( (bool) $value == false ) continue;
$slug = $key . '.' . $alias;
$data[$slug] = $value;
//$data[] = $slug;
}
}
return $data;
} | [
"protected",
"function",
"toDotPermissions",
"(",
"array",
"$",
"permissions",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"//$permissions = $this->permissions->lists('slug', 'name');",
"foreach",
"(",
"$",
"permissions",
"as",
"$",
"alias",
"=>",
"$",
"perm",
")",... | /*
|----------------------------------------------------------------------
| Slug Permission Related Protected Methods
|----------------------------------------------------------------------
| | [
"/",
"*",
"|",
"----------------------------------------------------------------------",
"|",
"Slug",
"Permission",
"Related",
"Protected",
"Methods",
"|",
"----------------------------------------------------------------------",
"|"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Helper/Helper.php#L36-L51 |
kodeine/laravel-acl | src/Kodeine/Acl/Helper/Helper.php | Helper.parseOperator | protected function parseOperator($str)
{
// if its an array lets use
// and operator by default
if ( is_array($str) ) {
$str = implode(',', $str);
}
if ( preg_match('/([,|])(?:\s+)?/', $str, $m) ) {
return $m[1] == '|' ? 'or' : 'and';
}
return false;
} | php | protected function parseOperator($str)
{
// if its an array lets use
// and operator by default
if ( is_array($str) ) {
$str = implode(',', $str);
}
if ( preg_match('/([,|])(?:\s+)?/', $str, $m) ) {
return $m[1] == '|' ? 'or' : 'and';
}
return false;
} | [
"protected",
"function",
"parseOperator",
"(",
"$",
"str",
")",
"{",
"// if its an array lets use",
"// and operator by default",
"if",
"(",
"is_array",
"(",
"$",
"str",
")",
")",
"{",
"$",
"str",
"=",
"implode",
"(",
"','",
",",
"$",
"str",
")",
";",
"}",... | /*
|----------------------------------------------------------------------
| Protected Methods
|----------------------------------------------------------------------
| | [
"/",
"*",
"|",
"----------------------------------------------------------------------",
"|",
"Protected",
"Methods",
"|",
"----------------------------------------------------------------------",
"|"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Helper/Helper.php#L60-L73 |
kodeine/laravel-acl | src/Kodeine/Acl/Helper/Helper.php | Helper.hasDelimiterToArray | protected function hasDelimiterToArray($str)
{
if ( is_string($str) && preg_match('/[,|]/is', $str) ) {
return preg_split('/ ?[,|] ?/', strtolower($str));
}
return is_array($str) ?
array_filter($str, 'strtolower') :
(is_object($str) ? $str : strtolower($str));
} | php | protected function hasDelimiterToArray($str)
{
if ( is_string($str) && preg_match('/[,|]/is', $str) ) {
return preg_split('/ ?[,|] ?/', strtolower($str));
}
return is_array($str) ?
array_filter($str, 'strtolower') :
(is_object($str) ? $str : strtolower($str));
} | [
"protected",
"function",
"hasDelimiterToArray",
"(",
"$",
"str",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"str",
")",
"&&",
"preg_match",
"(",
"'/[,|]/is'",
",",
"$",
"str",
")",
")",
"{",
"return",
"preg_split",
"(",
"'/ ?[,|] ?/'",
",",
"strtolower",
... | Converts strings having comma
or pipe to an array in
lowercase
@param $str
@return array | [
"Converts",
"strings",
"having",
"comma",
"or",
"pipe",
"to",
"an",
"array",
"in",
"lowercase"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Helper/Helper.php#L83-L92 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.handle | public function handle($request, Closure $next)
{
$this->request = $request;
// override crud resources via config
$this->crudConfigOverride();
// if route has access
if (( ! $this->getAction('is') or $this->hasRole()) and
( ! $this->getAction('can') or $this->hasPermission()) and
( ! $this->getAction('protect_alias') or $this->protectMethods())
) {
return $next($request);
}
if ( $request->isJson() || $request->wantsJson() ) {
return response()->json([
'error' => [
'status_code' => 401,
'code' => 'INSUFFICIENT_PERMISSIONS',
'description' => 'You are not authorized to access this resource.'
],
], 401);
}
return abort(401, 'You are not authorized to access this resource.');
} | php | public function handle($request, Closure $next)
{
$this->request = $request;
// override crud resources via config
$this->crudConfigOverride();
// if route has access
if (( ! $this->getAction('is') or $this->hasRole()) and
( ! $this->getAction('can') or $this->hasPermission()) and
( ! $this->getAction('protect_alias') or $this->protectMethods())
) {
return $next($request);
}
if ( $request->isJson() || $request->wantsJson() ) {
return response()->json([
'error' => [
'status_code' => 401,
'code' => 'INSUFFICIENT_PERMISSIONS',
'description' => 'You are not authorized to access this resource.'
],
], 401);
}
return abort(401, 'You are not authorized to access this resource.');
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"$",
"this",
"->",
"request",
"=",
"$",
"request",
";",
"// override crud resources via config",
"$",
"this",
"->",
"crudConfigOverride",
"(",
")",
";",
"// if route ha... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L37-L63 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.hasRole | protected function hasRole()
{
$request = $this->request;
$role = $this->getAction('is');
return ! $this->forbiddenRoute() && $request->user()->hasRole($role);
} | php | protected function hasRole()
{
$request = $this->request;
$role = $this->getAction('is');
return ! $this->forbiddenRoute() && $request->user()->hasRole($role);
} | [
"protected",
"function",
"hasRole",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request",
";",
"$",
"role",
"=",
"$",
"this",
"->",
"getAction",
"(",
"'is'",
")",
";",
"return",
"!",
"$",
"this",
"->",
"forbiddenRoute",
"(",
")",
"&&",
... | Check if user has requested route role.
@return bool | [
"Check",
"if",
"user",
"has",
"requested",
"route",
"role",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L70-L76 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.hasPermission | protected function hasPermission()
{
$request = $this->request;
$do = $this->getAction('can');
return ! $this->forbiddenRoute() && $request->user()->can($do);
} | php | protected function hasPermission()
{
$request = $this->request;
$do = $this->getAction('can');
return ! $this->forbiddenRoute() && $request->user()->can($do);
} | [
"protected",
"function",
"hasPermission",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request",
";",
"$",
"do",
"=",
"$",
"this",
"->",
"getAction",
"(",
"'can'",
")",
";",
"return",
"!",
"$",
"this",
"->",
"forbiddenRoute",
"(",
")",
"&&... | Check if user has requested route permissions.
@return bool | [
"Check",
"if",
"user",
"has",
"requested",
"route",
"permissions",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L83-L89 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.protectMethods | protected function protectMethods()
{
$request = $this->request;
// available methods for resources.
$resources = $this->crud['resources'];
// protection methods being passed in a route.
$methods = $this->getAction('protect_methods');
// get method being called on controller.
$caller = $this->parseMethod();
// determine if we use resource or restful http method to protect crud.
$called = in_array($caller, $resources) ? $caller : $request->method();
// if controller is a resource or closure
// and does not have methods like
// UserController@index but only
// UserController we use crud restful.
$methods = is_array($methods) ? $methods :
(in_array($caller, $resources) ?
$this->crud['resource'] : $this->crud['restful']);
// determine crud method we're trying to protect
$crud = $this->filterMethods($methods, function ($k, $v) use ($called) {
return in_array($called, $v);
});
// crud method is read, view, delete etc
// match it against our permissions
// view.user or delete.user
// multiple keys like create,store?
// use OR operator and join keys with alias.
$permission = implode('|', array_map(function ($e) {
return $e . '.' . $this->parseAlias();
}, array_keys($crud)));
return ! $this->forbiddenRoute() && $request->user()->can($permission);
} | php | protected function protectMethods()
{
$request = $this->request;
// available methods for resources.
$resources = $this->crud['resources'];
// protection methods being passed in a route.
$methods = $this->getAction('protect_methods');
// get method being called on controller.
$caller = $this->parseMethod();
// determine if we use resource or restful http method to protect crud.
$called = in_array($caller, $resources) ? $caller : $request->method();
// if controller is a resource or closure
// and does not have methods like
// UserController@index but only
// UserController we use crud restful.
$methods = is_array($methods) ? $methods :
(in_array($caller, $resources) ?
$this->crud['resource'] : $this->crud['restful']);
// determine crud method we're trying to protect
$crud = $this->filterMethods($methods, function ($k, $v) use ($called) {
return in_array($called, $v);
});
// crud method is read, view, delete etc
// match it against our permissions
// view.user or delete.user
// multiple keys like create,store?
// use OR operator and join keys with alias.
$permission = implode('|', array_map(function ($e) {
return $e . '.' . $this->parseAlias();
}, array_keys($crud)));
return ! $this->forbiddenRoute() && $request->user()->can($permission);
} | [
"protected",
"function",
"protectMethods",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request",
";",
"// available methods for resources.",
"$",
"resources",
"=",
"$",
"this",
"->",
"crud",
"[",
"'resources'",
"]",
";",
"// protection methods being pa... | Protect Crud functions of controller.
@return string | [
"Protect",
"Crud",
"functions",
"of",
"controller",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L96-L135 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.getAction | protected function getAction($key)
{
$action = $this->request->route()->getAction();
return isset($action[$key]) ? $action[$key] : false;
} | php | protected function getAction($key)
{
$action = $this->request->route()->getAction();
return isset($action[$key]) ? $action[$key] : false;
} | [
"protected",
"function",
"getAction",
"(",
"$",
"key",
")",
"{",
"$",
"action",
"=",
"$",
"this",
"->",
"request",
"->",
"route",
"(",
")",
"->",
"getAction",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"action",
"[",
"$",
"key",
"]",
")",
"?",
"... | Extract required action from requested route.
@param string $key action name
@return string | [
"Extract",
"required",
"action",
"from",
"requested",
"route",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L172-L177 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.parseAlias | protected function parseAlias()
{
if ( $alias = $this->getAction('protect_alias') ) {
return $alias;
}
$action = $this->request->route()->getActionName();
$ctrl = preg_match('/([^@]+)+/is', $action, $m) ? $m[1] : $action;
$name = last(explode('\\', $ctrl));
$name = str_replace('controller', '', strtolower($name));
$name = str_singular($name);
return $name;
} | php | protected function parseAlias()
{
if ( $alias = $this->getAction('protect_alias') ) {
return $alias;
}
$action = $this->request->route()->getActionName();
$ctrl = preg_match('/([^@]+)+/is', $action, $m) ? $m[1] : $action;
$name = last(explode('\\', $ctrl));
$name = str_replace('controller', '', strtolower($name));
$name = str_singular($name);
return $name;
} | [
"protected",
"function",
"parseAlias",
"(",
")",
"{",
"if",
"(",
"$",
"alias",
"=",
"$",
"this",
"->",
"getAction",
"(",
"'protect_alias'",
")",
")",
"{",
"return",
"$",
"alias",
";",
"}",
"$",
"action",
"=",
"$",
"this",
"->",
"request",
"->",
"rout... | Extract controller name, make it singular
to match it with model name to be able
to match against permissions view.user,
create.user etc.
@return string | [
"Extract",
"controller",
"name",
"make",
"it",
"singular",
"to",
"match",
"it",
"with",
"model",
"name",
"to",
"be",
"able",
"to",
"match",
"against",
"permissions",
"view",
".",
"user",
"create",
".",
"user",
"etc",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L187-L201 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.parseMethod | protected function parseMethod()
{
$action = $this->request->route()->getActionName();
// parse index, store, create etc
if ( preg_match('/@([^\s].+)$/is', $action, $m) ) {
$controller = $m[1];
if ( $controller != 'Closure' ) {
return $controller;
}
}
return false;
} | php | protected function parseMethod()
{
$action = $this->request->route()->getActionName();
// parse index, store, create etc
if ( preg_match('/@([^\s].+)$/is', $action, $m) ) {
$controller = $m[1];
if ( $controller != 'Closure' ) {
return $controller;
}
}
return false;
} | [
"protected",
"function",
"parseMethod",
"(",
")",
"{",
"$",
"action",
"=",
"$",
"this",
"->",
"request",
"->",
"route",
"(",
")",
"->",
"getActionName",
"(",
")",
";",
"// parse index, store, create etc",
"if",
"(",
"preg_match",
"(",
"'/@([^\\s].+)$/is'",
","... | Extract controller method
@return string | [
"Extract",
"controller",
"method"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L208-L221 |
kodeine/laravel-acl | src/Kodeine/Acl/Middleware/HasPermission.php | HasPermission.crudConfigOverride | protected function crudConfigOverride()
{
// Override crud restful from config.
if ( ($restful = config('acl.crud.restful')) != null ) {
$this->crud['restful'] = $restful;
}
// Override crud resource from config.
if ( ($resource = config('acl.crud.resource')) != null ) {
$this->crud['resource'] = $resource;
}
} | php | protected function crudConfigOverride()
{
// Override crud restful from config.
if ( ($restful = config('acl.crud.restful')) != null ) {
$this->crud['restful'] = $restful;
}
// Override crud resource from config.
if ( ($resource = config('acl.crud.resource')) != null ) {
$this->crud['resource'] = $resource;
}
} | [
"protected",
"function",
"crudConfigOverride",
"(",
")",
"{",
"// Override crud restful from config.",
"if",
"(",
"(",
"$",
"restful",
"=",
"config",
"(",
"'acl.crud.restful'",
")",
")",
"!=",
"null",
")",
"{",
"$",
"this",
"->",
"crud",
"[",
"'restful'",
"]",... | Override crud property via config. | [
"Override",
"crud",
"property",
"via",
"config",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Middleware/HasPermission.php#L226-L237 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermission.php | HasPermission.getPermissions | public function getPermissions()
{
// user permissions overridden from role.
$permissions = \Cache::remember(
'acl.getPermissionsById_'.$this->id,
config('acl.cacheMinutes'),
function () {
return $this->getPermissionsInherited();
}
);
// permissions based on role.
// more permissive permission wins
// if user has multiple roles we keep
// true values.
foreach ($this->roles as $role) {
foreach ($role->getPermissions() as $slug => $array) {
if ( array_key_exists($slug, $permissions) ) {
foreach ($array as $clearance => $value) {
if( !array_key_exists( $clearance, $permissions[$slug] ) ) {
! $value ?: $permissions[$slug][$clearance] = true;
}
}
} else {
$permissions = array_merge($permissions, [$slug => $array]);
}
}
}
return $permissions;
} | php | public function getPermissions()
{
// user permissions overridden from role.
$permissions = \Cache::remember(
'acl.getPermissionsById_'.$this->id,
config('acl.cacheMinutes'),
function () {
return $this->getPermissionsInherited();
}
);
// permissions based on role.
// more permissive permission wins
// if user has multiple roles we keep
// true values.
foreach ($this->roles as $role) {
foreach ($role->getPermissions() as $slug => $array) {
if ( array_key_exists($slug, $permissions) ) {
foreach ($array as $clearance => $value) {
if( !array_key_exists( $clearance, $permissions[$slug] ) ) {
! $value ?: $permissions[$slug][$clearance] = true;
}
}
} else {
$permissions = array_merge($permissions, [$slug => $array]);
}
}
}
return $permissions;
} | [
"public",
"function",
"getPermissions",
"(",
")",
"{",
"// user permissions overridden from role.",
"$",
"permissions",
"=",
"\\",
"Cache",
"::",
"remember",
"(",
"'acl.getPermissionsById_'",
".",
"$",
"this",
"->",
"id",
",",
"config",
"(",
"'acl.cacheMinutes'",
")... | Get all user permissions including
user all role permissions.
@return array|null | [
"Get",
"all",
"user",
"permissions",
"including",
"user",
"all",
"role",
"permissions",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermission.php#L34-L64 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermission.php | HasPermission.can | public function can($permission, $operator = null)
{
// user permissions including
// all of user role permissions
$merge = \Cache::remember(
'acl.getMergeById_'.$this->id,
config('acl.cacheMinutes'),
function () {
return $this->getPermissions();
}
);
// lets call our base can() method
// from role class. $merge already
// has user & role permissions
$model = config('acl.role', 'Kodeine\Acl\Models\Eloquent\Role');
return (new $model)->can($permission, $operator, $merge);
} | php | public function can($permission, $operator = null)
{
// user permissions including
// all of user role permissions
$merge = \Cache::remember(
'acl.getMergeById_'.$this->id,
config('acl.cacheMinutes'),
function () {
return $this->getPermissions();
}
);
// lets call our base can() method
// from role class. $merge already
// has user & role permissions
$model = config('acl.role', 'Kodeine\Acl\Models\Eloquent\Role');
return (new $model)->can($permission, $operator, $merge);
} | [
"public",
"function",
"can",
"(",
"$",
"permission",
",",
"$",
"operator",
"=",
"null",
")",
"{",
"// user permissions including",
"// all of user role permissions",
"$",
"merge",
"=",
"\\",
"Cache",
"::",
"remember",
"(",
"'acl.getMergeById_'",
".",
"$",
"this",
... | Check if User has the given permission.
@param string $permission
@param string $operator
@return bool | [
"Check",
"if",
"User",
"has",
"the",
"given",
"permission",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermission.php#L73-L91 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermission.php | HasPermission.assignPermission | public function assignPermission($permission)
{
return $this->mapArray($permission, function ($permission) {
$permissionId = $this->parsePermissionId($permission);
if ( ! $this->permissions->keyBy('id')->has($permissionId) ) {
$this->permissions()->attach($permissionId);
return $permission;
}
return false;
});
} | php | public function assignPermission($permission)
{
return $this->mapArray($permission, function ($permission) {
$permissionId = $this->parsePermissionId($permission);
if ( ! $this->permissions->keyBy('id')->has($permissionId) ) {
$this->permissions()->attach($permissionId);
return $permission;
}
return false;
});
} | [
"public",
"function",
"assignPermission",
"(",
"$",
"permission",
")",
"{",
"return",
"$",
"this",
"->",
"mapArray",
"(",
"$",
"permission",
",",
"function",
"(",
"$",
"permission",
")",
"{",
"$",
"permissionId",
"=",
"$",
"this",
"->",
"parsePermissionId",
... | Assigns the given permission to the user.
@param collection|object|array|string|int $permission
@return bool | [
"Assigns",
"the",
"given",
"permission",
"to",
"the",
"user",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermission.php#L99-L113 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermission.php | HasPermission.revokePermission | public function revokePermission($permission)
{
return $this->mapArray($permission, function ($permission) {
$permissionId = $this->parsePermissionId($permission);
return $this->permissions()->detach($permissionId);
});
} | php | public function revokePermission($permission)
{
return $this->mapArray($permission, function ($permission) {
$permissionId = $this->parsePermissionId($permission);
return $this->permissions()->detach($permissionId);
});
} | [
"public",
"function",
"revokePermission",
"(",
"$",
"permission",
")",
"{",
"return",
"$",
"this",
"->",
"mapArray",
"(",
"$",
"permission",
",",
"function",
"(",
"$",
"permission",
")",
"{",
"$",
"permissionId",
"=",
"$",
"this",
"->",
"parsePermissionId",
... | Revokes the given permission from the user.
@param collection|object|array|string|int $permission
@return bool | [
"Revokes",
"the",
"given",
"permission",
"from",
"the",
"user",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermission.php#L121-L129 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermission.php | HasPermission.syncPermissions | public function syncPermissions($permissions)
{
$sync = [];
$this->mapArray($permissions, function ($permission) use (&$sync) {
$sync[] = $this->parsePermissionId($permission);
return $sync;
});
return $this->permissions()->sync($sync);
} | php | public function syncPermissions($permissions)
{
$sync = [];
$this->mapArray($permissions, function ($permission) use (&$sync) {
$sync[] = $this->parsePermissionId($permission);
return $sync;
});
return $this->permissions()->sync($sync);
} | [
"public",
"function",
"syncPermissions",
"(",
"$",
"permissions",
")",
"{",
"$",
"sync",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"mapArray",
"(",
"$",
"permissions",
",",
"function",
"(",
"$",
"permission",
")",
"use",
"(",
"&",
"$",
"sync",
")",
"{",... | Syncs the given permission(s) with the user.
@param collection|object|array|string|int $permissions
@return bool | [
"Syncs",
"the",
"given",
"permission",
"(",
"s",
")",
"with",
"the",
"user",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermission.php#L137-L148 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermission.php | HasPermission.parsePermissionId | protected function parsePermissionId($permission)
{
if ( is_string($permission) || is_numeric($permission) ) {
$model = config('acl.permission', 'Kodeine\Acl\Models\Eloquent\Permission');
$key = is_numeric($permission) ? 'id' : 'name';
$alias = (new $model)->where($key, $permission)->first();
if ( ! is_object($alias) || ! $alias->exists ) {
throw new \InvalidArgumentException('Specified permission ' . $key . ' does not exists.');
}
$permission = $alias->getKey();
}
$model = '\Illuminate\Database\Eloquent\Model';
if ( is_object($permission) && $permission instanceof $model ) {
$permission = $permission->getKey();
}
return (int) $permission;
} | php | protected function parsePermissionId($permission)
{
if ( is_string($permission) || is_numeric($permission) ) {
$model = config('acl.permission', 'Kodeine\Acl\Models\Eloquent\Permission');
$key = is_numeric($permission) ? 'id' : 'name';
$alias = (new $model)->where($key, $permission)->first();
if ( ! is_object($alias) || ! $alias->exists ) {
throw new \InvalidArgumentException('Specified permission ' . $key . ' does not exists.');
}
$permission = $alias->getKey();
}
$model = '\Illuminate\Database\Eloquent\Model';
if ( is_object($permission) && $permission instanceof $model ) {
$permission = $permission->getKey();
}
return (int) $permission;
} | [
"protected",
"function",
"parsePermissionId",
"(",
"$",
"permission",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"permission",
")",
"||",
"is_numeric",
"(",
"$",
"permission",
")",
")",
"{",
"$",
"model",
"=",
"config",
"(",
"'acl.permission'",
",",
"'Kod... | Parses permission id from object or array.
@param object|array|int $permission
@return mixed | [
"Parses",
"permission",
"id",
"from",
"object",
"or",
"array",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermission.php#L174-L195 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasPermissionInheritance.php | HasPermissionInheritance.getPermissionsInherited | public function getPermissionsInherited()
{
$rights = [];
$permissions = $this->permissions;
// ntfs permissions
// determine if ntfs is enabled
// then more permissive wins
$tmp = [];
$letNtfs = function ($alias, $slug) use (&$tmp) {
if ( config('acl.most_permissive_wins', false) ) {
$ntfs[$alias] = array_diff($slug, [false]);
if ( sizeof($ntfs) > 0 ) {
$tmp = array_replace_recursive($tmp, $ntfs);
}
}
};
foreach ($permissions as $row) {
// permissions without inherit ids
if ( is_null($row->inherit_id) || ! $row->inherit_id ) {
// ntfs determination
$letNtfs($row->name, $row->slug);
// merge permissions
$rights = array_replace_recursive($rights, [$row->name => $row->slug], $tmp);
continue;
}
// process inherit_id recursively
$inherited = $this->getRecursiveInherit($row->inherit_id, $row->slug);
$merge = $permissions->where('name', $row->name);
$merge = method_exists($merge, 'pluck') ? $merge->pluck('slug', 'name') : $merge->lists('slug', 'name');
// fix for l5.1 and backward compatibility.
// lists() method should return as an array.
$merge = $this->collectionAsArray($merge);
// replace and merge permissions
$rights = array_replace_recursive($rights, $inherited, $merge);
// make sure we don't unset if
// inherited & slave permission
// have same names
if ( key($inherited) != $row->name )
unset($rights[$row->name]);
}
return $rights;
} | php | public function getPermissionsInherited()
{
$rights = [];
$permissions = $this->permissions;
// ntfs permissions
// determine if ntfs is enabled
// then more permissive wins
$tmp = [];
$letNtfs = function ($alias, $slug) use (&$tmp) {
if ( config('acl.most_permissive_wins', false) ) {
$ntfs[$alias] = array_diff($slug, [false]);
if ( sizeof($ntfs) > 0 ) {
$tmp = array_replace_recursive($tmp, $ntfs);
}
}
};
foreach ($permissions as $row) {
// permissions without inherit ids
if ( is_null($row->inherit_id) || ! $row->inherit_id ) {
// ntfs determination
$letNtfs($row->name, $row->slug);
// merge permissions
$rights = array_replace_recursive($rights, [$row->name => $row->slug], $tmp);
continue;
}
// process inherit_id recursively
$inherited = $this->getRecursiveInherit($row->inherit_id, $row->slug);
$merge = $permissions->where('name', $row->name);
$merge = method_exists($merge, 'pluck') ? $merge->pluck('slug', 'name') : $merge->lists('slug', 'name');
// fix for l5.1 and backward compatibility.
// lists() method should return as an array.
$merge = $this->collectionAsArray($merge);
// replace and merge permissions
$rights = array_replace_recursive($rights, $inherited, $merge);
// make sure we don't unset if
// inherited & slave permission
// have same names
if ( key($inherited) != $row->name )
unset($rights[$row->name]);
}
return $rights;
} | [
"public",
"function",
"getPermissionsInherited",
"(",
")",
"{",
"$",
"rights",
"=",
"[",
"]",
";",
"$",
"permissions",
"=",
"$",
"this",
"->",
"permissions",
";",
"// ntfs permissions",
"// determine if ntfs is enabled",
"// then more permissive wins",
"$",
"tmp",
"... | /*
|----------------------------------------------------------------------
| Permission Inheritance Trait Methods
|----------------------------------------------------------------------
| | [
"/",
"*",
"|",
"----------------------------------------------------------------------",
"|",
"Permission",
"Inheritance",
"Trait",
"Methods",
"|",
"----------------------------------------------------------------------",
"|"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasPermissionInheritance.php#L15-L67 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.getRoles | public function getRoles()
{
$this_roles = \Cache::remember(
'acl.getRolesById_'.$this->id,
config('acl.cacheMinutes'),
function () {
return $this->roles;
}
);
$slugs = method_exists($this_roles, 'pluck') ? $this_roles->pluck('slug','id') : $this_roles->lists('slug','id');
return is_null($this_roles)
? []
: $this->collectionAsArray($slugs);
} | php | public function getRoles()
{
$this_roles = \Cache::remember(
'acl.getRolesById_'.$this->id,
config('acl.cacheMinutes'),
function () {
return $this->roles;
}
);
$slugs = method_exists($this_roles, 'pluck') ? $this_roles->pluck('slug','id') : $this_roles->lists('slug','id');
return is_null($this_roles)
? []
: $this->collectionAsArray($slugs);
} | [
"public",
"function",
"getRoles",
"(",
")",
"{",
"$",
"this_roles",
"=",
"\\",
"Cache",
"::",
"remember",
"(",
"'acl.getRolesById_'",
".",
"$",
"this",
"->",
"id",
",",
"config",
"(",
"'acl.cacheMinutes'",
")",
",",
"function",
"(",
")",
"{",
"return",
"... | Get all roles.
@return array | [
"Get",
"all",
"roles",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L37-L51 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.scopeRole | public function scopeRole($query, $role, $column = null)
{
if (is_null($role)) {
return $query;
}
return $query->whereHas('roles', function ($query) use ($role, $column) {
if (is_array($role)) {
$queryColumn = !is_null($column) ? $column : 'roles.slug';
$query->whereIn($queryColumn, $role);
} else {
$queryColumn = !is_null($column) ? $column : (is_numeric($role) ? 'roles.id' : 'roles.slug');
$query->where($queryColumn, $role);
}
});
} | php | public function scopeRole($query, $role, $column = null)
{
if (is_null($role)) {
return $query;
}
return $query->whereHas('roles', function ($query) use ($role, $column) {
if (is_array($role)) {
$queryColumn = !is_null($column) ? $column : 'roles.slug';
$query->whereIn($queryColumn, $role);
} else {
$queryColumn = !is_null($column) ? $column : (is_numeric($role) ? 'roles.id' : 'roles.slug');
$query->where($queryColumn, $role);
}
});
} | [
"public",
"function",
"scopeRole",
"(",
"$",
"query",
",",
"$",
"role",
",",
"$",
"column",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"role",
")",
")",
"{",
"return",
"$",
"query",
";",
"}",
"return",
"$",
"query",
"->",
"whereHas",
... | Scope to select users having a specific
role. Role can be an id or slug.
@param \Illuminate\Database\Eloquent\Builder $query
@param int|string $role
@param string $column
@return \Illuminate\Database\Eloquent\Builder | [
"Scope",
"to",
"select",
"users",
"having",
"a",
"specific",
"role",
".",
"Role",
"can",
"be",
"an",
"id",
"or",
"slug",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L62-L79 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.hasRole | public function hasRole($slug, $operator = null)
{
$operator = is_null($operator) ? $this->parseOperator($slug) : $operator;
$roles = $this->getRoles();
$roles = $roles instanceof \Illuminate\Contracts\Support\Arrayable ? $roles->toArray() : (array) $roles;
$slug = $this->hasDelimiterToArray($slug);
// array of slugs
if ( is_array($slug) ) {
if ( ! in_array($operator, ['and', 'or']) ) {
$e = 'Invalid operator, available operators are "and", "or".';
throw new \InvalidArgumentException($e);
}
$call = 'isWith' . ucwords($operator);
return $this->$call($slug, $roles);
}
// single slug
return in_array($slug, $roles);
} | php | public function hasRole($slug, $operator = null)
{
$operator = is_null($operator) ? $this->parseOperator($slug) : $operator;
$roles = $this->getRoles();
$roles = $roles instanceof \Illuminate\Contracts\Support\Arrayable ? $roles->toArray() : (array) $roles;
$slug = $this->hasDelimiterToArray($slug);
// array of slugs
if ( is_array($slug) ) {
if ( ! in_array($operator, ['and', 'or']) ) {
$e = 'Invalid operator, available operators are "and", "or".';
throw new \InvalidArgumentException($e);
}
$call = 'isWith' . ucwords($operator);
return $this->$call($slug, $roles);
}
// single slug
return in_array($slug, $roles);
} | [
"public",
"function",
"hasRole",
"(",
"$",
"slug",
",",
"$",
"operator",
"=",
"null",
")",
"{",
"$",
"operator",
"=",
"is_null",
"(",
"$",
"operator",
")",
"?",
"$",
"this",
"->",
"parseOperator",
"(",
"$",
"slug",
")",
":",
"$",
"operator",
";",
"... | Checks if the user has the given role.
@param string $slug
@return bool | [
"Checks",
"if",
"the",
"user",
"has",
"the",
"given",
"role",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L87-L110 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.assignRole | public function assignRole($role)
{
return $this->mapArray($role, function ($role) {
$roleId = $this->parseRoleId($role);
if ( ! $this->roles->keyBy('id')->has($roleId) ) {
$this->roles()->attach($roleId);
return $role;
}
return false;
});
} | php | public function assignRole($role)
{
return $this->mapArray($role, function ($role) {
$roleId = $this->parseRoleId($role);
if ( ! $this->roles->keyBy('id')->has($roleId) ) {
$this->roles()->attach($roleId);
return $role;
}
return false;
});
} | [
"public",
"function",
"assignRole",
"(",
"$",
"role",
")",
"{",
"return",
"$",
"this",
"->",
"mapArray",
"(",
"$",
"role",
",",
"function",
"(",
"$",
"role",
")",
"{",
"$",
"roleId",
"=",
"$",
"this",
"->",
"parseRoleId",
"(",
"$",
"role",
")",
";"... | Assigns the given role to the user.
@param collection|object|array|string|int $role
@return bool | [
"Assigns",
"the",
"given",
"role",
"to",
"the",
"user",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L118-L132 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.revokeRole | public function revokeRole($role)
{
return $this->mapArray($role, function ($role) {
$roleId = $this->parseRoleId($role);
return $this->roles()->detach($roleId);
});
} | php | public function revokeRole($role)
{
return $this->mapArray($role, function ($role) {
$roleId = $this->parseRoleId($role);
return $this->roles()->detach($roleId);
});
} | [
"public",
"function",
"revokeRole",
"(",
"$",
"role",
")",
"{",
"return",
"$",
"this",
"->",
"mapArray",
"(",
"$",
"role",
",",
"function",
"(",
"$",
"role",
")",
"{",
"$",
"roleId",
"=",
"$",
"this",
"->",
"parseRoleId",
"(",
"$",
"role",
")",
";"... | Revokes the given role from the user.
@param collection|object|array|string|int $role
@return bool | [
"Revokes",
"the",
"given",
"role",
"from",
"the",
"user",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L140-L148 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.syncRoles | public function syncRoles($roles)
{
$sync = [];
$this->mapArray($roles, function ($role) use (&$sync) {
$sync[] = $this->parseRoleId($role);
return $sync;
});
return $this->roles()->sync($sync);
} | php | public function syncRoles($roles)
{
$sync = [];
$this->mapArray($roles, function ($role) use (&$sync) {
$sync[] = $this->parseRoleId($role);
return $sync;
});
return $this->roles()->sync($sync);
} | [
"public",
"function",
"syncRoles",
"(",
"$",
"roles",
")",
"{",
"$",
"sync",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"mapArray",
"(",
"$",
"roles",
",",
"function",
"(",
"$",
"role",
")",
"use",
"(",
"&",
"$",
"sync",
")",
"{",
"$",
"sync",
"[",... | Syncs the given role(s) with the user.
@param collection|object|array|string|int $roles
@return bool | [
"Syncs",
"the",
"given",
"role",
"(",
"s",
")",
"with",
"the",
"user",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L156-L167 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasRole.php | HasRoleImplementation.parseRoleId | protected function parseRoleId($role)
{
if ( is_string($role) || is_numeric($role) ) {
$model = config('acl.role', 'Kodeine\Acl\Models\Eloquent\Role');
$key = is_numeric($role) ? 'id' : 'slug';
$alias = (new $model)->where($key, $role)->first();
if ( ! is_object($alias) || ! $alias->exists ) {
throw new \InvalidArgumentException('Specified role ' . $key . ' does not exists.');
}
$role = $alias->getKey();
}
$model = '\Illuminate\Database\Eloquent\Model';
if ( is_object($role) && $role instanceof $model ) {
$role = $role->getKey();
}
return (int) $role;
} | php | protected function parseRoleId($role)
{
if ( is_string($role) || is_numeric($role) ) {
$model = config('acl.role', 'Kodeine\Acl\Models\Eloquent\Role');
$key = is_numeric($role) ? 'id' : 'slug';
$alias = (new $model)->where($key, $role)->first();
if ( ! is_object($alias) || ! $alias->exists ) {
throw new \InvalidArgumentException('Specified role ' . $key . ' does not exists.');
}
$role = $alias->getKey();
}
$model = '\Illuminate\Database\Eloquent\Model';
if ( is_object($role) && $role instanceof $model ) {
$role = $role->getKey();
}
return (int) $role;
} | [
"protected",
"function",
"parseRoleId",
"(",
"$",
"role",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"role",
")",
"||",
"is_numeric",
"(",
"$",
"role",
")",
")",
"{",
"$",
"model",
"=",
"config",
"(",
"'acl.role'",
",",
"'Kodeine\\Acl\\Models\\Eloquent\\R... | Parses role id from object, array
or a string.
@param object|array|string|int $role
@return int | [
"Parses",
"role",
"id",
"from",
"object",
"array",
"or",
"a",
"string",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasRole.php#L225-L246 |
kodeine/laravel-acl | src/Kodeine/Acl/AclServiceProvider.php | AclServiceProvider.boot | public function boot()
{
$this->publishConfig();
$this->publishMigration();
$laravel = app();
if ( starts_with($laravel::VERSION, '5.0') ) {
$this->registerBlade5_0();
} else if ( starts_with($laravel::VERSION, ['5.1', '5.2']) ) {
$this->registerBlade5_1();
} else {
$this->registerBlade5_3();
}
} | php | public function boot()
{
$this->publishConfig();
$this->publishMigration();
$laravel = app();
if ( starts_with($laravel::VERSION, '5.0') ) {
$this->registerBlade5_0();
} else if ( starts_with($laravel::VERSION, ['5.1', '5.2']) ) {
$this->registerBlade5_1();
} else {
$this->registerBlade5_3();
}
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"this",
"->",
"publishConfig",
"(",
")",
";",
"$",
"this",
"->",
"publishMigration",
"(",
")",
";",
"$",
"laravel",
"=",
"app",
"(",
")",
";",
"if",
"(",
"starts_with",
"(",
"$",
"laravel",
"::",
"V... | Bootstrap any application services.
@return void | [
"Bootstrap",
"any",
"application",
"services",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/AclServiceProvider.php#L20-L33 |
kodeine/laravel-acl | src/Kodeine/Acl/AclServiceProvider.php | AclServiceProvider.registerBlade5_1 | protected function registerBlade5_1()
{
// role
Blade::directive('role', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->is{$expression}): ?>";
});
Blade::directive('endrole', function () {
return "<?php endif; ?>";
});
// permission
Blade::directive('permission', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->can{$expression}): ?>";
});
Blade::directive('endpermission', function () {
return "<?php endif; ?>";
});
} | php | protected function registerBlade5_1()
{
// role
Blade::directive('role', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->is{$expression}): ?>";
});
Blade::directive('endrole', function () {
return "<?php endif; ?>";
});
// permission
Blade::directive('permission', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->can{$expression}): ?>";
});
Blade::directive('endpermission', function () {
return "<?php endif; ?>";
});
} | [
"protected",
"function",
"registerBlade5_1",
"(",
")",
"{",
"// role",
"Blade",
"::",
"directive",
"(",
"'role'",
",",
"function",
"(",
"$",
"expression",
")",
"{",
"return",
"\"<?php if (Auth::check() && Auth::user()->is{$expression}): ?>\"",
";",
"}",
")",
";",
"B... | Register Blade Template Extensions for >= L5.1 | [
"Register",
"Blade",
"Template",
"Extensions",
"for",
">",
"=",
"L5",
".",
"1"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/AclServiceProvider.php#L90-L109 |
kodeine/laravel-acl | src/Kodeine/Acl/AclServiceProvider.php | AclServiceProvider.registerBlade5_0 | protected function registerBlade5_0()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createMatcher('role');
return preg_replace($pattern, '<?php if (Auth::check() && Auth::user()->is$2): ?> ', $view);
});
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createPlainMatcher('endrole');
return preg_replace($pattern, '<?php endif; ?>', $view);
});
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createMatcher('permission');
return preg_replace($pattern, '<?php if (Auth::check() && Auth::user()->can$2): ?> ', $view);
});
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createPlainMatcher('endpermission');
return preg_replace($pattern, '<?php endif; ?>', $view);
});
} | php | protected function registerBlade5_0()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createMatcher('role');
return preg_replace($pattern, '<?php if (Auth::check() && Auth::user()->is$2): ?> ', $view);
});
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createPlainMatcher('endrole');
return preg_replace($pattern, '<?php endif; ?>', $view);
});
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createMatcher('permission');
return preg_replace($pattern, '<?php if (Auth::check() && Auth::user()->can$2): ?> ', $view);
});
$blade->extend(function ($view, $compiler) {
$pattern = $compiler->createPlainMatcher('endpermission');
return preg_replace($pattern, '<?php endif; ?>', $view);
});
} | [
"protected",
"function",
"registerBlade5_0",
"(",
")",
"{",
"$",
"blade",
"=",
"$",
"this",
"->",
"app",
"[",
"'view'",
"]",
"->",
"getEngineResolver",
"(",
")",
"->",
"resolve",
"(",
"'blade'",
")",
"->",
"getCompiler",
"(",
")",
";",
"$",
"blade",
"-... | Register Blade Template Extensions for <= L5.0 | [
"Register",
"Blade",
"Template",
"Extensions",
"for",
"<",
"=",
"L5",
".",
"0"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/AclServiceProvider.php#L114-L136 |
kodeine/laravel-acl | src/Kodeine/Acl/Models/Eloquent/Role.php | Role.can | public function can($permission, $operator = null, $mergePermissions = [])
{
$operator = is_null($operator) ? $this->parseOperator($permission) : $operator;
$permission = $this->hasDelimiterToArray($permission);
$permissions = $this->getPermissions() + $mergePermissions;
// make permissions to dot notation.
// create.user, delete.admin etc.
$permissions = $this->toDotPermissions($permissions);
// validate permissions array
if ( is_array($permission) ) {
if ( ! in_array($operator, ['and', 'or']) ) {
$e = 'Invalid operator, available operators are "and", "or".';
throw new \InvalidArgumentException($e);
}
$call = 'canWith' . ucwords($operator);
return $this->$call($permission, $permissions);
}
// validate single permission
return isset($permissions[$permission]) && $permissions[$permission] == true;
} | php | public function can($permission, $operator = null, $mergePermissions = [])
{
$operator = is_null($operator) ? $this->parseOperator($permission) : $operator;
$permission = $this->hasDelimiterToArray($permission);
$permissions = $this->getPermissions() + $mergePermissions;
// make permissions to dot notation.
// create.user, delete.admin etc.
$permissions = $this->toDotPermissions($permissions);
// validate permissions array
if ( is_array($permission) ) {
if ( ! in_array($operator, ['and', 'or']) ) {
$e = 'Invalid operator, available operators are "and", "or".';
throw new \InvalidArgumentException($e);
}
$call = 'canWith' . ucwords($operator);
return $this->$call($permission, $permissions);
}
// validate single permission
return isset($permissions[$permission]) && $permissions[$permission] == true;
} | [
"public",
"function",
"can",
"(",
"$",
"permission",
",",
"$",
"operator",
"=",
"null",
",",
"$",
"mergePermissions",
"=",
"[",
"]",
")",
"{",
"$",
"operator",
"=",
"is_null",
"(",
"$",
"operator",
")",
"?",
"$",
"this",
"->",
"parseOperator",
"(",
"... | Checks if the role has the given permission.
@param string $permission
@param string $operator
@param array $mergePermissions
@return bool | [
"Checks",
"if",
"the",
"role",
"has",
"the",
"given",
"permission",
"."
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Models/Eloquent/Role.php#L68-L94 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasUserPermission.php | HasUserPermission.addPermission | public function addPermission($name, $permission = true)
{
$slugs = $this->permissions->keyBy('name');
list($slug, $name) = $this->extractAlias($name);
if ( $slugs->has($name) && is_null($slug) && ! is_array($permission) ) {
return true;
}
if ( ! $slugs->has($name) && is_null($slug) ) {
return $this->addPermissionCrud($name);
}
$slug = is_array($permission)
? $permission : [$slug => (bool) $permission];
// if alias doesn't exist, create permission
if ( ! $slugs->has($name) ) {
$new = $this->permissions()->create(compact('name', 'slug'));
$this->permissions->push($new);
return $new;
}
// update slug
return $slugs[$name]->update(compact('slug'));
} | php | public function addPermission($name, $permission = true)
{
$slugs = $this->permissions->keyBy('name');
list($slug, $name) = $this->extractAlias($name);
if ( $slugs->has($name) && is_null($slug) && ! is_array($permission) ) {
return true;
}
if ( ! $slugs->has($name) && is_null($slug) ) {
return $this->addPermissionCrud($name);
}
$slug = is_array($permission)
? $permission : [$slug => (bool) $permission];
// if alias doesn't exist, create permission
if ( ! $slugs->has($name) ) {
$new = $this->permissions()->create(compact('name', 'slug'));
$this->permissions->push($new);
return $new;
}
// update slug
return $slugs[$name]->update(compact('slug'));
} | [
"public",
"function",
"addPermission",
"(",
"$",
"name",
",",
"$",
"permission",
"=",
"true",
")",
"{",
"$",
"slugs",
"=",
"$",
"this",
"->",
"permissions",
"->",
"keyBy",
"(",
"'name'",
")",
";",
"list",
"(",
"$",
"slug",
",",
"$",
"name",
")",
"=... | /*
|----------------------------------------------------------------------
| User Permission Trait Methods
|----------------------------------------------------------------------
| | [
"/",
"*",
"|",
"----------------------------------------------------------------------",
"|",
"User",
"Permission",
"Trait",
"Methods",
"|",
"----------------------------------------------------------------------",
"|"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasUserPermission.php#L15-L41 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasUserPermission.php | HasUserPermission.addPermissionCrud | protected function addPermissionCrud($name)
{
$slugs = $this->permissions->keyBy('name');
list(, $name) = $this->extractAlias($name);
$hasCrud = isset($slugs->get($name)->slug['create']);
if ( $slugs->has($name) && $hasCrud ) {
return true;
}
// crud slug
$slug = [
'create' => true, 'read' => true,
'view' => true, 'update' => true,
'delete' => true
];
// if alias doesn't exist, create crud permissions
if ( ! $slugs->has($name) ) {
$new = $this->permissions()->create(compact('name', 'slug'));
$this->permissions->push($new);
return $new;
}
// update crud slug
return $slugs[$name]->update(compact('slug'));
} | php | protected function addPermissionCrud($name)
{
$slugs = $this->permissions->keyBy('name');
list(, $name) = $this->extractAlias($name);
$hasCrud = isset($slugs->get($name)->slug['create']);
if ( $slugs->has($name) && $hasCrud ) {
return true;
}
// crud slug
$slug = [
'create' => true, 'read' => true,
'view' => true, 'update' => true,
'delete' => true
];
// if alias doesn't exist, create crud permissions
if ( ! $slugs->has($name) ) {
$new = $this->permissions()->create(compact('name', 'slug'));
$this->permissions->push($new);
return $new;
}
// update crud slug
return $slugs[$name]->update(compact('slug'));
} | [
"protected",
"function",
"addPermissionCrud",
"(",
"$",
"name",
")",
"{",
"$",
"slugs",
"=",
"$",
"this",
"->",
"permissions",
"->",
"keyBy",
"(",
"'name'",
")",
";",
"list",
"(",
",",
"$",
"name",
")",
"=",
"$",
"this",
"->",
"extractAlias",
"(",
"$... | /*
|----------------------------------------------------------------------
| Slug Permission Related Protected Methods
|----------------------------------------------------------------------
| | [
"/",
"*",
"|",
"----------------------------------------------------------------------",
"|",
"Slug",
"Permission",
"Related",
"Protected",
"Methods",
"|",
"----------------------------------------------------------------------",
"|"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasUserPermission.php#L71-L99 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasUserPermission.php | HasUserPermission.addSlug | protected function addSlug($alias, array $permissions)
{
$slugs = method_exists($this->permissions, 'pluck') ? $this->permissions->pluck('slug', 'name') : $this->permissions->lists('slug', 'name');
$collection = new Collection($slugs);
if ( $collection->has($alias) ) {
$permissions = $permissions + $collection->get($alias);
}
$collection->put($alias, $permissions);
return $collection->get($alias);
} | php | protected function addSlug($alias, array $permissions)
{
$slugs = method_exists($this->permissions, 'pluck') ? $this->permissions->pluck('slug', 'name') : $this->permissions->lists('slug', 'name');
$collection = new Collection($slugs);
if ( $collection->has($alias) ) {
$permissions = $permissions + $collection->get($alias);
}
$collection->put($alias, $permissions);
return $collection->get($alias);
} | [
"protected",
"function",
"addSlug",
"(",
"$",
"alias",
",",
"array",
"$",
"permissions",
")",
"{",
"$",
"slugs",
"=",
"method_exists",
"(",
"$",
"this",
"->",
"permissions",
",",
"'pluck'",
")",
"?",
"$",
"this",
"->",
"permissions",
"->",
"pluck",
"(",
... | Deprecated
@param $alias
@param array $permissions
@return mixed | [
"Deprecated"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasUserPermission.php#L118-L130 |
kodeine/laravel-acl | src/Kodeine/Acl/Traits/HasUserPermission.php | HasUserPermission.removeSlug | protected function removeSlug($alias, array $permissions)
{
$slugs = method_exists($this->permissions, 'pluck') ? $this->permissions->pluck('slug', 'name') : $this->permissions->lists('slug', 'name');
$collection = new Collection($slugs);
if ( $collection->has($alias) ) {
$new = array_diff_key($collection->get($alias), array_flip($permissions));
$collection->put($alias, $new);
}
return $collection->get($alias);
} | php | protected function removeSlug($alias, array $permissions)
{
$slugs = method_exists($this->permissions, 'pluck') ? $this->permissions->pluck('slug', 'name') : $this->permissions->lists('slug', 'name');
$collection = new Collection($slugs);
if ( $collection->has($alias) ) {
$new = array_diff_key($collection->get($alias), array_flip($permissions));
$collection->put($alias, $new);
}
return $collection->get($alias);
} | [
"protected",
"function",
"removeSlug",
"(",
"$",
"alias",
",",
"array",
"$",
"permissions",
")",
"{",
"$",
"slugs",
"=",
"method_exists",
"(",
"$",
"this",
"->",
"permissions",
",",
"'pluck'",
")",
"?",
"$",
"this",
"->",
"permissions",
"->",
"pluck",
"(... | Deprecated
@param $alias
@param array $permissions
@return mixed | [
"Deprecated"
] | train | https://github.com/kodeine/laravel-acl/blob/6c9d73e23a01ad68161319632d250c0f0694d880/src/Kodeine/Acl/Traits/HasUserPermission.php#L139-L150 |
repejota/phpnats | src/Nats/EncodedConnection.php | EncodedConnection.publish | public function publish($subject, $payload = null, $inbox = null)
{
$payload = $this->encoder->encode($payload);
parent::publish($subject, $payload, $inbox);
} | php | public function publish($subject, $payload = null, $inbox = null)
{
$payload = $this->encoder->encode($payload);
parent::publish($subject, $payload, $inbox);
} | [
"public",
"function",
"publish",
"(",
"$",
"subject",
",",
"$",
"payload",
"=",
"null",
",",
"$",
"inbox",
"=",
"null",
")",
"{",
"$",
"payload",
"=",
"$",
"this",
"->",
"encoder",
"->",
"encode",
"(",
"$",
"payload",
")",
";",
"parent",
"::",
"pub... | Publish publishes the data argument to the given subject.
@param string $subject Message topic.
@param string $payload Message data.
@param string $inbox Message inbox.
@return void | [
"Publish",
"publishes",
"the",
"data",
"argument",
"to",
"the",
"given",
"subject",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/EncodedConnection.php#L43-L47 |
repejota/phpnats | src/Nats/EncodedConnection.php | EncodedConnection.subscribe | public function subscribe($subject, \Closure $callback)
{
$c = function ($message) use ($callback) {
$message->setBody($this->encoder->decode($message->getBody()));
$callback($message);
};
return parent::subscribe($subject, $c);
} | php | public function subscribe($subject, \Closure $callback)
{
$c = function ($message) use ($callback) {
$message->setBody($this->encoder->decode($message->getBody()));
$callback($message);
};
return parent::subscribe($subject, $c);
} | [
"public",
"function",
"subscribe",
"(",
"$",
"subject",
",",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"c",
"=",
"function",
"(",
"$",
"message",
")",
"use",
"(",
"$",
"callback",
")",
"{",
"$",
"message",
"->",
"setBody",
"(",
"$",
"this",
... | Subscribes to an specific event given a subject.
@param string $subject Message topic.
@param \Closure $callback Closure to be executed as callback.
@return string | [
"Subscribes",
"to",
"an",
"specific",
"event",
"given",
"a",
"subject",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/EncodedConnection.php#L57-L64 |
repejota/phpnats | src/Nats/EncodedConnection.php | EncodedConnection.queueSubscribe | public function queueSubscribe($subject, $queue, \Closure $callback)
{
$c = function ($message) use ($callback) {
$message->setBody($this->encoder->decode($message->getBody()));
$callback($message);
};
parent::queueSubscribe($subject, $queue, $c);
} | php | public function queueSubscribe($subject, $queue, \Closure $callback)
{
$c = function ($message) use ($callback) {
$message->setBody($this->encoder->decode($message->getBody()));
$callback($message);
};
parent::queueSubscribe($subject, $queue, $c);
} | [
"public",
"function",
"queueSubscribe",
"(",
"$",
"subject",
",",
"$",
"queue",
",",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"c",
"=",
"function",
"(",
"$",
"message",
")",
"use",
"(",
"$",
"callback",
")",
"{",
"$",
"message",
"->",
"setBod... | Subscribes to an specific event given a subject and a queue.
@param string $subject Message topic.
@param string $queue Queue name.
@param \Closure $callback Closure to be executed as callback.
@return void | [
"Subscribes",
"to",
"an",
"specific",
"event",
"given",
"a",
"subject",
"and",
"a",
"queue",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/EncodedConnection.php#L75-L82 |
repejota/phpnats | src/Nats/Connection.php | Connection.setStreamTimeout | public function setStreamTimeout($seconds)
{
if ($this->isConnected() === true) {
if (is_numeric($seconds) === true) {
try {
$timeout = number_format($seconds, 3);
$seconds = floor($timeout);
$microseconds = (($timeout - $seconds) * 1000);
return stream_set_timeout($this->streamSocket, $seconds, $microseconds);
} catch (\Exception $e) {
return false;
}
}
}
return false;
} | php | public function setStreamTimeout($seconds)
{
if ($this->isConnected() === true) {
if (is_numeric($seconds) === true) {
try {
$timeout = number_format($seconds, 3);
$seconds = floor($timeout);
$microseconds = (($timeout - $seconds) * 1000);
return stream_set_timeout($this->streamSocket, $seconds, $microseconds);
} catch (\Exception $e) {
return false;
}
}
}
return false;
} | [
"public",
"function",
"setStreamTimeout",
"(",
"$",
"seconds",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
"===",
"true",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"seconds",
")",
"===",
"true",
")",
"{",
"try",
"{",
"$",
"t... | Set Stream Timeout.
@param float $seconds Before timeout on stream.
@return boolean | [
"Set",
"Stream",
"Timeout",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L175-L191 |
repejota/phpnats | src/Nats/Connection.php | Connection.getStream | private function getStream($address, $timeout, $context)
{
$errno = null;
$errstr = null;
set_error_handler(
function () {
return true;
}
);
$fp = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
restore_error_handler();
if ($fp === false) {
throw Exception::forStreamSocketClientError($errstr, $errno);
}
$timeout = number_format($timeout, 3);
$seconds = floor($timeout);
$microseconds = (($timeout - $seconds) * 1000);
stream_set_timeout($fp, $seconds, $microseconds);
return $fp;
} | php | private function getStream($address, $timeout, $context)
{
$errno = null;
$errstr = null;
set_error_handler(
function () {
return true;
}
);
$fp = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
restore_error_handler();
if ($fp === false) {
throw Exception::forStreamSocketClientError($errstr, $errno);
}
$timeout = number_format($timeout, 3);
$seconds = floor($timeout);
$microseconds = (($timeout - $seconds) * 1000);
stream_set_timeout($fp, $seconds, $microseconds);
return $fp;
} | [
"private",
"function",
"getStream",
"(",
"$",
"address",
",",
"$",
"timeout",
",",
"$",
"context",
")",
"{",
"$",
"errno",
"=",
"null",
";",
"$",
"errstr",
"=",
"null",
";",
"set_error_handler",
"(",
"function",
"(",
")",
"{",
"return",
"true",
";",
... | Returns an stream socket to the desired server.
@param string $address Server url string.
@param float $timeout Number of seconds until the connect() system call should timeout.
@throws \Exception Exception raised if connection fails.
@return resource | [
"Returns",
"an",
"stream",
"socket",
"to",
"the",
"desired",
"server",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L235-L259 |
repejota/phpnats | src/Nats/Connection.php | Connection.send | private function send($payload)
{
$msg = $payload."\r\n";
$len = strlen($msg);
while (true) {
$written = @fwrite($this->streamSocket, $msg);
if ($written === false) {
throw new \Exception('Error sending data');
}
if ($written === 0) {
throw new \Exception('Broken pipe or closed connection');
}
$len = ($len - $written);
if ($len > 0) {
$msg = substr($msg, (0 - $len));
} else {
break;
}
}
if ($this->debug === true) {
printf('>>>> %s', $msg);
}
} | php | private function send($payload)
{
$msg = $payload."\r\n";
$len = strlen($msg);
while (true) {
$written = @fwrite($this->streamSocket, $msg);
if ($written === false) {
throw new \Exception('Error sending data');
}
if ($written === 0) {
throw new \Exception('Broken pipe or closed connection');
}
$len = ($len - $written);
if ($len > 0) {
$msg = substr($msg, (0 - $len));
} else {
break;
}
}
if ($this->debug === true) {
printf('>>>> %s', $msg);
}
} | [
"private",
"function",
"send",
"(",
"$",
"payload",
")",
"{",
"$",
"msg",
"=",
"$",
"payload",
".",
"\"\\r\\n\"",
";",
"$",
"len",
"=",
"strlen",
"(",
"$",
"msg",
")",
";",
"while",
"(",
"true",
")",
"{",
"$",
"written",
"=",
"@",
"fwrite",
"(",
... | Sends data thought the stream.
@param string $payload Message data.
@throws \Exception Raises if fails sending data.
@return void | [
"Sends",
"data",
"thought",
"the",
"stream",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L322-L347 |
repejota/phpnats | src/Nats/Connection.php | Connection.receive | private function receive($len = 0)
{
if ($len > 0) {
$chunkSize = $this->chunkSize;
$line = null;
$receivedBytes = 0;
while ($receivedBytes < $len) {
$bytesLeft = ($len - $receivedBytes);
if ($bytesLeft < $this->chunkSize) {
$chunkSize = $bytesLeft;
}
$readChunk = fread($this->streamSocket, $chunkSize);
$receivedBytes += strlen($readChunk);
$line .= $readChunk;
}
} else {
$line = fgets($this->streamSocket);
}
if ($this->debug === true) {
printf('<<<< %s\r\n', $line);
}
return $line;
} | php | private function receive($len = 0)
{
if ($len > 0) {
$chunkSize = $this->chunkSize;
$line = null;
$receivedBytes = 0;
while ($receivedBytes < $len) {
$bytesLeft = ($len - $receivedBytes);
if ($bytesLeft < $this->chunkSize) {
$chunkSize = $bytesLeft;
}
$readChunk = fread($this->streamSocket, $chunkSize);
$receivedBytes += strlen($readChunk);
$line .= $readChunk;
}
} else {
$line = fgets($this->streamSocket);
}
if ($this->debug === true) {
printf('<<<< %s\r\n', $line);
}
return $line;
} | [
"private",
"function",
"receive",
"(",
"$",
"len",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"len",
">",
"0",
")",
"{",
"$",
"chunkSize",
"=",
"$",
"this",
"->",
"chunkSize",
";",
"$",
"line",
"=",
"null",
";",
"$",
"receivedBytes",
"=",
"0",
";",
"w... | Receives a message thought the stream.
@param integer $len Number of bytes to receive.
@return string | [
"Receives",
"a",
"message",
"thought",
"the",
"stream",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L356-L381 |
repejota/phpnats | src/Nats/Connection.php | Connection.handleMSG | private function handleMSG($line)
{
$parts = explode(' ', $line);
$subject = null;
$length = trim($parts[3]);
$sid = $parts[2];
if (count($parts) === 5) {
$length = trim($parts[4]);
$subject = $parts[3];
} elseif (count($parts) === 4) {
$length = trim($parts[3]);
$subject = $parts[1];
}
$payload = $this->receive($length);
$msg = new Message($subject, $payload, $sid, $this);
if (isset($this->subscriptions[$sid]) === false) {
throw Exception::forSubscriptionNotFound($sid);
}
$func = $this->subscriptions[$sid];
if (is_callable($func) === true) {
$func($msg);
} else {
throw Exception::forSubscriptionCallbackInvalid($sid);
}
} | php | private function handleMSG($line)
{
$parts = explode(' ', $line);
$subject = null;
$length = trim($parts[3]);
$sid = $parts[2];
if (count($parts) === 5) {
$length = trim($parts[4]);
$subject = $parts[3];
} elseif (count($parts) === 4) {
$length = trim($parts[3]);
$subject = $parts[1];
}
$payload = $this->receive($length);
$msg = new Message($subject, $payload, $sid, $this);
if (isset($this->subscriptions[$sid]) === false) {
throw Exception::forSubscriptionNotFound($sid);
}
$func = $this->subscriptions[$sid];
if (is_callable($func) === true) {
$func($msg);
} else {
throw Exception::forSubscriptionCallbackInvalid($sid);
}
} | [
"private",
"function",
"handleMSG",
"(",
"$",
"line",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"' '",
",",
"$",
"line",
")",
";",
"$",
"subject",
"=",
"null",
";",
"$",
"length",
"=",
"trim",
"(",
"$",
"parts",
"[",
"3",
"]",
")",
";",
"$",... | Handles MSG command.
@param string $line Message command from Nats.
@throws Exception If subscription not found.
@return void
@codeCoverageIgnore | [
"Handles",
"MSG",
"command",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L402-L430 |
repejota/phpnats | src/Nats/Connection.php | Connection.connect | public function connect($timeout = null)
{
if ($timeout === null) {
$timeout = intval(ini_get('default_socket_timeout'));
}
$this->timeout = $timeout;
$this->streamSocket = $this->getStream(
$this->options->getAddress(), $timeout, $this->options->getStreamContext());
$this->setStreamTimeout($timeout);
$infoResponse = $this->receive();
if ($this->isErrorResponse($infoResponse) === true) {
throw Exception::forFailedConnection($infoResponse);
} else {
$this->processServerInfo($infoResponse);
if ($this->serverInfo->isTLSRequired()) {
set_error_handler(
function ($errno, $errstr, $errfile, $errline) {
restore_error_handler();
throw Exception::forFailedConnection($errstr);
});
if (!stream_socket_enable_crypto(
$this->streamSocket, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT)) {
throw Exception::forFailedConnection('Error negotiating crypto');
}
restore_error_handler();
}
}
$msg = 'CONNECT '.$this->options;
$this->send($msg);
$this->ping();
$pingResponse = $this->receive();
if ($this->isErrorResponse($pingResponse) === true) {
throw Exception::forFailedPing($pingResponse);
}
} | php | public function connect($timeout = null)
{
if ($timeout === null) {
$timeout = intval(ini_get('default_socket_timeout'));
}
$this->timeout = $timeout;
$this->streamSocket = $this->getStream(
$this->options->getAddress(), $timeout, $this->options->getStreamContext());
$this->setStreamTimeout($timeout);
$infoResponse = $this->receive();
if ($this->isErrorResponse($infoResponse) === true) {
throw Exception::forFailedConnection($infoResponse);
} else {
$this->processServerInfo($infoResponse);
if ($this->serverInfo->isTLSRequired()) {
set_error_handler(
function ($errno, $errstr, $errfile, $errline) {
restore_error_handler();
throw Exception::forFailedConnection($errstr);
});
if (!stream_socket_enable_crypto(
$this->streamSocket, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT)) {
throw Exception::forFailedConnection('Error negotiating crypto');
}
restore_error_handler();
}
}
$msg = 'CONNECT '.$this->options;
$this->send($msg);
$this->ping();
$pingResponse = $this->receive();
if ($this->isErrorResponse($pingResponse) === true) {
throw Exception::forFailedPing($pingResponse);
}
} | [
"public",
"function",
"connect",
"(",
"$",
"timeout",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"timeout",
"===",
"null",
")",
"{",
"$",
"timeout",
"=",
"intval",
"(",
"ini_get",
"(",
"'default_socket_timeout'",
")",
")",
";",
"}",
"$",
"this",
"->",
"t... | Connect to server.
@param float $timeout Number of seconds until the connect() system call should timeout.
@throws \Exception Exception raised if connection fails.
@return void | [
"Connect",
"to",
"server",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L440-L481 |
repejota/phpnats | src/Nats/Connection.php | Connection.request | public function request($subject, $payload, \Closure $callback)
{
$inbox = uniqid('_INBOX.');
$sid = $this->subscribe(
$inbox,
$callback
);
$this->unsubscribe($sid, 1);
$this->publish($subject, $payload, $inbox);
$this->wait(1);
} | php | public function request($subject, $payload, \Closure $callback)
{
$inbox = uniqid('_INBOX.');
$sid = $this->subscribe(
$inbox,
$callback
);
$this->unsubscribe($sid, 1);
$this->publish($subject, $payload, $inbox);
$this->wait(1);
} | [
"public",
"function",
"request",
"(",
"$",
"subject",
",",
"$",
"payload",
",",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"inbox",
"=",
"uniqid",
"(",
"'_INBOX.'",
")",
";",
"$",
"sid",
"=",
"$",
"this",
"->",
"subscribe",
"(",
"$",
"inbox",
... | Request does a request and executes a callback with the response.
@param string $subject Message topic.
@param string $payload Message data.
@param \Closure $callback Closure to be executed as callback.
@return void | [
"Request",
"does",
"a",
"request",
"and",
"executes",
"a",
"callback",
"with",
"the",
"response",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L504-L514 |
repejota/phpnats | src/Nats/Connection.php | Connection.subscribe | public function subscribe($subject, \Closure $callback)
{
$sid = $this->randomGenerator->generateString(16);
$msg = 'SUB '.$subject.' '.$sid;
$this->send($msg);
$this->subscriptions[$sid] = $callback;
return $sid;
} | php | public function subscribe($subject, \Closure $callback)
{
$sid = $this->randomGenerator->generateString(16);
$msg = 'SUB '.$subject.' '.$sid;
$this->send($msg);
$this->subscriptions[$sid] = $callback;
return $sid;
} | [
"public",
"function",
"subscribe",
"(",
"$",
"subject",
",",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"sid",
"=",
"$",
"this",
"->",
"randomGenerator",
"->",
"generateString",
"(",
"16",
")",
";",
"$",
"msg",
"=",
"'SUB '",
".",
"$",
"subject",... | Subscribes to an specific event given a subject.
@param string $subject Message topic.
@param \Closure $callback Closure to be executed as callback.
@return string | [
"Subscribes",
"to",
"an",
"specific",
"event",
"given",
"a",
"subject",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L524-L531 |
repejota/phpnats | src/Nats/Connection.php | Connection.queueSubscribe | public function queueSubscribe($subject, $queue, \Closure $callback)
{
$sid = $this->randomGenerator->generateString(16);
$msg = 'SUB '.$subject.' '.$queue.' '.$sid;
$this->send($msg);
$this->subscriptions[$sid] = $callback;
return $sid;
} | php | public function queueSubscribe($subject, $queue, \Closure $callback)
{
$sid = $this->randomGenerator->generateString(16);
$msg = 'SUB '.$subject.' '.$queue.' '.$sid;
$this->send($msg);
$this->subscriptions[$sid] = $callback;
return $sid;
} | [
"public",
"function",
"queueSubscribe",
"(",
"$",
"subject",
",",
"$",
"queue",
",",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"sid",
"=",
"$",
"this",
"->",
"randomGenerator",
"->",
"generateString",
"(",
"16",
")",
";",
"$",
"msg",
"=",
"'SUB ... | Subscribes to an specific event given a subject and a queue.
@param string $subject Message topic.
@param string $queue Queue name.
@param \Closure $callback Closure to be executed as callback.
@return string | [
"Subscribes",
"to",
"an",
"specific",
"event",
"given",
"a",
"subject",
"and",
"a",
"queue",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L542-L549 |
repejota/phpnats | src/Nats/Connection.php | Connection.unsubscribe | public function unsubscribe($sid, $quantity = null)
{
$msg = 'UNSUB '.$sid;
if ($quantity !== null) {
$msg = $msg.' '.$quantity;
}
$this->send($msg);
if ($quantity === null) {
unset($this->subscriptions[$sid]);
}
} | php | public function unsubscribe($sid, $quantity = null)
{
$msg = 'UNSUB '.$sid;
if ($quantity !== null) {
$msg = $msg.' '.$quantity;
}
$this->send($msg);
if ($quantity === null) {
unset($this->subscriptions[$sid]);
}
} | [
"public",
"function",
"unsubscribe",
"(",
"$",
"sid",
",",
"$",
"quantity",
"=",
"null",
")",
"{",
"$",
"msg",
"=",
"'UNSUB '",
".",
"$",
"sid",
";",
"if",
"(",
"$",
"quantity",
"!==",
"null",
")",
"{",
"$",
"msg",
"=",
"$",
"msg",
".",
"' '",
... | Unsubscribe from a event given a subject.
@param string $sid Subscription ID.
@param integer $quantity Quantity of messages.
@return void | [
"Unsubscribe",
"from",
"a",
"event",
"given",
"a",
"subject",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L559-L570 |
repejota/phpnats | src/Nats/Connection.php | Connection.publish | public function publish($subject, $payload = null, $inbox = null)
{
$msg = 'PUB '.$subject;
if ($inbox !== null) {
$msg = $msg.' '.$inbox;
}
$msg = $msg.' '.strlen($payload);
$this->send($msg."\r\n".$payload);
$this->pubs += 1;
} | php | public function publish($subject, $payload = null, $inbox = null)
{
$msg = 'PUB '.$subject;
if ($inbox !== null) {
$msg = $msg.' '.$inbox;
}
$msg = $msg.' '.strlen($payload);
$this->send($msg."\r\n".$payload);
$this->pubs += 1;
} | [
"public",
"function",
"publish",
"(",
"$",
"subject",
",",
"$",
"payload",
"=",
"null",
",",
"$",
"inbox",
"=",
"null",
")",
"{",
"$",
"msg",
"=",
"'PUB '",
".",
"$",
"subject",
";",
"if",
"(",
"$",
"inbox",
"!==",
"null",
")",
"{",
"$",
"msg",
... | Publish publishes the data argument to the given subject.
@param string $subject Message topic.
@param string $payload Message data.
@param string $inbox Message inbox.
@throws Exception If subscription not found.
@return void | [
"Publish",
"publishes",
"the",
"data",
"argument",
"to",
"the",
"given",
"subject",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L583-L593 |
repejota/phpnats | src/Nats/Connection.php | Connection.wait | public function wait($quantity = 0)
{
$count = 0;
$info = stream_get_meta_data($this->streamSocket);
while (is_resource($this->streamSocket) === true && feof($this->streamSocket) === false && empty($info['timed_out']) === true) {
$line = $this->receive();
if ($line === false) {
return null;
}
if (strpos($line, 'PING') === 0) {
$this->handlePING();
}
if (strpos($line, 'MSG') === 0) {
$count++;
$this->handleMSG($line);
if (($quantity !== 0) && ($count >= $quantity)) {
return $this;
}
}
$info = stream_get_meta_data($this->streamSocket);
}
$this->close();
return $this;
} | php | public function wait($quantity = 0)
{
$count = 0;
$info = stream_get_meta_data($this->streamSocket);
while (is_resource($this->streamSocket) === true && feof($this->streamSocket) === false && empty($info['timed_out']) === true) {
$line = $this->receive();
if ($line === false) {
return null;
}
if (strpos($line, 'PING') === 0) {
$this->handlePING();
}
if (strpos($line, 'MSG') === 0) {
$count++;
$this->handleMSG($line);
if (($quantity !== 0) && ($count >= $quantity)) {
return $this;
}
}
$info = stream_get_meta_data($this->streamSocket);
}
$this->close();
return $this;
} | [
"public",
"function",
"wait",
"(",
"$",
"quantity",
"=",
"0",
")",
"{",
"$",
"count",
"=",
"0",
";",
"$",
"info",
"=",
"stream_get_meta_data",
"(",
"$",
"this",
"->",
"streamSocket",
")",
";",
"while",
"(",
"is_resource",
"(",
"$",
"this",
"->",
"str... | Waits for messages.
@param integer $quantity Number of messages to wait for.
@return Connection $connection Connection object | [
"Waits",
"for",
"messages",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L602-L631 |
repejota/phpnats | src/Nats/Connection.php | Connection.close | public function close()
{
if ($this->streamSocket === null) {
return;
}
fclose($this->streamSocket);
$this->streamSocket = null;
} | php | public function close()
{
if ($this->streamSocket === null) {
return;
}
fclose($this->streamSocket);
$this->streamSocket = null;
} | [
"public",
"function",
"close",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"streamSocket",
"===",
"null",
")",
"{",
"return",
";",
"}",
"fclose",
"(",
"$",
"this",
"->",
"streamSocket",
")",
";",
"$",
"this",
"->",
"streamSocket",
"=",
"null",
";",
... | Close will close the connection to the server.
@return void | [
"Close",
"will",
"close",
"the",
"connection",
"to",
"the",
"server",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/Connection.php#L650-L658 |
repejota/phpnats | src/Nats/ConnectionOptions.php | ConnectionOptions.initialize | protected function initialize($options)
{
if (is_array($options) === false && ($options instanceof Traversable) === false) {
throw new Exception('The $options argument must be either an array or Traversable');
}
foreach ($options as $key => $value) {
if (in_array($key, $this->configurable, true) === false) {
continue;
}
$method = 'set'.ucfirst($key);
if (method_exists($this, $method) === true) {
$this->$method($value);
}
}
} | php | protected function initialize($options)
{
if (is_array($options) === false && ($options instanceof Traversable) === false) {
throw new Exception('The $options argument must be either an array or Traversable');
}
foreach ($options as $key => $value) {
if (in_array($key, $this->configurable, true) === false) {
continue;
}
$method = 'set'.ucfirst($key);
if (method_exists($this, $method) === true) {
$this->$method($value);
}
}
} | [
"protected",
"function",
"initialize",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"options",
")",
"===",
"false",
"&&",
"(",
"$",
"options",
"instanceof",
"Traversable",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Exception",
"("... | Initialize the parameters.
@param Traversable|array $options The connection options.
@throws Exception When $options are an invalid type.
@return void | [
"Initialize",
"the",
"parameters",
"."
] | train | https://github.com/repejota/phpnats/blob/bd089ea66ef41f557830449872389750dd12a99f/src/Nats/ConnectionOptions.php#L479-L496 |
paragonie/sapient | src/Traits/StringSugar.php | StringSugar.decryptStringRequestWithSharedKey | public function decryptStringRequestWithSharedKey(
RequestInterface $request,
SharedEncryptionKey $key
): string {
return Simple::decrypt(
(string) $request->getBody(),
$key
);
} | php | public function decryptStringRequestWithSharedKey(
RequestInterface $request,
SharedEncryptionKey $key
): string {
return Simple::decrypt(
(string) $request->getBody(),
$key
);
} | [
"public",
"function",
"decryptStringRequestWithSharedKey",
"(",
"RequestInterface",
"$",
"request",
",",
"SharedEncryptionKey",
"$",
"key",
")",
":",
"string",
"{",
"return",
"Simple",
"::",
"decrypt",
"(",
"(",
"string",
")",
"$",
"request",
"->",
"getBody",
"(... | Decrypt an HTTP request with a pre-shared key, then get the body as a
string.
@param RequestInterface $request
@param SharedEncryptionKey $key
@return string | [
"Decrypt",
"an",
"HTTP",
"request",
"with",
"a",
"pre",
"-",
"shared",
"key",
"then",
"get",
"the",
"body",
"as",
"a",
"string",
"."
] | train | https://github.com/paragonie/sapient/blob/8d1f560ce3adc04497efde2673157ad057898e38/src/Traits/StringSugar.php#L53-L61 |
paragonie/sapient | src/Traits/StringSugar.php | StringSugar.decryptStringResponseWithSharedKey | public function decryptStringResponseWithSharedKey(
ResponseInterface $response,
SharedEncryptionKey $key
): string {
return Simple::decrypt(
(string) $response->getBody(),
$key
);
} | php | public function decryptStringResponseWithSharedKey(
ResponseInterface $response,
SharedEncryptionKey $key
): string {
return Simple::decrypt(
(string) $response->getBody(),
$key
);
} | [
"public",
"function",
"decryptStringResponseWithSharedKey",
"(",
"ResponseInterface",
"$",
"response",
",",
"SharedEncryptionKey",
"$",
"key",
")",
":",
"string",
"{",
"return",
"Simple",
"::",
"decrypt",
"(",
"(",
"string",
")",
"$",
"response",
"->",
"getBody",
... | Decrypt an HTTP response with a pre-shared key, then get the body as a
string.
@param ResponseInterface $response
@param SharedEncryptionKey $key
@return string | [
"Decrypt",
"an",
"HTTP",
"response",
"with",
"a",
"pre",
"-",
"shared",
"key",
"then",
"get",
"the",
"body",
"as",
"a",
"string",
"."
] | train | https://github.com/paragonie/sapient/blob/8d1f560ce3adc04497efde2673157ad057898e38/src/Traits/StringSugar.php#L71-L79 |
paragonie/sapient | src/Traits/StringSugar.php | StringSugar.unsealStringRequest | public function unsealStringRequest(
RequestInterface $request,
SealingSecretKey $secretKey
): string {
$body = Base64UrlSafe::decode((string) $request->getBody());
return Simple::unseal(
$body,
$secretKey
);
} | php | public function unsealStringRequest(
RequestInterface $request,
SealingSecretKey $secretKey
): string {
$body = Base64UrlSafe::decode((string) $request->getBody());
return Simple::unseal(
$body,
$secretKey
);
} | [
"public",
"function",
"unsealStringRequest",
"(",
"RequestInterface",
"$",
"request",
",",
"SealingSecretKey",
"$",
"secretKey",
")",
":",
"string",
"{",
"$",
"body",
"=",
"Base64UrlSafe",
"::",
"decode",
"(",
"(",
"string",
")",
"$",
"request",
"->",
"getBody... | Decrypt a message with your secret key, that had been encrypted with
your public key by the other endpoint, then get the body as a string.
@param RequestInterface $request
@param SealingSecretKey $secretKey
@return string
@throws InvalidMessageException | [
"Decrypt",
"a",
"message",
"with",
"your",
"secret",
"key",
"that",
"had",
"been",
"encrypted",
"with",
"your",
"public",
"key",
"by",
"the",
"other",
"endpoint",
"then",
"get",
"the",
"body",
"as",
"a",
"string",
"."
] | train | https://github.com/paragonie/sapient/blob/8d1f560ce3adc04497efde2673157ad057898e38/src/Traits/StringSugar.php#L90-L99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.