repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
davestewart/laravel-sketchpad | src/utils/Html.php | Html.md | public static function md($path, $data = [])
{
// find file
$abspath = preg_match('%^(/|[a-z]:)%i', $path) === 1
? $path
: \View::getFinder()->find($path);
// get contents
$contents = file_get_contents($abspath);
// update values
$data['route'] = app(SketchpadConfig::class)->route;
foreach ($data as $key => $value)
{
$contents = preg_replace('/\{\{\s*' .$key. '\s*\}\}/', $value, $contents);
}
// return
return '<div data-format="markdown">' .$contents. '</div>';
} | php | public static function md($path, $data = [])
{
// find file
$abspath = preg_match('%^(/|[a-z]:)%i', $path) === 1
? $path
: \View::getFinder()->find($path);
// get contents
$contents = file_get_contents($abspath);
// update values
$data['route'] = app(SketchpadConfig::class)->route;
foreach ($data as $key => $value)
{
$contents = preg_replace('/\{\{\s*' .$key. '\s*\}\}/', $value, $contents);
}
// return
return '<div data-format="markdown">' .$contents. '</div>';
} | [
"public",
"static",
"function",
"md",
"(",
"$",
"path",
",",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"// find file",
"$",
"abspath",
"=",
"preg_match",
"(",
"'%^(/|[a-z]:)%i'",
",",
"$",
"path",
")",
"===",
"1",
"?",
"$",
"path",
":",
"\\",
"View",
"... | Loads a Markdown file, and instructs Sketchpad to transform it in the front end
@param string $path An absolute or relative file reference
@param array $data
@return string | [
"Loads",
"a",
"Markdown",
"file",
"and",
"instructs",
"Sketchpad",
"to",
"transform",
"it",
"in",
"the",
"front",
"end"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Html.php#L310-L329 | train |
davestewart/laravel-sketchpad | src/utils/Html.php | Html.vue | public static function vue($path, array $data = null)
{
$path = \View::getFinder()->find($path);
$str = file_get_contents($path);
if($data)
{
$tag1 = '<scr'.'ipt>';
$tag2 = '</scr'.'ipt>';
$json = json_encode($data);
$str = str_replace($tag1, $tag1 . "(function () {\n\tvar \$data = $json;", $str);
$str = str_replace($tag2, '}())' . $tag2, $str);
}
return $str;
} | php | public static function vue($path, array $data = null)
{
$path = \View::getFinder()->find($path);
$str = file_get_contents($path);
if($data)
{
$tag1 = '<scr'.'ipt>';
$tag2 = '</scr'.'ipt>';
$json = json_encode($data);
$str = str_replace($tag1, $tag1 . "(function () {\n\tvar \$data = $json;", $str);
$str = str_replace($tag2, '}())' . $tag2, $str);
}
return $str;
} | [
"public",
"static",
"function",
"vue",
"(",
"$",
"path",
",",
"array",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"path",
"=",
"\\",
"View",
"::",
"getFinder",
"(",
")",
"->",
"find",
"(",
"$",
"path",
")",
";",
"$",
"str",
"=",
"file_get_contents",
... | Loads a Vue file and optionally injects data into it
@param string $path
@param mixed $data
@return string | [
"Loads",
"a",
"Vue",
"file",
"and",
"optionally",
"injects",
"data",
"into",
"it"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Html.php#L338-L351 | train |
davestewart/laravel-sketchpad | src/help/docs/MethodsController.php | MethodsController.run | public function run()
{
list($s, $m) = explode(".", microtime(true));
$date = date('H:i:s', $s) . '.' . $m;
return view('sketchpad::help/methods/run', compact('date'));
} | php | public function run()
{
list($s, $m) = explode(".", microtime(true));
$date = date('H:i:s', $s) . '.' . $m;
return view('sketchpad::help/methods/run', compact('date'));
} | [
"public",
"function",
"run",
"(",
")",
"{",
"list",
"(",
"$",
"s",
",",
"$",
"m",
")",
"=",
"explode",
"(",
"\".\"",
",",
"microtime",
"(",
"true",
")",
")",
";",
"$",
"date",
"=",
"date",
"(",
"'H:i:s'",
",",
"$",
"s",
")",
".",
"'.'",
".",
... | Run a method just by clicking on its label
@group Execution | [
"Run",
"a",
"method",
"just",
"by",
"clicking",
"on",
"its",
"label"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/MethodsController.php#L27-L33 | train |
davestewart/laravel-sketchpad | src/help/docs/MethodsController.php | MethodsController.variables | public function variables(SketchpadConfig $config)
{
$route = $config->route;
$views = $config->views;
$fullroute = Sketchpad::$route;
return view('sketchpad::help/methods/variables', compact('route', 'fullroute', 'views'));
} | php | public function variables(SketchpadConfig $config)
{
$route = $config->route;
$views = $config->views;
$fullroute = Sketchpad::$route;
return view('sketchpad::help/methods/variables', compact('route', 'fullroute', 'views'));
} | [
"public",
"function",
"variables",
"(",
"SketchpadConfig",
"$",
"config",
")",
"{",
"$",
"route",
"=",
"$",
"config",
"->",
"route",
";",
"$",
"views",
"=",
"$",
"config",
"->",
"views",
";",
"$",
"fullroute",
"=",
"Sketchpad",
"::",
"$",
"route",
";",... | Sketchpad makes a few classes and variables available to you | [
"Sketchpad",
"makes",
"a",
"few",
"classes",
"and",
"variables",
"available",
"to",
"you"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/MethodsController.php#L96-L102 | train |
davestewart/laravel-sketchpad | src/services/Router.php | Router.getCall | public function getCall($route, array $params = [])
{
// variables
$route = AbstractScanner::folderize($route);
$routes = $this->getRoutes();
// debug
// pr($route, $routes);
// first, attempt to find an exact match
// an exact match will either be a controller or a folder
if(isset($routes[$route]))
{
return $routes[$route];
}
// otherwise, the passed path will be at least a "controller/method" in which case,
// we need to find the nearest partial match, then extract the component parts
else
{
// variables
/** @var CallReference $ref */
$ref = null;
// loop over routes and grab matches
// the last full match will be the one that we want
foreach($routes as $key => $value)
{
//pr('KEY', $key, $value);
if(strpos($route, $key) === 0)
{
$ref = $value;
}
}
// debug
//pr('REF', $ref);
// if we got a matching route, update the ref with method and params
if($ref instanceof ControllerReference)
{
return CallReference::fromControllerRef($ref)
->setMethod($route)
->setParams($params);
}
if($ref instanceof ControllerErrorReference)
{
return CallReference::fromRef($ref)
->setMethod($route)
->setParams($params);
}
}
// return
return null;
} | php | public function getCall($route, array $params = [])
{
// variables
$route = AbstractScanner::folderize($route);
$routes = $this->getRoutes();
// debug
// pr($route, $routes);
// first, attempt to find an exact match
// an exact match will either be a controller or a folder
if(isset($routes[$route]))
{
return $routes[$route];
}
// otherwise, the passed path will be at least a "controller/method" in which case,
// we need to find the nearest partial match, then extract the component parts
else
{
// variables
/** @var CallReference $ref */
$ref = null;
// loop over routes and grab matches
// the last full match will be the one that we want
foreach($routes as $key => $value)
{
//pr('KEY', $key, $value);
if(strpos($route, $key) === 0)
{
$ref = $value;
}
}
// debug
//pr('REF', $ref);
// if we got a matching route, update the ref with method and params
if($ref instanceof ControllerReference)
{
return CallReference::fromControllerRef($ref)
->setMethod($route)
->setParams($params);
}
if($ref instanceof ControllerErrorReference)
{
return CallReference::fromRef($ref)
->setMethod($route)
->setParams($params);
}
}
// return
return null;
} | [
"public",
"function",
"getCall",
"(",
"$",
"route",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"// variables",
"$",
"route",
"=",
"AbstractScanner",
"::",
"folderize",
"(",
"$",
"route",
")",
";",
"$",
"routes",
"=",
"$",
"this",
"->",
"ge... | Reverse route lookup
Compares a given route against routes determined when controllers were scanned
Determines the controller, method and parameters to call if there is a match
@param string $route
@param $params
@return ControllerReference|FolderReference|null | [
"Reverse",
"route",
"lookup"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/services/Router.php#L114-L171 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.file | public static function file($path, $format = '')
{
if ($format === '')
{
$format = self::getExtension($path);
}
$text = file_get_contents($path);
return self::output($text, $format);
} | php | public static function file($path, $format = '')
{
if ($format === '')
{
$format = self::getExtension($path);
}
$text = file_get_contents($path);
return self::output($text, $format);
} | [
"public",
"static",
"function",
"file",
"(",
"$",
"path",
",",
"$",
"format",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"format",
"===",
"''",
")",
"{",
"$",
"format",
"=",
"self",
"::",
"getExtension",
"(",
"$",
"path",
")",
";",
"}",
"$",
"text",
... | Output the contents of an entire file
@param string $path
@param string $format
@return string | [
"Output",
"the",
"contents",
"of",
"an",
"entire",
"file"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L29-L37 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.section | public static function section($path, $start = 0, $end = 0, $undent = false)
{
$format = self::getExtension($path);
$text = file_get_contents($path);
if ($start !== 0 || $end !== 0)
{
$text = self::lines($text, $start, $end);
if ($undent)
{
$text = self::undent($text);
}
}
return self::output($text, $format);
} | php | public static function section($path, $start = 0, $end = 0, $undent = false)
{
$format = self::getExtension($path);
$text = file_get_contents($path);
if ($start !== 0 || $end !== 0)
{
$text = self::lines($text, $start, $end);
if ($undent)
{
$text = self::undent($text);
}
}
return self::output($text, $format);
} | [
"public",
"static",
"function",
"section",
"(",
"$",
"path",
",",
"$",
"start",
"=",
"0",
",",
"$",
"end",
"=",
"0",
",",
"$",
"undent",
"=",
"false",
")",
"{",
"$",
"format",
"=",
"self",
"::",
"getExtension",
"(",
"$",
"path",
")",
";",
"$",
... | Output a section of a single file
@param string $path
@param int $start
@param int $end
@param bool $undent
@return string | [
"Output",
"a",
"section",
"of",
"a",
"single",
"file"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L48-L61 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.method | public static function method($class, $method, $comment = false)
{
$ref = new \ReflectionMethod($class, $method);
$start = $ref->getStartLine();
$end = $ref->getEndLine();
$text = file_get_contents($ref->getFileName());
$text = self::lines($text, $start, $end);
$text = self::undent($text);
if ($comment)
{
$text = preg_replace('/^\s+\*/m', ' *', $ref->getDocComment()) . PHP_EOL . $text;
}
return self::output($text, 'php');
} | php | public static function method($class, $method, $comment = false)
{
$ref = new \ReflectionMethod($class, $method);
$start = $ref->getStartLine();
$end = $ref->getEndLine();
$text = file_get_contents($ref->getFileName());
$text = self::lines($text, $start, $end);
$text = self::undent($text);
if ($comment)
{
$text = preg_replace('/^\s+\*/m', ' *', $ref->getDocComment()) . PHP_EOL . $text;
}
return self::output($text, 'php');
} | [
"public",
"static",
"function",
"method",
"(",
"$",
"class",
",",
"$",
"method",
",",
"$",
"comment",
"=",
"false",
")",
"{",
"$",
"ref",
"=",
"new",
"\\",
"ReflectionMethod",
"(",
"$",
"class",
",",
"$",
"method",
")",
";",
"$",
"start",
"=",
"$",... | Output the contents of a method
@param string $class
@param string $method
@param bool $comment
@return string | [
"Output",
"the",
"contents",
"of",
"a",
"method"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L71-L84 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.classfile | public static function classfile($class, $comment = false)
{
$ref = new \ReflectionClass($class);
$start = $ref->getStartLine();
$end = $ref->getEndLine();
$text = file_get_contents($ref->getFileName());
$text = self::lines($text, $start, $end);
if ($comment)
{
$text = preg_replace('/^\s+\*/m', ' *', $ref->getDocComment()) . PHP_EOL . $text;
}
return self::output($text, 'php');
} | php | public static function classfile($class, $comment = false)
{
$ref = new \ReflectionClass($class);
$start = $ref->getStartLine();
$end = $ref->getEndLine();
$text = file_get_contents($ref->getFileName());
$text = self::lines($text, $start, $end);
if ($comment)
{
$text = preg_replace('/^\s+\*/m', ' *', $ref->getDocComment()) . PHP_EOL . $text;
}
return self::output($text, 'php');
} | [
"public",
"static",
"function",
"classfile",
"(",
"$",
"class",
",",
"$",
"comment",
"=",
"false",
")",
"{",
"$",
"ref",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"class",
")",
";",
"$",
"start",
"=",
"$",
"ref",
"->",
"getStartLine",
"(",
")",
... | Output the contents of a class
@param string $class
@param bool $comment
@return string | [
"Output",
"the",
"contents",
"of",
"a",
"class"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L93-L105 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.lines | public static function lines($text, $start, $end)
{
$lines = explode(PHP_EOL, $text);
$code = implode(PHP_EOL, array_slice($lines, $start - 1, $end - $start + 1));
return $code;
} | php | public static function lines($text, $start, $end)
{
$lines = explode(PHP_EOL, $text);
$code = implode(PHP_EOL, array_slice($lines, $start - 1, $end - $start + 1));
return $code;
} | [
"public",
"static",
"function",
"lines",
"(",
"$",
"text",
",",
"$",
"start",
",",
"$",
"end",
")",
"{",
"$",
"lines",
"=",
"explode",
"(",
"PHP_EOL",
",",
"$",
"text",
")",
";",
"$",
"code",
"=",
"implode",
"(",
"PHP_EOL",
",",
"array_slice",
"(",... | Return a range of lines from a block of text
@param string $text
@param int $start
@param int $end
@return string | [
"Return",
"a",
"range",
"of",
"lines",
"from",
"a",
"block",
"of",
"text"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L115-L120 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.signature | public static function signature($args = [])
{
$values = array_map(function ($v) {
return is_string($v)
? "'$v'"
: (is_bool($v)
? !! $v ? 'true' : 'false'
: $v);
}, $args);
return '(' . implode(', ', $values) . ')';
} | php | public static function signature($args = [])
{
$values = array_map(function ($v) {
return is_string($v)
? "'$v'"
: (is_bool($v)
? !! $v ? 'true' : 'false'
: $v);
}, $args);
return '(' . implode(', ', $values) . ')';
} | [
"public",
"static",
"function",
"signature",
"(",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"$",
"values",
"=",
"array_map",
"(",
"function",
"(",
"$",
"v",
")",
"{",
"return",
"is_string",
"(",
"$",
"v",
")",
"?",
"\"'$v'\"",
":",
"(",
"is_bool",
"(",... | Return a formatted function signature
@param array $args
@return string | [
"Return",
"a",
"formatted",
"function",
"signature"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L128-L138 | train |
davestewart/laravel-sketchpad | src/utils/Code.php | Code.undent | public static function undent($text)
{
preg_match('/^\s+/', $text, $matches);
list ($indent) = $matches;
if ($indent)
{
$text = preg_replace("/^$indent/m", '', $text);
}
return $text;
} | php | public static function undent($text)
{
preg_match('/^\s+/', $text, $matches);
list ($indent) = $matches;
if ($indent)
{
$text = preg_replace("/^$indent/m", '', $text);
}
return $text;
} | [
"public",
"static",
"function",
"undent",
"(",
"$",
"text",
")",
"{",
"preg_match",
"(",
"'/^\\s+/'",
",",
"$",
"text",
",",
"$",
"matches",
")",
";",
"list",
"(",
"$",
"indent",
")",
"=",
"$",
"matches",
";",
"if",
"(",
"$",
"indent",
")",
"{",
... | Remove any indent from a block of text, based on the first line
@param string $text
@return string | [
"Remove",
"any",
"indent",
"from",
"a",
"block",
"of",
"text",
"based",
"on",
"the",
"first",
"line"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/utils/Code.php#L146-L155 | train |
davestewart/laravel-sketchpad | src/services/Setup.php | Setup.view | public function view()
{
// default variables
$finder = new Finder();
$finder->start();
// config
$config = app(SketchpadConfig::class);
// base name
$basePath = Paths::fix(base_path('/'));
$baseSegments = explode('/', rtrim($basePath, '/'));
$baseName = array_pop($baseSegments) . '/';
// view path
$viewPaths = Config::get('view.paths');
$viewPath = substr(Paths::fix($viewPaths[0]), strlen($basePath));
// variables
$app = app();
$data =
[
'route' => $config->route,
'assets' => $config->route . 'assets/',
'settings' =>
[
'route' => $config->route,
'basepath' => $basePath,
'basename' => $baseName,
'viewpath' => $viewPath,
'storagepath' => Paths::relative($config->settings->src),
'controllerpath' => trim(Paths::relative($finder->path), '/'),
'namespace' => method_exists($app, 'getNamespace')
? trim($app->getNamespace(), '\\')
: 'App\\',
'namespaces' => (new JSON('composer.json'))->get('autoload.psr-4')
]
];
// return view
return view('sketchpad::setup', $data);
} | php | public function view()
{
// default variables
$finder = new Finder();
$finder->start();
// config
$config = app(SketchpadConfig::class);
// base name
$basePath = Paths::fix(base_path('/'));
$baseSegments = explode('/', rtrim($basePath, '/'));
$baseName = array_pop($baseSegments) . '/';
// view path
$viewPaths = Config::get('view.paths');
$viewPath = substr(Paths::fix($viewPaths[0]), strlen($basePath));
// variables
$app = app();
$data =
[
'route' => $config->route,
'assets' => $config->route . 'assets/',
'settings' =>
[
'route' => $config->route,
'basepath' => $basePath,
'basename' => $baseName,
'viewpath' => $viewPath,
'storagepath' => Paths::relative($config->settings->src),
'controllerpath' => trim(Paths::relative($finder->path), '/'),
'namespace' => method_exists($app, 'getNamespace')
? trim($app->getNamespace(), '\\')
: 'App\\',
'namespaces' => (new JSON('composer.json'))->get('autoload.psr-4')
]
];
// return view
return view('sketchpad::setup', $data);
} | [
"public",
"function",
"view",
"(",
")",
"{",
"// default variables",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"finder",
"->",
"start",
"(",
")",
";",
"// config",
"$",
"config",
"=",
"app",
"(",
"SketchpadConfig",
"::",
"class",
")",
";... | Shows the setup form view
@return mixed | [
"Shows",
"the",
"setup",
"form",
"view"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/services/Setup.php#L44-L85 | train |
davestewart/laravel-sketchpad | src/objects/file/Folder.php | Folder.process | public function process($recursive = false)
{
// reset
$this->folders = [];
$this->controllers = [];
// variables
$files = array_diff(scandir($this->path), ['.', '..']);
// loop
foreach ($files as $file)
{
$path = $this->path . $file;
if(is_dir($path))
{
$this->folders[] = new Folder($path, $recursive);
}
else if(is_file($path) && preg_match('/Controller.php$/', $path))
{
$this->controllers[] = new Controller($path);
}
}
} | php | public function process($recursive = false)
{
// reset
$this->folders = [];
$this->controllers = [];
// variables
$files = array_diff(scandir($this->path), ['.', '..']);
// loop
foreach ($files as $file)
{
$path = $this->path . $file;
if(is_dir($path))
{
$this->folders[] = new Folder($path, $recursive);
}
else if(is_file($path) && preg_match('/Controller.php$/', $path))
{
$this->controllers[] = new Controller($path);
}
}
} | [
"public",
"function",
"process",
"(",
"$",
"recursive",
"=",
"false",
")",
"{",
"// reset\r",
"$",
"this",
"->",
"folders",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"controllers",
"=",
"[",
"]",
";",
"// variables\r",
"$",
"files",
"=",
"array_diff",
"("... | Process contained folders and controllers
@param bool $recursive An optional flag to recursively get child folders | [
"Process",
"contained",
"folders",
"and",
"controllers"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/file/Folder.php#L71-L93 | train |
davestewart/laravel-sketchpad | src/objects/install/FilesystemObject.php | FilesystemObject.makePath | protected function makePath($path)
{
$path = $this->fs->isAbsolutePath($path)
? $path
: base_path($path);
return Paths::fix($path);
} | php | protected function makePath($path)
{
$path = $this->fs->isAbsolutePath($path)
? $path
: base_path($path);
return Paths::fix($path);
} | [
"protected",
"function",
"makePath",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"fs",
"->",
"isAbsolutePath",
"(",
"$",
"path",
")",
"?",
"$",
"path",
":",
"base_path",
"(",
"$",
"path",
")",
";",
"return",
"Paths",
"::",
"fix... | Utility function to return an absolute path from a relative or absolute path
@param $path
@return string | [
"Utility",
"function",
"to",
"return",
"an",
"absolute",
"path",
"from",
"a",
"relative",
"or",
"absolute",
"path"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/install/FilesystemObject.php#L24-L30 | train |
davestewart/laravel-sketchpad | src/config/Paths.php | Paths.make | public static function make($path, $relative = false)
{
return $relative
? Paths::relative($path)
: Paths::fix($path);
} | php | public static function make($path, $relative = false)
{
return $relative
? Paths::relative($path)
: Paths::fix($path);
} | [
"public",
"static",
"function",
"make",
"(",
"$",
"path",
",",
"$",
"relative",
"=",
"false",
")",
"{",
"return",
"$",
"relative",
"?",
"Paths",
"::",
"relative",
"(",
"$",
"path",
")",
":",
"Paths",
"::",
"fix",
"(",
"$",
"path",
")",
";",
"}"
] | Utility method to create a path; fixing and optionally making relative to the base path
@param string $path The path to process
@param bool $relative An optional flag to return the path relative to the base path
@return string The final path | [
"Utility",
"method",
"to",
"create",
"a",
"path",
";",
"fixing",
"and",
"optionally",
"making",
"relative",
"to",
"the",
"base",
"path"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/config/Paths.php#L79-L84 | train |
davestewart/laravel-sketchpad | src/config/Paths.php | Paths.folder | public static function folder($path, $relative = false)
{
$path = Paths::make($path, $relative);
return rtrim($path, '/') . '/';
} | php | public static function folder($path, $relative = false)
{
$path = Paths::make($path, $relative);
return rtrim($path, '/') . '/';
} | [
"public",
"static",
"function",
"folder",
"(",
"$",
"path",
",",
"$",
"relative",
"=",
"false",
")",
"{",
"$",
"path",
"=",
"Paths",
"::",
"make",
"(",
"$",
"path",
",",
"$",
"relative",
")",
";",
"return",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
... | Utility method to return a path with a trailing slash
@param string $path The path to process
@param bool $relative An optional flag to return the path relative to the base path
@return string The final path | [
"Utility",
"method",
"to",
"return",
"a",
"path",
"with",
"a",
"trailing",
"slash"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/config/Paths.php#L104-L108 | train |
davestewart/laravel-sketchpad | src/help/docs/OutputController.php | OutputController.pagination | public function pagination($start = 1, $length = 10)
{
// manually create paginator
$data = array_map(function ($num) {
return ['id' => $num, 'value' => "Item $num"];
}, range(1, 100));
$page = Paginator::resolveCurrentPage('page');
$path = Paginator::resolveCurrentPath();
$items = array_slice($data, abs($start - 1) + (($page - 1) * $length), $length);
$paginator = new LengthAwarePaginator($items, count($data), $length, $page, [
'path' => $path,
'pageName' => 'page',
]);
// append existing parameters
$paginator->appends(Sketchpad::$params);
// output
return view('sketchpad::help/output/pagination', compact('items', 'paginator'));
} | php | public function pagination($start = 1, $length = 10)
{
// manually create paginator
$data = array_map(function ($num) {
return ['id' => $num, 'value' => "Item $num"];
}, range(1, 100));
$page = Paginator::resolveCurrentPage('page');
$path = Paginator::resolveCurrentPath();
$items = array_slice($data, abs($start - 1) + (($page - 1) * $length), $length);
$paginator = new LengthAwarePaginator($items, count($data), $length, $page, [
'path' => $path,
'pageName' => 'page',
]);
// append existing parameters
$paginator->appends(Sketchpad::$params);
// output
return view('sketchpad::help/output/pagination', compact('items', 'paginator'));
} | [
"public",
"function",
"pagination",
"(",
"$",
"start",
"=",
"1",
",",
"$",
"length",
"=",
"10",
")",
"{",
"// manually create paginator",
"$",
"data",
"=",
"array_map",
"(",
"function",
"(",
"$",
"num",
")",
"{",
"return",
"[",
"'id'",
"=>",
"$",
"num"... | Sketchpad is designed to work invisibly with pagination, by preserving URL variables between front and back end
@param int $start
@param int $length | [
"Sketchpad",
"is",
"designed",
"to",
"work",
"invisibly",
"with",
"pagination",
"by",
"preserving",
"URL",
"variables",
"between",
"front",
"and",
"back",
"end"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/OutputController.php#L134-L154 | train |
davestewart/laravel-sketchpad | src/objects/reflection/Comment.php | Comment.getField | public function getField($name)
{
return isset($this->fields[$name])
? $this->fields[$name]
: null;
} | php | public function getField($name)
{
return isset($this->fields[$name])
? $this->fields[$name]
: null;
} | [
"public",
"function",
"getField",
"(",
"$",
"name",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"fields",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"fields",
"[",
"$",
"name",
"]",
":",
"null",
";",
"}"
] | Returns a field by name
@param string $name
@return Field|null | [
"Returns",
"a",
"field",
"by",
"name"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/reflection/Comment.php#L175-L180 | train |
davestewart/laravel-sketchpad | src/objects/reflection/Parameter.php | Parameter.getType | protected function getType($param, $value, $type = null)
{
// attempt to get the type
$type = method_exists($param, 'getType')
? $param->getType()
: $type
? $type
: gettype($value);
// coerce type to something javascript will understand
if($type == 'double' || $type == 'float' || $type == 'integer' || $type == 'int')
{
$type = 'number';
}
else if($type == 'bool')
{
$type = 'boolean';
}
else if($type == 'NULL')
{
$type = 'null';
}
// return
return $type;
} | php | protected function getType($param, $value, $type = null)
{
// attempt to get the type
$type = method_exists($param, 'getType')
? $param->getType()
: $type
? $type
: gettype($value);
// coerce type to something javascript will understand
if($type == 'double' || $type == 'float' || $type == 'integer' || $type == 'int')
{
$type = 'number';
}
else if($type == 'bool')
{
$type = 'boolean';
}
else if($type == 'NULL')
{
$type = 'null';
}
// return
return $type;
} | [
"protected",
"function",
"getType",
"(",
"$",
"param",
",",
"$",
"value",
",",
"$",
"type",
"=",
"null",
")",
"{",
"// attempt to get the type\r",
"$",
"type",
"=",
"method_exists",
"(",
"$",
"param",
",",
"'getType'",
")",
"?",
"$",
"param",
"->",
"getT... | Gets the parameter type
@param ReflectionParameter $param
@param mixed $value
@param string $type
@return string | [
"Gets",
"the",
"parameter",
"type"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/reflection/Parameter.php#L111-L136 | train |
davestewart/laravel-sketchpad | src/controllers/SetupController.php | SetupController.submit | public function submit(Request $request)
{
$input = $request->all();
$state = $this->setup->saveData($input);
$result = [
'step' => 'config',
'success' => $state,
'message' => $state ? 'Config saved OK' : 'Unable to save config',
'data' => $input
];
if($state)
{
return $this->install();
}
return $result;
} | php | public function submit(Request $request)
{
$input = $request->all();
$state = $this->setup->saveData($input);
$result = [
'step' => 'config',
'success' => $state,
'message' => $state ? 'Config saved OK' : 'Unable to save config',
'data' => $input
];
if($state)
{
return $this->install();
}
return $result;
} | [
"public",
"function",
"submit",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"input",
"=",
"$",
"request",
"->",
"all",
"(",
")",
";",
"$",
"state",
"=",
"$",
"this",
"->",
"setup",
"->",
"saveData",
"(",
"$",
"input",
")",
";",
"$",
"result",
... | Handles form data from the setup controller
@method POST
@param Request $request
@return array | [
"Handles",
"form",
"data",
"from",
"the",
"setup",
"controller"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/controllers/SetupController.php#L75-L90 | train |
davestewart/laravel-sketchpad | src/objects/scanners/Scanner.php | Scanner.scan | protected function scan($path = '')
{
// add folder
$this->addFolder($path);
// get elements
$root = AbstractScanner::folderize($this->path . $path);
$els = array_diff(scandir($root), ['.', '..']);
// split elements
$files = [];
$folders = [];
foreach ($els as $el)
{
is_dir($root . $el)
? array_push($folders, $el)
: array_push($files, $el);
}
// get all controllers
$controllers = [];
$ordered = [];
foreach ($files as $file)
{
$abspath = $root . $file;
if($this->isController($abspath))
{
$controller = $this->addController($abspath, $path);
if ($controller)
{
property_exists($controller, 'order') && $controller->order !== 0
? array_push($ordered, $controller)
: array_push($controllers, $controller);
}
}
}
// re-insert ordered controllers
uasort($ordered, function ($a, $b) { return $a->order - $b->order; });
foreach($ordered as $c)
{
array_splice($controllers, $c->order - 1, 0, [$c]);
}
// add controllers
$this->controllers = array_merge($this->controllers, array_values($controllers));
// folders
foreach ($folders as $folder)
{
$relpath = $path . $folder;
$this->scan($relpath . '/');
}
} | php | protected function scan($path = '')
{
// add folder
$this->addFolder($path);
// get elements
$root = AbstractScanner::folderize($this->path . $path);
$els = array_diff(scandir($root), ['.', '..']);
// split elements
$files = [];
$folders = [];
foreach ($els as $el)
{
is_dir($root . $el)
? array_push($folders, $el)
: array_push($files, $el);
}
// get all controllers
$controllers = [];
$ordered = [];
foreach ($files as $file)
{
$abspath = $root . $file;
if($this->isController($abspath))
{
$controller = $this->addController($abspath, $path);
if ($controller)
{
property_exists($controller, 'order') && $controller->order !== 0
? array_push($ordered, $controller)
: array_push($controllers, $controller);
}
}
}
// re-insert ordered controllers
uasort($ordered, function ($a, $b) { return $a->order - $b->order; });
foreach($ordered as $c)
{
array_splice($controllers, $c->order - 1, 0, [$c]);
}
// add controllers
$this->controllers = array_merge($this->controllers, array_values($controllers));
// folders
foreach ($folders as $folder)
{
$relpath = $path . $folder;
$this->scan($relpath . '/');
}
} | [
"protected",
"function",
"scan",
"(",
"$",
"path",
"=",
"''",
")",
"{",
"// add folder",
"$",
"this",
"->",
"addFolder",
"(",
"$",
"path",
")",
";",
"// get elements",
"$",
"root",
"=",
"AbstractScanner",
"::",
"folderize",
"(",
"$",
"this",
"->",
"path"... | Recursively finds all controllers and folders
Sets controllers and folders elements as they are found
@param string $path The sketchpad controllers path-relative path to the folder, i.e. "foo/bar/" | [
"Recursively",
"finds",
"all",
"controllers",
"and",
"folders"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/scanners/Scanner.php#L96-L150 | train |
davestewart/laravel-sketchpad | src/objects/scanners/Scanner.php | Scanner.addFolder | protected function addFolder($path)
{
$route = rtrim($this->route . $path, '/');
$ref = new FolderReference($route, $this->path . $path);
$this->addRoute($route, $ref);
} | php | protected function addFolder($path)
{
$route = rtrim($this->route . $path, '/');
$ref = new FolderReference($route, $this->path . $path);
$this->addRoute($route, $ref);
} | [
"protected",
"function",
"addFolder",
"(",
"$",
"path",
")",
"{",
"$",
"route",
"=",
"rtrim",
"(",
"$",
"this",
"->",
"route",
".",
"$",
"path",
",",
"'/'",
")",
";",
"$",
"ref",
"=",
"new",
"FolderReference",
"(",
"$",
"route",
",",
"$",
"this",
... | Adds a folder to the internal routes array
@param string $path The controller-root relative path to the folder | [
"Adds",
"a",
"folder",
"to",
"the",
"internal",
"routes",
"array"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/scanners/Scanner.php#L157-L162 | train |
davestewart/laravel-sketchpad | src/objects/scanners/Scanner.php | Scanner.addController | protected function addController($abspath, $route)
{
// variables
$name = pathinfo($abspath, PATHINFO_FILENAME);
$segment = preg_replace('/Controller$/', '', $name);
$route = strtolower($this->route . $route . $segment);
// objects
$instance = Controller::fromPath($abspath, $route);
// add
if($instance instanceof Controller)
{
// controller isn't abstract, has methods, isn't private
if ($instance->isValid())
{
$ref = $instance->getReference();
$this->addRoute($route, $ref);
return $instance;
}
}
else
{
$ref = $instance->getReference();
$this->addRoute($route, $ref);
return $instance;
}
} | php | protected function addController($abspath, $route)
{
// variables
$name = pathinfo($abspath, PATHINFO_FILENAME);
$segment = preg_replace('/Controller$/', '', $name);
$route = strtolower($this->route . $route . $segment);
// objects
$instance = Controller::fromPath($abspath, $route);
// add
if($instance instanceof Controller)
{
// controller isn't abstract, has methods, isn't private
if ($instance->isValid())
{
$ref = $instance->getReference();
$this->addRoute($route, $ref);
return $instance;
}
}
else
{
$ref = $instance->getReference();
$this->addRoute($route, $ref);
return $instance;
}
} | [
"protected",
"function",
"addController",
"(",
"$",
"abspath",
",",
"$",
"route",
")",
"{",
"// variables",
"$",
"name",
"=",
"pathinfo",
"(",
"$",
"abspath",
",",
"PATHINFO_FILENAME",
")",
";",
"$",
"segment",
"=",
"preg_replace",
"(",
"'/Controller$/'",
",... | Adds a controller to the internal routes array
@param string $abspath
@param string $route
@return Controller|\davestewart\sketchpad\objects\reflection\ControllerError | [
"Adds",
"a",
"controller",
"to",
"the",
"internal",
"routes",
"array"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/scanners/Scanner.php#L171-L199 | train |
davestewart/laravel-sketchpad | src/objects/install/NamespaceResolver.php | NamespaceResolver.loadNamespaces | public function loadNamespaces()
{
$data = json_decode(file_get_contents(base_path('composer.json')), JSON_OBJECT_AS_ARRAY);
$namespaces = array_get($data, 'autoload.psr-4');
$this->setNamespaces($namespaces);
return $this;
} | php | public function loadNamespaces()
{
$data = json_decode(file_get_contents(base_path('composer.json')), JSON_OBJECT_AS_ARRAY);
$namespaces = array_get($data, 'autoload.psr-4');
$this->setNamespaces($namespaces);
return $this;
} | [
"public",
"function",
"loadNamespaces",
"(",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"file_get_contents",
"(",
"base_path",
"(",
"'composer.json'",
")",
")",
",",
"JSON_OBJECT_AS_ARRAY",
")",
";",
"$",
"namespaces",
"=",
"array_get",
"(",
"$",
"data",
... | Loads namespaces from composer.json
@return $this | [
"Loads",
"namespaces",
"from",
"composer",
".",
"json"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/install/NamespaceResolver.php#L25-L31 | train |
davestewart/laravel-sketchpad | src/objects/install/NamespaceResolver.php | NamespaceResolver.getNamespace | public function getNamespace($file, $defaultToPath = false)
{
// massage file path into a format compatible with PSR-4 entries
$file = str_replace('\\', '/', $file);
$base = str_replace('\\', '/', base_path()) . '/';
$file = str_replace($base, '', $file);
// compare file path against existing entries
foreach($this->namespaces as $ns => $path)
{
// convert paths to all use forward slashes
$path = str_replace('\\', '/', $path);
// if the file starts with the namespace path
if(strpos($file, $path) === 0)
{
$file = substr($file, strlen($path));
$file = preg_replace('%/[^/]+$%', '', $file);
$file = str_replace('/', '\\', $file);
// defensive trim, in case any double slashes
return trim($ns . $file, '\\');
}
}
// namespace could not be resolved
$info = pathinfo($file);
return $defaultToPath
? str_replace('/', '\\', $info['dirname'])
: null;
} | php | public function getNamespace($file, $defaultToPath = false)
{
// massage file path into a format compatible with PSR-4 entries
$file = str_replace('\\', '/', $file);
$base = str_replace('\\', '/', base_path()) . '/';
$file = str_replace($base, '', $file);
// compare file path against existing entries
foreach($this->namespaces as $ns => $path)
{
// convert paths to all use forward slashes
$path = str_replace('\\', '/', $path);
// if the file starts with the namespace path
if(strpos($file, $path) === 0)
{
$file = substr($file, strlen($path));
$file = preg_replace('%/[^/]+$%', '', $file);
$file = str_replace('/', '\\', $file);
// defensive trim, in case any double slashes
return trim($ns . $file, '\\');
}
}
// namespace could not be resolved
$info = pathinfo($file);
return $defaultToPath
? str_replace('/', '\\', $info['dirname'])
: null;
} | [
"public",
"function",
"getNamespace",
"(",
"$",
"file",
",",
"$",
"defaultToPath",
"=",
"false",
")",
"{",
"// massage file path into a format compatible with PSR-4 entries",
"$",
"file",
"=",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"file",
")",
";",
... | Attempts to get the namespace for a file
@param string $file base-relative file path
@param bool $defaultToPath flag to use file path as namespace if namespace cannot be matched
@return null|string | [
"Attempts",
"to",
"get",
"the",
"namespace",
"for",
"a",
"file"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/objects/install/NamespaceResolver.php#L52-L84 | train |
davestewart/laravel-sketchpad | src/help/docs/TagsController.php | TagsController.field | public function field($select = 1, $range = 0, $date = '2015-01-01', $color = 'ff0000')
{
$splits =
[
[
'operator' => '<code>|</code>',
'grouping' => 'attributes',
'example' => '<code>min:0|max:100</code>',
],
[
'operator' => '<code>:</code>',
'grouping' => 'attribute name / attribute value',
'example' => '<code>step:5</code>',
],
[
'operator' => '<code>,</code>',
'grouping' => 'options (<code>select</code> and <code>datalist</code> only)',
'example' => '<code>foo,bar,baz</code>',
],
[
'operator' => '<code>=</code>',
'grouping' => 'option text / option value',
'example' => '<code>Yes=1</code>',
],
];
$format = 'html:example|cols:100,400,200';
$params = Sketchpad::$params;
return view('sketchpad::help/tags/field', compact('types', 'attributes', 'format', 'params', 'splits'));
} | php | public function field($select = 1, $range = 0, $date = '2015-01-01', $color = 'ff0000')
{
$splits =
[
[
'operator' => '<code>|</code>',
'grouping' => 'attributes',
'example' => '<code>min:0|max:100</code>',
],
[
'operator' => '<code>:</code>',
'grouping' => 'attribute name / attribute value',
'example' => '<code>step:5</code>',
],
[
'operator' => '<code>,</code>',
'grouping' => 'options (<code>select</code> and <code>datalist</code> only)',
'example' => '<code>foo,bar,baz</code>',
],
[
'operator' => '<code>=</code>',
'grouping' => 'option text / option value',
'example' => '<code>Yes=1</code>',
],
];
$format = 'html:example|cols:100,400,200';
$params = Sketchpad::$params;
return view('sketchpad::help/tags/field', compact('types', 'attributes', 'format', 'params', 'splits'));
} | [
"public",
"function",
"field",
"(",
"$",
"select",
"=",
"1",
",",
"$",
"range",
"=",
"0",
",",
"$",
"date",
"=",
"'2015-01-01'",
",",
"$",
"color",
"=",
"'ff0000'",
")",
"{",
"$",
"splits",
"=",
"[",
"[",
"'operator'",
"=>",
"'<code>|</code>'",
",",
... | Override basic HTML inputs with more complex HTML input types and attributes
@group Input / Output
@param int $select
@field select $select options:One=1,Two=2,Three=3
@param int $range
@field number $range min:0|max:100|step:5
@param string $date
@field date $date
@param string $color
@field color $color | [
"Override",
"basic",
"HTML",
"inputs",
"with",
"more",
"complex",
"HTML",
"input",
"types",
"and",
"attributes"
] | ebd3365265f8844f7d400d7d530605512a20011c | https://github.com/davestewart/laravel-sketchpad/blob/ebd3365265f8844f7d400d7d530605512a20011c/src/help/docs/TagsController.php#L113-L144 | train |
thecatontheflat/atlassian-connect-bundle | Service/JWTGenerator.php | JWTGenerator.generate | public static function generate(RequestInterface $request, string $issuer, string $secret): string
{
$data = [
'iss' => $issuer,
'iat' => \time(),
'exp' => \strtotime('+1 day'),
'qsh' => QSHGenerator::generate((string) $request->getUri(), $request->getMethod()),
];
return JWT::encode($data, $secret);
} | php | public static function generate(RequestInterface $request, string $issuer, string $secret): string
{
$data = [
'iss' => $issuer,
'iat' => \time(),
'exp' => \strtotime('+1 day'),
'qsh' => QSHGenerator::generate((string) $request->getUri(), $request->getMethod()),
];
return JWT::encode($data, $secret);
} | [
"public",
"static",
"function",
"generate",
"(",
"RequestInterface",
"$",
"request",
",",
"string",
"$",
"issuer",
",",
"string",
"$",
"secret",
")",
":",
"string",
"{",
"$",
"data",
"=",
"[",
"'iss'",
"=>",
"$",
"issuer",
",",
"'iat'",
"=>",
"\\",
"ti... | Create JWT token used by Atlassian REST API request
@param RequestInterface $request
@param string $issuer Key of the add-on
@param string $secret Shared secret of the Tenant
@return string | [
"Create",
"JWT",
"token",
"used",
"by",
"Atlassian",
"REST",
"API",
"request"
] | 4691ae2410eb55dce1140733f5f6821b6f230ca8 | https://github.com/thecatontheflat/atlassian-connect-bundle/blob/4691ae2410eb55dce1140733f5f6821b6f230ca8/Service/JWTGenerator.php#L22-L32 | train |
thecatontheflat/atlassian-connect-bundle | Service/GuzzleJWTMiddleware.php | GuzzleJWTMiddleware.authTokenMiddleware | public static function authTokenMiddleware(string $issuer, string $secret): callable
{
return Middleware::mapRequest(
function (RequestInterface $request) use ($issuer, $secret) {
return new Request(
$request->getMethod(),
$request->getUri(),
\array_merge($request->getHeaders(), ['Authorization' => 'JWT '.JWTGenerator::generate($request, $issuer, $secret)]),
$request->getBody()
);
}
);
} | php | public static function authTokenMiddleware(string $issuer, string $secret): callable
{
return Middleware::mapRequest(
function (RequestInterface $request) use ($issuer, $secret) {
return new Request(
$request->getMethod(),
$request->getUri(),
\array_merge($request->getHeaders(), ['Authorization' => 'JWT '.JWTGenerator::generate($request, $issuer, $secret)]),
$request->getBody()
);
}
);
} | [
"public",
"static",
"function",
"authTokenMiddleware",
"(",
"string",
"$",
"issuer",
",",
"string",
"$",
"secret",
")",
":",
"callable",
"{",
"return",
"Middleware",
"::",
"mapRequest",
"(",
"function",
"(",
"RequestInterface",
"$",
"request",
")",
"use",
"(",... | JWT Authentication middleware for Guzzle
@param string $issuer Add-on key in most cases
@param string $secret Shared secret
@return callable | [
"JWT",
"Authentication",
"middleware",
"for",
"Guzzle"
] | 4691ae2410eb55dce1140733f5f6821b6f230ca8 | https://github.com/thecatontheflat/atlassian-connect-bundle/blob/4691ae2410eb55dce1140733f5f6821b6f230ca8/Service/GuzzleJWTMiddleware.php#L23-L35 | train |
summerblue/laravel-taggable | src/Model/Tag.php | Tag.scopeByTagName | public function scopeByTagName($query, $tag_name)
{
// mormalize string
$tag_name = app(TaggingUtility::class)->normalizeTagName(trim($tag_name));
return $query->where('name', $tag_name);
} | php | public function scopeByTagName($query, $tag_name)
{
// mormalize string
$tag_name = app(TaggingUtility::class)->normalizeTagName(trim($tag_name));
return $query->where('name', $tag_name);
} | [
"public",
"function",
"scopeByTagName",
"(",
"$",
"query",
",",
"$",
"tag_name",
")",
"{",
"// mormalize string",
"$",
"tag_name",
"=",
"app",
"(",
"TaggingUtility",
"::",
"class",
")",
"->",
"normalizeTagName",
"(",
"trim",
"(",
"$",
"tag_name",
")",
")",
... | Get one Tag item by tag name | [
"Get",
"one",
"Tag",
"item",
"by",
"tag",
"name"
] | 35125bdc29d6d454c91ab65c457a9d8bdc1f7b86 | https://github.com/summerblue/laravel-taggable/blob/35125bdc29d6d454c91ab65c457a9d8bdc1f7b86/src/Model/Tag.php#L108-L113 | train |
summerblue/laravel-taggable | src/Model/Tag.php | Tag.scopeByTagNames | public function scopeByTagNames($query, $tag_names)
{
$normalize_tag_names = [];
foreach ($tag_names as $tag_name) {
// mormalize string
$normalize_tag_names[] = app(TaggingUtility::class)->normalizeTagName(trim($tag_name));
}
return $query->whereIn('name', $normalize_tag_names);
} | php | public function scopeByTagNames($query, $tag_names)
{
$normalize_tag_names = [];
foreach ($tag_names as $tag_name) {
// mormalize string
$normalize_tag_names[] = app(TaggingUtility::class)->normalizeTagName(trim($tag_name));
}
return $query->whereIn('name', $normalize_tag_names);
} | [
"public",
"function",
"scopeByTagNames",
"(",
"$",
"query",
",",
"$",
"tag_names",
")",
"{",
"$",
"normalize_tag_names",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"tag_names",
"as",
"$",
"tag_name",
")",
"{",
"// mormalize string",
"$",
"normalize_tag_names",
... | Get Tag collection by tag name array | [
"Get",
"Tag",
"collection",
"by",
"tag",
"name",
"array"
] | 35125bdc29d6d454c91ab65c457a9d8bdc1f7b86 | https://github.com/summerblue/laravel-taggable/blob/35125bdc29d6d454c91ab65c457a9d8bdc1f7b86/src/Model/Tag.php#L121-L129 | train |
thecatontheflat/atlassian-connect-bundle | Service/AtlassianRestClient.php | AtlassianRestClient.createClient | private function createClient(): Client
{
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
if ($this->user === null) {
$stack->push(GuzzleJWTMiddleware::authTokenMiddleware(
$this->tenant->getAddonKey(),
$this->tenant->getSharedSecret()
));
} else {
$stack->push(GuzzleJWTMiddleware::authUserTokenMiddleware(
$this->tenant->getOauthClientId(),
$this->tenant->getSharedSecret(),
$this->tenant->getBaseUrl(),
$this->user
));
}
return new Client(['handler' => $stack]);
} | php | private function createClient(): Client
{
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
if ($this->user === null) {
$stack->push(GuzzleJWTMiddleware::authTokenMiddleware(
$this->tenant->getAddonKey(),
$this->tenant->getSharedSecret()
));
} else {
$stack->push(GuzzleJWTMiddleware::authUserTokenMiddleware(
$this->tenant->getOauthClientId(),
$this->tenant->getSharedSecret(),
$this->tenant->getBaseUrl(),
$this->user
));
}
return new Client(['handler' => $stack]);
} | [
"private",
"function",
"createClient",
"(",
")",
":",
"Client",
"{",
"$",
"stack",
"=",
"new",
"HandlerStack",
"(",
")",
";",
"$",
"stack",
"->",
"setHandler",
"(",
"new",
"CurlHandler",
"(",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"user",
"==="... | Create a HTTP client
@return Client | [
"Create",
"a",
"HTTP",
"client"
] | 4691ae2410eb55dce1140733f5f6821b6f230ca8 | https://github.com/thecatontheflat/atlassian-connect-bundle/blob/4691ae2410eb55dce1140733f5f6821b6f230ca8/Service/AtlassianRestClient.php#L151-L171 | train |
thecatontheflat/atlassian-connect-bundle | Service/QSHGenerator.php | QSHGenerator.generate | public static function generate(string $url, string $method): string
{
$parts = \parse_url($url);
// Remove "/wiki" part from the path for the Confluence
// Really, I didn't find this part in the docs, but it works
$path = \str_replace('/wiki', '', $parts['path']);
$canonicalQuery = '';
if (!empty($parts['query'])) {
$query = $parts['query'];
$queryParts = \explode('&', $query);
$queryArray = [];
foreach ($queryParts as $queryPart) {
$pieces = \explode('=', $queryPart);
$key = \array_shift($pieces);
$key = \rawurlencode($key);
$value = \mb_substr($queryPart, \mb_strlen($key) + 1);
$value = \rawurlencode($value);
$queryArray[$key][] = $value;
}
\ksort($queryArray);
foreach ($queryArray as $key => $pieceOfQuery) {
$pieceOfQuery = \implode(',', $pieceOfQuery);
$canonicalQuery .= $key.'='.$pieceOfQuery.'&';
}
$canonicalQuery = \rtrim($canonicalQuery, '&');
}
return \hash('sha256', \implode('&', [\mb_strtoupper($method), $path, $canonicalQuery]));
} | php | public static function generate(string $url, string $method): string
{
$parts = \parse_url($url);
// Remove "/wiki" part from the path for the Confluence
// Really, I didn't find this part in the docs, but it works
$path = \str_replace('/wiki', '', $parts['path']);
$canonicalQuery = '';
if (!empty($parts['query'])) {
$query = $parts['query'];
$queryParts = \explode('&', $query);
$queryArray = [];
foreach ($queryParts as $queryPart) {
$pieces = \explode('=', $queryPart);
$key = \array_shift($pieces);
$key = \rawurlencode($key);
$value = \mb_substr($queryPart, \mb_strlen($key) + 1);
$value = \rawurlencode($value);
$queryArray[$key][] = $value;
}
\ksort($queryArray);
foreach ($queryArray as $key => $pieceOfQuery) {
$pieceOfQuery = \implode(',', $pieceOfQuery);
$canonicalQuery .= $key.'='.$pieceOfQuery.'&';
}
$canonicalQuery = \rtrim($canonicalQuery, '&');
}
return \hash('sha256', \implode('&', [\mb_strtoupper($method), $path, $canonicalQuery]));
} | [
"public",
"static",
"function",
"generate",
"(",
"string",
"$",
"url",
",",
"string",
"$",
"method",
")",
":",
"string",
"{",
"$",
"parts",
"=",
"\\",
"parse_url",
"(",
"$",
"url",
")",
";",
"// Remove \"/wiki\" part from the path for the Confluence",
"// Really... | Create Query String Hash
More details:
https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html#creating-token
@param string $url URL of the request
@param string $method HTTP method
@return string | [
"Create",
"Query",
"String",
"Hash"
] | 4691ae2410eb55dce1140733f5f6821b6f230ca8 | https://github.com/thecatontheflat/atlassian-connect-bundle/blob/4691ae2410eb55dce1140733f5f6821b6f230ca8/Service/QSHGenerator.php#L21-L50 | train |
summerblue/laravel-taggable | src/Util.php | Util.uniqueSlug | public function uniqueSlug($slug_str, $tag_name)
{
$model = $this->tagModelString();
if (!empty($slug_str) && $tag = $model::where('slug', $slug_str)->first()) {
// 只有当 slug 一样但 tagname 不一样的情况下,才自动设置随机 slug 后缀
if ($tag->name != $this->normalizeTagName($tag_name)) {
$slug_str .= '-'. mt_rand(1000, 9999);
}
}
return $slug_str;
} | php | public function uniqueSlug($slug_str, $tag_name)
{
$model = $this->tagModelString();
if (!empty($slug_str) && $tag = $model::where('slug', $slug_str)->first()) {
// 只有当 slug 一样但 tagname 不一样的情况下,才自动设置随机 slug 后缀
if ($tag->name != $this->normalizeTagName($tag_name)) {
$slug_str .= '-'. mt_rand(1000, 9999);
}
}
return $slug_str;
} | [
"public",
"function",
"uniqueSlug",
"(",
"$",
"slug_str",
",",
"$",
"tag_name",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"tagModelString",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"slug_str",
")",
"&&",
"$",
"tag",
"=",
"$",
"model"... | Check DB Slug Dulplication | [
"Check",
"DB",
"Slug",
"Dulplication"
] | 35125bdc29d6d454c91ab65c457a9d8bdc1f7b86 | https://github.com/summerblue/laravel-taggable/blob/35125bdc29d6d454c91ab65c457a9d8bdc1f7b86/src/Util.php#L222-L232 | train |
KnpLabs/KnpZendCacheBundle | DependencyInjection/KnpZendCacheExtension.php | KnpZendCacheExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('manager.xml');
$templates = array();
foreach ($configs as $config) {
$templates = array_merge($templates, $config['templates']);
}
foreach($templates as $name => $template) {
$container->findDefinition('knp_zend_cache.manager')->addMethodCall('setCacheTemplate', array($name, $template));
}
} | php | public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('manager.xml');
$templates = array();
foreach ($configs as $config) {
$templates = array_merge($templates, $config['templates']);
}
foreach($templates as $name => $template) {
$container->findDefinition('knp_zend_cache.manager')->addMethodCall('setCacheTemplate', array($name, $template));
}
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"loader",
"=",
"new",
"XmlFileLoader",
"(",
"$",
"container",
",",
"new",
"FileLocator",
"(",
"__DIR__",
".",
"'/../Resources/config'",
")",
... | Loads the cache manager configuration. | [
"Loads",
"the",
"cache",
"manager",
"configuration",
"."
] | 36b0815c274a5a8114de9bc8dcd4dfeae95c7265 | https://github.com/KnpLabs/KnpZendCacheBundle/blob/36b0815c274a5a8114de9bc8dcd4dfeae95c7265/DependencyInjection/KnpZendCacheExtension.php#L25-L38 | train |
UnionOfRAD/li3_docs | doc/Docblock.php | Docblock.tag | public function tag($name) {
if (!isset($this->_tags[$name])) {
return false;
}
foreach ($this->_tags[$name] as $item) {
return $item;
}
} | php | public function tag($name) {
if (!isset($this->_tags[$name])) {
return false;
}
foreach ($this->_tags[$name] as $item) {
return $item;
}
} | [
"public",
"function",
"tag",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"_tags",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"_tags",
"[",
"$",
"name",
... | Retrieve a single tag item. Good for i.e. `return` tags, that can
by definition only appear once.
@param string $name The tag name to retrieve.
@return array|boolean The tag information or `false` if tag does not exist. | [
"Retrieve",
"a",
"single",
"tag",
"item",
".",
"Good",
"for",
"i",
".",
"e",
".",
"return",
"tags",
"that",
"can",
"by",
"definition",
"only",
"appear",
"once",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/doc/Docblock.php#L86-L93 | train |
UnionOfRAD/li3_docs | doc/Docblock.php | Docblock._parse | protected function _parse($comment) {
$summary = null;
$description = null;
$tags = array();
$comment = trim(preg_replace('/^(\s*\/\*\*|\s*\*{1,2}\/|\s*\* ?)/m', '', $comment));
$comment = str_replace("\r\n", "\n", $comment);
if ($items = preg_split('/\n@/ms', $comment, 2)) {
list($summary, $tags) = $items + array('', '');
$this->_tags = $tags ? $this->_parseTags("@{$tags}") : array();
}
if (strpos($summary, "\n\n")) {
list($summary, $description) = explode("\n\n", $summary, 2);
}
$this->_summary = $this->_clean($summary);
$this->_description = $this->_clean($description);
} | php | protected function _parse($comment) {
$summary = null;
$description = null;
$tags = array();
$comment = trim(preg_replace('/^(\s*\/\*\*|\s*\*{1,2}\/|\s*\* ?)/m', '', $comment));
$comment = str_replace("\r\n", "\n", $comment);
if ($items = preg_split('/\n@/ms', $comment, 2)) {
list($summary, $tags) = $items + array('', '');
$this->_tags = $tags ? $this->_parseTags("@{$tags}") : array();
}
if (strpos($summary, "\n\n")) {
list($summary, $description) = explode("\n\n", $summary, 2);
}
$this->_summary = $this->_clean($summary);
$this->_description = $this->_clean($description);
} | [
"protected",
"function",
"_parse",
"(",
"$",
"comment",
")",
"{",
"$",
"summary",
"=",
"null",
";",
"$",
"description",
"=",
"null",
";",
"$",
"tags",
"=",
"array",
"(",
")",
";",
"$",
"comment",
"=",
"trim",
"(",
"preg_replace",
"(",
"'/^(\\s*\\/\\*\\... | Parses a docblock into its major components of `summary`, `description` and `tags`.
@param string $comment The docblock string to be parsed
@return void | [
"Parses",
"a",
"docblock",
"into",
"its",
"major",
"components",
"of",
"summary",
"description",
"and",
"tags",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/doc/Docblock.php#L116-L133 | train |
UnionOfRAD/li3_docs | doc/Docblock.php | Docblock._parseTag | protected function _parseTag($string, array $keys = []) {
$parts = explode(' ', $string, count($keys));
$result = array_fill_keys($keys, null);
foreach ($keys as $i => $key) {
if (isset($parts[$i])) {
if ($key === 'description') {
$result[$key] = $this->_clean($parts[$i]);
} else {
$result[$key] = $parts[$i];
}
}
}
return $result;
} | php | protected function _parseTag($string, array $keys = []) {
$parts = explode(' ', $string, count($keys));
$result = array_fill_keys($keys, null);
foreach ($keys as $i => $key) {
if (isset($parts[$i])) {
if ($key === 'description') {
$result[$key] = $this->_clean($parts[$i]);
} else {
$result[$key] = $parts[$i];
}
}
}
return $result;
} | [
"protected",
"function",
"_parseTag",
"(",
"$",
"string",
",",
"array",
"$",
"keys",
"=",
"[",
"]",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"' '",
",",
"$",
"string",
",",
"count",
"(",
"$",
"keys",
")",
")",
";",
"$",
"result",
"=",
"array_... | Parses space delimited docblock tags to separate out keys.
@param string
@param array Keys (order matters) to parse out.
@return array Returns an array containing the given keys. | [
"Parses",
"space",
"delimited",
"docblock",
"tags",
"to",
"separate",
"out",
"keys",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/doc/Docblock.php#L191-L205 | train |
UnionOfRAD/li3_docs | controllers/ApisController.php | ApisController.view | public function view() {
$index = Indexes::find('first', [
'conditions' => [
'type' => 'api',
'name' => $this->request->name,
// $this->request->version gives HTTP version.
'version' => isset($this->request->params['version']) ? $this->request->params['version'] : null
]
]);
if (!$index) {
throw new Exception('Index not found.');
}
if (!$this->request->symbol && $index->namespace) {
return $this->redirect([
'library' => 'li3_docs',
'controller' => 'Apis',
'action' => 'view',
'name' => $index->name,
'version' => $index->version,
'symbol' => $index->namespace
]);
}
if (!$symbol = $index->symbol($this->request->symbol)) {
// Just class members are handled below.
if (strpos($this->request->symbol, '::') === false) {
throw new Exception('Symbol not found.');
}
// As Markdown does not allow closing () on method links or sends
// them out as just ) or ( we'll see if there's method symbol
// similiar to this one and redirect to that.
$fixed = rtrim($this->request->symbol, '()') . '()';
if ($symbol = $index->symbol($fixed)) {
return $this->redirect([
'library' => 'li3_docs',
'controller' => 'Apis',
'action' => 'view',
'name' => $index->name,
'version' => $index->version,
'symbol' => $symbol->name
]);
}
// From documentation links may be generated to inherited
// members of a class. We redirect to the class where they
// were defined. Document::$_parent -> Entity::$_parent
list($class, $member) = explode('::', $this->request->symbol, 2) + [null, null];
if (!$symbol = $index->symbol($class)) {
throw new Exception('Symbol not found.');
}
if ($member[0] === '$') {
$type = 'property';
} elseif (strtoupper($member[0]) === $member[0]) {
$type = 'constant';
} else {
$type = 'method';
}
$symbol = $symbol->members(compact('type'))->first(function($item) use ($member) {
return $item->title(['last' => true]) === $member;
});
if (!$symbol) {
throw new Exception('Symbol not found.');
}
return $this->redirect([
'library' => 'li3_docs',
'controller' => 'Apis',
'action' => 'view',
'name' => $index->name,
'version' => $index->version,
'symbol' => $symbol->name
]);
}
$crumbs = $this->_crumbsForSymbol($index, $symbol);
return compact('index', 'symbol', 'crumbs');
} | php | public function view() {
$index = Indexes::find('first', [
'conditions' => [
'type' => 'api',
'name' => $this->request->name,
// $this->request->version gives HTTP version.
'version' => isset($this->request->params['version']) ? $this->request->params['version'] : null
]
]);
if (!$index) {
throw new Exception('Index not found.');
}
if (!$this->request->symbol && $index->namespace) {
return $this->redirect([
'library' => 'li3_docs',
'controller' => 'Apis',
'action' => 'view',
'name' => $index->name,
'version' => $index->version,
'symbol' => $index->namespace
]);
}
if (!$symbol = $index->symbol($this->request->symbol)) {
// Just class members are handled below.
if (strpos($this->request->symbol, '::') === false) {
throw new Exception('Symbol not found.');
}
// As Markdown does not allow closing () on method links or sends
// them out as just ) or ( we'll see if there's method symbol
// similiar to this one and redirect to that.
$fixed = rtrim($this->request->symbol, '()') . '()';
if ($symbol = $index->symbol($fixed)) {
return $this->redirect([
'library' => 'li3_docs',
'controller' => 'Apis',
'action' => 'view',
'name' => $index->name,
'version' => $index->version,
'symbol' => $symbol->name
]);
}
// From documentation links may be generated to inherited
// members of a class. We redirect to the class where they
// were defined. Document::$_parent -> Entity::$_parent
list($class, $member) = explode('::', $this->request->symbol, 2) + [null, null];
if (!$symbol = $index->symbol($class)) {
throw new Exception('Symbol not found.');
}
if ($member[0] === '$') {
$type = 'property';
} elseif (strtoupper($member[0]) === $member[0]) {
$type = 'constant';
} else {
$type = 'method';
}
$symbol = $symbol->members(compact('type'))->first(function($item) use ($member) {
return $item->title(['last' => true]) === $member;
});
if (!$symbol) {
throw new Exception('Symbol not found.');
}
return $this->redirect([
'library' => 'li3_docs',
'controller' => 'Apis',
'action' => 'view',
'name' => $index->name,
'version' => $index->version,
'symbol' => $symbol->name
]);
}
$crumbs = $this->_crumbsForSymbol($index, $symbol);
return compact('index', 'symbol', 'crumbs');
} | [
"public",
"function",
"view",
"(",
")",
"{",
"$",
"index",
"=",
"Indexes",
"::",
"find",
"(",
"'first'",
",",
"[",
"'conditions'",
"=>",
"[",
"'type'",
"=>",
"'api'",
",",
"'name'",
"=>",
"$",
"this",
"->",
"request",
"->",
"name",
",",
"// $this->requ... | This action renders the detail page for all API elements, including namespaces, classes,
properties and methods. The action determines what type of entity is being displayed, and
gathers all available data on it. Any wiki text embedded in the data is then post-processed
and prepped for display.
Handles broken URL parsers by matching method URLs with no closing ) or no () at all
and redirecting.
@return array Returns an array with the following keys:
- `'name'`: A string containing the full name of the entity being displayed
- `'library'`: An array with the details of the current class library being
browsed, in which the current entity is contained.
- `'object'`: A multi-level array containing all data extracted about the
current entity. | [
"This",
"action",
"renders",
"the",
"detail",
"page",
"for",
"all",
"API",
"elements",
"including",
"namespaces",
"classes",
"properties",
"and",
"methods",
".",
"The",
"action",
"determines",
"what",
"type",
"of",
"entity",
"is",
"being",
"displayed",
"and",
... | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/controllers/ApisController.php#L41-L116 | train |
UnionOfRAD/li3_docs | models/Pages.php | Pages._parse | protected static function _parse($file) {
$header = '';
$content = '';
if (!$stream = fopen($file, 'r')) {
throw new Exception('Failed to open file.');
}
$isHeader = false;
while (!feof($stream)) {
$line = rtrim(fgets($stream));
if ($line === '---') {
$isHeader = !$isHeader;
continue;
}
if ($isHeader) {
$header .= $line . "\n";
} else {
$content .= $line . "\n";
}
}
if ($header) {
$info = Yaml::parse($header);
} else {
$info = [];
}
fclose($stream);
return [$info, $content];
} | php | protected static function _parse($file) {
$header = '';
$content = '';
if (!$stream = fopen($file, 'r')) {
throw new Exception('Failed to open file.');
}
$isHeader = false;
while (!feof($stream)) {
$line = rtrim(fgets($stream));
if ($line === '---') {
$isHeader = !$isHeader;
continue;
}
if ($isHeader) {
$header .= $line . "\n";
} else {
$content .= $line . "\n";
}
}
if ($header) {
$info = Yaml::parse($header);
} else {
$info = [];
}
fclose($stream);
return [$info, $content];
} | [
"protected",
"static",
"function",
"_parse",
"(",
"$",
"file",
")",
"{",
"$",
"header",
"=",
"''",
";",
"$",
"content",
"=",
"''",
";",
"if",
"(",
"!",
"$",
"stream",
"=",
"fopen",
"(",
"$",
"file",
",",
"'r'",
")",
")",
"{",
"throw",
"new",
"E... | Does not parse file body. | [
"Does",
"not",
"parse",
"file",
"body",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/models/Pages.php#L100-L131 | train |
UnionOfRAD/li3_docs | extensions/command/Docs.php | Docs.index | public function index() {
$pdo = Pages::connection()->connection;
$pdo->beginTransaction();
$this->out('Removing all pages and symbols...');
Pages::remove();
Symbols::remove();
foreach (Indexes::find('all') as $index) {
$this->out('Processing index:' . var_export($index->data(), true));
if ($index->type === 'api') {
$this->out('Harvesting symbols...');
if (!Symbols::harvest($index)) {
$this->error('FAILED');
$pdo->rollback();
return false;
}
}
$this->out('Harvesting pages...');
if (!Pages::harvest($index)) {
$this->error('FAILED');
$pdo->rollback();
return false;
}
}
$pdo->commit();
} | php | public function index() {
$pdo = Pages::connection()->connection;
$pdo->beginTransaction();
$this->out('Removing all pages and symbols...');
Pages::remove();
Symbols::remove();
foreach (Indexes::find('all') as $index) {
$this->out('Processing index:' . var_export($index->data(), true));
if ($index->type === 'api') {
$this->out('Harvesting symbols...');
if (!Symbols::harvest($index)) {
$this->error('FAILED');
$pdo->rollback();
return false;
}
}
$this->out('Harvesting pages...');
if (!Pages::harvest($index)) {
$this->error('FAILED');
$pdo->rollback();
return false;
}
}
$pdo->commit();
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"pdo",
"=",
"Pages",
"::",
"connection",
"(",
")",
"->",
"connection",
";",
"$",
"pdo",
"->",
"beginTransaction",
"(",
")",
";",
"$",
"this",
"->",
"out",
"(",
"'Removing all pages and symbols...'",
")",
... | Generates index for registered libraries. | [
"Generates",
"index",
"for",
"registered",
"libraries",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/extensions/command/Docs.php#L20-L49 | train |
UnionOfRAD/li3_docs | doc/UorMarkdown.php | UorMarkdown.renderHeadline | protected function renderHeadline($block) {
$tag = 'h' . $block['level'];
$text = $this->renderAbsy($block['content']);
$slug = strtolower(Inflector::slug($text));
return sprintf(
'<%s><a id="%s" class="anchor" href="%s">%s</a></%s>' . "\n",
$tag,
$slug,
'#' . $slug,
$text,
$tag
);
} | php | protected function renderHeadline($block) {
$tag = 'h' . $block['level'];
$text = $this->renderAbsy($block['content']);
$slug = strtolower(Inflector::slug($text));
return sprintf(
'<%s><a id="%s" class="anchor" href="%s">%s</a></%s>' . "\n",
$tag,
$slug,
'#' . $slug,
$text,
$tag
);
} | [
"protected",
"function",
"renderHeadline",
"(",
"$",
"block",
")",
"{",
"$",
"tag",
"=",
"'h'",
".",
"$",
"block",
"[",
"'level'",
"]",
";",
"$",
"text",
"=",
"$",
"this",
"->",
"renderAbsy",
"(",
"$",
"block",
"[",
"'content'",
"]",
")",
";",
"$",... | Overwritten to make headlines linkable. | [
"Overwritten",
"to",
"make",
"headlines",
"linkable",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/doc/UorMarkdown.php#L26-L39 | train |
UnionOfRAD/li3_docs | doc/UorMarkdown.php | UorMarkdown.consumeFencedCode | protected function consumeFencedCode($lines, $current) {
list($block, $i) = parent::consumeFencedCode($lines, $current);
if (empty($block['language'])) {
$block['language'] = 'php';
}
return [$block, $i];
} | php | protected function consumeFencedCode($lines, $current) {
list($block, $i) = parent::consumeFencedCode($lines, $current);
if (empty($block['language'])) {
$block['language'] = 'php';
}
return [$block, $i];
} | [
"protected",
"function",
"consumeFencedCode",
"(",
"$",
"lines",
",",
"$",
"current",
")",
"{",
"list",
"(",
"$",
"block",
",",
"$",
"i",
")",
"=",
"parent",
"::",
"consumeFencedCode",
"(",
"$",
"lines",
",",
"$",
"current",
")",
";",
"if",
"(",
"emp... | Overwritten to default to PHP language in code blocks. | [
"Overwritten",
"to",
"default",
"to",
"PHP",
"language",
"in",
"code",
"blocks",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/doc/UorMarkdown.php#L44-L51 | train |
UnionOfRAD/li3_docs | models/Symbols.php | Symbols.page | public function page($entity) {
if ($entity->type !== 'namespace') {
return false;
}
return Pages::find('first', [
'conditions' => [
'index' => $entity->index,
'name' => $entity->name
]
]);
} | php | public function page($entity) {
if ($entity->type !== 'namespace') {
return false;
}
return Pages::find('first', [
'conditions' => [
'index' => $entity->index,
'name' => $entity->name
]
]);
} | [
"public",
"function",
"page",
"(",
"$",
"entity",
")",
"{",
"if",
"(",
"$",
"entity",
"->",
"type",
"!==",
"'namespace'",
")",
"{",
"return",
"false",
";",
"}",
"return",
"Pages",
"::",
"find",
"(",
"'first'",
",",
"[",
"'conditions'",
"=>",
"[",
"'i... | Namespace symbols may have a corresponding page. | [
"Namespace",
"symbols",
"may",
"have",
"a",
"corresponding",
"page",
"."
] | 4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c | https://github.com/UnionOfRAD/li3_docs/blob/4ee7c26c0bef0ef49b078a98a6762c1e7f03d36c/models/Symbols.php#L194-L204 | train |
bitrix-expert/bbc-module | lib/helpers/componentparameters.php | ComponentParameters.getParameters | public static function getParameters($component, $prepareParams = [], $arCurrentValues, $selectOnlyListed = false)
{
$additionalComponentParams = [];
$componentParams = \CComponentUtil::GetComponentProps($component, $arCurrentValues);
if ($componentParams === false)
{
throw new Main\LoaderException('Failed loading parameters for ' . $component);
}
if (!empty($prepareParams))
{
foreach ($componentParams['PARAMETERS'] as $code => &$params)
{
if ($prepareParams[$code]['DELETE'] || ($selectOnlyListed === true && !isset($prepareParams[$code])))
{
unset($componentParams['PARAMETERS'][$code]);
continue;
}
if ($prepareParams[$code]['MOVE'])
{
$params['PARENT'] = $prepareParams[$code]['MOVE'];
}
if ($prepareParams[$code]['NAME'])
{
$params['NAME'] = $prepareParams[$code]['NAME'];
}
if ($prepareParams[$code]['RENAME'])
{
$additionalComponentParams[$prepareParams[$code]['RENAME']] = $params;
unset($componentParams['PARAMETERS'][$code]);
}
}
unset($params);
$componentParams['PARAMETERS'] = array_replace_recursive($componentParams['PARAMETERS'], $additionalComponentParams);
}
return $componentParams;
} | php | public static function getParameters($component, $prepareParams = [], $arCurrentValues, $selectOnlyListed = false)
{
$additionalComponentParams = [];
$componentParams = \CComponentUtil::GetComponentProps($component, $arCurrentValues);
if ($componentParams === false)
{
throw new Main\LoaderException('Failed loading parameters for ' . $component);
}
if (!empty($prepareParams))
{
foreach ($componentParams['PARAMETERS'] as $code => &$params)
{
if ($prepareParams[$code]['DELETE'] || ($selectOnlyListed === true && !isset($prepareParams[$code])))
{
unset($componentParams['PARAMETERS'][$code]);
continue;
}
if ($prepareParams[$code]['MOVE'])
{
$params['PARENT'] = $prepareParams[$code]['MOVE'];
}
if ($prepareParams[$code]['NAME'])
{
$params['NAME'] = $prepareParams[$code]['NAME'];
}
if ($prepareParams[$code]['RENAME'])
{
$additionalComponentParams[$prepareParams[$code]['RENAME']] = $params;
unset($componentParams['PARAMETERS'][$code]);
}
}
unset($params);
$componentParams['PARAMETERS'] = array_replace_recursive($componentParams['PARAMETERS'], $additionalComponentParams);
}
return $componentParams;
} | [
"public",
"static",
"function",
"getParameters",
"(",
"$",
"component",
",",
"$",
"prepareParams",
"=",
"[",
"]",
",",
"$",
"arCurrentValues",
",",
"$",
"selectOnlyListed",
"=",
"false",
")",
"{",
"$",
"additionalComponentParams",
"=",
"[",
"]",
";",
"$",
... | Prepare and returns parameters of the component
@param string $component Component name. For example: basis:elements.list
@param array $prepareParams Array with settings for prepare parameters of merged the component. For example:
<code>
[
'SELECT_FIELDS' => array(
'RENAME' => 'LIST_SELECT_FIELDS',
'MOVE' => 'LIST'
]
</code>
Options:
<ul>
<li> RENAME — rename parameter
<li> NAME — add new name (title) for parameter
<li> MOVE — move parameter to another parameter group
<li> DELETE — true or false
</ul>
@param array $arCurrentValues Don't change the name! It's used in the .parameters.php file (Hello from Bitrix)
@param bool $selectOnlyListed Select parameters only listed in $prepareParams
@return array Array for use in variable $arComponentParameters in the .parameters.php
@throws \Bitrix\Main\LoaderException | [
"Prepare",
"and",
"returns",
"parameters",
"of",
"the",
"component"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/helpers/componentparameters.php#L60-L105 | train |
bitrix-expert/bbc-module | lib/traits/common.php | Common.startAjax | private function startAjax()
{
if ($this->arParams['USE_AJAX'] !== 'Y')
{
return false;
}
if (strlen($this->arParams['AJAX_PARAM_NAME']) <= 0)
{
$this->arParams['AJAX_PARAM_NAME'] = 'compid';
}
if (strlen($this->arParams['AJAX_COMPONENT_ID']) <= 0)
{
$this->arParams['AJAX_COMPONENT_ID'] = \CAjax::GetComponentID($this->getName(), $this->getTemplateName(), $this->ajaxComponentIdSalt);
}
if ($this->isAjax())
{
global $APPLICATION;
if ($this->arParams['AJAX_HEAD_RELOAD'] === 'Y')
{
$APPLICATION->ShowAjaxHead();
}
else
{
$APPLICATION->RestartBuffer();
}
if ($this->arParams['AJAX_TYPE'] === 'JSON')
{
header('Content-Type: application/json');
}
if (strlen($this->arParams['AJAX_TEMPLATE_PAGE']) > 0)
{
$this->templatePage = basename($this->arParams['AJAX_TEMPLATE_PAGE']);
}
}
} | php | private function startAjax()
{
if ($this->arParams['USE_AJAX'] !== 'Y')
{
return false;
}
if (strlen($this->arParams['AJAX_PARAM_NAME']) <= 0)
{
$this->arParams['AJAX_PARAM_NAME'] = 'compid';
}
if (strlen($this->arParams['AJAX_COMPONENT_ID']) <= 0)
{
$this->arParams['AJAX_COMPONENT_ID'] = \CAjax::GetComponentID($this->getName(), $this->getTemplateName(), $this->ajaxComponentIdSalt);
}
if ($this->isAjax())
{
global $APPLICATION;
if ($this->arParams['AJAX_HEAD_RELOAD'] === 'Y')
{
$APPLICATION->ShowAjaxHead();
}
else
{
$APPLICATION->RestartBuffer();
}
if ($this->arParams['AJAX_TYPE'] === 'JSON')
{
header('Content-Type: application/json');
}
if (strlen($this->arParams['AJAX_TEMPLATE_PAGE']) > 0)
{
$this->templatePage = basename($this->arParams['AJAX_TEMPLATE_PAGE']);
}
}
} | [
"private",
"function",
"startAjax",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'USE_AJAX'",
"]",
"!==",
"'Y'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'AJAX_PARAM_NAME'",... | Restart buffer if AJAX request | [
"Restart",
"buffer",
"if",
"AJAX",
"request"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/common.php#L182-L222 | train |
bitrix-expert/bbc-module | lib/traits/common.php | Common.return404 | public function return404($notifier = false, \Exception $exception = null)
{
if (!defined('ERROR_404'))
{
define('ERROR_404', 'Y');
}
\CHTTP::SetStatus('404 Not Found');
if ($exception !== false)
{
if ($notifier === false)
{
$this->exceptionNotifier = false;
}
if ($exception instanceof \Exception)
{
throw $exception;
}
else
{
throw new \Exception('Page not found');
}
}
} | php | public function return404($notifier = false, \Exception $exception = null)
{
if (!defined('ERROR_404'))
{
define('ERROR_404', 'Y');
}
\CHTTP::SetStatus('404 Not Found');
if ($exception !== false)
{
if ($notifier === false)
{
$this->exceptionNotifier = false;
}
if ($exception instanceof \Exception)
{
throw $exception;
}
else
{
throw new \Exception('Page not found');
}
}
} | [
"public",
"function",
"return404",
"(",
"$",
"notifier",
"=",
"false",
",",
"\\",
"Exception",
"$",
"exception",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"defined",
"(",
"'ERROR_404'",
")",
")",
"{",
"define",
"(",
"'ERROR_404'",
",",
"'Y'",
")",
";",
... | Set status 404 and throw exception
@param bool $notifier Sent notify to admin email
@param \Exception|null|false $exception Exception which will be throwing or "false" what not throwing exceptions. Default — throw new \Exception()
@throws \Exception | [
"Set",
"status",
"404",
"and",
"throw",
"exception"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/common.php#L354-L379 | train |
bitrix-expert/bbc-module | lib/traits/common.php | Common.catchException | protected function catchException(\Exception $exception, $notifier = null)
{
global $USER;
$this->abortCache();
if ($USER->IsAdmin())
{
$this->showExceptionAdmin($exception);
}
else
{
$this->showExceptionUser($exception);
}
if (($notifier === true) || ($this->exceptionNotifier && $notifier !== false) && BX_EXC_NOTIFY !== false)
{
$this->sendNotifyException($exception);
}
} | php | protected function catchException(\Exception $exception, $notifier = null)
{
global $USER;
$this->abortCache();
if ($USER->IsAdmin())
{
$this->showExceptionAdmin($exception);
}
else
{
$this->showExceptionUser($exception);
}
if (($notifier === true) || ($this->exceptionNotifier && $notifier !== false) && BX_EXC_NOTIFY !== false)
{
$this->sendNotifyException($exception);
}
} | [
"protected",
"function",
"catchException",
"(",
"\\",
"Exception",
"$",
"exception",
",",
"$",
"notifier",
"=",
"null",
")",
"{",
"global",
"$",
"USER",
";",
"$",
"this",
"->",
"abortCache",
"(",
")",
";",
"if",
"(",
"$",
"USER",
"->",
"IsAdmin",
"(",
... | Called when an error occurs
Resets the cache, show error message (two mode: for users and for admins),
sending notification to admin email
@param \Exception $exception
@param bool $notifier Sent notify to admin email. Default — value of property $this->exceptionNotifier
@uses exceptionNotifier | [
"Called",
"when",
"an",
"error",
"occurs"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/common.php#L391-L410 | train |
bitrix-expert/bbc-module | lib/traits/common.php | Common.isAjax | public function isAjax()
{
if (
strlen($this->arParams['AJAX_COMPONENT_ID']) > 0
&& strlen($this->arParams['AJAX_PARAM_NAME']) > 0
&& $_REQUEST[$this->arParams['AJAX_PARAM_NAME']] === $this->arParams['AJAX_COMPONENT_ID']
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
)
{
return true;
}
return false;
} | php | public function isAjax()
{
if (
strlen($this->arParams['AJAX_COMPONENT_ID']) > 0
&& strlen($this->arParams['AJAX_PARAM_NAME']) > 0
&& $_REQUEST[$this->arParams['AJAX_PARAM_NAME']] === $this->arParams['AJAX_COMPONENT_ID']
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
)
{
return true;
}
return false;
} | [
"public",
"function",
"isAjax",
"(",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'AJAX_COMPONENT_ID'",
"]",
")",
">",
"0",
"&&",
"strlen",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'AJAX_PARAM_NAME'",
"]",
")",
">",
"0",
... | Is AJAX request
@return bool | [
"Is",
"AJAX",
"request"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/common.php#L478-L492 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.setSeoTags | protected function setSeoTags()
{
global $APPLICATION;
if ($this->arParams['SET_SEO_TAGS'] !== 'Y')
{
return false;
}
if ($this->arResult['SEO_TAGS']['TITLE'])
{
$APPLICATION->SetPageProperty('title', $this->arResult['SEO_TAGS']['TITLE']);
}
if ($this->arResult['SEO_TAGS']['DESCRIPTION'])
{
$APPLICATION->SetPageProperty('description', $this->arResult['SEO_TAGS']['DESCRIPTION']);
}
if ($this->arResult['SEO_TAGS']['KEYWORDS'])
{
$APPLICATION->SetPageProperty('keywords', $this->arResult['SEO_TAGS']['KEYWORDS']);
}
} | php | protected function setSeoTags()
{
global $APPLICATION;
if ($this->arParams['SET_SEO_TAGS'] !== 'Y')
{
return false;
}
if ($this->arResult['SEO_TAGS']['TITLE'])
{
$APPLICATION->SetPageProperty('title', $this->arResult['SEO_TAGS']['TITLE']);
}
if ($this->arResult['SEO_TAGS']['DESCRIPTION'])
{
$APPLICATION->SetPageProperty('description', $this->arResult['SEO_TAGS']['DESCRIPTION']);
}
if ($this->arResult['SEO_TAGS']['KEYWORDS'])
{
$APPLICATION->SetPageProperty('keywords', $this->arResult['SEO_TAGS']['KEYWORDS']);
}
} | [
"protected",
"function",
"setSeoTags",
"(",
")",
"{",
"global",
"$",
"APPLICATION",
";",
"if",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'SET_SEO_TAGS'",
"]",
"!==",
"'Y'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"arResult"... | Setting meta tags
<ul> Uses:
<li> title
<li> description
<li> keywords
</ul>
@uses arResult['SEO_TAGS'] | [
"Setting",
"meta",
"tags"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L342-L365 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.setOgTags | protected function setOgTags()
{
if ($this->arResult['OG_TAGS']['TITLE'])
{
Asset::getInstance()->addString('<meta property="og:title" content="'.$this->arResult['OG_TAGS']['TITLE'].'" />', true);
}
if ($this->arResult['OG_TAGS']['DESCRIPTION'])
{
Asset::getInstance()->addString('<meta property="og:description" content="'.$this->arResult['OG_TAGS']['DESCRIPTION'].'" />', true);
}
if ($this->arResult['OG_TAGS']['URL'])
{
Asset::getInstance()->addString('<meta property="og:url" content="'.$this->arResult['OG_TAGS']['URL'].'" />', true);
}
if ($this->arResult['OG_TAGS']['IMAGE'])
{
Asset::getInstance()->addString('<meta property="og:image" content="'.$this->arResult['OG_TAGS']['IMAGE'].'" />', true);
}
} | php | protected function setOgTags()
{
if ($this->arResult['OG_TAGS']['TITLE'])
{
Asset::getInstance()->addString('<meta property="og:title" content="'.$this->arResult['OG_TAGS']['TITLE'].'" />', true);
}
if ($this->arResult['OG_TAGS']['DESCRIPTION'])
{
Asset::getInstance()->addString('<meta property="og:description" content="'.$this->arResult['OG_TAGS']['DESCRIPTION'].'" />', true);
}
if ($this->arResult['OG_TAGS']['URL'])
{
Asset::getInstance()->addString('<meta property="og:url" content="'.$this->arResult['OG_TAGS']['URL'].'" />', true);
}
if ($this->arResult['OG_TAGS']['IMAGE'])
{
Asset::getInstance()->addString('<meta property="og:image" content="'.$this->arResult['OG_TAGS']['IMAGE'].'" />', true);
}
} | [
"protected",
"function",
"setOgTags",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"arResult",
"[",
"'OG_TAGS'",
"]",
"[",
"'TITLE'",
"]",
")",
"{",
"Asset",
"::",
"getInstance",
"(",
")",
"->",
"addString",
"(",
"'<meta property=\"og:title\" content=\"'",
"... | Setting open graph tags for current page
<ul> Uses:
<li> og:title
<li> og:url
<li> og:image
</ul>
@uses arResult['OG_TAGS'] | [
"Setting",
"open",
"graph",
"tags",
"for",
"current",
"page"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L403-L424 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.setEditButtons | protected function setEditButtons()
{
global $APPLICATION;
if (!$APPLICATION->GetShowIncludeAreas() || $this->showEditButtons === false)
{
return false;
}
$buttons = \CIBlock::GetPanelButtons(
$this->arParams['IBLOCK_ID'],
$this->arResult['ID'],
$this->arParams['SECTION_ID'],
[]
);
$this->addIncludeAreaIcons(\CIBlock::GetComponentMenu($APPLICATION->GetPublicShowMode(), $buttons));
if (is_array($buttons['intranet']))
{
Asset::getInstance()->addJs(BX_ROOT.'/js/main/utils.js');
foreach ($buttons['intranet'] as $button)
{
$this->addEditButton($button);
}
}
} | php | protected function setEditButtons()
{
global $APPLICATION;
if (!$APPLICATION->GetShowIncludeAreas() || $this->showEditButtons === false)
{
return false;
}
$buttons = \CIBlock::GetPanelButtons(
$this->arParams['IBLOCK_ID'],
$this->arResult['ID'],
$this->arParams['SECTION_ID'],
[]
);
$this->addIncludeAreaIcons(\CIBlock::GetComponentMenu($APPLICATION->GetPublicShowMode(), $buttons));
if (is_array($buttons['intranet']))
{
Asset::getInstance()->addJs(BX_ROOT.'/js/main/utils.js');
foreach ($buttons['intranet'] as $button)
{
$this->addEditButton($button);
}
}
} | [
"protected",
"function",
"setEditButtons",
"(",
")",
"{",
"global",
"$",
"APPLICATION",
";",
"if",
"(",
"!",
"$",
"APPLICATION",
"->",
"GetShowIncludeAreas",
"(",
")",
"||",
"$",
"this",
"->",
"showEditButtons",
"===",
"false",
")",
"{",
"return",
"false",
... | Add to page buttons for edit elements and sections of info-block | [
"Add",
"to",
"page",
"buttons",
"for",
"edit",
"elements",
"and",
"sections",
"of",
"info",
"-",
"block"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L429-L456 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.setParamsFilters | protected function setParamsFilters()
{
if ($this->arParams['IBLOCK_TYPE'])
{
$this->filterParams['IBLOCK_TYPE'] = $this->arParams['IBLOCK_TYPE'];
}
if ($this->arParams['IBLOCK_ID'])
{
$this->filterParams['IBLOCK_ID'] = $this->arParams['IBLOCK_ID'];
}
if ($this->arParams['SECTION_CODE'])
{
$this->filterParams['SECTION_CODE'] = $this->arParams['SECTION_CODE'];
}
elseif ($this->arParams['SECTION_ID'])
{
$this->filterParams['SECTION_ID'] = $this->arParams['SECTION_ID'];
}
if ($this->arParams['INCLUDE_SUBSECTIONS'] === 'Y')
{
$this->filterParams['INCLUDE_SUBSECTIONS'] = 'Y';
}
if ($this->arParams['ELEMENT_CODE'])
{
$this->filterParams['CODE'] = $this->arParams['ELEMENT_CODE'];
}
elseif ($this->arParams['ELEMENT_ID'])
{
$this->filterParams['ID'] = $this->arParams['ELEMENT_ID'];
}
if ($this->arParams['CHECK_PERMISSIONS'])
{
$this->filterParams['CHECK_PERMISSIONS'] = $this->arParams['CHECK_PERMISSIONS'];
}
if (!isset($this->filterParams['ACTIVE']))
{
$this->filterParams['ACTIVE'] = 'Y';
}
if (strlen($this->arParams['EX_FILTER_NAME']) > 0
&& preg_match("/^[A-Za-z_][A-Za-z01-9_]*$/", $this->arParams['EX_FILTER_NAME'])
&& is_array($GLOBALS[$this->arParams['EX_FILTER_NAME']])
)
{
$this->filterParams = array_merge_recursive($this->filterParams, $GLOBALS[$this->arParams['EX_FILTER_NAME']]);
$this->addCacheAdditionalId($GLOBALS[$this->arParams['EX_FILTER_NAME']]);
}
} | php | protected function setParamsFilters()
{
if ($this->arParams['IBLOCK_TYPE'])
{
$this->filterParams['IBLOCK_TYPE'] = $this->arParams['IBLOCK_TYPE'];
}
if ($this->arParams['IBLOCK_ID'])
{
$this->filterParams['IBLOCK_ID'] = $this->arParams['IBLOCK_ID'];
}
if ($this->arParams['SECTION_CODE'])
{
$this->filterParams['SECTION_CODE'] = $this->arParams['SECTION_CODE'];
}
elseif ($this->arParams['SECTION_ID'])
{
$this->filterParams['SECTION_ID'] = $this->arParams['SECTION_ID'];
}
if ($this->arParams['INCLUDE_SUBSECTIONS'] === 'Y')
{
$this->filterParams['INCLUDE_SUBSECTIONS'] = 'Y';
}
if ($this->arParams['ELEMENT_CODE'])
{
$this->filterParams['CODE'] = $this->arParams['ELEMENT_CODE'];
}
elseif ($this->arParams['ELEMENT_ID'])
{
$this->filterParams['ID'] = $this->arParams['ELEMENT_ID'];
}
if ($this->arParams['CHECK_PERMISSIONS'])
{
$this->filterParams['CHECK_PERMISSIONS'] = $this->arParams['CHECK_PERMISSIONS'];
}
if (!isset($this->filterParams['ACTIVE']))
{
$this->filterParams['ACTIVE'] = 'Y';
}
if (strlen($this->arParams['EX_FILTER_NAME']) > 0
&& preg_match("/^[A-Za-z_][A-Za-z01-9_]*$/", $this->arParams['EX_FILTER_NAME'])
&& is_array($GLOBALS[$this->arParams['EX_FILTER_NAME']])
)
{
$this->filterParams = array_merge_recursive($this->filterParams, $GLOBALS[$this->arParams['EX_FILTER_NAME']]);
$this->addCacheAdditionalId($GLOBALS[$this->arParams['EX_FILTER_NAME']]);
}
} | [
"protected",
"function",
"setParamsFilters",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'IBLOCK_TYPE'",
"]",
")",
"{",
"$",
"this",
"->",
"filterParams",
"[",
"'IBLOCK_TYPE'",
"]",
"=",
"$",
"this",
"->",
"arParams",
"[",
"'IBLOCK_TYPE'... | Getting global filter and write his to component parameters | [
"Getting",
"global",
"filter",
"and",
"write",
"his",
"to",
"component",
"parameters"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L461-L515 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.addGlobalFilters | public function addGlobalFilters(array $fields, $recursiveMerge = false)
{
if (is_array($fields) && !empty($fields))
{
if ($recursiveMerge)
{
$this->filterParams = array_merge_recursive($this->filterParams, $fields);
}
else
{
$this->filterParams = array_merge($this->filterParams, $fields);
}
$this->addCacheAdditionalId($fields);
}
} | php | public function addGlobalFilters(array $fields, $recursiveMerge = false)
{
if (is_array($fields) && !empty($fields))
{
if ($recursiveMerge)
{
$this->filterParams = array_merge_recursive($this->filterParams, $fields);
}
else
{
$this->filterParams = array_merge($this->filterParams, $fields);
}
$this->addCacheAdditionalId($fields);
}
} | [
"public",
"function",
"addGlobalFilters",
"(",
"array",
"$",
"fields",
",",
"$",
"recursiveMerge",
"=",
"false",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fields",
")",
"&&",
"!",
"empty",
"(",
"$",
"fields",
")",
")",
"{",
"if",
"(",
"$",
"recursi... | Add new fields to global filter
@param array $fields Array with fields
@param bool $recursiveMerge If true, $fields will be recursive merged with
other parameters (used array_merge_recursive()), otherwise not recursive merge (used array_merge()). | [
"Add",
"new",
"fields",
"to",
"global",
"filter"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L524-L539 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.addParamsGrouping | public function addParamsGrouping($fields = [])
{
if (is_array($fields) && !empty($fields))
{
$this->groupingParams = array_merge(is_array($this->groupingParams) ? $this->groupingParams : [], $fields);
}
} | php | public function addParamsGrouping($fields = [])
{
if (is_array($fields) && !empty($fields))
{
$this->groupingParams = array_merge(is_array($this->groupingParams) ? $this->groupingParams : [], $fields);
}
} | [
"public",
"function",
"addParamsGrouping",
"(",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fields",
")",
"&&",
"!",
"empty",
"(",
"$",
"fields",
")",
")",
"{",
"$",
"this",
"->",
"groupingParams",
"=",
"array_merge",
"(... | Add parameters to grouping
@param array $fields
@uses groupingParams | [
"Add",
"parameters",
"to",
"grouping"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L547-L553 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.addParamsNavStart | public function addParamsNavStart($params = [])
{
if (is_array($params) && !empty($params))
{
$this->navStartParams = array_merge(is_array($this->navStartParams) ? $this->navStartParams : array(), $params);
}
} | php | public function addParamsNavStart($params = [])
{
if (is_array($params) && !empty($params))
{
$this->navStartParams = array_merge(is_array($this->navStartParams) ? $this->navStartParams : array(), $params);
}
} | [
"public",
"function",
"addParamsNavStart",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"params",
")",
"&&",
"!",
"empty",
"(",
"$",
"params",
")",
")",
"{",
"$",
"this",
"->",
"navStartParams",
"=",
"array_merge",
"(... | Add parameters to pagination settings
@param array $params
@uses navStartParams | [
"Add",
"parameters",
"to",
"pagination",
"settings"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L561-L567 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.addParamsSelected | public function addParamsSelected($fields = null, $props = null)
{
if (is_array($fields) && !empty($fields))
{
$this->arParams['SELECT_FIELDS'] = array_merge($this->arParams['SELECT_FIELDS'], $fields);
}
if (is_array($props) && !empty($props))
{
$this->arParams['SELECT_PROPS'] = array_merge($this->arParams['SELECT_PROPS'], $props);
}
} | php | public function addParamsSelected($fields = null, $props = null)
{
if (is_array($fields) && !empty($fields))
{
$this->arParams['SELECT_FIELDS'] = array_merge($this->arParams['SELECT_FIELDS'], $fields);
}
if (is_array($props) && !empty($props))
{
$this->arParams['SELECT_PROPS'] = array_merge($this->arParams['SELECT_PROPS'], $props);
}
} | [
"public",
"function",
"addParamsSelected",
"(",
"$",
"fields",
"=",
"null",
",",
"$",
"props",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"fields",
")",
"&&",
"!",
"empty",
"(",
"$",
"fields",
")",
")",
"{",
"$",
"this",
"->",
"arParam... | Add selected fields and properties to parameters
@param array $fields
@param array $props | [
"Add",
"selected",
"fields",
"and",
"properties",
"to",
"parameters"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L575-L586 | train |
bitrix-expert/bbc-module | lib/traits/elements.php | Elements.processingElementsResult | protected function processingElementsResult($element)
{
$arElement = $element;
if ($this->arParams['RESULT_PROCESSING_MODE'] === 'EXTENDED')
{
$arElement = $element->GetFields();
$arElement['PROPS'] = $element->GetProperties();
}
elseif (!empty($this->arParams['SELECT_PROPS']))
{
foreach ($this->arParams['SELECT_PROPS'] as $propCode)
{
if (trim($propCode))
{
$arProp = explode('.', $propCode);
$propCode = array_shift($arProp);
$propValue = $element['PROPERTY_'.$propCode.'_VALUE'];
$propDescr = $element['PROPERTY_'.$propCode.'_DESCRIPTION'];
if ($propValue)
{
$arElement['PROPS'][$propCode]['VALUE'] = $propValue;
}
if ($propDescr)
{
$arElement['PROPS'][$propCode]['DESCRIPTION'] = $propDescr;
}
if (!empty($arElement['PROPS'][$propCode]))
{
foreach ($arProp as $field)
{
$arElement['PROPS'][$propCode]['LINKED'][$field] = $element['PROPERTY_'.$propCode.'_'.$field];
}
}
}
}
}
if ($arElement = $this->prepareElementsResult($arElement))
{
return $arElement;
}
else
{
return false;
}
} | php | protected function processingElementsResult($element)
{
$arElement = $element;
if ($this->arParams['RESULT_PROCESSING_MODE'] === 'EXTENDED')
{
$arElement = $element->GetFields();
$arElement['PROPS'] = $element->GetProperties();
}
elseif (!empty($this->arParams['SELECT_PROPS']))
{
foreach ($this->arParams['SELECT_PROPS'] as $propCode)
{
if (trim($propCode))
{
$arProp = explode('.', $propCode);
$propCode = array_shift($arProp);
$propValue = $element['PROPERTY_'.$propCode.'_VALUE'];
$propDescr = $element['PROPERTY_'.$propCode.'_DESCRIPTION'];
if ($propValue)
{
$arElement['PROPS'][$propCode]['VALUE'] = $propValue;
}
if ($propDescr)
{
$arElement['PROPS'][$propCode]['DESCRIPTION'] = $propDescr;
}
if (!empty($arElement['PROPS'][$propCode]))
{
foreach ($arProp as $field)
{
$arElement['PROPS'][$propCode]['LINKED'][$field] = $element['PROPERTY_'.$propCode.'_'.$field];
}
}
}
}
}
if ($arElement = $this->prepareElementsResult($arElement))
{
return $arElement;
}
else
{
return false;
}
} | [
"protected",
"function",
"processingElementsResult",
"(",
"$",
"element",
")",
"{",
"$",
"arElement",
"=",
"$",
"element",
";",
"if",
"(",
"$",
"this",
"->",
"arParams",
"[",
"'RESULT_PROCESSING_MODE'",
"]",
"===",
"'EXTENDED'",
")",
"{",
"$",
"arElement",
"... | Processing request of the elements
@param \CIBlockResult $element
@return array | [
"Processing",
"request",
"of",
"the",
"elements"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/traits/elements.php#L754-L803 | train |
bitrix-expert/bbc-module | lib/basis.php | Basis.executeTraits | private function executeTraits($type)
{
if (empty($this->usedTraits))
{
return;
}
switch ($type)
{
case 'prolog':
$type = 'Prolog';
break;
case 'main':
$type = 'Main';
break;
default:
$type = 'Epilog';
break;
}
foreach ($this->usedTraits as $trait => $name)
{
$method = 'execute'.$type.$name;
if (method_exists($trait, $method))
{
$this->$method();
}
}
} | php | private function executeTraits($type)
{
if (empty($this->usedTraits))
{
return;
}
switch ($type)
{
case 'prolog':
$type = 'Prolog';
break;
case 'main':
$type = 'Main';
break;
default:
$type = 'Epilog';
break;
}
foreach ($this->usedTraits as $trait => $name)
{
$method = 'execute'.$type.$name;
if (method_exists($trait, $method))
{
$this->$method();
}
}
} | [
"private",
"function",
"executeTraits",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"usedTraits",
")",
")",
"{",
"return",
";",
"}",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'prolog'",
":",
"$",
"type",
"=",
"'Prol... | Executing methods prolog, getResult and epilog included traits
@param string $type prolog, getResult or epilog | [
"Executing",
"methods",
"prolog",
"getResult",
"and",
"epilog",
"included",
"traits"
] | cc51b307e91b88ef8658e34a500ec4134be03689 | https://github.com/bitrix-expert/bbc-module/blob/cc51b307e91b88ef8658e34a500ec4134be03689/lib/basis.php#L34-L65 | train |
tipsyphp/tipsy | src/Resource.php | Resource.load | public function load($id = null) {
// fill the object with blank properties based on the fields of that table
$fields = $this->fields();
foreach ($fields as $key => $field) {
$this->{$key} = $this->{$key} ? $this->{$key} : '';
}
if (!$id && $this->dbId()) {
$id = $this->dbId();
}
if (is_object($id)) {
$node = $id;
} elseif (is_array($id)) {
$node = (object)$id;
} elseif ($id) {
if (!$node) {
$node = (object)$this->db()->get('select * from `' . $this->table() . '` where `'.$this->idVar().'` = ? limit 1', [$id])[0];
}
}
if (!$node) {
$node = new Model;
}
if (isset($node)) {
foreach(get_object_vars($node) as $var => $value) {
$this->$var = $value;
}
}
foreach ($this->fields() as $field) {
switch ($field->type) {
case 'int':
$this->{$field->field} = (int)$this->{$field->field};
break;
case 'boolean':
$this->{$field->field} = $this->{$field->field} ? true : false;
break;
}
}
if ($this->tipsy() && $this->tipsy()->config()['tipsy']['factory'] !== false) {
$this->tipsy()->factory($this);
}
return $this;
} | php | public function load($id = null) {
// fill the object with blank properties based on the fields of that table
$fields = $this->fields();
foreach ($fields as $key => $field) {
$this->{$key} = $this->{$key} ? $this->{$key} : '';
}
if (!$id && $this->dbId()) {
$id = $this->dbId();
}
if (is_object($id)) {
$node = $id;
} elseif (is_array($id)) {
$node = (object)$id;
} elseif ($id) {
if (!$node) {
$node = (object)$this->db()->get('select * from `' . $this->table() . '` where `'.$this->idVar().'` = ? limit 1', [$id])[0];
}
}
if (!$node) {
$node = new Model;
}
if (isset($node)) {
foreach(get_object_vars($node) as $var => $value) {
$this->$var = $value;
}
}
foreach ($this->fields() as $field) {
switch ($field->type) {
case 'int':
$this->{$field->field} = (int)$this->{$field->field};
break;
case 'boolean':
$this->{$field->field} = $this->{$field->field} ? true : false;
break;
}
}
if ($this->tipsy() && $this->tipsy()->config()['tipsy']['factory'] !== false) {
$this->tipsy()->factory($this);
}
return $this;
} | [
"public",
"function",
"load",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"// fill the object with blank properties based on the fields of that table",
"$",
"fields",
"=",
"$",
"this",
"->",
"fields",
"(",
")",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"key",
... | Load the object with properties
Passing in an object will populate $this with the current vars of that object
as public properties. Passing in an int id will load the object with the
table and key associated with the object.
@param $id object|int | [
"Load",
"the",
"object",
"with",
"properties"
] | 9d46d31dd6d29664a0dd5f85bd6a96d8b21e24af | https://github.com/tipsyphp/tipsy/blob/9d46d31dd6d29664a0dd5f85bd6a96d8b21e24af/src/Resource.php#L251-L300 | train |
tipsyphp/tipsy | src/Resource.php | Resource.delete | public function delete() {
if ($this->dbId()) {
$this->db()->query('DELETE FROM `'.$this->table().'` WHERE `'.$this->idVar().'` = ?', [$this->dbId()]);
} else {
throw new Exception('Cannot delete. No ID was given.');
}
return $this;
} | php | public function delete() {
if ($this->dbId()) {
$this->db()->query('DELETE FROM `'.$this->table().'` WHERE `'.$this->idVar().'` = ?', [$this->dbId()]);
} else {
throw new Exception('Cannot delete. No ID was given.');
}
return $this;
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"dbId",
"(",
")",
")",
"{",
"$",
"this",
"->",
"db",
"(",
")",
"->",
"query",
"(",
"'DELETE FROM `'",
".",
"$",
"this",
"->",
"table",
"(",
")",
".",
"'` WHERE `'",
".",... | Delete a row in a table | [
"Delete",
"a",
"row",
"in",
"a",
"table"
] | 9d46d31dd6d29664a0dd5f85bd6a96d8b21e24af | https://github.com/tipsyphp/tipsy/blob/9d46d31dd6d29664a0dd5f85bd6a96d8b21e24af/src/Resource.php#L411-L418 | train |
elcobvg/laravel-opcache | src/Repository.php | Repository.flush | public function flush()
{
$this->tags->getNames() ? $this->store->flushSub() : $this->store->flush();
} | php | public function flush()
{
$this->tags->getNames() ? $this->store->flushSub() : $this->store->flush();
} | [
"public",
"function",
"flush",
"(",
")",
"{",
"$",
"this",
"->",
"tags",
"->",
"getNames",
"(",
")",
"?",
"$",
"this",
"->",
"store",
"->",
"flushSub",
"(",
")",
":",
"$",
"this",
"->",
"store",
"->",
"flush",
"(",
")",
";",
"}"
] | Remove all items from the cache. If called with tags, only reset them.
@return void | [
"Remove",
"all",
"items",
"from",
"the",
"cache",
".",
"If",
"called",
"with",
"tags",
"only",
"reset",
"them",
"."
] | 2b559c22521a78b089f7121f01203e03be0ee987 | https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Repository.php#L35-L38 | train |
elcobvg/laravel-opcache | src/Store.php | Store.exists | protected function exists($key)
{
if ($this->enabled && opcache_is_script_cached($this->filePath($key))) {
return true;
}
return file_exists($this->filePath($key));
} | php | protected function exists($key)
{
if ($this->enabled && opcache_is_script_cached($this->filePath($key))) {
return true;
}
return file_exists($this->filePath($key));
} | [
"protected",
"function",
"exists",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"enabled",
"&&",
"opcache_is_script_cached",
"(",
"$",
"this",
"->",
"filePath",
"(",
"$",
"key",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"f... | Determines whether the key exists within the cache.
@param string $key
@return bool | [
"Determines",
"whether",
"the",
"key",
"exists",
"within",
"the",
"cache",
"."
] | 2b559c22521a78b089f7121f01203e03be0ee987 | https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Store.php#L101-L107 | train |
elcobvg/laravel-opcache | src/Store.php | Store.writeFile | protected function writeFile(string $key, int $exp, $val)
{
// Write to temp file first to ensure atomicity. Use crc32 for speed
$dir = $this->getFullDirectory();
$this->checkDirectory($dir);
$tmp = $dir . DIRECTORY_SEPARATOR . crc32($key) . '-' . uniqid('', true) . '.tmp';
file_put_contents($tmp, '<?php $exp = ' . $exp . '; $val = ' . $val . ';', LOCK_EX);
return rename($tmp, $this->filePath($key));
} | php | protected function writeFile(string $key, int $exp, $val)
{
// Write to temp file first to ensure atomicity. Use crc32 for speed
$dir = $this->getFullDirectory();
$this->checkDirectory($dir);
$tmp = $dir . DIRECTORY_SEPARATOR . crc32($key) . '-' . uniqid('', true) . '.tmp';
file_put_contents($tmp, '<?php $exp = ' . $exp . '; $val = ' . $val . ';', LOCK_EX);
return rename($tmp, $this->filePath($key));
} | [
"protected",
"function",
"writeFile",
"(",
"string",
"$",
"key",
",",
"int",
"$",
"exp",
",",
"$",
"val",
")",
"{",
"// Write to temp file first to ensure atomicity. Use crc32 for speed",
"$",
"dir",
"=",
"$",
"this",
"->",
"getFullDirectory",
"(",
")",
";",
"$"... | Write the cache file to disk
@param string $key
@param int $exp
@param mixed $val
@return bool | [
"Write",
"the",
"cache",
"file",
"to",
"disk"
] | 2b559c22521a78b089f7121f01203e03be0ee987 | https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Store.php#L353-L361 | train |
elcobvg/laravel-opcache | src/Store.php | Store.extendExpiration | public function extendExpiration(string $key, int $minutes = 1)
{
@include $this->filePath($key);
if (isset($exp)) {
$extended = strtotime('+' . $minutes . ' minutes', $exp);
return $this->writeFile($key, $extended, var_export($val, true));
}
return false;
} | php | public function extendExpiration(string $key, int $minutes = 1)
{
@include $this->filePath($key);
if (isset($exp)) {
$extended = strtotime('+' . $minutes . ' minutes', $exp);
return $this->writeFile($key, $extended, var_export($val, true));
}
return false;
} | [
"public",
"function",
"extendExpiration",
"(",
"string",
"$",
"key",
",",
"int",
"$",
"minutes",
"=",
"1",
")",
"{",
"@",
"include",
"$",
"this",
"->",
"filePath",
"(",
"$",
"key",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"exp",
")",
")",
"{",
"$"... | Extend expiration time with given minutes
@param string $key
@param int $minutes
@return bool | [
"Extend",
"expiration",
"time",
"with",
"given",
"minutes"
] | 2b559c22521a78b089f7121f01203e03be0ee987 | https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Store.php#L392-L401 | train |
hocza/sendy-laravel | src/Sendy.php | Sendy.subscribe | public function subscribe(array $values)
{
$result = $this->buildAndSend('subscribe', $values);
/**
* Prepare the array to return
*/
$notice = [
'status' => true,
'message' => '',
];
/**
* Handle results
*/
switch (strval($result)) {
case '1':
$notice['message'] = 'Subscribed.';
break;
case 'Already subscribed.':
$notice['message'] = $result;
break;
default:
$notice = [
'status' => false,
'message' => $result
];
break;
}
return $notice;
} | php | public function subscribe(array $values)
{
$result = $this->buildAndSend('subscribe', $values);
/**
* Prepare the array to return
*/
$notice = [
'status' => true,
'message' => '',
];
/**
* Handle results
*/
switch (strval($result)) {
case '1':
$notice['message'] = 'Subscribed.';
break;
case 'Already subscribed.':
$notice['message'] = $result;
break;
default:
$notice = [
'status' => false,
'message' => $result
];
break;
}
return $notice;
} | [
"public",
"function",
"subscribe",
"(",
"array",
"$",
"values",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"buildAndSend",
"(",
"'subscribe'",
",",
"$",
"values",
")",
";",
"/**\n * Prepare the array to return\n */",
"$",
"notice",
"=",
"["... | Method to add a new subscriber to a list
@param array $values
@return array | [
"Method",
"to",
"add",
"a",
"new",
"subscriber",
"to",
"a",
"list"
] | d1e7b8e1ee8315e4aa4d1d33e86deeae55357110 | https://github.com/hocza/sendy-laravel/blob/d1e7b8e1ee8315e4aa4d1d33e86deeae55357110/src/Sendy.php#L69-L103 | train |
hocza/sendy-laravel | src/Sendy.php | Sendy.unsubscribe | public function unsubscribe($email)
{
$result = $this->buildAndSend('unsubscribe', ['email' => $email]);
/**
* Prepare the array to return
*/
$notice = [
'status' => true,
'message' => '',
];
/**
* Handle results
*/
switch (strval($result)) {
case '1':
$notice['message'] = 'Unsubscribed';
break;
default:
$notice = [
'status' => false,
'message' => $result
];
break;
}
return $notice;
} | php | public function unsubscribe($email)
{
$result = $this->buildAndSend('unsubscribe', ['email' => $email]);
/**
* Prepare the array to return
*/
$notice = [
'status' => true,
'message' => '',
];
/**
* Handle results
*/
switch (strval($result)) {
case '1':
$notice['message'] = 'Unsubscribed';
break;
default:
$notice = [
'status' => false,
'message' => $result
];
break;
}
return $notice;
} | [
"public",
"function",
"unsubscribe",
"(",
"$",
"email",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"buildAndSend",
"(",
"'unsubscribe'",
",",
"[",
"'email'",
"=>",
"$",
"email",
"]",
")",
";",
"/**\n * Prepare the array to return\n */",
"$"... | Method to unsubscribe a user from a list
@param $email
@return array | [
"Method",
"to",
"unsubscribe",
"a",
"user",
"from",
"a",
"list"
] | d1e7b8e1ee8315e4aa4d1d33e86deeae55357110 | https://github.com/hocza/sendy-laravel/blob/d1e7b8e1ee8315e4aa4d1d33e86deeae55357110/src/Sendy.php#L130-L160 | train |
hocza/sendy-laravel | src/Sendy.php | Sendy.checkProperties | private function checkProperties()
{
if (!isset($this->listId)) {
throw new \Exception('[listId] is not set', 1);
}
if (!isset($this->installationUrl)) {
throw new \Exception('[installationUrl] is not set', 1);
}
if (!isset($this->apiKey)) {
throw new \Exception('[apiKey] is not set', 1);
}
} | php | private function checkProperties()
{
if (!isset($this->listId)) {
throw new \Exception('[listId] is not set', 1);
}
if (!isset($this->installationUrl)) {
throw new \Exception('[installationUrl] is not set', 1);
}
if (!isset($this->apiKey)) {
throw new \Exception('[apiKey] is not set', 1);
}
} | [
"private",
"function",
"checkProperties",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"listId",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'[listId] is not set'",
",",
"1",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",... | Checks the properties
@throws \Exception | [
"Checks",
"the",
"properties"
] | d1e7b8e1ee8315e4aa4d1d33e86deeae55357110 | https://github.com/hocza/sendy-laravel/blob/d1e7b8e1ee8315e4aa4d1d33e86deeae55357110/src/Sendy.php#L285-L298 | train |
CarbonDate/Carbon | src/Carbon/Carbon.php | Carbon.createSafe | public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
{
$fields = array(
'year' => array(0, 9999),
'month' => array(0, 12),
'day' => array(0, 31),
'hour' => array(0, 24),
'minute' => array(0, 59),
'second' => array(0, 59),
);
foreach ($fields as $field => $range) {
if ($$field !== null && (!is_int($$field) || $$field < $range[0] || $$field > $range[1])) {
throw new InvalidDateException($field, $$field);
}
}
$instance = static::create($year, $month, $day, $hour, $minute, $second, $tz);
foreach (array_reverse($fields) as $field => $range) {
if ($$field !== null && (!is_int($$field) || $$field !== $instance->$field)) {
throw new InvalidDateException($field, $$field);
}
}
return $instance;
} | php | public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
{
$fields = array(
'year' => array(0, 9999),
'month' => array(0, 12),
'day' => array(0, 31),
'hour' => array(0, 24),
'minute' => array(0, 59),
'second' => array(0, 59),
);
foreach ($fields as $field => $range) {
if ($$field !== null && (!is_int($$field) || $$field < $range[0] || $$field > $range[1])) {
throw new InvalidDateException($field, $$field);
}
}
$instance = static::create($year, $month, $day, $hour, $minute, $second, $tz);
foreach (array_reverse($fields) as $field => $range) {
if ($$field !== null && (!is_int($$field) || $$field !== $instance->$field)) {
throw new InvalidDateException($field, $$field);
}
}
return $instance;
} | [
"public",
"static",
"function",
"createSafe",
"(",
"$",
"year",
"=",
"null",
",",
"$",
"month",
"=",
"null",
",",
"$",
"day",
"=",
"null",
",",
"$",
"hour",
"=",
"null",
",",
"$",
"minute",
"=",
"null",
",",
"$",
"second",
"=",
"null",
",",
"$",
... | Create a new safe Carbon instance from a specific date and time.
If any of $year, $month or $day are set to null their now() values will
be used.
If $hour is null it will be set to its now() value and the default
values for $minute and $second will be their now() values.
If $hour is not null then the default values for $minute and $second
will be 0.
If one of the set values is not valid, an \InvalidArgumentException
will be thrown.
@param int|null $year
@param int|null $month
@param int|null $day
@param int|null $hour
@param int|null $minute
@param int|null $second
@param \DateTimeZone|string|null $tz
@throws \Carbon\Exceptions\InvalidDateException|\InvalidArgumentException
@return static | [
"Create",
"a",
"new",
"safe",
"Carbon",
"instance",
"from",
"a",
"specific",
"date",
"and",
"time",
"."
] | 81476b3fb6b907087ddbe4eabd581eba38d55661 | https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L728-L754 | train |
CarbonDate/Carbon | src/Carbon/Carbon.php | Carbon.setTimeFrom | public function setTimeFrom($date)
{
$date = static::instance($date);
$this->setTime($date->hour, $date->minute, $date->second);
return $this;
} | php | public function setTimeFrom($date)
{
$date = static::instance($date);
$this->setTime($date->hour, $date->minute, $date->second);
return $this;
} | [
"public",
"function",
"setTimeFrom",
"(",
"$",
"date",
")",
"{",
"$",
"date",
"=",
"static",
"::",
"instance",
"(",
"$",
"date",
")",
";",
"$",
"this",
"->",
"setTime",
"(",
"$",
"date",
"->",
"hour",
",",
"$",
"date",
"->",
"minute",
",",
"$",
"... | Set the hour, day, and time for this instance to that of the passed instance.
@param \Carbon\Carbon|\DateTimeInterface $date
@return static | [
"Set",
"the",
"hour",
"day",
"and",
"time",
"for",
"this",
"instance",
"to",
"that",
"of",
"the",
"passed",
"instance",
"."
] | 81476b3fb6b907087ddbe4eabd581eba38d55661 | https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L1339-L1346 | train |
CarbonDate/Carbon | src/Carbon/Carbon.php | Carbon.toArray | public function toArray()
{
return array(
'year' => $this->year,
'month' => $this->month,
'day' => $this->day,
'dayOfWeek' => $this->dayOfWeek,
'dayOfYear' => $this->dayOfYear,
'hour' => $this->hour,
'minute' => $this->minute,
'second' => $this->second,
'micro' => $this->micro,
'timestamp' => $this->timestamp,
'formatted' => $this->format(self::DEFAULT_TO_STRING_FORMAT),
'timezone' => $this->timezone,
);
} | php | public function toArray()
{
return array(
'year' => $this->year,
'month' => $this->month,
'day' => $this->day,
'dayOfWeek' => $this->dayOfWeek,
'dayOfYear' => $this->dayOfYear,
'hour' => $this->hour,
'minute' => $this->minute,
'second' => $this->second,
'micro' => $this->micro,
'timestamp' => $this->timestamp,
'formatted' => $this->format(self::DEFAULT_TO_STRING_FORMAT),
'timezone' => $this->timezone,
);
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"return",
"array",
"(",
"'year'",
"=>",
"$",
"this",
"->",
"year",
",",
"'month'",
"=>",
"$",
"this",
"->",
"month",
",",
"'day'",
"=>",
"$",
"this",
"->",
"day",
",",
"'dayOfWeek'",
"=>",
"$",
"this",
... | Get default array representation
@return array | [
"Get",
"default",
"array",
"representation"
] | 81476b3fb6b907087ddbe4eabd581eba38d55661 | https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L1835-L1851 | train |
CarbonDate/Carbon | src/Carbon/Carbon.php | Carbon.mixin | public static function mixin($mixin)
{
$reflection = new \ReflectionClass($mixin);
$methods = $reflection->getMethods(
\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED
);
foreach ($methods as $method) {
$method->setAccessible(true);
static::macro($method->name, $method->invoke($mixin));
}
} | php | public static function mixin($mixin)
{
$reflection = new \ReflectionClass($mixin);
$methods = $reflection->getMethods(
\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED
);
foreach ($methods as $method) {
$method->setAccessible(true);
static::macro($method->name, $method->invoke($mixin));
}
} | [
"public",
"static",
"function",
"mixin",
"(",
"$",
"mixin",
")",
"{",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"mixin",
")",
";",
"$",
"methods",
"=",
"$",
"reflection",
"->",
"getMethods",
"(",
"\\",
"ReflectionMethod",
"::",
"I... | Mix another object into the class.
@param object $mixin
@throws \ReflectionException
@return void | [
"Mix",
"another",
"object",
"into",
"the",
"class",
"."
] | 81476b3fb6b907087ddbe4eabd581eba38d55661 | https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L4454-L4466 | train |
CarbonDate/Carbon | src/Carbon/CarbonInterval.php | CarbonInterval.fromString | public static function fromString($intervalDefinition)
{
if (empty($intervalDefinition)) {
return new static(0);
}
$years = 0;
$months = 0;
$weeks = 0;
$days = 0;
$hours = 0;
$minutes = 0;
$seconds = 0;
$pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i';
preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER);
while ($match = array_shift($parts)) {
list($part, $value, $unit) = $match;
$intValue = intval($value);
$fraction = floatval($value) - $intValue;
switch (strtolower($unit)) {
case 'year':
case 'years':
case 'y':
$years += $intValue;
break;
case 'month':
case 'months':
case 'mo':
$months += $intValue;
break;
case 'week':
case 'weeks':
case 'w':
$weeks += $intValue;
if ($fraction != 0) {
$parts[] = array(null, $fraction * Carbon::DAYS_PER_WEEK, 'd');
}
break;
case 'day':
case 'days':
case 'd':
$days += $intValue;
if ($fraction != 0) {
$parts[] = array(null, $fraction * Carbon::HOURS_PER_DAY, 'h');
}
break;
case 'hour':
case 'hours':
case 'h':
$hours += $intValue;
if ($fraction != 0) {
$parts[] = array(null, $fraction * Carbon::MINUTES_PER_HOUR, 'm');
}
break;
case 'minute':
case 'minutes':
case 'm':
$minutes += $intValue;
if ($fraction != 0) {
$seconds += round($fraction * Carbon::SECONDS_PER_MINUTE);
}
break;
case 'second':
case 'seconds':
case 's':
$seconds += $intValue;
break;
default:
throw new InvalidArgumentException(
sprintf('Invalid part %s in definition %s', $part, $intervalDefinition)
);
}
}
return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds);
} | php | public static function fromString($intervalDefinition)
{
if (empty($intervalDefinition)) {
return new static(0);
}
$years = 0;
$months = 0;
$weeks = 0;
$days = 0;
$hours = 0;
$minutes = 0;
$seconds = 0;
$pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i';
preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER);
while ($match = array_shift($parts)) {
list($part, $value, $unit) = $match;
$intValue = intval($value);
$fraction = floatval($value) - $intValue;
switch (strtolower($unit)) {
case 'year':
case 'years':
case 'y':
$years += $intValue;
break;
case 'month':
case 'months':
case 'mo':
$months += $intValue;
break;
case 'week':
case 'weeks':
case 'w':
$weeks += $intValue;
if ($fraction != 0) {
$parts[] = array(null, $fraction * Carbon::DAYS_PER_WEEK, 'd');
}
break;
case 'day':
case 'days':
case 'd':
$days += $intValue;
if ($fraction != 0) {
$parts[] = array(null, $fraction * Carbon::HOURS_PER_DAY, 'h');
}
break;
case 'hour':
case 'hours':
case 'h':
$hours += $intValue;
if ($fraction != 0) {
$parts[] = array(null, $fraction * Carbon::MINUTES_PER_HOUR, 'm');
}
break;
case 'minute':
case 'minutes':
case 'm':
$minutes += $intValue;
if ($fraction != 0) {
$seconds += round($fraction * Carbon::SECONDS_PER_MINUTE);
}
break;
case 'second':
case 'seconds':
case 's':
$seconds += $intValue;
break;
default:
throw new InvalidArgumentException(
sprintf('Invalid part %s in definition %s', $part, $intervalDefinition)
);
}
}
return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds);
} | [
"public",
"static",
"function",
"fromString",
"(",
"$",
"intervalDefinition",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"intervalDefinition",
")",
")",
"{",
"return",
"new",
"static",
"(",
"0",
")",
";",
"}",
"$",
"years",
"=",
"0",
";",
"$",
"months",
... | Creates a CarbonInterval from string
Format:
Suffix | Unit | Example | DateInterval expression
-------|---------|---------|------------------------
y | years | 1y | P1Y
mo | months | 3mo | P3M
w | weeks | 2w | P2W
d | days | 28d | P28D
h | hours | 4h | PT4H
m | minutes | 12m | PT12M
s | seconds | 59s | PT59S
e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds.
Special cases:
- An empty string will return a zero interval
- Fractions are allowed for weeks, days, hours and minutes and will be converted
and rounded to the next smaller value (caution: 0.5w = 4d)
@param string $intervalDefinition
@return static | [
"Creates",
"a",
"CarbonInterval",
"from",
"string"
] | 81476b3fb6b907087ddbe4eabd581eba38d55661 | https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/CarbonInterval.php#L244-L327 | train |
CarbonDate/Carbon | src/Carbon/CarbonInterval.php | CarbonInterval.compareDateIntervals | public static function compareDateIntervals(DateInterval $a, DateInterval $b)
{
$current = Carbon::now();
$passed = $current->copy()->add($b);
$current->add($a);
if ($current < $passed) {
return -1;
} elseif ($current > $passed) {
return 1;
}
return 0;
} | php | public static function compareDateIntervals(DateInterval $a, DateInterval $b)
{
$current = Carbon::now();
$passed = $current->copy()->add($b);
$current->add($a);
if ($current < $passed) {
return -1;
} elseif ($current > $passed) {
return 1;
}
return 0;
} | [
"public",
"static",
"function",
"compareDateIntervals",
"(",
"DateInterval",
"$",
"a",
",",
"DateInterval",
"$",
"b",
")",
"{",
"$",
"current",
"=",
"Carbon",
"::",
"now",
"(",
")",
";",
"$",
"passed",
"=",
"$",
"current",
"->",
"copy",
"(",
")",
"->",... | Comparing 2 date intervals
@param DateInterval $a
@param DateInterval $b
@return int | [
"Comparing",
"2",
"date",
"intervals"
] | 81476b3fb6b907087ddbe4eabd581eba38d55661 | https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/CarbonInterval.php#L703-L716 | train |
oat-sa/extension-tao-outcomerds | model/RdsResultStorage.php | RdsResultStorage.storeRelatedDelivery | public function storeRelatedDelivery($deliveryResultIdentifier, $deliveryIdentifier)
{
$sql = 'SELECT COUNT(*) FROM ' . self::RESULTS_TABLENAME .
' WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
$params = array($deliveryResultIdentifier);
if ($this->getPersistence()->query($sql, $params)->fetchColumn() == 0) {
$this->getPersistence()->insert(
self::RESULTS_TABLENAME,
array(self::DELIVERY_COLUMN => $deliveryIdentifier, self::RESULTS_TABLE_ID => $deliveryResultIdentifier)
);
} else {
$sqlUpdate = 'UPDATE ' . self::RESULTS_TABLENAME . ' SET ' . self::DELIVERY_COLUMN . ' = ? WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
$paramsUpdate = array($deliveryIdentifier, $deliveryResultIdentifier);
$this->getPersistence()->exec($sqlUpdate, $paramsUpdate);
}
} | php | public function storeRelatedDelivery($deliveryResultIdentifier, $deliveryIdentifier)
{
$sql = 'SELECT COUNT(*) FROM ' . self::RESULTS_TABLENAME .
' WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
$params = array($deliveryResultIdentifier);
if ($this->getPersistence()->query($sql, $params)->fetchColumn() == 0) {
$this->getPersistence()->insert(
self::RESULTS_TABLENAME,
array(self::DELIVERY_COLUMN => $deliveryIdentifier, self::RESULTS_TABLE_ID => $deliveryResultIdentifier)
);
} else {
$sqlUpdate = 'UPDATE ' . self::RESULTS_TABLENAME . ' SET ' . self::DELIVERY_COLUMN . ' = ? WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
$paramsUpdate = array($deliveryIdentifier, $deliveryResultIdentifier);
$this->getPersistence()->exec($sqlUpdate, $paramsUpdate);
}
} | [
"public",
"function",
"storeRelatedDelivery",
"(",
"$",
"deliveryResultIdentifier",
",",
"$",
"deliveryIdentifier",
")",
"{",
"$",
"sql",
"=",
"'SELECT COUNT(*) FROM '",
".",
"self",
"::",
"RESULTS_TABLENAME",
".",
"' WHERE '",
".",
"self",
"::",
"RESULTS_TABLE_ID",
... | Store Delivery corresponding to the current test
@param $deliveryResultIdentifier
@param $deliveryIdentifier | [
"Store",
"Delivery",
"corresponding",
"to",
"the",
"current",
"test"
] | 692699d12dafe84eafece38fad03e7728370c9ac | https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L234-L249 | train |
oat-sa/extension-tao-outcomerds | model/RdsResultStorage.php | RdsResultStorage.getVariable | public function getVariable($callId, $variableIdentifier)
{
$sql = 'SELECT * FROM ' . self::VARIABLES_TABLENAME . '
WHERE (' . self::CALL_ID_ITEM_COLUMN . ' = ? OR ' . self::CALL_ID_TEST_COLUMN . ' = ?)
AND ' . self::VARIABLE_IDENTIFIER . ' = ?';
$params = array($callId, $callId, $variableIdentifier);
$variables = $this->getPersistence()->query($sql, $params);
$returnValue = array();
// for each variable we construct the array
foreach ($variables as $variable) {
$returnValue[$variable[self::VARIABLES_TABLE_ID]] = $this->getResultRow($variable);
}
return $returnValue;
} | php | public function getVariable($callId, $variableIdentifier)
{
$sql = 'SELECT * FROM ' . self::VARIABLES_TABLENAME . '
WHERE (' . self::CALL_ID_ITEM_COLUMN . ' = ? OR ' . self::CALL_ID_TEST_COLUMN . ' = ?)
AND ' . self::VARIABLE_IDENTIFIER . ' = ?';
$params = array($callId, $callId, $variableIdentifier);
$variables = $this->getPersistence()->query($sql, $params);
$returnValue = array();
// for each variable we construct the array
foreach ($variables as $variable) {
$returnValue[$variable[self::VARIABLES_TABLE_ID]] = $this->getResultRow($variable);
}
return $returnValue;
} | [
"public",
"function",
"getVariable",
"(",
"$",
"callId",
",",
"$",
"variableIdentifier",
")",
"{",
"$",
"sql",
"=",
"'SELECT * FROM '",
".",
"self",
"::",
"VARIABLES_TABLENAME",
".",
"'\n WHERE ('",
".",
"self",
"::",
"CALL_ID_ITEM_COLUMN",
".",
"' = ? OR '... | Get a variable from callId and Variable identifier
@param $callId
@param $variableIdentifier
@return array | [
"Get",
"a",
"variable",
"from",
"callId",
"and",
"Variable",
"identifier"
] | 692699d12dafe84eafece38fad03e7728370c9ac | https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L321-L338 | train |
oat-sa/extension-tao-outcomerds | model/RdsResultStorage.php | RdsResultStorage.getDelivery | public function getDelivery($deliveryResultIdentifier)
{
$sql = 'SELECT ' . self::DELIVERY_COLUMN . ' FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
$params = array($deliveryResultIdentifier);
return $this->getPersistence()->query($sql, $params)->fetchColumn();
} | php | public function getDelivery($deliveryResultIdentifier)
{
$sql = 'SELECT ' . self::DELIVERY_COLUMN . ' FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
$params = array($deliveryResultIdentifier);
return $this->getPersistence()->query($sql, $params)->fetchColumn();
} | [
"public",
"function",
"getDelivery",
"(",
"$",
"deliveryResultIdentifier",
")",
"{",
"$",
"sql",
"=",
"'SELECT '",
".",
"self",
"::",
"DELIVERY_COLUMN",
".",
"' FROM '",
".",
"self",
"::",
"RESULTS_TABLENAME",
".",
"' WHERE '",
".",
"self",
"::",
"RESULTS_TABLE_... | get delivery corresponding to a result
@param $deliveryResultIdentifier
@return mixed | [
"get",
"delivery",
"corresponding",
"to",
"a",
"result"
] | 692699d12dafe84eafece38fad03e7728370c9ac | https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L374-L379 | train |
oat-sa/extension-tao-outcomerds | model/RdsResultStorage.php | RdsResultStorage.getResultByDelivery | public function getResultByDelivery($delivery, $options = array())
{
$returnValue = array();
$sql = 'SELECT * FROM ' . self::RESULTS_TABLENAME;
$params = array();
if (count($delivery) > 0) {
$sql .= ' WHERE ';
$inQuery = implode(',', array_fill(0, count($delivery), '?'));
$sql .= self::DELIVERY_COLUMN . ' IN (' . $inQuery . ')';
$params = array_merge($params, $delivery);
}
if(isset($options['order']) && in_array($options['order'], [self::DELIVERY_COLUMN, self::TEST_TAKER_COLUMN, self::RESULTS_TABLE_ID])){
$sql .= ' ORDER BY ' . $options['order'];
if(isset($options['orderdir']) && (strtolower($options['orderdir']) === 'asc' || strtolower($options['orderdir']) === 'desc')) {
$sql .= ' ' . $options['orderdir'];
}
}
if(isset($options['offset']) || isset($options['limit'])){
$offset = (isset($options['offset']))?$options['offset']:0;
$limit = (isset($options['limit']))?$options['limit']:1000;
$sql = $this->getPersistence()->getPlatForm()->limitStatement($sql, $limit, $offset);
}
$results = $this->getPersistence()->query($sql, $params);
foreach ($results as $value) {
$returnValue[] = array(
"deliveryResultIdentifier" => $value[self::RESULTS_TABLE_ID],
"testTakerIdentifier" => $value[self::TEST_TAKER_COLUMN],
"deliveryIdentifier" => $value[self::DELIVERY_COLUMN]
);
}
return $returnValue;
} | php | public function getResultByDelivery($delivery, $options = array())
{
$returnValue = array();
$sql = 'SELECT * FROM ' . self::RESULTS_TABLENAME;
$params = array();
if (count($delivery) > 0) {
$sql .= ' WHERE ';
$inQuery = implode(',', array_fill(0, count($delivery), '?'));
$sql .= self::DELIVERY_COLUMN . ' IN (' . $inQuery . ')';
$params = array_merge($params, $delivery);
}
if(isset($options['order']) && in_array($options['order'], [self::DELIVERY_COLUMN, self::TEST_TAKER_COLUMN, self::RESULTS_TABLE_ID])){
$sql .= ' ORDER BY ' . $options['order'];
if(isset($options['orderdir']) && (strtolower($options['orderdir']) === 'asc' || strtolower($options['orderdir']) === 'desc')) {
$sql .= ' ' . $options['orderdir'];
}
}
if(isset($options['offset']) || isset($options['limit'])){
$offset = (isset($options['offset']))?$options['offset']:0;
$limit = (isset($options['limit']))?$options['limit']:1000;
$sql = $this->getPersistence()->getPlatForm()->limitStatement($sql, $limit, $offset);
}
$results = $this->getPersistence()->query($sql, $params);
foreach ($results as $value) {
$returnValue[] = array(
"deliveryResultIdentifier" => $value[self::RESULTS_TABLE_ID],
"testTakerIdentifier" => $value[self::TEST_TAKER_COLUMN],
"deliveryIdentifier" => $value[self::DELIVERY_COLUMN]
);
}
return $returnValue;
} | [
"public",
"function",
"getResultByDelivery",
"(",
"$",
"delivery",
",",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"returnValue",
"=",
"array",
"(",
")",
";",
"$",
"sql",
"=",
"'SELECT * FROM '",
".",
"self",
"::",
"RESULTS_TABLENAME",
";",
"... | order, orderdir, offset, limit | [
"order",
"orderdir",
"offset",
"limit"
] | 692699d12dafe84eafece38fad03e7728370c9ac | https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L474-L510 | train |
oat-sa/extension-tao-outcomerds | scripts/tools/KvToRdsMigration.php | KvToRdsMigration.getCurrentKvResultStorage | protected function getCurrentKvResultStorage()
{
/** @var ResultServerService $resultService */
$resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID);
$resultStorageKey = $resultService->getOption(ResultServerService::OPTION_RESULT_STORAGE);
if ($resultStorageKey != 'taoAltResultStorage/KeyValueResultStorage') {
throw new \common_Exception('Result storage is not on KeyValue storage mode.');
}
return $resultService->instantiateResultStorage($resultStorageKey);
} | php | protected function getCurrentKvResultStorage()
{
/** @var ResultServerService $resultService */
$resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID);
$resultStorageKey = $resultService->getOption(ResultServerService::OPTION_RESULT_STORAGE);
if ($resultStorageKey != 'taoAltResultStorage/KeyValueResultStorage') {
throw new \common_Exception('Result storage is not on KeyValue storage mode.');
}
return $resultService->instantiateResultStorage($resultStorageKey);
} | [
"protected",
"function",
"getCurrentKvResultStorage",
"(",
")",
"{",
"/** @var ResultServerService $resultService */",
"$",
"resultService",
"=",
"$",
"this",
"->",
"getServiceLocator",
"(",
")",
"->",
"get",
"(",
"ResultServerService",
"::",
"SERVICE_ID",
")",
";",
"... | Get the configured service to deal with result storage
@return \taoResultServer_models_classes_WritableResultStorage
@throws \common_exception If the service is not a key value interface | [
"Get",
"the",
"configured",
"service",
"to",
"deal",
"with",
"result",
"storage"
] | 692699d12dafe84eafece38fad03e7728370c9ac | https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/scripts/tools/KvToRdsMigration.php#L198-L207 | train |
oat-sa/extension-tao-outcomerds | scripts/tools/KvToRdsMigration.php | KvToRdsMigration.setCurrentResultStorageToRdsStorage | protected function setCurrentResultStorageToRdsStorage()
{
if ($this->isDryrun()) {
return;
}
/** @var ResultServerService $resultService */
$resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID);
$resultService->setOption(ResultServerService::OPTION_RESULT_STORAGE, RdsResultStorage::SERVICE_ID);
$this->registerService(ResultServerService::SERVICE_ID, $resultService);
$this->report->add(\common_report_Report::createSuccess('Storage type successfully updated to RDS Storage'));
} | php | protected function setCurrentResultStorageToRdsStorage()
{
if ($this->isDryrun()) {
return;
}
/** @var ResultServerService $resultService */
$resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID);
$resultService->setOption(ResultServerService::OPTION_RESULT_STORAGE, RdsResultStorage::SERVICE_ID);
$this->registerService(ResultServerService::SERVICE_ID, $resultService);
$this->report->add(\common_report_Report::createSuccess('Storage type successfully updated to RDS Storage'));
} | [
"protected",
"function",
"setCurrentResultStorageToRdsStorage",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isDryrun",
"(",
")",
")",
"{",
"return",
";",
"}",
"/** @var ResultServerService $resultService */",
"$",
"resultService",
"=",
"$",
"this",
"->",
"getSer... | Register rdsStorage as default result storage
@throws \common_Exception | [
"Register",
"rdsStorage",
"as",
"default",
"result",
"storage"
] | 692699d12dafe84eafece38fad03e7728370c9ac | https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/scripts/tools/KvToRdsMigration.php#L214-L224 | train |
simoebenhida/Laramin | publishable/database/seeds/LaratrustSeeder.php | LaratrustSeeder.truncateLaratrustTables | public function truncateLaratrustTables()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
DB::table('permission_role')->truncate();
DB::table('permission_user')->truncate();
DB::table('role_user')->truncate();
\App\User::truncate();
\Simoja\Laramin\Models\Role::truncate();
\Simoja\Laramin\Models\Permission::truncate();
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
} | php | public function truncateLaratrustTables()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
DB::table('permission_role')->truncate();
DB::table('permission_user')->truncate();
DB::table('role_user')->truncate();
\App\User::truncate();
\Simoja\Laramin\Models\Role::truncate();
\Simoja\Laramin\Models\Permission::truncate();
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
} | [
"public",
"function",
"truncateLaratrustTables",
"(",
")",
"{",
"DB",
"::",
"statement",
"(",
"'SET FOREIGN_KEY_CHECKS = 0'",
")",
";",
"DB",
"::",
"table",
"(",
"'permission_role'",
")",
"->",
"truncate",
"(",
")",
";",
"DB",
"::",
"table",
"(",
"'permission_... | Truncates all the laratrust tables and the users table
@return void | [
"Truncates",
"all",
"the",
"laratrust",
"tables",
"and",
"the",
"users",
"table"
] | 4012b5a7f19c639dab1b238926679e09fee79c31 | https://github.com/simoebenhida/Laramin/blob/4012b5a7f19c639dab1b238926679e09fee79c31/publishable/database/seeds/LaratrustSeeder.php#L103-L113 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.sanitizePluralExpression | public static function sanitizePluralExpression($expr)
{
// Parse equation
$expr = explode(';', $expr);
if (count($expr) >= 2) {
$expr = $expr[1];
} else {
$expr = $expr[0];
}
$expr = trim(strtolower($expr));
// Strip plural prefix
if (substr($expr, 0, 6) === 'plural') {
$expr = ltrim(substr($expr, 6));
}
// Strip equals
if (substr($expr, 0, 1) === '=') {
$expr = ltrim(substr($expr, 1));
}
// Cleanup from unwanted chars
$expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr);
return $expr;
} | php | public static function sanitizePluralExpression($expr)
{
// Parse equation
$expr = explode(';', $expr);
if (count($expr) >= 2) {
$expr = $expr[1];
} else {
$expr = $expr[0];
}
$expr = trim(strtolower($expr));
// Strip plural prefix
if (substr($expr, 0, 6) === 'plural') {
$expr = ltrim(substr($expr, 6));
}
// Strip equals
if (substr($expr, 0, 1) === '=') {
$expr = ltrim(substr($expr, 1));
}
// Cleanup from unwanted chars
$expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr);
return $expr;
} | [
"public",
"static",
"function",
"sanitizePluralExpression",
"(",
"$",
"expr",
")",
"{",
"// Parse equation",
"$",
"expr",
"=",
"explode",
"(",
"';'",
",",
"$",
"expr",
")",
";",
"if",
"(",
"count",
"(",
"$",
"expr",
")",
">=",
"2",
")",
"{",
"$",
"ex... | Sanitize plural form expression for use in ExpressionLanguage.
@param string $expr Expression to sanitize
@return string sanitized plural form expression | [
"Sanitize",
"plural",
"form",
"expression",
"for",
"use",
"in",
"ExpressionLanguage",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L176-L199 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.extractPluralCount | public static function extractPluralCount($expr)
{
$parts = explode(';', $expr, 2);
$nplurals = explode('=', trim($parts[0]), 2);
if (strtolower(rtrim($nplurals[0])) != 'nplurals') {
return 1;
}
if (count($nplurals) == 1) {
return 1;
}
return intval($nplurals[1]);
} | php | public static function extractPluralCount($expr)
{
$parts = explode(';', $expr, 2);
$nplurals = explode('=', trim($parts[0]), 2);
if (strtolower(rtrim($nplurals[0])) != 'nplurals') {
return 1;
}
if (count($nplurals) == 1) {
return 1;
}
return intval($nplurals[1]);
} | [
"public",
"static",
"function",
"extractPluralCount",
"(",
"$",
"expr",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"';'",
",",
"$",
"expr",
",",
"2",
")",
";",
"$",
"nplurals",
"=",
"explode",
"(",
"'='",
",",
"trim",
"(",
"$",
"parts",
"[",
"0",... | Extracts number of plurals from plurals form expression.
@param string $expr Expression to process
@return int Total number of plurals | [
"Extracts",
"number",
"of",
"plurals",
"from",
"plurals",
"form",
"expression",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L208-L220 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.extractPluralsForms | public static function extractPluralsForms($header)
{
$headers = explode("\n", $header);
$expr = 'nplurals=2; plural=n == 1 ? 0 : 1;';
foreach ($headers as $header) {
if (stripos($header, 'Plural-Forms:') === 0) {
$expr = substr($header, 13);
}
}
return $expr;
} | php | public static function extractPluralsForms($header)
{
$headers = explode("\n", $header);
$expr = 'nplurals=2; plural=n == 1 ? 0 : 1;';
foreach ($headers as $header) {
if (stripos($header, 'Plural-Forms:') === 0) {
$expr = substr($header, 13);
}
}
return $expr;
} | [
"public",
"static",
"function",
"extractPluralsForms",
"(",
"$",
"header",
")",
"{",
"$",
"headers",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"header",
")",
";",
"$",
"expr",
"=",
"'nplurals=2; plural=n == 1 ? 0 : 1;'",
";",
"foreach",
"(",
"$",
"headers",
... | Parse full PO header and extract only plural forms line.
@param string $header Gettext header
@return string verbatim plural form header field | [
"Parse",
"full",
"PO",
"header",
"and",
"extract",
"only",
"plural",
"forms",
"line",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L229-L240 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.getPluralForms | private function getPluralForms()
{
// lets assume message number 0 is header
// this is true, right?
// cache header field for plural forms
if (is_null($this->pluralequation)) {
if (isset($this->cache_translations[''])) {
$header = $this->cache_translations[''];
} else {
$header = '';
}
$expr = $this->extractPluralsForms($header);
$this->pluralequation = $this->sanitizePluralExpression($expr);
$this->pluralcount = $this->extractPluralCount($expr);
}
return $this->pluralequation;
} | php | private function getPluralForms()
{
// lets assume message number 0 is header
// this is true, right?
// cache header field for plural forms
if (is_null($this->pluralequation)) {
if (isset($this->cache_translations[''])) {
$header = $this->cache_translations[''];
} else {
$header = '';
}
$expr = $this->extractPluralsForms($header);
$this->pluralequation = $this->sanitizePluralExpression($expr);
$this->pluralcount = $this->extractPluralCount($expr);
}
return $this->pluralequation;
} | [
"private",
"function",
"getPluralForms",
"(",
")",
"{",
"// lets assume message number 0 is header",
"// this is true, right?",
"// cache header field for plural forms",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"pluralequation",
")",
")",
"{",
"if",
"(",
"isset",
"... | Get possible plural forms from MO header.
@return string plural form header | [
"Get",
"possible",
"plural",
"forms",
"from",
"MO",
"header",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L247-L265 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.selectString | private function selectString($n)
{
if (is_null($this->pluralexpression)) {
$this->pluralexpression = new ExpressionLanguage();
}
try {
$plural = $this->pluralexpression->evaluate(
$this->getPluralForms(),
['n' => $n]
);
} catch (\Exception $e) {
$plural = 0;
}
if ($plural >= $this->pluralcount) {
$plural = $this->pluralcount - 1;
}
return $plural;
} | php | private function selectString($n)
{
if (is_null($this->pluralexpression)) {
$this->pluralexpression = new ExpressionLanguage();
}
try {
$plural = $this->pluralexpression->evaluate(
$this->getPluralForms(),
['n' => $n]
);
} catch (\Exception $e) {
$plural = 0;
}
if ($plural >= $this->pluralcount) {
$plural = $this->pluralcount - 1;
}
return $plural;
} | [
"private",
"function",
"selectString",
"(",
"$",
"n",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"pluralexpression",
")",
")",
"{",
"$",
"this",
"->",
"pluralexpression",
"=",
"new",
"ExpressionLanguage",
"(",
")",
";",
"}",
"try",
"{",
"$... | Detects which plural form to take.
@param int $n count of objects
@return int array index of the right plural form | [
"Detects",
"which",
"plural",
"form",
"to",
"take",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L274-L293 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.pgettext | public function pgettext($msgctxt, $msgid)
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->gettext($key);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
} | php | public function pgettext($msgctxt, $msgid)
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->gettext($key);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
} | [
"public",
"function",
"pgettext",
"(",
"$",
"msgctxt",
",",
"$",
"msgid",
")",
"{",
"$",
"key",
"=",
"implode",
"(",
"chr",
"(",
"4",
")",
",",
"[",
"$",
"msgctxt",
",",
"$",
"msgid",
"]",
")",
";",
"$",
"ret",
"=",
"$",
"this",
"->",
"gettext"... | Translate with context.
@param string $msgctxt Context
@param string $msgid String to be translated
@return string translated plural form | [
"Translate",
"with",
"context",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L333-L342 | train |
phpmyadmin/motranslator | src/Translator.php | Translator.npgettext | public function npgettext($msgctxt, $msgid, $msgidPlural, $number)
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->ngettext($key, $msgidPlural, $number);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
} | php | public function npgettext($msgctxt, $msgid, $msgidPlural, $number)
{
$key = implode(chr(4), [$msgctxt, $msgid]);
$ret = $this->ngettext($key, $msgidPlural, $number);
if (strpos($ret, chr(4)) !== false) {
return $msgid;
}
return $ret;
} | [
"public",
"function",
"npgettext",
"(",
"$",
"msgctxt",
",",
"$",
"msgid",
",",
"$",
"msgidPlural",
",",
"$",
"number",
")",
"{",
"$",
"key",
"=",
"implode",
"(",
"chr",
"(",
"4",
")",
",",
"[",
"$",
"msgctxt",
",",
"$",
"msgid",
"]",
")",
";",
... | Plural version of pgettext.
@param string $msgctxt Context
@param string $msgid Single form
@param string $msgidPlural Plural form
@param int $number Number of objects
@return string translated plural form | [
"Plural",
"version",
"of",
"pgettext",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L354-L363 | train |
phpmyadmin/motranslator | src/StringReader.php | StringReader.read | public function read($pos, $bytes)
{
if ($pos + $bytes > $this->_len) {
throw new ReaderException('Not enough bytes!');
}
return substr($this->_str, $pos, $bytes);
} | php | public function read($pos, $bytes)
{
if ($pos + $bytes > $this->_len) {
throw new ReaderException('Not enough bytes!');
}
return substr($this->_str, $pos, $bytes);
} | [
"public",
"function",
"read",
"(",
"$",
"pos",
",",
"$",
"bytes",
")",
"{",
"if",
"(",
"$",
"pos",
"+",
"$",
"bytes",
">",
"$",
"this",
"->",
"_len",
")",
"{",
"throw",
"new",
"ReaderException",
"(",
"'Not enough bytes!'",
")",
";",
"}",
"return",
... | Read number of bytes from given offset.
@param int $pos Offset
@param int $bytes Number of bytes to read
@return string | [
"Read",
"number",
"of",
"bytes",
"from",
"given",
"offset",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/StringReader.php#L54-L61 | train |
phpmyadmin/motranslator | src/StringReader.php | StringReader.readint | public function readint($unpack, $pos)
{
$data = unpack($unpack, $this->read($pos, 4));
$result = $data[1];
/* We're reading unsigned int, but PHP will happily
* give us negative number on 32-bit platforms.
*
* See also documentation:
* https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes
*/
return $result < 0 ? PHP_INT_MAX : $result;
} | php | public function readint($unpack, $pos)
{
$data = unpack($unpack, $this->read($pos, 4));
$result = $data[1];
/* We're reading unsigned int, but PHP will happily
* give us negative number on 32-bit platforms.
*
* See also documentation:
* https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes
*/
return $result < 0 ? PHP_INT_MAX : $result;
} | [
"public",
"function",
"readint",
"(",
"$",
"unpack",
",",
"$",
"pos",
")",
"{",
"$",
"data",
"=",
"unpack",
"(",
"$",
"unpack",
",",
"$",
"this",
"->",
"read",
"(",
"$",
"pos",
",",
"4",
")",
")",
";",
"$",
"result",
"=",
"$",
"data",
"[",
"1... | Reads a 32bit integer from the stream.
@param string $unpack Unpack string
@param int $pos Position
@return int Ingerer from the stream | [
"Reads",
"a",
"32bit",
"integer",
"from",
"the",
"stream",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/StringReader.php#L71-L83 | train |
phpmyadmin/motranslator | src/StringReader.php | StringReader.readintarray | public function readintarray($unpack, $pos, $count)
{
return unpack($unpack . $count, $this->read($pos, 4 * $count));
} | php | public function readintarray($unpack, $pos, $count)
{
return unpack($unpack . $count, $this->read($pos, 4 * $count));
} | [
"public",
"function",
"readintarray",
"(",
"$",
"unpack",
",",
"$",
"pos",
",",
"$",
"count",
")",
"{",
"return",
"unpack",
"(",
"$",
"unpack",
".",
"$",
"count",
",",
"$",
"this",
"->",
"read",
"(",
"$",
"pos",
",",
"4",
"*",
"$",
"count",
")",
... | Reads an array of integers from the stream.
@param string $unpack Unpack string
@param int $pos Position
@param int $count How many elements should be read
@return array Array of Integers | [
"Reads",
"an",
"array",
"of",
"integers",
"from",
"the",
"stream",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/StringReader.php#L94-L97 | train |
nimbusoftltd/flysystem-openstack-swift | src/SwiftAdapter.php | SwiftAdapter.getObjectInstance | protected function getObjectInstance($path)
{
$location = $this->applyPathPrefix($path);
$object = $this->container->getObject($location);
return $object;
} | php | protected function getObjectInstance($path)
{
$location = $this->applyPathPrefix($path);
$object = $this->container->getObject($location);
return $object;
} | [
"protected",
"function",
"getObjectInstance",
"(",
"$",
"path",
")",
"{",
"$",
"location",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"$",
"object",
"=",
"$",
"this",
"->",
"container",
"->",
"getObject",
"(",
"$",
"location",... | Get an object instance.
@param string $path
@return StorageObject | [
"Get",
"an",
"object",
"instance",
"."
] | 7dbf0164245592104eead065ed56d0453b07f0da | https://github.com/nimbusoftltd/flysystem-openstack-swift/blob/7dbf0164245592104eead065ed56d0453b07f0da/src/SwiftAdapter.php#L262-L269 | train |
nimbusoftltd/flysystem-openstack-swift | src/SwiftAdapter.php | SwiftAdapter.normalizeObject | protected function normalizeObject(StorageObject $object)
{
$name = $this->removePathPrefix($object->name);
$mimetype = explode('; ', $object->contentType);
if ($object->lastModified instanceof \DateTimeInterface) {
$timestamp = $object->lastModified->getTimestamp();
} else {
$timestamp = strtotime($object->lastModified);
}
return [
'type' => 'file',
'dirname' => Util::dirname($name),
'path' => $name,
'timestamp' => $timestamp,
'mimetype' => reset($mimetype),
'size' => $object->contentLength,
];
} | php | protected function normalizeObject(StorageObject $object)
{
$name = $this->removePathPrefix($object->name);
$mimetype = explode('; ', $object->contentType);
if ($object->lastModified instanceof \DateTimeInterface) {
$timestamp = $object->lastModified->getTimestamp();
} else {
$timestamp = strtotime($object->lastModified);
}
return [
'type' => 'file',
'dirname' => Util::dirname($name),
'path' => $name,
'timestamp' => $timestamp,
'mimetype' => reset($mimetype),
'size' => $object->contentLength,
];
} | [
"protected",
"function",
"normalizeObject",
"(",
"StorageObject",
"$",
"object",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"removePathPrefix",
"(",
"$",
"object",
"->",
"name",
")",
";",
"$",
"mimetype",
"=",
"explode",
"(",
"'; '",
",",
"$",
"objec... | Normalize Openstack "StorageObject" object into an array
@param StorageObject $object
@return array | [
"Normalize",
"Openstack",
"StorageObject",
"object",
"into",
"an",
"array"
] | 7dbf0164245592104eead065ed56d0453b07f0da | https://github.com/nimbusoftltd/flysystem-openstack-swift/blob/7dbf0164245592104eead065ed56d0453b07f0da/src/SwiftAdapter.php#L292-L311 | train |
phpmyadmin/motranslator | src/Loader.php | Loader.getTranslator | public function getTranslator($domain = '')
{
if (empty($domain)) {
$domain = $this->default_domain;
}
if (! isset($this->domains[$this->locale])) {
$this->domains[$this->locale] = [];
}
if (! isset($this->domains[$this->locale][$domain])) {
if (isset($this->paths[$domain])) {
$base = $this->paths[$domain];
} else {
$base = './';
}
$locale_names = $this->listLocales($this->locale);
$filename = '';
foreach ($locale_names as $locale) {
$filename = "$base/$locale/LC_MESSAGES/$domain.mo";
if (file_exists($filename)) {
break;
}
}
// We don't care about invalid path, we will get fallback
// translator here
$this->domains[$this->locale][$domain] = new Translator($filename);
}
return $this->domains[$this->locale][$domain];
} | php | public function getTranslator($domain = '')
{
if (empty($domain)) {
$domain = $this->default_domain;
}
if (! isset($this->domains[$this->locale])) {
$this->domains[$this->locale] = [];
}
if (! isset($this->domains[$this->locale][$domain])) {
if (isset($this->paths[$domain])) {
$base = $this->paths[$domain];
} else {
$base = './';
}
$locale_names = $this->listLocales($this->locale);
$filename = '';
foreach ($locale_names as $locale) {
$filename = "$base/$locale/LC_MESSAGES/$domain.mo";
if (file_exists($filename)) {
break;
}
}
// We don't care about invalid path, we will get fallback
// translator here
$this->domains[$this->locale][$domain] = new Translator($filename);
}
return $this->domains[$this->locale][$domain];
} | [
"public",
"function",
"getTranslator",
"(",
"$",
"domain",
"=",
"''",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"domain",
")",
")",
"{",
"$",
"domain",
"=",
"$",
"this",
"->",
"default_domain",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"... | Returns Translator object for domain or for default domain.
@param string $domain Translation domain
@return Translator | [
"Returns",
"Translator",
"object",
"for",
"domain",
"or",
"for",
"default",
"domain",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Loader.php#L155-L188 | train |
phpmyadmin/motranslator | src/Loader.php | Loader.detectlocale | public function detectlocale()
{
if (isset($GLOBALS['lang'])) {
return $GLOBALS['lang'];
} elseif (getenv('LC_ALL')) {
return getenv('LC_ALL');
} elseif (getenv('LC_MESSAGES')) {
return getenv('LC_MESSAGES');
} elseif (getenv('LANG')) {
return getenv('LANG');
}
return 'en';
} | php | public function detectlocale()
{
if (isset($GLOBALS['lang'])) {
return $GLOBALS['lang'];
} elseif (getenv('LC_ALL')) {
return getenv('LC_ALL');
} elseif (getenv('LC_MESSAGES')) {
return getenv('LC_MESSAGES');
} elseif (getenv('LANG')) {
return getenv('LANG');
}
return 'en';
} | [
"public",
"function",
"detectlocale",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"GLOBALS",
"[",
"'lang'",
"]",
")",
")",
"{",
"return",
"$",
"GLOBALS",
"[",
"'lang'",
"]",
";",
"}",
"elseif",
"(",
"getenv",
"(",
"'LC_ALL'",
")",
")",
"{",
"retur... | Detects currently configured locale.
It checks:
- global lang variable
- environment for LC_ALL, LC_MESSAGES and LANG
@return string with locale name | [
"Detects",
"currently",
"configured",
"locale",
"."
] | 3938b916952f22234bf461541d30eb1889cc1f4a | https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Loader.php#L237-L250 | train |
mateusjatenee/php-json-feed | src/FeedItem.php | FeedItem.build | public function build()
{
return array_filter(
$this->flatMap($this->acceptedProperties, function ($property) {
return [$property => $this->getValueForProperty($property)];
})
);
} | php | public function build()
{
return array_filter(
$this->flatMap($this->acceptedProperties, function ($property) {
return [$property => $this->getValueForProperty($property)];
})
);
} | [
"public",
"function",
"build",
"(",
")",
"{",
"return",
"array_filter",
"(",
"$",
"this",
"->",
"flatMap",
"(",
"$",
"this",
"->",
"acceptedProperties",
",",
"function",
"(",
"$",
"property",
")",
"{",
"return",
"[",
"$",
"property",
"=>",
"$",
"this",
... | Builds the structure of the feed item
@return array | [
"Builds",
"the",
"structure",
"of",
"the",
"feed",
"item"
] | 07281c090894e892be5b762b8fd93eda5a082033 | https://github.com/mateusjatenee/php-json-feed/blob/07281c090894e892be5b762b8fd93eda5a082033/src/FeedItem.php#L58-L65 | train |
mateusjatenee/php-json-feed | src/JsonFeed.php | JsonFeed.build | public function build()
{
if (!$this->hasCorrectStructure()) {
throw (new IncorrectFeedStructureException)->setProperties($this->getMissingProperties());
}
return $this
->filterProperties() + ['version' => $this->getVersion(), 'items' => $this->buildItems()];
} | php | public function build()
{
if (!$this->hasCorrectStructure()) {
throw (new IncorrectFeedStructureException)->setProperties($this->getMissingProperties());
}
return $this
->filterProperties() + ['version' => $this->getVersion(), 'items' => $this->buildItems()];
} | [
"public",
"function",
"build",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasCorrectStructure",
"(",
")",
")",
"{",
"throw",
"(",
"new",
"IncorrectFeedStructureException",
")",
"->",
"setProperties",
"(",
"$",
"this",
"->",
"getMissingProperties",
"(... | Builds a collection following the JSON Feed spec
@throws \Mateusjatenee\JsonFeed\Exceptions\IncorrectFeedStructureException
@return \Illuminate\Support\Collection | [
"Builds",
"a",
"collection",
"following",
"the",
"JSON",
"Feed",
"spec"
] | 07281c090894e892be5b762b8fd93eda5a082033 | https://github.com/mateusjatenee/php-json-feed/blob/07281c090894e892be5b762b8fd93eda5a082033/src/JsonFeed.php#L74-L82 | train |
async-interop/event-loop | src/Loop.php | Loop.setFactory | public static function setFactory(DriverFactory $factory = null)
{
if (self::$level > 0) {
throw new \RuntimeException("Setting a new factory while running isn't allowed!");
}
self::$factory = $factory;
// reset it here, it will be actually instantiated inside execute() or get()
self::$driver = null;
} | php | public static function setFactory(DriverFactory $factory = null)
{
if (self::$level > 0) {
throw new \RuntimeException("Setting a new factory while running isn't allowed!");
}
self::$factory = $factory;
// reset it here, it will be actually instantiated inside execute() or get()
self::$driver = null;
} | [
"public",
"static",
"function",
"setFactory",
"(",
"DriverFactory",
"$",
"factory",
"=",
"null",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"level",
">",
"0",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Setting a new factory while running isn't allo... | Set the factory to be used to create a default drivers.
Setting a factory is only allowed as long as no loop is currently running. Passing null will reset the
default driver and remove the factory.
The factory will be invoked if none is passed to `Loop::execute`. A default driver will be created to
support synchronous waits in traditional applications.
@param DriverFactory|null $factory New factory to replace the previous one. | [
"Set",
"the",
"factory",
"to",
"be",
"used",
"to",
"create",
"a",
"default",
"drivers",
"."
] | ca3a70f6dc91f03336f33f040405b4d3ab4bff50 | https://github.com/async-interop/event-loop/blob/ca3a70f6dc91f03336f33f040405b4d3ab4bff50/src/Loop.php#L43-L53 | train |
async-interop/event-loop | src/Loop.php | Loop.execute | public static function execute(callable $callback, Driver $driver = null)
{
$previousDriver = self::$driver;
self::$driver = $driver ?: self::createDriver();
self::$level++;
try {
self::$driver->defer($callback);
self::$driver->run();
} finally {
self::$driver = $previousDriver;
self::$level--;
}
} | php | public static function execute(callable $callback, Driver $driver = null)
{
$previousDriver = self::$driver;
self::$driver = $driver ?: self::createDriver();
self::$level++;
try {
self::$driver->defer($callback);
self::$driver->run();
} finally {
self::$driver = $previousDriver;
self::$level--;
}
} | [
"public",
"static",
"function",
"execute",
"(",
"callable",
"$",
"callback",
",",
"Driver",
"$",
"driver",
"=",
"null",
")",
"{",
"$",
"previousDriver",
"=",
"self",
"::",
"$",
"driver",
";",
"self",
"::",
"$",
"driver",
"=",
"$",
"driver",
"?",
":",
... | Execute a callback within the scope of an event loop driver.
The loop MUST continue to run until it is either stopped explicitly, no referenced watchers exist anymore, or an
exception is thrown that cannot be handled. Exceptions that cannot be handled are exceptions thrown from an
error handler or exceptions that would be passed to an error handler but none exists to handle them.
@param callable $callback The callback to execute.
@param Driver $driver The event loop driver. If `null`, a new one is created from the set factory.
@return void
@see \AsyncInterop\Loop::setFactory() | [
"Execute",
"a",
"callback",
"within",
"the",
"scope",
"of",
"an",
"event",
"loop",
"driver",
"."
] | ca3a70f6dc91f03336f33f040405b4d3ab4bff50 | https://github.com/async-interop/event-loop/blob/ca3a70f6dc91f03336f33f040405b4d3ab4bff50/src/Loop.php#L69-L83 | train |
async-interop/event-loop | src/Loop.php | Loop.createDriver | private static function createDriver()
{
if (self::$factory === null) {
throw new \Exception("No loop driver factory set; Either pass a driver to Loop::execute or set a factory.");
}
$driver = self::$factory->create();
if (!$driver instanceof Driver) {
$type = is_object($driver) ? "an instance of " . get_class($driver) : gettype($driver);
throw new \Exception("Loop driver factory returned {$type}, but must return an instance of Driver.");
}
return $driver;
} | php | private static function createDriver()
{
if (self::$factory === null) {
throw new \Exception("No loop driver factory set; Either pass a driver to Loop::execute or set a factory.");
}
$driver = self::$factory->create();
if (!$driver instanceof Driver) {
$type = is_object($driver) ? "an instance of " . get_class($driver) : gettype($driver);
throw new \Exception("Loop driver factory returned {$type}, but must return an instance of Driver.");
}
return $driver;
} | [
"private",
"static",
"function",
"createDriver",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"factory",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"No loop driver factory set; Either pass a driver to Loop::execute or set a factory.\"",
")",
";... | Create a new driver if a factory is present, otherwise throw.
@return Driver
@throws \Exception If no factory is set or no driver returned from factory. | [
"Create",
"a",
"new",
"driver",
"if",
"a",
"factory",
"is",
"present",
"otherwise",
"throw",
"."
] | ca3a70f6dc91f03336f33f040405b4d3ab4bff50 | https://github.com/async-interop/event-loop/blob/ca3a70f6dc91f03336f33f040405b4d3ab4bff50/src/Loop.php#L92-L106 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.