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 |
|---|---|---|---|---|---|---|---|---|---|---|
symfony/assetic-bundle | Templating/AsseticHelper.php | AsseticHelper.javascripts | public function javascripts($inputs = array(), $filters = array(), array $options = array())
{
if (!isset($options['output'])) {
$options['output'] = 'js/*.js';
}
return $this->getAssetUrls($inputs, $filters, $options);
} | php | public function javascripts($inputs = array(), $filters = array(), array $options = array())
{
if (!isset($options['output'])) {
$options['output'] = 'js/*.js';
}
return $this->getAssetUrls($inputs, $filters, $options);
} | [
"public",
"function",
"javascripts",
"(",
"$",
"inputs",
"=",
"array",
"(",
")",
",",
"$",
"filters",
"=",
"array",
"(",
")",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'out... | Returns an array of javascript urls. | [
"Returns",
"an",
"array",
"of",
"javascript",
"urls",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Templating/AsseticHelper.php#L41-L48 |
symfony/assetic-bundle | Templating/AsseticHelper.php | AsseticHelper.stylesheets | public function stylesheets($inputs = array(), $filters = array(), array $options = array())
{
if (!isset($options['output'])) {
$options['output'] = 'css/*.css';
}
return $this->getAssetUrls($inputs, $filters, $options);
} | php | public function stylesheets($inputs = array(), $filters = array(), array $options = array())
{
if (!isset($options['output'])) {
$options['output'] = 'css/*.css';
}
return $this->getAssetUrls($inputs, $filters, $options);
} | [
"public",
"function",
"stylesheets",
"(",
"$",
"inputs",
"=",
"array",
"(",
")",
",",
"$",
"filters",
"=",
"array",
"(",
")",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'out... | Returns an array of stylesheet urls. | [
"Returns",
"an",
"array",
"of",
"stylesheet",
"urls",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Templating/AsseticHelper.php#L53-L60 |
symfony/assetic-bundle | Templating/AsseticHelper.php | AsseticHelper.image | public function image($inputs = array(), $filters = array(), array $options = array())
{
if (!isset($options['output'])) {
$options['output'] = 'images/*';
}
$options['single'] = true;
return $this->getAssetUrls($inputs, $filters, $options);
} | php | public function image($inputs = array(), $filters = array(), array $options = array())
{
if (!isset($options['output'])) {
$options['output'] = 'images/*';
}
$options['single'] = true;
return $this->getAssetUrls($inputs, $filters, $options);
} | [
"public",
"function",
"image",
"(",
"$",
"inputs",
"=",
"array",
"(",
")",
",",
"$",
"filters",
"=",
"array",
"(",
")",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'output'",... | Returns an array of one image url. | [
"Returns",
"an",
"array",
"of",
"one",
"image",
"url",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Templating/AsseticHelper.php#L65-L74 |
symfony/assetic-bundle | Templating/AsseticHelper.php | AsseticHelper.getAssetUrls | private function getAssetUrls($inputs = array(), $filters = array(), array $options = array())
{
$explode = function ($value) {
return array_map('trim', explode(',', $value));
};
if (!is_array($inputs)) {
$inputs = $explode($inputs);
}
if (!is_array($filters)) {
$filters = $explode($filters);
}
if (!isset($options['debug'])) {
$options['debug'] = $this->factory->isDebug();
}
if (!isset($options['combine'])) {
$options['combine'] = !$options['debug'];
}
if (isset($options['single']) && $options['single'] && 1 < count($inputs)) {
$inputs = array_slice($inputs, -1);
}
if (!isset($options['name'])) {
$options['name'] = $this->factory->generateAssetName($inputs, $filters, $options);
}
$asset = $this->factory->createAsset($inputs, $filters, $options);
$one = $this->getAssetUrl($asset, $options);
$many = array();
if ($options['combine']) {
$many[] = $one;
} else {
$i = 0;
foreach ($asset as $leaf) {
$many[] = $this->getAssetUrl($leaf, array_replace($options, array(
'name' => $options['name'].'_'.$i++,
)));
}
}
return new TraversableString($one, $many);
} | php | private function getAssetUrls($inputs = array(), $filters = array(), array $options = array())
{
$explode = function ($value) {
return array_map('trim', explode(',', $value));
};
if (!is_array($inputs)) {
$inputs = $explode($inputs);
}
if (!is_array($filters)) {
$filters = $explode($filters);
}
if (!isset($options['debug'])) {
$options['debug'] = $this->factory->isDebug();
}
if (!isset($options['combine'])) {
$options['combine'] = !$options['debug'];
}
if (isset($options['single']) && $options['single'] && 1 < count($inputs)) {
$inputs = array_slice($inputs, -1);
}
if (!isset($options['name'])) {
$options['name'] = $this->factory->generateAssetName($inputs, $filters, $options);
}
$asset = $this->factory->createAsset($inputs, $filters, $options);
$one = $this->getAssetUrl($asset, $options);
$many = array();
if ($options['combine']) {
$many[] = $one;
} else {
$i = 0;
foreach ($asset as $leaf) {
$many[] = $this->getAssetUrl($leaf, array_replace($options, array(
'name' => $options['name'].'_'.$i++,
)));
}
}
return new TraversableString($one, $many);
} | [
"private",
"function",
"getAssetUrls",
"(",
"$",
"inputs",
"=",
"array",
"(",
")",
",",
"$",
"filters",
"=",
"array",
"(",
")",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"explode",
"=",
"function",
"(",
"$",
"value",
")",... | Gets the URLs for the configured asset.
Usage looks something like this:
<?php foreach ($view['assetic']->assets('@jquery, js/src/core/*', '?yui_js') as $url): ?>
<script src="<?php echo $url ?>" type="text/javascript"></script>
<?php endforeach; ?>
When in debug mode, the helper returns an array of one or more URLs.
When not in debug mode it returns an array of one URL.
@param array|string $inputs An array or comma-separated list of input strings
@param array|string $filters An array or comma-separated list of filter names
@param array $options An array of options
@return array An array of URLs for the asset | [
"Gets",
"the",
"URLs",
"for",
"the",
"configured",
"asset",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Templating/AsseticHelper.php#L94-L140 |
symfony/assetic-bundle | Command/AbstractCommand.php | AbstractCommand.dumpAsset | public function dumpAsset($name, OutputInterface $stdout)
{
$asset = $this->am->get($name);
$formula = $this->am->hasFormula($name) ? $this->am->getFormula($name) : array();
// start by dumping the main asset
$this->doDump($asset, $stdout);
$debug = isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug();
$combine = isset($formula[2]['combine']) ? $formula[2]['combine'] : !$debug;
// dump each leaf if no combine
if (!$combine) {
foreach ($asset as $leaf) {
$this->doDump($leaf, $stdout);
}
}
} | php | public function dumpAsset($name, OutputInterface $stdout)
{
$asset = $this->am->get($name);
$formula = $this->am->hasFormula($name) ? $this->am->getFormula($name) : array();
// start by dumping the main asset
$this->doDump($asset, $stdout);
$debug = isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug();
$combine = isset($formula[2]['combine']) ? $formula[2]['combine'] : !$debug;
// dump each leaf if no combine
if (!$combine) {
foreach ($asset as $leaf) {
$this->doDump($leaf, $stdout);
}
}
} | [
"public",
"function",
"dumpAsset",
"(",
"$",
"name",
",",
"OutputInterface",
"$",
"stdout",
")",
"{",
"$",
"asset",
"=",
"$",
"this",
"->",
"am",
"->",
"get",
"(",
"$",
"name",
")",
";",
"$",
"formula",
"=",
"$",
"this",
"->",
"am",
"->",
"hasFormu... | Writes an asset.
If the application or asset is in debug mode, each leaf asset will be
dumped as well.
@param string $name An asset name
@param OutputInterface $stdout The command output | [
"Writes",
"an",
"asset",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Command/AbstractCommand.php#L45-L62 |
symfony/assetic-bundle | Command/AbstractCommand.php | AbstractCommand.doDump | private function doDump(AssetInterface $asset, OutputInterface $stdout)
{
$combinations = VarUtils::getCombinations(
$asset->getVars(),
$this->getContainer()->getParameter('assetic.variables')
);
foreach ($combinations as $combination) {
$asset->setValues($combination);
// resolve the target path
$target = rtrim($this->basePath, '/').'/'.$asset->getTargetPath();
$target = str_replace('_controller/', '', $target);
$target = VarUtils::resolve($target, $asset->getVars(), $asset->getValues());
if (!is_dir($dir = dirname($target))) {
$stdout->writeln(sprintf(
'<comment>%s</comment> <info>[dir+]</info> %s',
date('H:i:s'),
$dir
));
if (false === @mkdir($dir, 0777, true)) {
throw new \RuntimeException('Unable to create directory '.$dir);
}
}
$stdout->writeln(sprintf(
'<comment>%s</comment> <info>[file+]</info> %s',
date('H:i:s'),
$target
));
if (OutputInterface::VERBOSITY_VERBOSE <= $stdout->getVerbosity()) {
if ($asset instanceof AssetCollectionInterface) {
foreach ($asset as $leaf) {
$root = $leaf->getSourceRoot();
$path = $leaf->getSourcePath();
$stdout->writeln(sprintf(' <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
}
} else {
$root = $asset->getSourceRoot();
$path = $asset->getSourcePath();
$stdout->writeln(sprintf(' <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
}
}
if (false === @file_put_contents($target, $asset->dump())) {
throw new \RuntimeException('Unable to write file '.$target);
}
}
} | php | private function doDump(AssetInterface $asset, OutputInterface $stdout)
{
$combinations = VarUtils::getCombinations(
$asset->getVars(),
$this->getContainer()->getParameter('assetic.variables')
);
foreach ($combinations as $combination) {
$asset->setValues($combination);
// resolve the target path
$target = rtrim($this->basePath, '/').'/'.$asset->getTargetPath();
$target = str_replace('_controller/', '', $target);
$target = VarUtils::resolve($target, $asset->getVars(), $asset->getValues());
if (!is_dir($dir = dirname($target))) {
$stdout->writeln(sprintf(
'<comment>%s</comment> <info>[dir+]</info> %s',
date('H:i:s'),
$dir
));
if (false === @mkdir($dir, 0777, true)) {
throw new \RuntimeException('Unable to create directory '.$dir);
}
}
$stdout->writeln(sprintf(
'<comment>%s</comment> <info>[file+]</info> %s',
date('H:i:s'),
$target
));
if (OutputInterface::VERBOSITY_VERBOSE <= $stdout->getVerbosity()) {
if ($asset instanceof AssetCollectionInterface) {
foreach ($asset as $leaf) {
$root = $leaf->getSourceRoot();
$path = $leaf->getSourcePath();
$stdout->writeln(sprintf(' <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
}
} else {
$root = $asset->getSourceRoot();
$path = $asset->getSourcePath();
$stdout->writeln(sprintf(' <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
}
}
if (false === @file_put_contents($target, $asset->dump())) {
throw new \RuntimeException('Unable to write file '.$target);
}
}
} | [
"private",
"function",
"doDump",
"(",
"AssetInterface",
"$",
"asset",
",",
"OutputInterface",
"$",
"stdout",
")",
"{",
"$",
"combinations",
"=",
"VarUtils",
"::",
"getCombinations",
"(",
"$",
"asset",
"->",
"getVars",
"(",
")",
",",
"$",
"this",
"->",
"get... | Performs the asset dump.
@param AssetInterface $asset An asset
@param OutputInterface $stdout The command output
@throws RuntimeException If there is a problem writing the asset | [
"Performs",
"the",
"asset",
"dump",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Command/AbstractCommand.php#L72-L123 |
symfony/assetic-bundle | DependencyInjection/Compiler/StaticAsseticHelperPass.php | StaticAsseticHelperPass.process | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('assetic.helper.static')) {
return;
}
if ($container->hasDefinition('assets.packages')) {
return;
}
// Templating disabled in Symfony <2.6 or on 2.7+, remove the assetic helper
if (!$container->hasDefinition('templating.helper.assets') || '' === $container->getDefinition('templating.helper.assets')->getArgument(0)) {
$container->removeDefinition('assetic.helper.static');
return;
}
$definition = $container->getDefinition('assetic.helper.static');
$definition->replaceArgument(0, new Reference('templating.helper.assets'));
if (!method_exists($definition, 'setShared') && 'request' === $container->getDefinition('templating.helper.assets')->getScope()) {
$definition->setScope('request');
}
} | php | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('assetic.helper.static')) {
return;
}
if ($container->hasDefinition('assets.packages')) {
return;
}
// Templating disabled in Symfony <2.6 or on 2.7+, remove the assetic helper
if (!$container->hasDefinition('templating.helper.assets') || '' === $container->getDefinition('templating.helper.assets')->getArgument(0)) {
$container->removeDefinition('assetic.helper.static');
return;
}
$definition = $container->getDefinition('assetic.helper.static');
$definition->replaceArgument(0, new Reference('templating.helper.assets'));
if (!method_exists($definition, 'setShared') && 'request' === $container->getDefinition('templating.helper.assets')->getScope()) {
$definition->setScope('request');
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"if",
"(",
"!",
"$",
"container",
"->",
"hasDefinition",
"(",
"'assetic.helper.static'",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"container",
"->",
"hasDefinitio... | {@inheritdoc} | [
"{"
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/DependencyInjection/Compiler/StaticAsseticHelperPass.php#L17-L40 |
symfony/assetic-bundle | Routing/AsseticLoader.php | AsseticLoader.loadRouteForAsset | private function loadRouteForAsset(RouteCollection $routes, AssetInterface $asset, $name, $pos = null)
{
$defaults = array(
'_controller' => 'assetic.controller:render',
'name' => $name,
'pos' => $pos,
);
$requirements = array();
// remove the fake front controller
$pattern = str_replace('_controller/', '', $asset->getTargetPath());
if ($format = pathinfo($pattern, PATHINFO_EXTENSION)) {
$defaults['_format'] = $format;
}
$route = '_assetic_'.$name;
if (null !== $pos) {
$route .= '_'.$pos;
}
foreach ($asset->getVars() as $var) {
if (empty($this->varValues[$var])) {
throw new \UnexpectedValueException(sprintf('The possible values for the asset variable "%s" are not known', $var));
}
$values = array();
foreach ($this->varValues[$var] as $value) {
$values[] = preg_quote($value, '#');
}
$requirements[$var] = implode('|', $values);
}
$routes->add($route, new Route($pattern, $defaults, $requirements));
} | php | private function loadRouteForAsset(RouteCollection $routes, AssetInterface $asset, $name, $pos = null)
{
$defaults = array(
'_controller' => 'assetic.controller:render',
'name' => $name,
'pos' => $pos,
);
$requirements = array();
// remove the fake front controller
$pattern = str_replace('_controller/', '', $asset->getTargetPath());
if ($format = pathinfo($pattern, PATHINFO_EXTENSION)) {
$defaults['_format'] = $format;
}
$route = '_assetic_'.$name;
if (null !== $pos) {
$route .= '_'.$pos;
}
foreach ($asset->getVars() as $var) {
if (empty($this->varValues[$var])) {
throw new \UnexpectedValueException(sprintf('The possible values for the asset variable "%s" are not known', $var));
}
$values = array();
foreach ($this->varValues[$var] as $value) {
$values[] = preg_quote($value, '#');
}
$requirements[$var] = implode('|', $values);
}
$routes->add($route, new Route($pattern, $defaults, $requirements));
} | [
"private",
"function",
"loadRouteForAsset",
"(",
"RouteCollection",
"$",
"routes",
",",
"AssetInterface",
"$",
"asset",
",",
"$",
"name",
",",
"$",
"pos",
"=",
"null",
")",
"{",
"$",
"defaults",
"=",
"array",
"(",
"'_controller'",
"=>",
"'assetic.controller:re... | Loads a route to serve an supplied asset.
The fake front controller that {@link UseControllerWorker} adds to the
target URL will be removed before set as a route pattern.
@param RouteCollection $routes The route collection
@param AssetInterface $asset The asset
@param string $name The name to use
@param integer $pos The leaf index | [
"Loads",
"a",
"route",
"to",
"serve",
"an",
"supplied",
"asset",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Routing/AsseticLoader.php#L106-L142 |
symfony/assetic-bundle | Factory/AssetFactory.php | AssetFactory.parseInput | protected function parseInput($input, array $options = array())
{
$input = $this->parameterBag->resolveValue($input);
// expand bundle notation
if ('@' == $input[0] && false !== strpos($input, '/')) {
// use the bundle path as this asset's root
$bundle = substr($input, 1);
if (false !== $pos = strpos($bundle, '/')) {
$bundle = substr($bundle, 0, $pos);
}
$options['root'] = array($this->kernel->getBundle($bundle)->getPath());
// canonicalize the input
if (false !== $pos = strpos($input, '*')) {
// locateResource() does not support globs so we provide a naive implementation here
list($before, $after) = explode('*', $input, 2);
$input = $this->kernel->locateResource($before).'*'.$after;
} else {
$input = $this->kernel->locateResource($input);
}
}
return parent::parseInput($input, $options);
} | php | protected function parseInput($input, array $options = array())
{
$input = $this->parameterBag->resolveValue($input);
// expand bundle notation
if ('@' == $input[0] && false !== strpos($input, '/')) {
// use the bundle path as this asset's root
$bundle = substr($input, 1);
if (false !== $pos = strpos($bundle, '/')) {
$bundle = substr($bundle, 0, $pos);
}
$options['root'] = array($this->kernel->getBundle($bundle)->getPath());
// canonicalize the input
if (false !== $pos = strpos($input, '*')) {
// locateResource() does not support globs so we provide a naive implementation here
list($before, $after) = explode('*', $input, 2);
$input = $this->kernel->locateResource($before).'*'.$after;
} else {
$input = $this->kernel->locateResource($input);
}
}
return parent::parseInput($input, $options);
} | [
"protected",
"function",
"parseInput",
"(",
"$",
"input",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"input",
"=",
"$",
"this",
"->",
"parameterBag",
"->",
"resolveValue",
"(",
"$",
"input",
")",
";",
"// expand bundle notation",
... | Adds support for bundle notation file and glob assets and parameter placeholders.
FIXME: This is a naive implementation of globs in that it doesn't
attempt to support bundle inheritance within the glob pattern itself. | [
"Adds",
"support",
"for",
"bundle",
"notation",
"file",
"and",
"glob",
"assets",
"and",
"parameter",
"placeholders",
"."
] | train | https://github.com/symfony/assetic-bundle/blob/7ffdefece4e809864f70ac69739567b6ed6fb274/Factory/AssetFactory.php#L54-L78 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.isOne | public function isOne($role)
{
foreach ($this->getArrayFrom($role) as $role) {
if ($this->hasRole($role)) {
return true;
}
}
return false;
} | php | public function isOne($role)
{
foreach ($this->getArrayFrom($role) as $role) {
if ($this->hasRole($role)) {
return true;
}
}
return false;
} | [
"public",
"function",
"isOne",
"(",
"$",
"role",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getArrayFrom",
"(",
"$",
"role",
")",
"as",
"$",
"role",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasRole",
"(",
"$",
"role",
")",
")",
"{",
"return",
... | Check if the user has at least one role.
@param int|string|array $role
@return bool | [
"Check",
"if",
"the",
"user",
"has",
"at",
"least",
"one",
"role",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L67-L76 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.isAll | public function isAll($role)
{
foreach ($this->getArrayFrom($role) as $role) {
if (!$this->hasRole($role)) {
return false;
}
}
return true;
} | php | public function isAll($role)
{
foreach ($this->getArrayFrom($role) as $role) {
if (!$this->hasRole($role)) {
return false;
}
}
return true;
} | [
"public",
"function",
"isAll",
"(",
"$",
"role",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getArrayFrom",
"(",
"$",
"role",
")",
"as",
"$",
"role",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasRole",
"(",
"$",
"role",
")",
")",
"{",
"re... | Check if the user has all roles.
@param int|string|array $role
@return bool | [
"Check",
"if",
"the",
"user",
"has",
"all",
"roles",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L84-L93 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.attachRole | public function attachRole($role)
{
return (!$this->getRoles()->contains($role)) ? $this->roles()->attach($role) : true;
} | php | public function attachRole($role)
{
return (!$this->getRoles()->contains($role)) ? $this->roles()->attach($role) : true;
} | [
"public",
"function",
"attachRole",
"(",
"$",
"role",
")",
"{",
"return",
"(",
"!",
"$",
"this",
"->",
"getRoles",
"(",
")",
"->",
"contains",
"(",
"$",
"role",
")",
")",
"?",
"$",
"this",
"->",
"roles",
"(",
")",
"->",
"attach",
"(",
"$",
"role"... | Attach role to a user.
@param int|\Bican\Roles\Models\Role $role
@return null|bool | [
"Attach",
"role",
"to",
"a",
"user",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L114-L117 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.rolePermissions | public function rolePermissions()
{
$permissionModel = app(config('roles.models.permission'));
if (!$permissionModel instanceof Model) {
throw new InvalidArgumentException('[roles.models.permission] must be an instance of \Illuminate\Database\Eloquent\Model');
}
return $permissionModel::select(['permissions.*', 'permission_role.created_at as pivot_created_at', 'permission_role.updated_at as pivot_updated_at'])
->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id')->join('roles', 'roles.id', '=', 'permission_role.role_id')
->whereIn('roles.id', $this->getRoles()->lists('id')->toArray()) ->orWhere('roles.level', '<', $this->level())
->groupBy(['permissions.id', 'pivot_created_at', 'pivot_updated_at']);
} | php | public function rolePermissions()
{
$permissionModel = app(config('roles.models.permission'));
if (!$permissionModel instanceof Model) {
throw new InvalidArgumentException('[roles.models.permission] must be an instance of \Illuminate\Database\Eloquent\Model');
}
return $permissionModel::select(['permissions.*', 'permission_role.created_at as pivot_created_at', 'permission_role.updated_at as pivot_updated_at'])
->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id')->join('roles', 'roles.id', '=', 'permission_role.role_id')
->whereIn('roles.id', $this->getRoles()->lists('id')->toArray()) ->orWhere('roles.level', '<', $this->level())
->groupBy(['permissions.id', 'pivot_created_at', 'pivot_updated_at']);
} | [
"public",
"function",
"rolePermissions",
"(",
")",
"{",
"$",
"permissionModel",
"=",
"app",
"(",
"config",
"(",
"'roles.models.permission'",
")",
")",
";",
"if",
"(",
"!",
"$",
"permissionModel",
"instanceof",
"Model",
")",
"{",
"throw",
"new",
"InvalidArgumen... | Get all permissions from roles.
@return \Illuminate\Database\Eloquent\Builder | [
"Get",
"all",
"permissions",
"from",
"roles",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L159-L171 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.can | public function can($permission, $all = false)
{
if ($this->isPretendEnabled()) {
return $this->pretend('can');
}
return $this->{$this->getMethodName('can', $all)}($permission);
} | php | public function can($permission, $all = false)
{
if ($this->isPretendEnabled()) {
return $this->pretend('can');
}
return $this->{$this->getMethodName('can', $all)}($permission);
} | [
"public",
"function",
"can",
"(",
"$",
"permission",
",",
"$",
"all",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isPretendEnabled",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"pretend",
"(",
"'can'",
")",
";",
"}",
"return",
"$",
... | Check if the user has a permission or permissions.
@param int|string|array $permission
@param bool $all
@return bool | [
"Check",
"if",
"the",
"user",
"has",
"a",
"permission",
"or",
"permissions",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L200-L207 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.canOne | public function canOne($permission)
{
foreach ($this->getArrayFrom($permission) as $permission) {
if ($this->hasPermission($permission)) {
return true;
}
}
return false;
} | php | public function canOne($permission)
{
foreach ($this->getArrayFrom($permission) as $permission) {
if ($this->hasPermission($permission)) {
return true;
}
}
return false;
} | [
"public",
"function",
"canOne",
"(",
"$",
"permission",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getArrayFrom",
"(",
"$",
"permission",
")",
"as",
"$",
"permission",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasPermission",
"(",
"$",
"permission",
... | Check if the user has at least one permission.
@param int|string|array $permission
@return bool | [
"Check",
"if",
"the",
"user",
"has",
"at",
"least",
"one",
"permission",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L215-L224 |
romanbican/roles | src/Bican/Roles/Traits/HasRoleAndPermission.php | HasRoleAndPermission.canAll | public function canAll($permission)
{
foreach ($this->getArrayFrom($permission) as $permission) {
if (!$this->hasPermission($permission)) {
return false;
}
}
return true;
} | php | public function canAll($permission)
{
foreach ($this->getArrayFrom($permission) as $permission) {
if (!$this->hasPermission($permission)) {
return false;
}
}
return true;
} | [
"public",
"function",
"canAll",
"(",
"$",
"permission",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getArrayFrom",
"(",
"$",
"permission",
")",
"as",
"$",
"permission",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasPermission",
"(",
"$",
"permissi... | Check if the user has all permissions.
@param int|string|array $permission
@return bool | [
"Check",
"if",
"the",
"user",
"has",
"all",
"permissions",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/Traits/HasRoleAndPermission.php#L232-L241 |
romanbican/roles | src/Bican/Roles/RolesServiceProvider.php | RolesServiceProvider.boot | public function boot()
{
$this->publishes([
__DIR__ . '/../../config/roles.php' => config_path('roles.php')
], 'config');
$this->publishes([
__DIR__ . '/../../migrations/' => base_path('/database/migrations')
], 'migrations');
$this->registerBladeExtensions();
} | php | public function boot()
{
$this->publishes([
__DIR__ . '/../../config/roles.php' => config_path('roles.php')
], 'config');
$this->publishes([
__DIR__ . '/../../migrations/' => base_path('/database/migrations')
], 'migrations');
$this->registerBladeExtensions();
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/../../config/roles.php'",
"=>",
"config_path",
"(",
"'roles.php'",
")",
"]",
",",
"'config'",
")",
";",
"$",
"this",
"->",
"publishes",
"(",
"[",
"_... | Bootstrap any application services.
@return void | [
"Bootstrap",
"any",
"application",
"services",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/RolesServiceProvider.php#L14-L25 |
romanbican/roles | src/Bican/Roles/RolesServiceProvider.php | RolesServiceProvider.registerBladeExtensions | protected function registerBladeExtensions()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->directive('role', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->is{$expression}): ?>";
});
$blade->directive('endrole', function () {
return "<?php endif; ?>";
});
$blade->directive('permission', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->can{$expression}): ?>";
});
$blade->directive('endpermission', function () {
return "<?php endif; ?>";
});
$blade->directive('level', function ($expression) {
$level = trim($expression, '()');
return "<?php if (Auth::check() && Auth::user()->level() >= {$level}): ?>";
});
$blade->directive('endlevel', function () {
return "<?php endif; ?>";
});
$blade->directive('allowed', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->allowed{$expression}): ?>";
});
$blade->directive('endallowed', function () {
return "<?php endif; ?>";
});
} | php | protected function registerBladeExtensions()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->directive('role', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->is{$expression}): ?>";
});
$blade->directive('endrole', function () {
return "<?php endif; ?>";
});
$blade->directive('permission', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->can{$expression}): ?>";
});
$blade->directive('endpermission', function () {
return "<?php endif; ?>";
});
$blade->directive('level', function ($expression) {
$level = trim($expression, '()');
return "<?php if (Auth::check() && Auth::user()->level() >= {$level}): ?>";
});
$blade->directive('endlevel', function () {
return "<?php endif; ?>";
});
$blade->directive('allowed', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->allowed{$expression}): ?>";
});
$blade->directive('endallowed', function () {
return "<?php endif; ?>";
});
} | [
"protected",
"function",
"registerBladeExtensions",
"(",
")",
"{",
"$",
"blade",
"=",
"$",
"this",
"->",
"app",
"[",
"'view'",
"]",
"->",
"getEngineResolver",
"(",
")",
"->",
"resolve",
"(",
"'blade'",
")",
"->",
"getCompiler",
"(",
")",
";",
"$",
"blade... | Register Blade extensions.
@return void | [
"Register",
"Blade",
"extensions",
"."
] | train | https://github.com/romanbican/roles/blob/582349795ef0af9ff1a64bb2c1b884bbd5ab7c98/src/Bican/Roles/RolesServiceProvider.php#L42-L79 |
thunderer/Shortcode | src/Serializer/JsonSerializer.php | JsonSerializer.unserialize | public function unserialize($text)
{
$data = json_decode($text, true);
if (!is_array($data)) {
throw new \InvalidArgumentException('Invalid JSON, cannot unserialize Shortcode!');
}
if (!array_diff_key($data, array('name', 'parameters', 'content'))) {
throw new \InvalidArgumentException('Malformed Shortcode JSON, expected name, parameters, and content!');
}
$name = array_key_exists('name', $data) ? $data['name'] : null;
$parameters = array_key_exists('parameters', $data) ? $data['parameters'] : array();
$content = array_key_exists('content', $data) ? $data['content'] : null;
$bbCode = array_key_exists('bbCode', $data) ? $data['bbCode'] : null;
if(!is_array($parameters)) {
throw new \InvalidArgumentException('Parameters must be an array!');
}
return new Shortcode($name, $parameters, $content, $bbCode);
} | php | public function unserialize($text)
{
$data = json_decode($text, true);
if (!is_array($data)) {
throw new \InvalidArgumentException('Invalid JSON, cannot unserialize Shortcode!');
}
if (!array_diff_key($data, array('name', 'parameters', 'content'))) {
throw new \InvalidArgumentException('Malformed Shortcode JSON, expected name, parameters, and content!');
}
$name = array_key_exists('name', $data) ? $data['name'] : null;
$parameters = array_key_exists('parameters', $data) ? $data['parameters'] : array();
$content = array_key_exists('content', $data) ? $data['content'] : null;
$bbCode = array_key_exists('bbCode', $data) ? $data['bbCode'] : null;
if(!is_array($parameters)) {
throw new \InvalidArgumentException('Parameters must be an array!');
}
return new Shortcode($name, $parameters, $content, $bbCode);
} | [
"public",
"function",
"unserialize",
"(",
"$",
"text",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"text",
",",
"true",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
... | @param string $text
@return Shortcode | [
"@param",
"string",
"$text"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Serializer/JsonSerializer.php#L27-L48 |
thunderer/Shortcode | src/Processor/Processor.php | Processor.process | public function process($text)
{
$iterations = $this->maxIterations === null ? 1 : $this->maxIterations;
$context = new ProcessorContext();
$context->processor = $this;
while ($iterations--) {
$context->iterationNumber++;
$newText = $this->processIteration($text, $context, null);
if ($newText === $text) {
break;
}
$text = $newText;
$iterations += $this->maxIterations === null ? 1 : 0;
}
return $text;
} | php | public function process($text)
{
$iterations = $this->maxIterations === null ? 1 : $this->maxIterations;
$context = new ProcessorContext();
$context->processor = $this;
while ($iterations--) {
$context->iterationNumber++;
$newText = $this->processIteration($text, $context, null);
if ($newText === $text) {
break;
}
$text = $newText;
$iterations += $this->maxIterations === null ? 1 : 0;
}
return $text;
} | [
"public",
"function",
"process",
"(",
"$",
"text",
")",
"{",
"$",
"iterations",
"=",
"$",
"this",
"->",
"maxIterations",
"===",
"null",
"?",
"1",
":",
"$",
"this",
"->",
"maxIterations",
";",
"$",
"context",
"=",
"new",
"ProcessorContext",
"(",
")",
";... | Entry point for shortcode processing. Implements iterative algorithm for
both limited and unlimited number of iterations.
@param string $text Text to process
@return string | [
"Entry",
"point",
"for",
"shortcode",
"processing",
".",
"Implements",
"iterative",
"algorithm",
"for",
"both",
"limited",
"and",
"unlimited",
"number",
"of",
"iterations",
"."
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Processor/Processor.php#L45-L62 |
thunderer/Shortcode | src/Processor/Processor.php | Processor.withRecursionDepth | public function withRecursionDepth($depth)
{
if (null !== $depth && !(is_int($depth) && $depth >= 0)) {
$msg = 'Recursion depth must be null (infinite) or integer >= 0!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->recursionDepth = $depth;
return $self;
} | php | public function withRecursionDepth($depth)
{
if (null !== $depth && !(is_int($depth) && $depth >= 0)) {
$msg = 'Recursion depth must be null (infinite) or integer >= 0!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->recursionDepth = $depth;
return $self;
} | [
"public",
"function",
"withRecursionDepth",
"(",
"$",
"depth",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"depth",
"&&",
"!",
"(",
"is_int",
"(",
"$",
"depth",
")",
"&&",
"$",
"depth",
">=",
"0",
")",
")",
"{",
"$",
"msg",
"=",
"'Recursion depth must b... | Recursion depth level, null means infinite, any integer greater than or
equal to zero sets value (number of recursion levels). Zero disables
recursion. Defaults to null.
@param int|null $depth
@return self | [
"Recursion",
"depth",
"level",
"null",
"means",
"infinite",
"any",
"integer",
"greater",
"than",
"or",
"equal",
"to",
"zero",
"sets",
"value",
"(",
"number",
"of",
"recursion",
"levels",
")",
".",
"Zero",
"disables",
"recursion",
".",
"Defaults",
"to",
"null... | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Processor/Processor.php#L186-L197 |
thunderer/Shortcode | src/Processor/Processor.php | Processor.withMaxIterations | public function withMaxIterations($iterations)
{
if (null !== $iterations && !(is_int($iterations) && $iterations > 0)) {
$msg = 'Maximum number of iterations must be null (infinite) or integer > 0!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->maxIterations = $iterations;
return $self;
} | php | public function withMaxIterations($iterations)
{
if (null !== $iterations && !(is_int($iterations) && $iterations > 0)) {
$msg = 'Maximum number of iterations must be null (infinite) or integer > 0!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->maxIterations = $iterations;
return $self;
} | [
"public",
"function",
"withMaxIterations",
"(",
"$",
"iterations",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"iterations",
"&&",
"!",
"(",
"is_int",
"(",
"$",
"iterations",
")",
"&&",
"$",
"iterations",
">",
"0",
")",
")",
"{",
"$",
"msg",
"=",
"'Maxi... | Maximum number of iterations, null means infinite, any integer greater
than zero sets value. Zero is invalid because there must be at least one
iteration. Defaults to 1. Loop breaks if result of two consequent
iterations shows no change in processed text.
@param int|null $iterations
@return self | [
"Maximum",
"number",
"of",
"iterations",
"null",
"means",
"infinite",
"any",
"integer",
"greater",
"than",
"zero",
"sets",
"value",
".",
"Zero",
"is",
"invalid",
"because",
"there",
"must",
"be",
"at",
"least",
"one",
"iteration",
".",
"Defaults",
"to",
"1",... | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Processor/Processor.php#L209-L220 |
thunderer/Shortcode | src/Processor/Processor.php | Processor.withAutoProcessContent | public function withAutoProcessContent($flag)
{
if (!is_bool($flag)) {
$msg = 'Auto processing flag must be a boolean value!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->autoProcessContent = (bool)$flag;
return $self;
} | php | public function withAutoProcessContent($flag)
{
if (!is_bool($flag)) {
$msg = 'Auto processing flag must be a boolean value!';
throw new \InvalidArgumentException($msg);
}
$self = clone $this;
$self->autoProcessContent = (bool)$flag;
return $self;
} | [
"public",
"function",
"withAutoProcessContent",
"(",
"$",
"flag",
")",
"{",
"if",
"(",
"!",
"is_bool",
"(",
"$",
"flag",
")",
")",
"{",
"$",
"msg",
"=",
"'Auto processing flag must be a boolean value!'",
";",
"throw",
"new",
"\\",
"InvalidArgumentException",
"("... | Whether shortcode content will be automatically processed and handler
already receives shortcode with processed content. If false, every
shortcode handler needs to process content on its own. Default true.
@param bool $flag True if enabled (default), false otherwise
@return self | [
"Whether",
"shortcode",
"content",
"will",
"be",
"automatically",
"processed",
"and",
"handler",
"already",
"receives",
"shortcode",
"with",
"processed",
"content",
".",
"If",
"false",
"every",
"shortcode",
"handler",
"needs",
"to",
"process",
"content",
"on",
"it... | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Processor/Processor.php#L231-L242 |
thunderer/Shortcode | src/Parser/WordpressParser.php | WordpressParser.parse | public function parse($text)
{
$names = $this->names
? implode('|', array_map('preg_quote', $this->names))
: RegexBuilderUtility::buildNameRegex();
$regex = str_replace('<NAMES>', $names, static::$shortcodeRegex);
preg_match_all($regex, $text, $matches, PREG_OFFSET_CAPTURE);
$shortcodes = array();
$count = count($matches[0]);
for($i = 0; $i < $count; $i++) {
$name = $matches[2][$i][0];
$parameters = static::parseParameters($matches[3][$i][0]);
$content = $matches[5][$i][1] !== -1 ? $matches[5][$i][0] : null;
$match = $matches[0][$i][0];
$offset = mb_strlen(substr($text, 0, $matches[0][$i][1]), 'utf-8');
$shortcode = new Shortcode($name, $parameters, $content, null);
$shortcodes[] = new ParsedShortcode($shortcode, $match, $offset);
}
return $shortcodes;
} | php | public function parse($text)
{
$names = $this->names
? implode('|', array_map('preg_quote', $this->names))
: RegexBuilderUtility::buildNameRegex();
$regex = str_replace('<NAMES>', $names, static::$shortcodeRegex);
preg_match_all($regex, $text, $matches, PREG_OFFSET_CAPTURE);
$shortcodes = array();
$count = count($matches[0]);
for($i = 0; $i < $count; $i++) {
$name = $matches[2][$i][0];
$parameters = static::parseParameters($matches[3][$i][0]);
$content = $matches[5][$i][1] !== -1 ? $matches[5][$i][0] : null;
$match = $matches[0][$i][0];
$offset = mb_strlen(substr($text, 0, $matches[0][$i][1]), 'utf-8');
$shortcode = new Shortcode($name, $parameters, $content, null);
$shortcodes[] = new ParsedShortcode($shortcode, $match, $offset);
}
return $shortcodes;
} | [
"public",
"function",
"parse",
"(",
"$",
"text",
")",
"{",
"$",
"names",
"=",
"$",
"this",
"->",
"names",
"?",
"implode",
"(",
"'|'",
",",
"array_map",
"(",
"'preg_quote'",
",",
"$",
"this",
"->",
"names",
")",
")",
":",
"RegexBuilderUtility",
"::",
... | @param string $text
@return ParsedShortcode[] | [
"@param",
"string",
"$text"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Parser/WordpressParser.php#L60-L82 |
thunderer/Shortcode | src/Parser/RegularParser.php | RegularParser.parse | public function parse($text)
{
$nestingLevel = ini_set('xdebug.max_nesting_level', -1);
$this->tokens = $this->tokenize($text);
$this->backtracks = array();
$this->lastBacktrack = 0;
$this->position = 0;
$this->tokensCount = \count($this->tokens);
$shortcodes = array();
while($this->position < $this->tokensCount) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
$this->position++;
}
$names = array();
$this->beginBacktrack();
$matches = $this->shortcode($names);
if(false === $matches) {
$this->backtrack();
$this->match(null, true);
continue;
}
if(\is_array($matches)) {
foreach($matches as $shortcode) {
$shortcodes[] = $shortcode;
}
}
}
ini_set('xdebug.max_nesting_level', $nestingLevel);
return $shortcodes;
} | php | public function parse($text)
{
$nestingLevel = ini_set('xdebug.max_nesting_level', -1);
$this->tokens = $this->tokenize($text);
$this->backtracks = array();
$this->lastBacktrack = 0;
$this->position = 0;
$this->tokensCount = \count($this->tokens);
$shortcodes = array();
while($this->position < $this->tokensCount) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
$this->position++;
}
$names = array();
$this->beginBacktrack();
$matches = $this->shortcode($names);
if(false === $matches) {
$this->backtrack();
$this->match(null, true);
continue;
}
if(\is_array($matches)) {
foreach($matches as $shortcode) {
$shortcodes[] = $shortcode;
}
}
}
ini_set('xdebug.max_nesting_level', $nestingLevel);
return $shortcodes;
} | [
"public",
"function",
"parse",
"(",
"$",
"text",
")",
"{",
"$",
"nestingLevel",
"=",
"ini_set",
"(",
"'xdebug.max_nesting_level'",
",",
"-",
"1",
")",
";",
"$",
"this",
"->",
"tokens",
"=",
"$",
"this",
"->",
"tokenize",
"(",
"$",
"text",
")",
";",
"... | @param string $text
@return ParsedShortcode[] | [
"@param",
"string",
"$text"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Parser/RegularParser.php#L43-L74 |
thunderer/Shortcode | src/Parser/RegularParser.php | RegularParser.shortcode | private function shortcode(array &$names)
{
if(!$this->match(self::TOKEN_OPEN, false)) { return false; }
$offset = $this->tokens[$this->position - 1][2];
$this->match(self::TOKEN_WS, false);
if('' === $name = $this->match(self::TOKEN_STRING, false)) { return false; }
if($this->lookahead(self::TOKEN_STRING)) { return false; }
if(1 !== preg_match($this->nameRegex, $name, $matches)) { return false; }
$this->match(self::TOKEN_WS, false);
// bbCode
$bbCode = $this->match(self::TOKEN_SEPARATOR, true) ? $this->value() : null;
if(false === $bbCode) { return false; }
// parameters
if(false === ($parameters = $this->parameters())) { return false; }
// self-closing
if($this->match(self::TOKEN_MARKER, true)) {
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
return array($this->getObject($name, $parameters, $bbCode, $offset, null, $this->getBacktrack()));
}
// just-closed or with-content
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
$this->beginBacktrack();
$names[] = $name;
// begin inlined content()
$content = '';
$shortcodes = array();
$closingName = null;
while($this->position < $this->tokensCount) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
$content .= $this->match(null, true);
}
$this->beginBacktrack();
$contentMatchedShortcodes = $this->shortcode($names);
if(\is_string($contentMatchedShortcodes)) {
$closingName = $contentMatchedShortcodes;
break;
}
if(\is_array($contentMatchedShortcodes)) {
foreach($contentMatchedShortcodes as $matchedShortcode) {
$shortcodes[] = $matchedShortcode;
}
continue;
}
$this->backtrack();
$this->beginBacktrack();
if(false !== ($closingName = $this->close($names))) {
if(null === $content) { $content = ''; }
$this->backtrack();
$shortcodes = array();
break;
}
$closingName = null;
$this->backtrack();
$content .= $this->match(null, false);
}
$content = $this->position < $this->tokensCount ? $content : false;
// end inlined content()
if(null !== $closingName && $closingName !== $name) {
array_pop($names);
array_pop($this->backtracks);
array_pop($this->backtracks);
return $closingName;
}
if(false === $content || $closingName !== $name) {
$this->backtrack(false);
$text = $this->backtrack(false);
array_pop($names);
return array_merge(array($this->getObject($name, $parameters, $bbCode, $offset, null, $text)), $shortcodes);
}
$content = $this->getBacktrack();
if(!$this->close($names)) { return false; }
array_pop($names);
return array($this->getObject($name, $parameters, $bbCode, $offset, $content, $this->getBacktrack()));
} | php | private function shortcode(array &$names)
{
if(!$this->match(self::TOKEN_OPEN, false)) { return false; }
$offset = $this->tokens[$this->position - 1][2];
$this->match(self::TOKEN_WS, false);
if('' === $name = $this->match(self::TOKEN_STRING, false)) { return false; }
if($this->lookahead(self::TOKEN_STRING)) { return false; }
if(1 !== preg_match($this->nameRegex, $name, $matches)) { return false; }
$this->match(self::TOKEN_WS, false);
// bbCode
$bbCode = $this->match(self::TOKEN_SEPARATOR, true) ? $this->value() : null;
if(false === $bbCode) { return false; }
// parameters
if(false === ($parameters = $this->parameters())) { return false; }
// self-closing
if($this->match(self::TOKEN_MARKER, true)) {
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
return array($this->getObject($name, $parameters, $bbCode, $offset, null, $this->getBacktrack()));
}
// just-closed or with-content
if(!$this->match(self::TOKEN_CLOSE, false)) { return false; }
$this->beginBacktrack();
$names[] = $name;
// begin inlined content()
$content = '';
$shortcodes = array();
$closingName = null;
while($this->position < $this->tokensCount) {
while($this->position < $this->tokensCount && false === $this->lookahead(self::TOKEN_OPEN)) {
$content .= $this->match(null, true);
}
$this->beginBacktrack();
$contentMatchedShortcodes = $this->shortcode($names);
if(\is_string($contentMatchedShortcodes)) {
$closingName = $contentMatchedShortcodes;
break;
}
if(\is_array($contentMatchedShortcodes)) {
foreach($contentMatchedShortcodes as $matchedShortcode) {
$shortcodes[] = $matchedShortcode;
}
continue;
}
$this->backtrack();
$this->beginBacktrack();
if(false !== ($closingName = $this->close($names))) {
if(null === $content) { $content = ''; }
$this->backtrack();
$shortcodes = array();
break;
}
$closingName = null;
$this->backtrack();
$content .= $this->match(null, false);
}
$content = $this->position < $this->tokensCount ? $content : false;
// end inlined content()
if(null !== $closingName && $closingName !== $name) {
array_pop($names);
array_pop($this->backtracks);
array_pop($this->backtracks);
return $closingName;
}
if(false === $content || $closingName !== $name) {
$this->backtrack(false);
$text = $this->backtrack(false);
array_pop($names);
return array_merge(array($this->getObject($name, $parameters, $bbCode, $offset, null, $text)), $shortcodes);
}
$content = $this->getBacktrack();
if(!$this->close($names)) { return false; }
array_pop($names);
return array($this->getObject($name, $parameters, $bbCode, $offset, $content, $this->getBacktrack()));
} | [
"private",
"function",
"shortcode",
"(",
"array",
"&",
"$",
"names",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"match",
"(",
"self",
"::",
"TOKEN_OPEN",
",",
"false",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"offset",
"=",
"$",
"this",
... | /* --- RULES ----------------------------------------------------------- | [
"/",
"*",
"---",
"RULES",
"-----------------------------------------------------------"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Parser/RegularParser.php#L83-L168 |
thunderer/Shortcode | src/Parser/RegularParser.php | RegularParser.tokenize | private function tokenize($text)
{
$count = preg_match_all($this->lexerRegex, $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
if(false === $count || preg_last_error() !== PREG_NO_ERROR) {
throw new \RuntimeException(sprintf('PCRE failure `%s`.', preg_last_error()));
}
$tokens = array();
$position = 0;
foreach($matches as $match) {
switch(true) {
case -1 !== $match['string'][1]: { $token = $match['string'][0]; $type = self::TOKEN_STRING; break; }
case -1 !== $match['ws'][1]: { $token = $match['ws'][0]; $type = self::TOKEN_WS; break; }
case -1 !== $match['marker'][1]: { $token = $match['marker'][0]; $type = self::TOKEN_MARKER; break; }
case -1 !== $match['delimiter'][1]: { $token = $match['delimiter'][0]; $type = self::TOKEN_DELIMITER; break; }
case -1 !== $match['separator'][1]: { $token = $match['separator'][0]; $type = self::TOKEN_SEPARATOR; break; }
case -1 !== $match['open'][1]: { $token = $match['open'][0]; $type = self::TOKEN_OPEN; break; }
case -1 !== $match['close'][1]: { $token = $match['close'][0]; $type = self::TOKEN_CLOSE; break; }
default: { throw new \RuntimeException(sprintf('Invalid token.')); }
}
$tokens[] = array($type, $token, $position);
$position += mb_strlen($token, 'utf-8');
}
return $tokens;
} | php | private function tokenize($text)
{
$count = preg_match_all($this->lexerRegex, $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
if(false === $count || preg_last_error() !== PREG_NO_ERROR) {
throw new \RuntimeException(sprintf('PCRE failure `%s`.', preg_last_error()));
}
$tokens = array();
$position = 0;
foreach($matches as $match) {
switch(true) {
case -1 !== $match['string'][1]: { $token = $match['string'][0]; $type = self::TOKEN_STRING; break; }
case -1 !== $match['ws'][1]: { $token = $match['ws'][0]; $type = self::TOKEN_WS; break; }
case -1 !== $match['marker'][1]: { $token = $match['marker'][0]; $type = self::TOKEN_MARKER; break; }
case -1 !== $match['delimiter'][1]: { $token = $match['delimiter'][0]; $type = self::TOKEN_DELIMITER; break; }
case -1 !== $match['separator'][1]: { $token = $match['separator'][0]; $type = self::TOKEN_SEPARATOR; break; }
case -1 !== $match['open'][1]: { $token = $match['open'][0]; $type = self::TOKEN_OPEN; break; }
case -1 !== $match['close'][1]: { $token = $match['close'][0]; $type = self::TOKEN_CLOSE; break; }
default: { throw new \RuntimeException(sprintf('Invalid token.')); }
}
$tokens[] = array($type, $token, $position);
$position += mb_strlen($token, 'utf-8');
}
return $tokens;
} | [
"private",
"function",
"tokenize",
"(",
"$",
"text",
")",
"{",
"$",
"count",
"=",
"preg_match_all",
"(",
"$",
"this",
"->",
"lexerRegex",
",",
"$",
"text",
",",
"$",
"matches",
",",
"PREG_SET_ORDER",
"|",
"PREG_OFFSET_CAPTURE",
")",
";",
"if",
"(",
"fals... | /* --- LEXER ----------------------------------------------------------- | [
"/",
"*",
"---",
"LEXER",
"-----------------------------------------------------------"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Parser/RegularParser.php#L283-L309 |
thunderer/Shortcode | src/Parser/RegexParser.php | RegexParser.parse | public function parse($text)
{
preg_match_all($this->shortcodeRegex, $text, $matches, PREG_OFFSET_CAPTURE);
// loop instead of array_map to pass the arguments explicitly
$shortcodes = array();
foreach($matches[0] as $match) {
$offset = mb_strlen(substr($text, 0, $match[1]), 'utf-8');
$shortcodes[] = $this->parseSingle($match[0], $offset);
}
return array_filter($shortcodes);
} | php | public function parse($text)
{
preg_match_all($this->shortcodeRegex, $text, $matches, PREG_OFFSET_CAPTURE);
// loop instead of array_map to pass the arguments explicitly
$shortcodes = array();
foreach($matches[0] as $match) {
$offset = mb_strlen(substr($text, 0, $match[1]), 'utf-8');
$shortcodes[] = $this->parseSingle($match[0], $offset);
}
return array_filter($shortcodes);
} | [
"public",
"function",
"parse",
"(",
"$",
"text",
")",
"{",
"preg_match_all",
"(",
"$",
"this",
"->",
"shortcodeRegex",
",",
"$",
"text",
",",
"$",
"matches",
",",
"PREG_OFFSET_CAPTURE",
")",
";",
"// loop instead of array_map to pass the arguments explicitly",
"$",
... | @param string $text
@return ParsedShortcode[] | [
"@param",
"string",
"$text"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Parser/RegexParser.php#L34-L46 |
thunderer/Shortcode | src/Serializer/YamlSerializer.php | YamlSerializer.unserialize | public function unserialize($text)
{
$data = Yaml::parse($text);
if(!$data || !is_array($data)) {
throw new \InvalidArgumentException('Invalid YAML, cannot unserialize Shortcode!');
}
if (!array_intersect(array_keys($data), array('name', 'parameters', 'content'))) {
throw new \InvalidArgumentException('Malformed shortcode YAML, expected name, parameters, and content!');
}
$name = array_key_exists('name', $data) ? $data['name'] : null;
$parameters = array_key_exists('parameters', $data) ? $data['parameters'] : array();
$content = array_key_exists('content', $data) ? $data['content'] : null;
$bbCode = array_key_exists('bbCode', $data) ? $data['bbCode'] : null;
if(!is_array($parameters)) {
throw new \InvalidArgumentException('Parameters must be an array!');
}
return new Shortcode($name, $parameters, $content, $bbCode);
} | php | public function unserialize($text)
{
$data = Yaml::parse($text);
if(!$data || !is_array($data)) {
throw new \InvalidArgumentException('Invalid YAML, cannot unserialize Shortcode!');
}
if (!array_intersect(array_keys($data), array('name', 'parameters', 'content'))) {
throw new \InvalidArgumentException('Malformed shortcode YAML, expected name, parameters, and content!');
}
$name = array_key_exists('name', $data) ? $data['name'] : null;
$parameters = array_key_exists('parameters', $data) ? $data['parameters'] : array();
$content = array_key_exists('content', $data) ? $data['content'] : null;
$bbCode = array_key_exists('bbCode', $data) ? $data['bbCode'] : null;
if(!is_array($parameters)) {
throw new \InvalidArgumentException('Parameters must be an array!');
}
return new Shortcode($name, $parameters, $content, $bbCode);
} | [
"public",
"function",
"unserialize",
"(",
"$",
"text",
")",
"{",
"$",
"data",
"=",
"Yaml",
"::",
"parse",
"(",
"$",
"text",
")",
";",
"if",
"(",
"!",
"$",
"data",
"||",
"!",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"In... | @param string $text
@return Shortcode | [
"@param",
"string",
"$text"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Serializer/YamlSerializer.php#L28-L49 |
thunderer/Shortcode | src/ShortcodeFacade.php | ShortcodeFacade.serialize | public function serialize(ShortcodeInterface $shortcode, $format)
{
switch($format) {
case 'text': return $this->textSerializer->serialize($shortcode);
case 'json': return $this->jsonSerializer->serialize($shortcode);
case 'yaml': return $this->yamlSerializer->serialize($shortcode);
case 'xml': return $this->xmlSerializer->serialize($shortcode);
default: throw new \InvalidArgumentException(sprintf('Invalid serialization format %s!', $format));
}
} | php | public function serialize(ShortcodeInterface $shortcode, $format)
{
switch($format) {
case 'text': return $this->textSerializer->serialize($shortcode);
case 'json': return $this->jsonSerializer->serialize($shortcode);
case 'yaml': return $this->yamlSerializer->serialize($shortcode);
case 'xml': return $this->xmlSerializer->serialize($shortcode);
default: throw new \InvalidArgumentException(sprintf('Invalid serialization format %s!', $format));
}
} | [
"public",
"function",
"serialize",
"(",
"ShortcodeInterface",
"$",
"shortcode",
",",
"$",
"format",
")",
"{",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"'text'",
":",
"return",
"$",
"this",
"->",
"textSerializer",
"->",
"serialize",
"(",
"$",
"shortc... | /* --- SERIALIZATION --------------------------------------------------- | [
"/",
"*",
"---",
"SERIALIZATION",
"---------------------------------------------------"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/ShortcodeFacade.php#L120-L129 |
thunderer/Shortcode | src/Serializer/XmlSerializer.php | XmlSerializer.serialize | public function serialize(ShortcodeInterface $shortcode)
{
$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$code = $doc->createElement('shortcode');
$code->setAttribute('name', $shortcode->getName());
$xml = $doc->appendChild($code);
$xml->appendChild($this->createCDataNode($doc, 'bbCode', $shortcode->getBbCode()));
$parameters = $xml->appendChild($doc->createElement('parameters'));
foreach($shortcode->getParameters() as $key => $value) {
$parameter = $doc->createElement('parameter');
$parameter->setAttribute('name', $key);
if(null !== $value) {
$parameter->appendChild($doc->createCDATASection($value));
}
$parameters->appendChild($parameter);
}
$xml->appendChild($this->createCDataNode($doc, 'content', $shortcode->getContent()));
return $doc->saveXML();
} | php | public function serialize(ShortcodeInterface $shortcode)
{
$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$code = $doc->createElement('shortcode');
$code->setAttribute('name', $shortcode->getName());
$xml = $doc->appendChild($code);
$xml->appendChild($this->createCDataNode($doc, 'bbCode', $shortcode->getBbCode()));
$parameters = $xml->appendChild($doc->createElement('parameters'));
foreach($shortcode->getParameters() as $key => $value) {
$parameter = $doc->createElement('parameter');
$parameter->setAttribute('name', $key);
if(null !== $value) {
$parameter->appendChild($doc->createCDATASection($value));
}
$parameters->appendChild($parameter);
}
$xml->appendChild($this->createCDataNode($doc, 'content', $shortcode->getContent()));
return $doc->saveXML();
} | [
"public",
"function",
"serialize",
"(",
"ShortcodeInterface",
"$",
"shortcode",
")",
"{",
"$",
"doc",
"=",
"new",
"\\",
"DOMDocument",
"(",
"'1.0'",
",",
"'UTF-8'",
")",
";",
"$",
"doc",
"->",
"preserveWhiteSpace",
"=",
"false",
";",
"$",
"doc",
"->",
"f... | <shortcode name="NAME">
<bbCode>BBCODE</bbCode>
<parameters>
<parameter name="KEY">VALUE</parameter>
<parameter name="KEY">VALUE</parameter>
</parameters>
<content>CONTENT></content>
</shortcode>
@param ShortcodeInterface $shortcode
@return string | [
"<shortcode",
"name",
"=",
"NAME",
">",
"<bbCode",
">",
"BBCODE<",
"/",
"bbCode",
">",
"<parameters",
">",
"<parameter",
"name",
"=",
"KEY",
">",
"VALUE<",
"/",
"parameter",
">",
"<parameter",
"name",
"=",
"KEY",
">",
"VALUE<",
"/",
"parameter",
">",
"<"... | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Serializer/XmlSerializer.php#L26-L51 |
thunderer/Shortcode | src/Serializer/XmlSerializer.php | XmlSerializer.unserialize | public function unserialize($text)
{
$xml = new \DOMDocument();
$internalErrors = libxml_use_internal_errors(true);
if(!$text || ($text && !$xml->loadXML($text))) {
libxml_use_internal_errors($internalErrors);
throw new \InvalidArgumentException('Failed to parse provided XML!');
}
libxml_use_internal_errors($internalErrors);
$xpath = new \DOMXPath($xml);
$shortcode = $xpath->query('/shortcode');
if($shortcode->length !== 1) {
throw new \InvalidArgumentException('Invalid shortcode XML!');
}
$name = $this->getAttribute($shortcode->item(0), 'name');
$bbCode = $this->getValue($xpath->query('/shortcode/bbCode'));
$content = $this->getValue($xpath->query('/shortcode/content'));
$parameters = array();
$elements = $xpath->query('/shortcode/parameters/parameter');
for($i = 0; $i < $elements->length; $i++) {
$node = $elements->item($i);
$parameters[$this->getAttribute($node, 'name')] = $node->hasChildNodes() ? $node->nodeValue : null;
}
return new Shortcode($name, $parameters, $content, $bbCode);
} | php | public function unserialize($text)
{
$xml = new \DOMDocument();
$internalErrors = libxml_use_internal_errors(true);
if(!$text || ($text && !$xml->loadXML($text))) {
libxml_use_internal_errors($internalErrors);
throw new \InvalidArgumentException('Failed to parse provided XML!');
}
libxml_use_internal_errors($internalErrors);
$xpath = new \DOMXPath($xml);
$shortcode = $xpath->query('/shortcode');
if($shortcode->length !== 1) {
throw new \InvalidArgumentException('Invalid shortcode XML!');
}
$name = $this->getAttribute($shortcode->item(0), 'name');
$bbCode = $this->getValue($xpath->query('/shortcode/bbCode'));
$content = $this->getValue($xpath->query('/shortcode/content'));
$parameters = array();
$elements = $xpath->query('/shortcode/parameters/parameter');
for($i = 0; $i < $elements->length; $i++) {
$node = $elements->item($i);
$parameters[$this->getAttribute($node, 'name')] = $node->hasChildNodes() ? $node->nodeValue : null;
}
return new Shortcode($name, $parameters, $content, $bbCode);
} | [
"public",
"function",
"unserialize",
"(",
"$",
"text",
")",
"{",
"$",
"xml",
"=",
"new",
"\\",
"DOMDocument",
"(",
")",
";",
"$",
"internalErrors",
"=",
"libxml_use_internal_errors",
"(",
"true",
")",
";",
"if",
"(",
"!",
"$",
"text",
"||",
"(",
"$",
... | @param string $text
@return Shortcode | [
"@param",
"string",
"$text"
] | train | https://github.com/thunderer/Shortcode/blob/d19ded97c7faf88d93bdfd93c7de358d57be9999/src/Serializer/XmlSerializer.php#L69-L98 |
Gargron/fileupload | src/FileUpload/Validator/SizeValidator.php | SizeValidator.setErrorMessages | public function setErrorMessages(array $messages)
{
foreach ($messages as $key => $value) {
$this->errorMessages[$key] = $value;
}
} | php | public function setErrorMessages(array $messages)
{
foreach ($messages as $key => $value) {
$this->errorMessages[$key] = $value;
}
} | [
"public",
"function",
"setErrorMessages",
"(",
"array",
"$",
"messages",
")",
"{",
"foreach",
"(",
"$",
"messages",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"errorMessages",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",... | {@inheritdoc} | [
"{"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/Validator/SizeValidator.php#L93-L98 |
Gargron/fileupload | src/FileUpload/Validator/SizeValidator.php | SizeValidator.validate | public function validate(File $file, $currentSize = null)
{
if ($file->getSize() < $this->minSize) {
$file->error = $this->errorMessages[self::FILE_SIZE_IS_TOO_SMALL];
$this->isValid = false;
}
if ($file->getSize() > $this->maxSize || $currentSize > $this->maxSize) {
$file->error = $this->errorMessages[self::FILE_SIZE_IS_TOO_LARGE];
$this->isValid = false;
}
return $this->isValid;
} | php | public function validate(File $file, $currentSize = null)
{
if ($file->getSize() < $this->minSize) {
$file->error = $this->errorMessages[self::FILE_SIZE_IS_TOO_SMALL];
$this->isValid = false;
}
if ($file->getSize() > $this->maxSize || $currentSize > $this->maxSize) {
$file->error = $this->errorMessages[self::FILE_SIZE_IS_TOO_LARGE];
$this->isValid = false;
}
return $this->isValid;
} | [
"public",
"function",
"validate",
"(",
"File",
"$",
"file",
",",
"$",
"currentSize",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"file",
"->",
"getSize",
"(",
")",
"<",
"$",
"this",
"->",
"minSize",
")",
"{",
"$",
"file",
"->",
"error",
"=",
"$",
"thi... | {@inheritdoc} | [
"{"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/Validator/SizeValidator.php#L103-L116 |
Gargron/fileupload | src/FileUpload/FileNameGenerator/Random.php | Random.getFileName | public function getFileName($source_name, $type, $tmp_name, $index, $content_range, FileUpload $upload)
{
$this->pathresolver = $upload->getPathResolver();
$this->filesystem = $upload->getFileSystem();
$extension = pathinfo($source_name, PATHINFO_EXTENSION);
return ($this->getUniqueFilename($source_name, $type, $index, $content_range, $extension));
} | php | public function getFileName($source_name, $type, $tmp_name, $index, $content_range, FileUpload $upload)
{
$this->pathresolver = $upload->getPathResolver();
$this->filesystem = $upload->getFileSystem();
$extension = pathinfo($source_name, PATHINFO_EXTENSION);
return ($this->getUniqueFilename($source_name, $type, $index, $content_range, $extension));
} | [
"public",
"function",
"getFileName",
"(",
"$",
"source_name",
",",
"$",
"type",
",",
"$",
"tmp_name",
",",
"$",
"index",
",",
"$",
"content_range",
",",
"FileUpload",
"$",
"upload",
")",
"{",
"$",
"this",
"->",
"pathresolver",
"=",
"$",
"upload",
"->",
... | Get file_name
@param string $source_name
@param string $type
@param string $tmp_name
@param integer $index
@param string $content_range
@param FileUpload $upload
@return string | [
"Get",
"file_name"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileNameGenerator/Random.php#L45-L52 |
Gargron/fileupload | src/FileUpload/FileNameGenerator/Random.php | Random.getUniqueFilename | protected function getUniqueFilename($name, $type, $index, $content_range, $extension)
{
$name = $this->generateRandom() . "." . $extension;
while ($this->filesystem->isDir($this->pathresolver->getUploadPath($name))) {
$name = $this->generateRandom() . "." . $extension;
}
$uploaded_bytes = Util::fixIntegerOverflow(intval($content_range[1]));
while ($this->filesystem->isFile($this->pathresolver->getUploadPath($name))) {
if ($uploaded_bytes == $this->filesystem->getFilesize($this->pathresolver->getUploadPath($name))) {
break;
}
$name = $this->generateRandom() . "." . $extension;
}
return $name;
} | php | protected function getUniqueFilename($name, $type, $index, $content_range, $extension)
{
$name = $this->generateRandom() . "." . $extension;
while ($this->filesystem->isDir($this->pathresolver->getUploadPath($name))) {
$name = $this->generateRandom() . "." . $extension;
}
$uploaded_bytes = Util::fixIntegerOverflow(intval($content_range[1]));
while ($this->filesystem->isFile($this->pathresolver->getUploadPath($name))) {
if ($uploaded_bytes == $this->filesystem->getFilesize($this->pathresolver->getUploadPath($name))) {
break;
}
$name = $this->generateRandom() . "." . $extension;
}
return $name;
} | [
"protected",
"function",
"getUniqueFilename",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"index",
",",
"$",
"content_range",
",",
"$",
"extension",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"generateRandom",
"(",
")",
".",
"\".\"",
".",
"$",
... | Get unique but consistent name
@param string $name
@param string $type
@param integer $index
@param array $content_range
@param string $extension
@return string | [
"Get",
"unique",
"but",
"consistent",
"name"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileNameGenerator/Random.php#L63-L81 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.prepareMessages | private function prepareMessages()
{
$prepared = [];
foreach ($this->messages as $key => $msg) {
$prepared[(string)$key] = $msg;
}
$this->messages = $prepared;
} | php | private function prepareMessages()
{
$prepared = [];
foreach ($this->messages as $key => $msg) {
$prepared[(string)$key] = $msg;
}
$this->messages = $prepared;
} | [
"private",
"function",
"prepareMessages",
"(",
")",
"{",
"$",
"prepared",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"messages",
"as",
"$",
"key",
"=>",
"$",
"msg",
")",
"{",
"$",
"prepared",
"[",
"(",
"string",
")",
"$",
"key",
"]",
... | Converts $messages array into a hash with strings as keys
This allows us to work with the keys and values as if it was a hash
Which it really should be but, well, arrays in PHP, am I right? | [
"Converts",
"$messages",
"array",
"into",
"a",
"hash",
"with",
"strings",
"as",
"keys",
"This",
"allows",
"us",
"to",
"work",
"with",
"the",
"keys",
"and",
"values",
"as",
"if",
"it",
"was",
"a",
"hash",
"Which",
"it",
"really",
"should",
"be",
"but",
... | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L105-L114 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.processAll | public function processAll()
{
$content_range = $this->getContentRange();
$size = $this->getSize();
$this->files = [];
$upload = $this->upload;
if ($this->logger) {
$this->logger->debug('Processing uploads', [
'Content-range' => $content_range,
'Size' => $size,
'Upload array' => $upload,
'Server array' => $this->server,
]);
}
if ($upload && is_array($upload['tmp_name'])) {
foreach ($upload['tmp_name'] as $index => $tmp_name) {
if (empty($tmp_name)) {
// Discard empty uploads
continue;
}
$this->files[] = $this->process(
$tmp_name,
$upload['name'][$index],
$size ? $size : $upload['size'][$index],
$upload['type'][$index],
$upload['error'][$index],
$index,
$content_range
);
}
} else {
if ($upload && ! empty($upload['tmp_name'])) {
$this->files[] = $this->process(
$upload['tmp_name'],
$upload['name'],
$size ? $size : (isset($upload['size']) ? $upload['size'] : $this->getContentLength()),
isset($upload['type']) ? $upload['type'] : $this->getContentType(),
$upload['error'],
0,
$content_range
);
} else {
if ($upload && $upload['error'] != 0) {
// $this->fileContainer is empty at this point
// $upload['tmp_name'] is also empty
// So we create a File instance from $upload['name']
$file = new File($upload['name'], basename($upload['name']));
$file->error = $this->getMessage($upload['error']);
$file->errorCode = $upload['error'];
$this->files[] = $file;
}
}
}
return [$this->files, $this->getNewHeaders($this->files, $content_range)];
} | php | public function processAll()
{
$content_range = $this->getContentRange();
$size = $this->getSize();
$this->files = [];
$upload = $this->upload;
if ($this->logger) {
$this->logger->debug('Processing uploads', [
'Content-range' => $content_range,
'Size' => $size,
'Upload array' => $upload,
'Server array' => $this->server,
]);
}
if ($upload && is_array($upload['tmp_name'])) {
foreach ($upload['tmp_name'] as $index => $tmp_name) {
if (empty($tmp_name)) {
// Discard empty uploads
continue;
}
$this->files[] = $this->process(
$tmp_name,
$upload['name'][$index],
$size ? $size : $upload['size'][$index],
$upload['type'][$index],
$upload['error'][$index],
$index,
$content_range
);
}
} else {
if ($upload && ! empty($upload['tmp_name'])) {
$this->files[] = $this->process(
$upload['tmp_name'],
$upload['name'],
$size ? $size : (isset($upload['size']) ? $upload['size'] : $this->getContentLength()),
isset($upload['type']) ? $upload['type'] : $this->getContentType(),
$upload['error'],
0,
$content_range
);
} else {
if ($upload && $upload['error'] != 0) {
// $this->fileContainer is empty at this point
// $upload['tmp_name'] is also empty
// So we create a File instance from $upload['name']
$file = new File($upload['name'], basename($upload['name']));
$file->error = $this->getMessage($upload['error']);
$file->errorCode = $upload['error'];
$this->files[] = $file;
}
}
}
return [$this->files, $this->getNewHeaders($this->files, $content_range)];
} | [
"public",
"function",
"processAll",
"(",
")",
"{",
"$",
"content_range",
"=",
"$",
"this",
"->",
"getContentRange",
"(",
")",
";",
"$",
"size",
"=",
"$",
"this",
"->",
"getSize",
"(",
")",
";",
"$",
"this",
"->",
"files",
"=",
"[",
"]",
";",
"$",
... | Process entire submitted request
@return array Files and response headers | [
"Process",
"entire",
"submitted",
"request"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L216-L274 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.process | protected function process($tmp_name, $name, $size, $type, $error, $index = 0, $content_range = null)
{
$this->fileContainer = $file = new File($tmp_name, $name);
$file->name = $this->getFilename($name, $type, $index, $content_range, $tmp_name);
$file->size = $this->fixIntegerOverflow(intval($size));
$completed = false;
if ($file->name) { //since the md5 filename generator would return false if it's allowDuplicate property is set to false and the file already exists.
if ($this->validate($tmp_name, $file, $error, $index)) {
// Now that we passed the validation, we can work with the file
$upload_path = $this->pathresolver->getUploadPath();
$file_path = $this->pathresolver->getUploadPath($file->name);
$append_file = $content_range && $this->filesystem->isFile($file_path) && $file->size > $this->getFilesize($file_path);
if ($tmp_name && $this->filesystem->isUploadedFile($tmp_name)) {
// This is a normal upload from temporary file
if ($append_file) {
// Adding to existing file (chunked uploads)
$this->filesystem->writeToFile($file_path, $this->filesystem->getFileStream($tmp_name), true);
} else {
// Upload full file
$this->filesystem->moveUploadedFile($tmp_name, $file_path);
}
} else {
// This is a PUT-type upload
$this->filesystem->writeToFile($file_path, $this->filesystem->getInputStream(), $append_file);
}
$file_size = $this->getFilesize($file_path, $append_file);
if ($this->logger) {
$this->logger->debug('Processing ' . $file->name, [
'File path' => $file_path,
'File object' => $file,
'Append to file?' => $append_file,
'File exists?' => $this->filesystem->isFile($file_path),
'File size' => $file_size,
]);
}
if ($file->size == $file_size) {
// Yay, upload is complete!
$completed = true;
} else {
if (! $content_range) {
// The file is incomplete and it's not a chunked upload, abort
$this->filesystem->unlink($file_path);
$file->error = 'abort';
}
}
$file = new File($file_path, $name);
$file->completed = $completed;
$file->size = $file_size;
if ($completed) {
$this->processCallbacksFor('completed', $file);
}
}
}
return $file;
} | php | protected function process($tmp_name, $name, $size, $type, $error, $index = 0, $content_range = null)
{
$this->fileContainer = $file = new File($tmp_name, $name);
$file->name = $this->getFilename($name, $type, $index, $content_range, $tmp_name);
$file->size = $this->fixIntegerOverflow(intval($size));
$completed = false;
if ($file->name) { //since the md5 filename generator would return false if it's allowDuplicate property is set to false and the file already exists.
if ($this->validate($tmp_name, $file, $error, $index)) {
// Now that we passed the validation, we can work with the file
$upload_path = $this->pathresolver->getUploadPath();
$file_path = $this->pathresolver->getUploadPath($file->name);
$append_file = $content_range && $this->filesystem->isFile($file_path) && $file->size > $this->getFilesize($file_path);
if ($tmp_name && $this->filesystem->isUploadedFile($tmp_name)) {
// This is a normal upload from temporary file
if ($append_file) {
// Adding to existing file (chunked uploads)
$this->filesystem->writeToFile($file_path, $this->filesystem->getFileStream($tmp_name), true);
} else {
// Upload full file
$this->filesystem->moveUploadedFile($tmp_name, $file_path);
}
} else {
// This is a PUT-type upload
$this->filesystem->writeToFile($file_path, $this->filesystem->getInputStream(), $append_file);
}
$file_size = $this->getFilesize($file_path, $append_file);
if ($this->logger) {
$this->logger->debug('Processing ' . $file->name, [
'File path' => $file_path,
'File object' => $file,
'Append to file?' => $append_file,
'File exists?' => $this->filesystem->isFile($file_path),
'File size' => $file_size,
]);
}
if ($file->size == $file_size) {
// Yay, upload is complete!
$completed = true;
} else {
if (! $content_range) {
// The file is incomplete and it's not a chunked upload, abort
$this->filesystem->unlink($file_path);
$file->error = 'abort';
}
}
$file = new File($file_path, $name);
$file->completed = $completed;
$file->size = $file_size;
if ($completed) {
$this->processCallbacksFor('completed', $file);
}
}
}
return $file;
} | [
"protected",
"function",
"process",
"(",
"$",
"tmp_name",
",",
"$",
"name",
",",
"$",
"size",
",",
"$",
"type",
",",
"$",
"error",
",",
"$",
"index",
"=",
"0",
",",
"$",
"content_range",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"fileContainer",
"=... | Process single submitted file
@param string $tmp_name
@param string $name
@param integer $size
@param string $type
@param integer $error
@param integer $index
@param array $content_range
@return File | [
"Process",
"single",
"submitted",
"file"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L308-L371 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.getFilename | protected function getFilename($name, $type, $index, $content_range, $tmp_name)
{
$name = $this->trimFilename($name, $type, $index, $content_range);
return ($this->fileNameGenerator->getFileName($name, $type, $tmp_name, $index, $content_range, $this));
} | php | protected function getFilename($name, $type, $index, $content_range, $tmp_name)
{
$name = $this->trimFilename($name, $type, $index, $content_range);
return ($this->fileNameGenerator->getFileName($name, $type, $tmp_name, $index, $content_range, $this));
} | [
"protected",
"function",
"getFilename",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"index",
",",
"$",
"content_range",
",",
"$",
"tmp_name",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"trimFilename",
"(",
"$",
"name",
",",
"$",
"type",
",",
... | Get filename for submitted filename
@param string $name
@param string $type
@param integer $index
@param array $content_range
@param string $tmp_name
@return string | [
"Get",
"filename",
"for",
"submitted",
"filename"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L382-L387 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.trimFilename | protected function trimFilename($name, $type, $index, $content_range)
{
$name = trim(basename(stripslashes($name)), ".\x00..\x20");
if (! $name) {
$name = str_replace('.', '-', microtime(true));
}
return $name;
} | php | protected function trimFilename($name, $type, $index, $content_range)
{
$name = trim(basename(stripslashes($name)), ".\x00..\x20");
if (! $name) {
$name = str_replace('.', '-', microtime(true));
}
return $name;
} | [
"protected",
"function",
"trimFilename",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"index",
",",
"$",
"content_range",
")",
"{",
"$",
"name",
"=",
"trim",
"(",
"basename",
"(",
"stripslashes",
"(",
"$",
"name",
")",
")",
",",
"\".\\x00..\\x20\"",
"... | Remove harmful characters from filename
@param string $name
@param string $type
@param integer $index
@param array $content_range
@return string | [
"Remove",
"harmful",
"characters",
"from",
"filename"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L397-L406 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.validate | protected function validate($tmp_name, File $file, $error, $index)
{
$this->processCallbacksFor('beforeValidation', $file);
if ($error !== 0) {
// PHP error
$file->error = $this->getMessage($error);
$file->errorCode = $error;
return false;
}
$content_length = $this->getContentLength();
$post_max_size = $this->getConfigBytes(ini_get('post_max_size'));
$upload_max_size = $this->getConfigBytes(ini_get('upload_max_filesize'));
if (($post_max_size && ($content_length > $post_max_size)) || ($upload_max_size && ($content_length > $upload_max_size))) {
// Uploaded file exceeds maximum filesize PHP accepts in the configs
$file->error = $this->getMessage(self::UPLOAD_ERR_PHP_SIZE);
$file->errorCode = self::UPLOAD_ERR_PHP_SIZE;
return false;
}
if ($tmp_name && $this->filesystem->isUploadedFile($tmp_name)) {
$current_size = $this->getFilesize($tmp_name);
} else {
$current_size = $content_length;
}
// Now that we passed basic, implementation-agnostic tests,
// let's do custom validators
foreach ($this->validators as $validator) {
if (! $validator->validate($file, $current_size)) {
return false;
}
}
$this->processCallbacksFor('afterValidation', $file);
return true;
} | php | protected function validate($tmp_name, File $file, $error, $index)
{
$this->processCallbacksFor('beforeValidation', $file);
if ($error !== 0) {
// PHP error
$file->error = $this->getMessage($error);
$file->errorCode = $error;
return false;
}
$content_length = $this->getContentLength();
$post_max_size = $this->getConfigBytes(ini_get('post_max_size'));
$upload_max_size = $this->getConfigBytes(ini_get('upload_max_filesize'));
if (($post_max_size && ($content_length > $post_max_size)) || ($upload_max_size && ($content_length > $upload_max_size))) {
// Uploaded file exceeds maximum filesize PHP accepts in the configs
$file->error = $this->getMessage(self::UPLOAD_ERR_PHP_SIZE);
$file->errorCode = self::UPLOAD_ERR_PHP_SIZE;
return false;
}
if ($tmp_name && $this->filesystem->isUploadedFile($tmp_name)) {
$current_size = $this->getFilesize($tmp_name);
} else {
$current_size = $content_length;
}
// Now that we passed basic, implementation-agnostic tests,
// let's do custom validators
foreach ($this->validators as $validator) {
if (! $validator->validate($file, $current_size)) {
return false;
}
}
$this->processCallbacksFor('afterValidation', $file);
return true;
} | [
"protected",
"function",
"validate",
"(",
"$",
"tmp_name",
",",
"File",
"$",
"file",
",",
"$",
"error",
",",
"$",
"index",
")",
"{",
"$",
"this",
"->",
"processCallbacksFor",
"(",
"'beforeValidation'",
",",
"$",
"file",
")",
";",
"if",
"(",
"$",
"error... | Validate upload using some default rules, and custom
validators added via addValidator. Default rules:
- No PHP errors from $_FILES
- File size permitted by PHP config
@param string $tmp_name
@param File $file
@param integer $error
@param integer $index
@return boolean | [
"Validate",
"upload",
"using",
"some",
"default",
"rules",
"and",
"custom",
"validators",
"added",
"via",
"addValidator",
".",
"Default",
"rules",
":"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L435-L476 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.processCallbacksFor | protected function processCallbacksFor($eventName, File $file)
{
if (! array_key_exists($eventName, $this->callbacks) || empty($this->callbacks[$eventName])) {
return;
}
foreach ($this->callbacks[$eventName] as $callback) {
$callback($file);
}
} | php | protected function processCallbacksFor($eventName, File $file)
{
if (! array_key_exists($eventName, $this->callbacks) || empty($this->callbacks[$eventName])) {
return;
}
foreach ($this->callbacks[$eventName] as $callback) {
$callback($file);
}
} | [
"protected",
"function",
"processCallbacksFor",
"(",
"$",
"eventName",
",",
"File",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"eventName",
",",
"$",
"this",
"->",
"callbacks",
")",
"||",
"empty",
"(",
"$",
"this",
"->",
"callba... | Process callbacks for a given event
@param string $eventName
@param File $file
@return void | [
"Process",
"callbacks",
"for",
"a",
"given",
"event"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L484-L493 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.getConfigBytes | protected function getConfigBytes($val)
{
$val = trim($val);
$bytes = (int)(substr($val, 0, -1));
$last = strtolower($val[strlen($val) - 1]);
switch ($last) {
case 'g':
$bytes *= 1024;
case 'm':
$bytes *= 1024;
case 'k':
$bytes *= 1024;
}
return $this->fixIntegerOverflow($bytes);
} | php | protected function getConfigBytes($val)
{
$val = trim($val);
$bytes = (int)(substr($val, 0, -1));
$last = strtolower($val[strlen($val) - 1]);
switch ($last) {
case 'g':
$bytes *= 1024;
case 'm':
$bytes *= 1024;
case 'k':
$bytes *= 1024;
}
return $this->fixIntegerOverflow($bytes);
} | [
"protected",
"function",
"getConfigBytes",
"(",
"$",
"val",
")",
"{",
"$",
"val",
"=",
"trim",
"(",
"$",
"val",
")",
";",
"$",
"bytes",
"=",
"(",
"int",
")",
"(",
"substr",
"(",
"$",
"val",
",",
"0",
",",
"-",
"1",
")",
")",
";",
"$",
"last",... | Convert size format from PHP config into bytes
@param string $val
@return float | [
"Convert",
"size",
"format",
"from",
"PHP",
"config",
"into",
"bytes"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L519-L535 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.getFilesize | protected function getFilesize($path, $clear_cache = false)
{
if ($clear_cache) {
$this->filesystem->clearStatCache($path);
}
return $this->fixIntegerOverflow($this->filesystem->getFilesize($path));
} | php | protected function getFilesize($path, $clear_cache = false)
{
if ($clear_cache) {
$this->filesystem->clearStatCache($path);
}
return $this->fixIntegerOverflow($this->filesystem->getFilesize($path));
} | [
"protected",
"function",
"getFilesize",
"(",
"$",
"path",
",",
"$",
"clear_cache",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"clear_cache",
")",
"{",
"$",
"this",
"->",
"filesystem",
"->",
"clearStatCache",
"(",
"$",
"path",
")",
";",
"}",
"return",
"$",... | Get size of file
@param string $path
@param boolean $clear_cache
@return float | [
"Get",
"size",
"of",
"file"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L543-L550 |
Gargron/fileupload | src/FileUpload/FileUpload.php | FileUpload.getNewHeaders | protected function getNewHeaders(array $files, $content_range)
{
$headers = [
'pragma' => 'no-cache',
'cache-control' => 'no-store, no-cache, must-revalidate',
'content-disposition' => 'inline; filename="files.json"',
'x-content-type-options' => 'nosniff'
];
if ($content_range && is_object($files[0]) && isset($files[0]->size) && $files[0]->size) {
$headers['range'] = '0-' . ($this->fixIntegerOverflow($files[0]->size) - 1);
}
return $headers;
} | php | protected function getNewHeaders(array $files, $content_range)
{
$headers = [
'pragma' => 'no-cache',
'cache-control' => 'no-store, no-cache, must-revalidate',
'content-disposition' => 'inline; filename="files.json"',
'x-content-type-options' => 'nosniff'
];
if ($content_range && is_object($files[0]) && isset($files[0]->size) && $files[0]->size) {
$headers['range'] = '0-' . ($this->fixIntegerOverflow($files[0]->size) - 1);
}
return $headers;
} | [
"protected",
"function",
"getNewHeaders",
"(",
"array",
"$",
"files",
",",
"$",
"content_range",
")",
"{",
"$",
"headers",
"=",
"[",
"'pragma'",
"=>",
"'no-cache'",
",",
"'cache-control'",
"=>",
"'no-store, no-cache, must-revalidate'",
",",
"'content-disposition'",
... | Generate headers for response
@param array $files
@param array $content_range
@return array | [
"Generate",
"headers",
"for",
"response"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUpload.php#L575-L589 |
Gargron/fileupload | src/FileUpload/FileNameGenerator/Slug.php | Slug.getFileName | public function getFileName($source_name, $type, $tmp_name, $index, $content_range, FileUpload $upload)
{
$this->filesystem = $upload->getFileSystem();
$this->pathresolver = $upload->getPathResolver();
$source_name = $this->getSluggedFileName($source_name);
$uniqueFileName = $this->getUniqueFilename($source_name, $type, $index, $content_range);
return $this->getSluggedFileName($uniqueFileName);
} | php | public function getFileName($source_name, $type, $tmp_name, $index, $content_range, FileUpload $upload)
{
$this->filesystem = $upload->getFileSystem();
$this->pathresolver = $upload->getPathResolver();
$source_name = $this->getSluggedFileName($source_name);
$uniqueFileName = $this->getUniqueFilename($source_name, $type, $index, $content_range);
return $this->getSluggedFileName($uniqueFileName);
} | [
"public",
"function",
"getFileName",
"(",
"$",
"source_name",
",",
"$",
"type",
",",
"$",
"tmp_name",
",",
"$",
"index",
",",
"$",
"content_range",
",",
"FileUpload",
"$",
"upload",
")",
"{",
"$",
"this",
"->",
"filesystem",
"=",
"$",
"upload",
"->",
"... | Get file_name
@param string $source_name
@param string $type
@param string $tmp_name
@param integer $index
@param string $content_range
@param FileUpload $upload
@return string | [
"Get",
"file_name"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileNameGenerator/Slug.php#L41-L50 |
Gargron/fileupload | src/FileUpload/FileNameGenerator/Slug.php | Slug.getUniqueFilename | protected function getUniqueFilename($name, $type, $index, $content_range)
{
while ($this->filesystem->isDir($this->pathresolver->getUploadPath($this->getSluggedFileName($name)))) {
$name = $this->pathresolver->upcountName($name);
}
$uploaded_bytes = Util::fixIntegerOverflow(intval($content_range[1]));
while ($this->filesystem->isFile($this->pathresolver->getUploadPath($this->getSluggedFileName($name)))) {
if ($uploaded_bytes == $this->filesystem->getFilesize($this->pathresolver->getUploadPath($this->getSluggedFileName($name)))) {
break;
}
$name = $this->pathresolver->upcountName($name);
}
return $name;
} | php | protected function getUniqueFilename($name, $type, $index, $content_range)
{
while ($this->filesystem->isDir($this->pathresolver->getUploadPath($this->getSluggedFileName($name)))) {
$name = $this->pathresolver->upcountName($name);
}
$uploaded_bytes = Util::fixIntegerOverflow(intval($content_range[1]));
while ($this->filesystem->isFile($this->pathresolver->getUploadPath($this->getSluggedFileName($name)))) {
if ($uploaded_bytes == $this->filesystem->getFilesize($this->pathresolver->getUploadPath($this->getSluggedFileName($name)))) {
break;
}
$name = $this->pathresolver->upcountName($name);
}
return $name;
} | [
"protected",
"function",
"getUniqueFilename",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"index",
",",
"$",
"content_range",
")",
"{",
"while",
"(",
"$",
"this",
"->",
"filesystem",
"->",
"isDir",
"(",
"$",
"this",
"->",
"pathresolver",
"->",
"getUplo... | Get unique but consistent name
@param string $name
@param string $type
@param integer $index
@param array $content_range
@return string | [
"Get",
"unique",
"but",
"consistent",
"name"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileNameGenerator/Slug.php#L60-L77 |
Gargron/fileupload | src/FileUpload/FileNameGenerator/Slug.php | Slug.getSluggedFileName | public function getSluggedFileName($name)
{
$fileNameExploded = explode(".", $name);
$extension = array_pop($fileNameExploded);
$fileNameExploded = implode(".", $fileNameExploded);
return $this->slugify($fileNameExploded) . "." . $extension;
} | php | public function getSluggedFileName($name)
{
$fileNameExploded = explode(".", $name);
$extension = array_pop($fileNameExploded);
$fileNameExploded = implode(".", $fileNameExploded);
return $this->slugify($fileNameExploded) . "." . $extension;
} | [
"public",
"function",
"getSluggedFileName",
"(",
"$",
"name",
")",
"{",
"$",
"fileNameExploded",
"=",
"explode",
"(",
"\".\"",
",",
"$",
"name",
")",
";",
"$",
"extension",
"=",
"array_pop",
"(",
"$",
"fileNameExploded",
")",
";",
"$",
"fileNameExploded",
... | @param string $name
@return string | [
"@param",
"string",
"$name"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileNameGenerator/Slug.php#L84-L91 |
Gargron/fileupload | src/FileUpload/FileUploadFactory.php | FileUploadFactory.create | public function create($upload, $server)
{
$fileupload = new FileUpload($upload, $server);
$fileupload->setPathResolver($this->pathresolver);
$fileupload->setFileSystem($this->filesystem);
if (null !== $this->fileNameGenerator) {
$fileupload->setFileNameGenerator($this->fileNameGenerator);
}
foreach ($this->validators as $validator) {
$fileupload->addValidator($validator);
}
return $fileupload;
} | php | public function create($upload, $server)
{
$fileupload = new FileUpload($upload, $server);
$fileupload->setPathResolver($this->pathresolver);
$fileupload->setFileSystem($this->filesystem);
if (null !== $this->fileNameGenerator) {
$fileupload->setFileNameGenerator($this->fileNameGenerator);
}
foreach ($this->validators as $validator) {
$fileupload->addValidator($validator);
}
return $fileupload;
} | [
"public",
"function",
"create",
"(",
"$",
"upload",
",",
"$",
"server",
")",
"{",
"$",
"fileupload",
"=",
"new",
"FileUpload",
"(",
"$",
"upload",
",",
"$",
"server",
")",
";",
"$",
"fileupload",
"->",
"setPathResolver",
"(",
"$",
"this",
"->",
"pathre... | Create new instance of FileUpload with the preset modules
@param array $upload
@param array $server
@return FileUpload | [
"Create",
"new",
"instance",
"of",
"FileUpload",
"with",
"the",
"preset",
"modules"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileUploadFactory.php#L61-L75 |
Gargron/fileupload | src/FileUpload/FileNameGenerator/MD5.php | MD5.getFileName | public function getFileName(
$source_name,
$type,
$tmp_name,
$index,
$content_range,
FileUpload $upload
) {
$filename = pathinfo($source_name, PATHINFO_FILENAME);
$extension = pathinfo($source_name, PATHINFO_EXTENSION);
$md5ConcatenatedName = md5($filename) . "." . $extension;
if ($upload->getFileSystem()
->doesFileExist(
$upload->getPathResolver()->getUploadPath($md5ConcatenatedName)
) &&
$this->allowDuplicate === false
) {
$upload->getFileContainer()->error = "File already exist in the upload directory.
Please upload another file or change it's name";
return false;
}
return $md5ConcatenatedName;
} | php | public function getFileName(
$source_name,
$type,
$tmp_name,
$index,
$content_range,
FileUpload $upload
) {
$filename = pathinfo($source_name, PATHINFO_FILENAME);
$extension = pathinfo($source_name, PATHINFO_EXTENSION);
$md5ConcatenatedName = md5($filename) . "." . $extension;
if ($upload->getFileSystem()
->doesFileExist(
$upload->getPathResolver()->getUploadPath($md5ConcatenatedName)
) &&
$this->allowDuplicate === false
) {
$upload->getFileContainer()->error = "File already exist in the upload directory.
Please upload another file or change it's name";
return false;
}
return $md5ConcatenatedName;
} | [
"public",
"function",
"getFileName",
"(",
"$",
"source_name",
",",
"$",
"type",
",",
"$",
"tmp_name",
",",
"$",
"index",
",",
"$",
"content_range",
",",
"FileUpload",
"$",
"upload",
")",
"{",
"$",
"filename",
"=",
"pathinfo",
"(",
"$",
"source_name",
","... | Generate the md5 name of a file
@param string $source_name
@param string $type
@param string $tmp_name
@param integer $index
@param string $content_range
@param FileUpload $upload
@return bool|string if $allowDuplicate is set to false and a file with the same Md5'd name exists in the upload
directory, then a bool is returned. | [
"Generate",
"the",
"md5",
"name",
"of",
"a",
"file"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/FileNameGenerator/MD5.php#L37-L63 |
Gargron/fileupload | src/FileUpload/Validator/Simple.php | Simple.setMaxSize | public function setMaxSize($max_size)
{
if (is_numeric($max_size)) {
$this->max_size = $max_size;
} else {
$this->max_size = Util::humanReadableToBytes($max_size);
}
if ($this->max_size < 0 || $this->max_size == null) {
throw new \Exception('invalid max_size value');
}
} | php | public function setMaxSize($max_size)
{
if (is_numeric($max_size)) {
$this->max_size = $max_size;
} else {
$this->max_size = Util::humanReadableToBytes($max_size);
}
if ($this->max_size < 0 || $this->max_size == null) {
throw new \Exception('invalid max_size value');
}
} | [
"public",
"function",
"setMaxSize",
"(",
"$",
"max_size",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"max_size",
")",
")",
"{",
"$",
"this",
"->",
"max_size",
"=",
"$",
"max_size",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"max_size",
"=",
"Util",
... | Sets the max file size
@param mixed $max_size
@throws \Exception if the max_size value is invalid | [
"Sets",
"the",
"max",
"file",
"size"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/Validator/Simple.php#L49-L61 |
Gargron/fileupload | src/FileUpload/Validator/Simple.php | Simple.setErrorMessages | public function setErrorMessages(array $new_messages)
{
foreach ($new_messages as $key => $value) {
$this->messages[$key] = $value;
}
} | php | public function setErrorMessages(array $new_messages)
{
foreach ($new_messages as $key => $value) {
$this->messages[$key] = $value;
}
} | [
"public",
"function",
"setErrorMessages",
"(",
"array",
"$",
"new_messages",
")",
"{",
"foreach",
"(",
"$",
"new_messages",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"messages",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/Validator/Simple.php#L66-L71 |
Gargron/fileupload | src/FileUpload/Validator/Simple.php | Simple.validate | public function validate(File $file, $current_size = null)
{
if (! empty($this->allowed_types)) {
if (! in_array($file->getMimeType(), $this->allowed_types)) {
$file->error = $this->messages[self::UPLOAD_ERR_BAD_TYPE];
return false;
}
}
if ($file->getSize() > $this->max_size || $current_size > $this->max_size) {
$file->error = $this->messages[self::UPLOAD_ERR_TOO_LARGE];
return false;
}
return true;
} | php | public function validate(File $file, $current_size = null)
{
if (! empty($this->allowed_types)) {
if (! in_array($file->getMimeType(), $this->allowed_types)) {
$file->error = $this->messages[self::UPLOAD_ERR_BAD_TYPE];
return false;
}
}
if ($file->getSize() > $this->max_size || $current_size > $this->max_size) {
$file->error = $this->messages[self::UPLOAD_ERR_TOO_LARGE];
return false;
}
return true;
} | [
"public",
"function",
"validate",
"(",
"File",
"$",
"file",
",",
"$",
"current_size",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"allowed_types",
")",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"file",
"->",
"getMi... | {@inheritdoc} | [
"{"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/Validator/Simple.php#L76-L93 |
Gargron/fileupload | src/FileUpload/Validator/MimeTypeValidator.php | MimeTypeValidator.validate | public function validate(File $file, $currentSize = null)
{
if (! in_array($file->getMimeType(), $this->mimeTypes)) {
$this->isValid = false;
$file->error = $this->errorMessages[self::INVALID_MIMETYPE];
}
return $this->isValid;
} | php | public function validate(File $file, $currentSize = null)
{
if (! in_array($file->getMimeType(), $this->mimeTypes)) {
$this->isValid = false;
$file->error = $this->errorMessages[self::INVALID_MIMETYPE];
}
return $this->isValid;
} | [
"public",
"function",
"validate",
"(",
"File",
"$",
"file",
",",
"$",
"currentSize",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"file",
"->",
"getMimeType",
"(",
")",
",",
"$",
"this",
"->",
"mimeTypes",
")",
")",
"{",
"$",
"this"... | {@inheritdoc} | [
"{"
] | train | https://github.com/Gargron/fileupload/blob/1b7327f62e6d61bd56a3a5dc079af06d084efd39/src/FileUpload/Validator/MimeTypeValidator.php#L52-L60 |
sonata-project/cache | src/Adapter/Cache/MongoCache.php | MongoCache.flush | public function flush(array $keys = []): bool
{
$result = $this->getCollection()->remove($keys, [
'w' => 1,
]);
return 1 === $result['ok'] && null === $result['err'];
} | php | public function flush(array $keys = []): bool
{
$result = $this->getCollection()->remove($keys, [
'w' => 1,
]);
return 1 === $result['ok'] && null === $result['err'];
} | [
"public",
"function",
"flush",
"(",
"array",
"$",
"keys",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"remove",
"(",
"$",
"keys",
",",
"[",
"'w'",
"=>",
"1",
",",
"]",
")",
";",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MongoCache.php#L51-L58 |
sonata-project/cache | src/Adapter/Cache/MongoCache.php | MongoCache.set | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$time = time();
$cacheElement = new CacheElement($keys, $data, $ttl, $contextualKeys);
$keys = $cacheElement->getContextualKeys() + $cacheElement->getKeys();
$keys['_value'] = new \MongoBinData(serialize($cacheElement), \MongoBinData::BYTE_ARRAY);
$keys['_updated_at'] = $time;
$keys['_timeout'] = $time + $cacheElement->getTtl();
$this->getCollection()->save($keys);
return $cacheElement;
} | php | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$time = time();
$cacheElement = new CacheElement($keys, $data, $ttl, $contextualKeys);
$keys = $cacheElement->getContextualKeys() + $cacheElement->getKeys();
$keys['_value'] = new \MongoBinData(serialize($cacheElement), \MongoBinData::BYTE_ARRAY);
$keys['_updated_at'] = $time;
$keys['_timeout'] = $time + $cacheElement->getTtl();
$this->getCollection()->save($keys);
return $cacheElement;
} | [
"public",
"function",
"set",
"(",
"array",
"$",
"keys",
",",
"$",
"data",
",",
"int",
"$",
"ttl",
"=",
"CacheElement",
"::",
"DAY",
",",
"array",
"$",
"contextualKeys",
"=",
"[",
"]",
")",
":",
"CacheElementInterface",
"{",
"$",
"time",
"=",
"time",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MongoCache.php#L87-L101 |
sonata-project/cache | src/Adapter/Cache/MongoCache.php | MongoCache.get | public function get(array $keys): CacheElementInterface
{
$record = $this->getRecord($keys);
return $this->handleGet($keys, $record ? unserialize($record['_value']->bin) : null);
} | php | public function get(array $keys): CacheElementInterface
{
$record = $this->getRecord($keys);
return $this->handleGet($keys, $record ? unserialize($record['_value']->bin) : null);
} | [
"public",
"function",
"get",
"(",
"array",
"$",
"keys",
")",
":",
"CacheElementInterface",
"{",
"$",
"record",
"=",
"$",
"this",
"->",
"getRecord",
"(",
"$",
"keys",
")",
";",
"return",
"$",
"this",
"->",
"handleGet",
"(",
"$",
"keys",
",",
"$",
"rec... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MongoCache.php#L106-L111 |
sonata-project/cache | src/Adapter/Cache/MongoCache.php | MongoCache.getRecord | private function getRecord(array $keys)
{
$keys['_timeout'] = ['$gt' => time()];
$results = $this->getCollection()->find($keys);
if ($results->hasNext()) {
return $results->getNext();
}
} | php | private function getRecord(array $keys)
{
$keys['_timeout'] = ['$gt' => time()];
$results = $this->getCollection()->find($keys);
if ($results->hasNext()) {
return $results->getNext();
}
} | [
"private",
"function",
"getRecord",
"(",
"array",
"$",
"keys",
")",
"{",
"$",
"keys",
"[",
"'_timeout'",
"]",
"=",
"[",
"'$gt'",
"=>",
"time",
"(",
")",
"]",
";",
"$",
"results",
"=",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"find",
"(",... | @param array $keys
@return array|null | [
"@param",
"array",
"$keys"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MongoCache.php#L144-L153 |
sonata-project/cache | src/Adapter/Cache/OpCodeCache.php | OpCodeCache.flushAll | public function flushAll(): bool
{
if ($this->currentOnly) {
if (version_compare(PHP_VERSION, '5.5.0', '>=') && \function_exists('opcache_reset')) {
opcache_reset();
}
if (\function_exists('apc_clear_cache')) {
apc_clear_cache('user') && apc_clear_cache();
}
return true;
}
$result = true;
foreach ($this->servers as $server) {
if (4 === \count(explode('.', $server['ip']))) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
} else {
$socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
}
// generate the raw http request
$command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl());
$command .= sprintf("Host: %s\r\n", $server['domain']);
if ($server['basic']) {
$command .= sprintf("Authorization: Basic %s\r\n", $server['basic']);
}
$command .= "Connection: Close\r\n\r\n";
// setup the default timeout (avoid max execution time)
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $this->timeout['SND']);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $this->timeout['RCV']);
socket_connect($socket, $server['ip'], $server['port']);
socket_write($socket, $command);
$content = '';
do {
$buffer = socket_read($socket, 1024);
$content .= $buffer;
} while (!empty($buffer));
if ($result) {
$result = 'ok' === substr($content, -2);
}
}
return $result;
} | php | public function flushAll(): bool
{
if ($this->currentOnly) {
if (version_compare(PHP_VERSION, '5.5.0', '>=') && \function_exists('opcache_reset')) {
opcache_reset();
}
if (\function_exists('apc_clear_cache')) {
apc_clear_cache('user') && apc_clear_cache();
}
return true;
}
$result = true;
foreach ($this->servers as $server) {
if (4 === \count(explode('.', $server['ip']))) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
} else {
$socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
}
// generate the raw http request
$command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl());
$command .= sprintf("Host: %s\r\n", $server['domain']);
if ($server['basic']) {
$command .= sprintf("Authorization: Basic %s\r\n", $server['basic']);
}
$command .= "Connection: Close\r\n\r\n";
// setup the default timeout (avoid max execution time)
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $this->timeout['SND']);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $this->timeout['RCV']);
socket_connect($socket, $server['ip'], $server['port']);
socket_write($socket, $command);
$content = '';
do {
$buffer = socket_read($socket, 1024);
$content .= $buffer;
} while (!empty($buffer));
if ($result) {
$result = 'ok' === substr($content, -2);
}
}
return $result;
} | [
"public",
"function",
"flushAll",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"currentOnly",
")",
"{",
"if",
"(",
"version_compare",
"(",
"PHP_VERSION",
",",
"'5.5.0'",
",",
"'>='",
")",
"&&",
"\\",
"function_exists",
"(",
"'opcache_reset'",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/OpCodeCache.php#L91-L144 |
sonata-project/cache | src/Adapter/Cache/OpCodeCache.php | OpCodeCache.flush | public function flush(array $keys = []): bool
{
if ($this->currentOnly) {
$this->checkApc();
return apc_delete($this->computeCacheKeys($keys));
}
return $this->flushAll();
} | php | public function flush(array $keys = []): bool
{
if ($this->currentOnly) {
$this->checkApc();
return apc_delete($this->computeCacheKeys($keys));
}
return $this->flushAll();
} | [
"public",
"function",
"flush",
"(",
"array",
"$",
"keys",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"currentOnly",
")",
"{",
"$",
"this",
"->",
"checkApc",
"(",
")",
";",
"return",
"apc_delete",
"(",
"$",
"this",
"->",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/OpCodeCache.php#L149-L158 |
sonata-project/cache | src/Adapter/Cache/OpCodeCache.php | OpCodeCache.set | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$this->checkApc();
$cacheElement = new CacheElement($keys, $data, $ttl);
apc_store(
$this->computeCacheKeys($keys),
$cacheElement,
$cacheElement->getTtl()
);
return $cacheElement;
} | php | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$this->checkApc();
$cacheElement = new CacheElement($keys, $data, $ttl);
apc_store(
$this->computeCacheKeys($keys),
$cacheElement,
$cacheElement->getTtl()
);
return $cacheElement;
} | [
"public",
"function",
"set",
"(",
"array",
"$",
"keys",
",",
"$",
"data",
",",
"int",
"$",
"ttl",
"=",
"CacheElement",
"::",
"DAY",
",",
"array",
"$",
"contextualKeys",
"=",
"[",
"]",
")",
":",
"CacheElementInterface",
"{",
"$",
"this",
"->",
"checkApc... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/OpCodeCache.php#L173-L186 |
sonata-project/cache | src/Adapter/Cache/OpCodeCache.php | OpCodeCache.get | public function get(array $keys): CacheElementInterface
{
$this->checkApc();
return $this->handleGet($keys, apc_fetch($this->computeCacheKeys($keys)));
} | php | public function get(array $keys): CacheElementInterface
{
$this->checkApc();
return $this->handleGet($keys, apc_fetch($this->computeCacheKeys($keys)));
} | [
"public",
"function",
"get",
"(",
"array",
"$",
"keys",
")",
":",
"CacheElementInterface",
"{",
"$",
"this",
"->",
"checkApc",
"(",
")",
";",
"return",
"$",
"this",
"->",
"handleGet",
"(",
"$",
"keys",
",",
"apc_fetch",
"(",
"$",
"this",
"->",
"compute... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/OpCodeCache.php#L191-L196 |
sonata-project/cache | src/Invalidation/DoctrineORMListener.php | DoctrineORMListener.flush | protected function flush(LifecycleEventArgs $args): void
{
$identifier = $this->collectionIdentifiers->getIdentifier($args->getEntity());
if (false === $identifier) {
return;
}
$parameters = [
ClassUtils::getClass($args->getEntity()) => $identifier,
];
foreach ($this->caches as $cache) {
$cache->flush($parameters);
}
} | php | protected function flush(LifecycleEventArgs $args): void
{
$identifier = $this->collectionIdentifiers->getIdentifier($args->getEntity());
if (false === $identifier) {
return;
}
$parameters = [
ClassUtils::getClass($args->getEntity()) => $identifier,
];
foreach ($this->caches as $cache) {
$cache->flush($parameters);
}
} | [
"protected",
"function",
"flush",
"(",
"LifecycleEventArgs",
"$",
"args",
")",
":",
"void",
"{",
"$",
"identifier",
"=",
"$",
"this",
"->",
"collectionIdentifiers",
"->",
"getIdentifier",
"(",
"$",
"args",
"->",
"getEntity",
"(",
")",
")",
";",
"if",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Invalidation/DoctrineORMListener.php#L83-L98 |
sonata-project/cache | src/CacheElement.php | CacheElement.getExpirationDate | public function getExpirationDate(): \DateTimeInterface
{
if ($this->isExpired()) {
return new \DateTime();
}
$date = clone $this->createdAt;
$date = $date->add(new \DateInterval(sprintf('PT%sS', $this->ttl)));
return $date;
} | php | public function getExpirationDate(): \DateTimeInterface
{
if ($this->isExpired()) {
return new \DateTime();
}
$date = clone $this->createdAt;
$date = $date->add(new \DateInterval(sprintf('PT%sS', $this->ttl)));
return $date;
} | [
"public",
"function",
"getExpirationDate",
"(",
")",
":",
"\\",
"DateTimeInterface",
"{",
"if",
"(",
"$",
"this",
"->",
"isExpired",
"(",
")",
")",
"{",
"return",
"new",
"\\",
"DateTime",
"(",
")",
";",
"}",
"$",
"date",
"=",
"clone",
"$",
"this",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/CacheElement.php#L101-L111 |
sonata-project/cache | src/CacheManager.php | CacheManager.addCacheService | public function addCacheService(string $name, CacheAdapterInterface $cacheManager): void
{
$this->cacheServices[$name] = $cacheManager;
} | php | public function addCacheService(string $name, CacheAdapterInterface $cacheManager): void
{
$this->cacheServices[$name] = $cacheManager;
} | [
"public",
"function",
"addCacheService",
"(",
"string",
"$",
"name",
",",
"CacheAdapterInterface",
"$",
"cacheManager",
")",
":",
"void",
"{",
"$",
"this",
"->",
"cacheServices",
"[",
"$",
"name",
"]",
"=",
"$",
"cacheManager",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/CacheManager.php#L51-L54 |
sonata-project/cache | src/CacheManager.php | CacheManager.getCacheService | public function getCacheService(string $name): CacheAdapterInterface
{
if (!$this->hasCacheService($name)) {
throw new \RuntimeException(sprintf('The cache service %s does not exist.', $name));
}
return $this->cacheServices[$name];
} | php | public function getCacheService(string $name): CacheAdapterInterface
{
if (!$this->hasCacheService($name)) {
throw new \RuntimeException(sprintf('The cache service %s does not exist.', $name));
}
return $this->cacheServices[$name];
} | [
"public",
"function",
"getCacheService",
"(",
"string",
"$",
"name",
")",
":",
"CacheAdapterInterface",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasCacheService",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/CacheManager.php#L59-L66 |
sonata-project/cache | src/CacheManager.php | CacheManager.hasCacheService | public function hasCacheService(string $id): bool
{
return isset($this->cacheServices[$id]) ? true : false;
} | php | public function hasCacheService(string $id): bool
{
return isset($this->cacheServices[$id]) ? true : false;
} | [
"public",
"function",
"hasCacheService",
"(",
"string",
"$",
"id",
")",
":",
"bool",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"cacheServices",
"[",
"$",
"id",
"]",
")",
"?",
"true",
":",
"false",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/CacheManager.php#L79-L82 |
sonata-project/cache | src/Adapter/Cache/PRedisCache.php | PRedisCache.flushAll | public function flushAll(): bool
{
$command = $this->getClient()->createCommand('flushdb');
$connection = $this->getClient()->getConnection();
if ($connection instanceof PredisCluster) {
foreach ($connection->executeCommandOnNodes($command) as $status) {
if (!$status) {
return false;
}
}
return true;
}
return $this->getClient()->executeCommand($command);
} | php | public function flushAll(): bool
{
$command = $this->getClient()->createCommand('flushdb');
$connection = $this->getClient()->getConnection();
if ($connection instanceof PredisCluster) {
foreach ($connection->executeCommandOnNodes($command) as $status) {
if (!$status) {
return false;
}
}
return true;
}
return $this->getClient()->executeCommand($command);
} | [
"public",
"function",
"flushAll",
"(",
")",
":",
"bool",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"createCommand",
"(",
"'flushdb'",
")",
";",
"$",
"connection",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"g... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/PRedisCache.php#L45-L61 |
sonata-project/cache | src/Adapter/Cache/PRedisCache.php | PRedisCache.flush | public function flush(array $keys = []): bool
{
$this->getClient()->del($this->computeCacheKeys($keys));
// http://redis.io/commands/del
// it is not possible to know is the command succeed as the del command returns
// the number of row deleted.
// we can flush an non existant row
return true;
} | php | public function flush(array $keys = []): bool
{
$this->getClient()->del($this->computeCacheKeys($keys));
// http://redis.io/commands/del
// it is not possible to know is the command succeed as the del command returns
// the number of row deleted.
// we can flush an non existant row
return true;
} | [
"public",
"function",
"flush",
"(",
"array",
"$",
"keys",
"=",
"[",
"]",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"del",
"(",
"$",
"this",
"->",
"computeCacheKeys",
"(",
"$",
"keys",
")",
")",
";",
"// http://redis.io/co... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/PRedisCache.php#L66-L76 |
sonata-project/cache | src/Adapter/Cache/PRedisCache.php | PRedisCache.set | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$cacheElement = new CacheElement($keys, $data, $ttl);
$key = $this->computeCacheKeys($keys);
$this->getClient()->hset($key, 'sonata__data', serialize($cacheElement));
foreach ($contextualKeys as $name => $value) {
if (!is_scalar($value)) {
$value = serialize($value);
}
$this->getClient()->hset($key, $name, $value);
}
foreach ($keys as $name => $value) {
if (!is_scalar($value)) {
$value = serialize($value);
}
$this->getClient()->hset($key, $name, $value);
}
$this->getClient()->expire($key, $cacheElement->getTtl());
return $cacheElement;
} | php | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$cacheElement = new CacheElement($keys, $data, $ttl);
$key = $this->computeCacheKeys($keys);
$this->getClient()->hset($key, 'sonata__data', serialize($cacheElement));
foreach ($contextualKeys as $name => $value) {
if (!is_scalar($value)) {
$value = serialize($value);
}
$this->getClient()->hset($key, $name, $value);
}
foreach ($keys as $name => $value) {
if (!is_scalar($value)) {
$value = serialize($value);
}
$this->getClient()->hset($key, $name, $value);
}
$this->getClient()->expire($key, $cacheElement->getTtl());
return $cacheElement;
} | [
"public",
"function",
"set",
"(",
"array",
"$",
"keys",
",",
"$",
"data",
",",
"int",
"$",
"ttl",
"=",
"CacheElement",
"::",
"DAY",
",",
"array",
"$",
"contextualKeys",
"=",
"[",
"]",
")",
":",
"CacheElementInterface",
"{",
"$",
"cacheElement",
"=",
"n... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/PRedisCache.php#L89-L116 |
sonata-project/cache | src/Adapter/Cache/PRedisCache.php | PRedisCache.get | public function get(array $keys): CacheElementInterface
{
return $this->handleGet($keys, unserialize($this->getClient()->hget($this->computeCacheKeys($keys), 'sonata__data')));
} | php | public function get(array $keys): CacheElementInterface
{
return $this->handleGet($keys, unserialize($this->getClient()->hget($this->computeCacheKeys($keys), 'sonata__data')));
} | [
"public",
"function",
"get",
"(",
"array",
"$",
"keys",
")",
":",
"CacheElementInterface",
"{",
"return",
"$",
"this",
"->",
"handleGet",
"(",
"$",
"keys",
",",
"unserialize",
"(",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"hget",
"(",
"$",
"this... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/PRedisCache.php#L121-L124 |
sonata-project/cache | src/Adapter/Cache/BaseCacheHandler.php | BaseCacheHandler.handleGet | protected function handleGet(array $keys, $data = null): CacheElementInterface
{
if ($data instanceof CacheElementInterface) {
return $data;
}
return new CacheElement($keys, null, -1000);
} | php | protected function handleGet(array $keys, $data = null): CacheElementInterface
{
if ($data instanceof CacheElementInterface) {
return $data;
}
return new CacheElement($keys, null, -1000);
} | [
"protected",
"function",
"handleGet",
"(",
"array",
"$",
"keys",
",",
"$",
"data",
"=",
"null",
")",
":",
"CacheElementInterface",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"CacheElementInterface",
")",
"{",
"return",
"$",
"data",
";",
"}",
"return",
"new... | @param array $keys
@param mixed $data
@return CacheElementInterface | [
"@param",
"array",
"$keys",
"@param",
"mixed",
"$data"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/BaseCacheHandler.php#L28-L35 |
sonata-project/cache | src/Invalidation/SimpleCacheInvalidation.php | SimpleCacheInvalidation.invalidate | public function invalidate(array $caches, array $keys)
{
foreach ($caches as $cache) {
if (!$cache instanceof CacheAdapterInterface) {
throw new \RuntimeException('The object must implements the CacheAdapterInterface interface');
}
try {
if ($this->logger) {
$this->logger->info(sprintf('[%s] flushing cache keys : %s', __CLASS__, json_encode($keys)));
}
$cache->flush($keys);
} catch (\Exception $e) {
if ($this->logger) {
$this->logger->alert(sprintf('[%s] %s', __CLASS__, $e->getMessage()));
} else {
throw new \RunTimeException('', 0, $e);
}
}
}
return true;
} | php | public function invalidate(array $caches, array $keys)
{
foreach ($caches as $cache) {
if (!$cache instanceof CacheAdapterInterface) {
throw new \RuntimeException('The object must implements the CacheAdapterInterface interface');
}
try {
if ($this->logger) {
$this->logger->info(sprintf('[%s] flushing cache keys : %s', __CLASS__, json_encode($keys)));
}
$cache->flush($keys);
} catch (\Exception $e) {
if ($this->logger) {
$this->logger->alert(sprintf('[%s] %s', __CLASS__, $e->getMessage()));
} else {
throw new \RunTimeException('', 0, $e);
}
}
}
return true;
} | [
"public",
"function",
"invalidate",
"(",
"array",
"$",
"caches",
",",
"array",
"$",
"keys",
")",
"{",
"foreach",
"(",
"$",
"caches",
"as",
"$",
"cache",
")",
"{",
"if",
"(",
"!",
"$",
"cache",
"instanceof",
"CacheAdapterInterface",
")",
"{",
"throw",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Invalidation/SimpleCacheInvalidation.php#L37-L60 |
sonata-project/cache | src/Invalidation/Recorder.php | Recorder.push | public function push(): void
{
$this->stack[$this->current + 1] = $this->stack[$this->current];
++$this->current;
} | php | public function push(): void
{
$this->stack[$this->current + 1] = $this->stack[$this->current];
++$this->current;
} | [
"public",
"function",
"push",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"stack",
"[",
"$",
"this",
"->",
"current",
"+",
"1",
"]",
"=",
"$",
"this",
"->",
"stack",
"[",
"$",
"this",
"->",
"current",
"]",
";",
"++",
"$",
"this",
"->",
"curr... | Add a new elements into the stack. | [
"Add",
"a",
"new",
"elements",
"into",
"the",
"stack",
"."
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Invalidation/Recorder.php#L58-L63 |
sonata-project/cache | src/Invalidation/Recorder.php | Recorder.pop | public function pop()
{
$value = $this->stack[$this->current];
unset($this->stack[$this->current]);
--$this->current;
if ($this->current < 0) {
$this->reset();
}
return $value;
} | php | public function pop()
{
$value = $this->stack[$this->current];
unset($this->stack[$this->current]);
--$this->current;
if ($this->current < 0) {
$this->reset();
}
return $value;
} | [
"public",
"function",
"pop",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"stack",
"[",
"$",
"this",
"->",
"current",
"]",
";",
"unset",
"(",
"$",
"this",
"->",
"stack",
"[",
"$",
"this",
"->",
"current",
"]",
")",
";",
"--",
"$",
"this... | Remove an element from the stack and return it.
@return array | [
"Remove",
"an",
"element",
"from",
"the",
"stack",
"and",
"return",
"it",
"."
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Invalidation/Recorder.php#L70-L83 |
sonata-project/cache | src/Adapter/Counter/ApcCounter.php | ApcCounter.increment | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = apc_inc($this->prefix.'/'.$counter->getName(), $number);
return $this->handleIncrement($value, $counter, $number);
} | php | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = apc_inc($this->prefix.'/'.$counter->getName(), $number);
return $this->handleIncrement($value, $counter, $number);
} | [
"public",
"function",
"increment",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"$",
"value",
"=",
"apc_inc",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/ApcCounter.php#L41-L48 |
sonata-project/cache | src/Adapter/Counter/ApcCounter.php | ApcCounter.decrement | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = apc_dec($this->prefix.'/'.$counter->getName(), $number);
return $this->handleDecrement($value, $counter, $number);
} | php | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = apc_dec($this->prefix.'/'.$counter->getName(), $number);
return $this->handleDecrement($value, $counter, $number);
} | [
"public",
"function",
"decrement",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"$",
"value",
"=",
"apc_dec",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/ApcCounter.php#L53-L60 |
sonata-project/cache | src/Adapter/Counter/ApcCounter.php | ApcCounter.set | public function set(Counter $counter): Counter
{
apc_store($this->prefix.'/'.$counter->getName(), $counter->getValue());
return $counter;
} | php | public function set(Counter $counter): Counter
{
apc_store($this->prefix.'/'.$counter->getName(), $counter->getValue());
return $counter;
} | [
"public",
"function",
"set",
"(",
"Counter",
"$",
"counter",
")",
":",
"Counter",
"{",
"apc_store",
"(",
"$",
"this",
"->",
"prefix",
".",
"'/'",
".",
"$",
"counter",
"->",
"getName",
"(",
")",
",",
"$",
"counter",
"->",
"getValue",
"(",
")",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/ApcCounter.php#L65-L70 |
sonata-project/cache | src/Adapter/Counter/BaseCounter.php | BaseCounter.handleIncrement | protected function handleIncrement($value, Counter $counter, int $number): Counter
{
if (false === $value) {
$counter = $this->set(Counter::create($counter->getName(), $counter->getValue() + $number));
} else {
$counter = Counter::create($counter->getName(), $value);
}
return $counter;
} | php | protected function handleIncrement($value, Counter $counter, int $number): Counter
{
if (false === $value) {
$counter = $this->set(Counter::create($counter->getName(), $counter->getValue() + $number));
} else {
$counter = Counter::create($counter->getName(), $value);
}
return $counter;
} | [
"protected",
"function",
"handleIncrement",
"(",
"$",
"value",
",",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
")",
":",
"Counter",
"{",
"if",
"(",
"false",
"===",
"$",
"value",
")",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"set",
"(",... | @param mixed $value
@param Counter $counter
@param int $number
@return Counter | [
"@param",
"mixed",
"$value",
"@param",
"Counter",
"$counter",
"@param",
"int",
"$number"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/BaseCounter.php#L42-L51 |
sonata-project/cache | src/Adapter/Counter/MemcachedCounter.php | MemcachedCounter.increment | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = $this->getCollection()->increment($this->prefix.'.'.$counter->getName(), $number);
return $this->handleIncrement(0 !== $this->getCollection()->getResultCode() ? false : $value, $counter, $number);
} | php | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = $this->getCollection()->increment($this->prefix.'.'.$counter->getName(), $number);
return $this->handleIncrement(0 !== $this->getCollection()->getResultCode() ? false : $value, $counter, $number);
} | [
"public",
"function",
"increment",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"$",
"value",
"=",
"$",
"this",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MemcachedCounter.php#L39-L46 |
sonata-project/cache | src/Adapter/Counter/MemcachedCounter.php | MemcachedCounter.decrement | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = $this->getCollection()->decrement($this->prefix.'.'.$counter->getName(), $number);
return $this->handleDecrement(0 !== $this->getCollection()->getResultCode() ? false : $value, $counter, $number);
} | php | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$value = $this->getCollection()->decrement($this->prefix.'.'.$counter->getName(), $number);
return $this->handleDecrement(0 !== $this->getCollection()->getResultCode() ? false : $value, $counter, $number);
} | [
"public",
"function",
"decrement",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"$",
"value",
"=",
"$",
"this",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MemcachedCounter.php#L51-L58 |
sonata-project/cache | src/Adapter/Counter/MemcachedCounter.php | MemcachedCounter.set | public function set(Counter $counter): Counter
{
$this->getCollection()->add($this->prefix.'.'.$counter->getName(), $counter->getValue());
return $counter;
} | php | public function set(Counter $counter): Counter
{
$this->getCollection()->add($this->prefix.'.'.$counter->getName(), $counter->getValue());
return $counter;
} | [
"public",
"function",
"set",
"(",
"Counter",
"$",
"counter",
")",
":",
"Counter",
"{",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"prefix",
".",
"'.'",
".",
"$",
"counter",
"->",
"getName",
"(",
")",
",",
"$"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MemcachedCounter.php#L63-L68 |
sonata-project/cache | src/Adapter/Counter/MemcachedCounter.php | MemcachedCounter.get | public function get(string $name): Counter
{
return Counter::create($name, (int) $this->getCollection()->get($this->prefix.'.'.$name));
} | php | public function get(string $name): Counter
{
return Counter::create($name, (int) $this->getCollection()->get($this->prefix.'.'.$name));
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
")",
":",
"Counter",
"{",
"return",
"Counter",
"::",
"create",
"(",
"$",
"name",
",",
"(",
"int",
")",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"pref... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MemcachedCounter.php#L73-L76 |
sonata-project/cache | src/Adapter/Counter/MemcachedCounter.php | MemcachedCounter.getCollection | private function getCollection(): \Memcached
{
if (!$this->collection) {
$this->collection = new \Memcached();
foreach ($this->servers as $server) {
$this->collection->addServer($server['host'], $server['port'], $server['weight']);
}
}
return $this->collection;
} | php | private function getCollection(): \Memcached
{
if (!$this->collection) {
$this->collection = new \Memcached();
foreach ($this->servers as $server) {
$this->collection->addServer($server['host'], $server['port'], $server['weight']);
}
}
return $this->collection;
} | [
"private",
"function",
"getCollection",
"(",
")",
":",
"\\",
"Memcached",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"collection",
")",
"{",
"$",
"this",
"->",
"collection",
"=",
"new",
"\\",
"Memcached",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MemcachedCounter.php#L81-L92 |
sonata-project/cache | src/Adapter/Cache/MemcachedCache.php | MemcachedCache.has | public function has(array $keys): bool
{
return false !== $this->getCollection()->get($this->computeCacheKeys($keys));
} | php | public function has(array $keys): bool
{
return false !== $this->getCollection()->get($this->computeCacheKeys($keys));
} | [
"public",
"function",
"has",
"(",
"array",
"$",
"keys",
")",
":",
"bool",
"{",
"return",
"false",
"!==",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"computeCacheKeys",
"(",
"$",
"keys",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MemcachedCache.php#L56-L59 |
sonata-project/cache | src/Adapter/Cache/MemcachedCache.php | MemcachedCache.set | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$cacheElement = new CacheElement($keys, $data, $ttl);
$this->getCollection()->set(
$this->computeCacheKeys($keys),
$cacheElement,
/*
* The driver does not seems to behave as documented, so we provide a timestamp if the ttl > 30d
* http://code.google.com/p/memcached/wiki/NewProgramming#Cache_Invalidation
*/
$cacheElement->getTtl() + ($cacheElement->getTtl() > 2592000 ? time() : 0)
);
return $cacheElement;
} | php | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
$cacheElement = new CacheElement($keys, $data, $ttl);
$this->getCollection()->set(
$this->computeCacheKeys($keys),
$cacheElement,
/*
* The driver does not seems to behave as documented, so we provide a timestamp if the ttl > 30d
* http://code.google.com/p/memcached/wiki/NewProgramming#Cache_Invalidation
*/
$cacheElement->getTtl() + ($cacheElement->getTtl() > 2592000 ? time() : 0)
);
return $cacheElement;
} | [
"public",
"function",
"set",
"(",
"array",
"$",
"keys",
",",
"$",
"data",
",",
"int",
"$",
"ttl",
"=",
"CacheElement",
"::",
"DAY",
",",
"array",
"$",
"contextualKeys",
"=",
"[",
"]",
")",
":",
"CacheElementInterface",
"{",
"$",
"cacheElement",
"=",
"n... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MemcachedCache.php#L64-L79 |
sonata-project/cache | src/Adapter/Cache/MemcachedCache.php | MemcachedCache.get | public function get(array $keys): CacheElementInterface
{
return $this->handleGet($keys, $this->getCollection()->get($this->computeCacheKeys($keys)));
} | php | public function get(array $keys): CacheElementInterface
{
return $this->handleGet($keys, $this->getCollection()->get($this->computeCacheKeys($keys)));
} | [
"public",
"function",
"get",
"(",
"array",
"$",
"keys",
")",
":",
"CacheElementInterface",
"{",
"return",
"$",
"this",
"->",
"handleGet",
"(",
"$",
"keys",
",",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"compute... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MemcachedCache.php#L84-L87 |
sonata-project/cache | src/Adapter/Cache/MemcachedCache.php | MemcachedCache.computeCacheKeys | private function computeCacheKeys(array $keys): string
{
ksort($keys);
return md5($this->prefix.serialize($keys));
} | php | private function computeCacheKeys(array $keys): string
{
ksort($keys);
return md5($this->prefix.serialize($keys));
} | [
"private",
"function",
"computeCacheKeys",
"(",
"array",
"$",
"keys",
")",
":",
"string",
"{",
"ksort",
"(",
"$",
"keys",
")",
";",
"return",
"md5",
"(",
"$",
"this",
"->",
"prefix",
".",
"serialize",
"(",
"$",
"keys",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/MemcachedCache.php#L116-L121 |
sonata-project/cache | src/Adapter/Cache/NoopCache.php | NoopCache.set | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
return new CacheElement($keys, $data, $ttl, $contextualKeys);
} | php | public function set(array $keys, $data, int $ttl = CacheElement::DAY, array $contextualKeys = []): CacheElementInterface
{
return new CacheElement($keys, $data, $ttl, $contextualKeys);
} | [
"public",
"function",
"set",
"(",
"array",
"$",
"keys",
",",
"$",
"data",
",",
"int",
"$",
"ttl",
"=",
"CacheElement",
"::",
"DAY",
",",
"array",
"$",
"contextualKeys",
"=",
"[",
"]",
")",
":",
"CacheElementInterface",
"{",
"return",
"new",
"CacheElement... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Cache/NoopCache.php#L49-L52 |
sonata-project/cache | src/Adapter/Counter/PRedisCounter.php | PRedisCounter.increment | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
if (null === $this->getClient()->get($counter->getName())) {
$this->getClient()->set($counter->getName(), $value = $counter->getValue() + $number);
} else {
$value = $this->getClient()->incrby($counter->getName(), $number);
}
return Counter::create($counter->getName(), $value);
} | php | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
if (null === $this->getClient()->get($counter->getName())) {
$this->getClient()->set($counter->getName(), $value = $counter->getValue() + $number);
} else {
$value = $this->getClient()->incrby($counter->getName(), $number);
}
return Counter::create($counter->getName(), $value);
} | [
"public",
"function",
"increment",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"if",
"(",
"null",
"===",
"$",
"th... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/PRedisCounter.php#L40-L51 |
sonata-project/cache | src/Adapter/Counter/PRedisCounter.php | PRedisCounter.decrement | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
if (null === $this->getClient()->get($counter->getName())) {
$this->getClient()->set($counter->getName(), $value = $counter->getValue() - $number);
} else {
$value = $this->getClient()->decrby($counter->getName(), $number);
}
return Counter::create($counter->getName(), $value);
} | php | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
if (null === $this->getClient()->get($counter->getName())) {
$this->getClient()->set($counter->getName(), $value = $counter->getValue() - $number);
} else {
$value = $this->getClient()->decrby($counter->getName(), $number);
}
return Counter::create($counter->getName(), $value);
} | [
"public",
"function",
"decrement",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"if",
"(",
"null",
"===",
"$",
"th... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/PRedisCounter.php#L56-L67 |
sonata-project/cache | src/Adapter/Counter/PRedisCounter.php | PRedisCounter.set | public function set(Counter $counter): Counter
{
$this->getClient()->set($counter->getName(), $counter->getValue());
return $counter;
} | php | public function set(Counter $counter): Counter
{
$this->getClient()->set($counter->getName(), $counter->getValue());
return $counter;
} | [
"public",
"function",
"set",
"(",
"Counter",
"$",
"counter",
")",
":",
"Counter",
"{",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"set",
"(",
"$",
"counter",
"->",
"getName",
"(",
")",
",",
"$",
"counter",
"->",
"getValue",
"(",
")",
")",
";",... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/PRedisCounter.php#L72-L77 |
sonata-project/cache | src/Adapter/Counter/PRedisCounter.php | PRedisCounter.get | public function get(string $name): Counter
{
return Counter::create($name, (int) $this->getClient()->get($name));
} | php | public function get(string $name): Counter
{
return Counter::create($name, (int) $this->getClient()->get($name));
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
")",
":",
"Counter",
"{",
"return",
"Counter",
"::",
"create",
"(",
"$",
"name",
",",
"(",
"int",
")",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"get",
"(",
"$",
"name",
")",
")",
";"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/PRedisCounter.php#L82-L85 |
sonata-project/cache | src/Invalidation/ModelCollectionIdentifiers.php | ModelCollectionIdentifiers.getIdentifier | public function getIdentifier($object)
{
$identifier = $this->getMethod($object);
if (!$identifier) {
return false;
}
return \call_user_func([$object, $identifier]);
} | php | public function getIdentifier($object)
{
$identifier = $this->getMethod($object);
if (!$identifier) {
return false;
}
return \call_user_func([$object, $identifier]);
} | [
"public",
"function",
"getIdentifier",
"(",
"$",
"object",
")",
"{",
"$",
"identifier",
"=",
"$",
"this",
"->",
"getMethod",
"(",
"$",
"object",
")",
";",
"if",
"(",
"!",
"$",
"identifier",
")",
"{",
"return",
"false",
";",
"}",
"return",
"\\",
"call... | @param $object
@return bool|mixed | [
"@param",
"$object"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Invalidation/ModelCollectionIdentifiers.php#L44-L53 |
sonata-project/cache | src/Invalidation/ModelCollectionIdentifiers.php | ModelCollectionIdentifiers.getMethod | public function getMethod($object)
{
if (null === $object) {
return false;
}
foreach ($this->classes as $class => $identifier) {
if ($object instanceof $class) {
return $identifier;
}
}
$class = \get_class($object);
if (method_exists($object, 'getCacheIdentifier')) {
$this->addClass($class, 'getCacheIdentifier');
} elseif (method_exists($object, 'getId')) {
$this->addClass($class, 'getId');
} else {
return false;
}
return $this->classes[$class];
} | php | public function getMethod($object)
{
if (null === $object) {
return false;
}
foreach ($this->classes as $class => $identifier) {
if ($object instanceof $class) {
return $identifier;
}
}
$class = \get_class($object);
if (method_exists($object, 'getCacheIdentifier')) {
$this->addClass($class, 'getCacheIdentifier');
} elseif (method_exists($object, 'getId')) {
$this->addClass($class, 'getId');
} else {
return false;
}
return $this->classes[$class];
} | [
"public",
"function",
"getMethod",
"(",
"$",
"object",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"object",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"classes",
"as",
"$",
"class",
"=>",
"$",
"identifier",
")",
"{",
"i... | @param $object
@return mixed | [
"@param",
"$object"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Invalidation/ModelCollectionIdentifiers.php#L60-L83 |
sonata-project/cache | src/Adapter/Counter/MongoCounter.php | MongoCounter.increment | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$result = $this->getCollection()->findAndModify(
['counter' => $counter->getName()],
['$inc' => ['value' => $number]],
[],
['new' => true]
);
return $this->handleIncrement(0 === \count($result) ? false : $result['value'], $counter, $number);
} | php | public function increment(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$result = $this->getCollection()->findAndModify(
['counter' => $counter->getName()],
['$inc' => ['value' => $number]],
[],
['new' => true]
);
return $this->handleIncrement(0 === \count($result) ? false : $result['value'], $counter, $number);
} | [
"public",
"function",
"increment",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"$",
"result",
"=",
"$",
"this",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MongoCounter.php#L43-L55 |
sonata-project/cache | src/Adapter/Counter/MongoCounter.php | MongoCounter.decrement | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$result = $this->getCollection()->findAndModify(
['counter' => $counter->getName()],
['$inc' => ['value' => -1 * $number]],
[],
['new' => true]
);
return $this->handleDecrement(0 === \count($result) ? false : $result['value'], $counter, $number);
} | php | public function decrement(Counter $counter, int $number = 1): Counter
{
$counter = $this->transform($counter);
$result = $this->getCollection()->findAndModify(
['counter' => $counter->getName()],
['$inc' => ['value' => -1 * $number]],
[],
['new' => true]
);
return $this->handleDecrement(0 === \count($result) ? false : $result['value'], $counter, $number);
} | [
"public",
"function",
"decrement",
"(",
"Counter",
"$",
"counter",
",",
"int",
"$",
"number",
"=",
"1",
")",
":",
"Counter",
"{",
"$",
"counter",
"=",
"$",
"this",
"->",
"transform",
"(",
"$",
"counter",
")",
";",
"$",
"result",
"=",
"$",
"this",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MongoCounter.php#L60-L72 |
sonata-project/cache | src/Adapter/Counter/MongoCounter.php | MongoCounter.set | public function set(Counter $counter): Counter
{
$result = $this->getCollection()->findAndModify(
['counter' => $counter->getName()],
['$setOnInsert' => ['value' => $counter->getValue()]],
[],
['upsert' => true, 'new' => true]
);
return Counter::create($counter->getName(), $result['value']);
} | php | public function set(Counter $counter): Counter
{
$result = $this->getCollection()->findAndModify(
['counter' => $counter->getName()],
['$setOnInsert' => ['value' => $counter->getValue()]],
[],
['upsert' => true, 'new' => true]
);
return Counter::create($counter->getName(), $result['value']);
} | [
"public",
"function",
"set",
"(",
"Counter",
"$",
"counter",
")",
":",
"Counter",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"findAndModify",
"(",
"[",
"'counter'",
"=>",
"$",
"counter",
"->",
"getName",
"(",
")",
"]",... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MongoCounter.php#L77-L87 |
sonata-project/cache | src/Adapter/Counter/MongoCounter.php | MongoCounter.get | public function get(string $name): Counter
{
$result = $this->getCollection()->findOne(['counter' => $name]);
return Counter::create($name, $result ? (int) $result['value'] : 0);
} | php | public function get(string $name): Counter
{
$result = $this->getCollection()->findOne(['counter' => $name]);
return Counter::create($name, $result ? (int) $result['value'] : 0);
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"name",
")",
":",
"Counter",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"getCollection",
"(",
")",
"->",
"findOne",
"(",
"[",
"'counter'",
"=>",
"$",
"name",
"]",
")",
";",
"return",
"Counter",
"::",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/cache/blob/6e3e327d9d43ff125221552c7e4014bf6c09f7e4/src/Adapter/Counter/MongoCounter.php#L92-L97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.