repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
artkonekt/menu | src/Item.php | Item.activate | public function activate()
{
if ($this->menu->config->activeElement == 'item') {
$this->setToActive();
} else {
if ($this->link) {
$this->link->activate();
}
}
// If parent activation is enabled:
if ($this->menu->config->activateParents) {
// Moving up through the parent nodes, activating them as well.
if ($this->parent) {
$this->parent->activate();
}
}
} | php | public function activate()
{
if ($this->menu->config->activeElement == 'item') {
$this->setToActive();
} else {
if ($this->link) {
$this->link->activate();
}
}
// If parent activation is enabled:
if ($this->menu->config->activateParents) {
// Moving up through the parent nodes, activating them as well.
if ($this->parent) {
$this->parent->activate();
}
}
} | [
"public",
"function",
"activate",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"menu",
"->",
"config",
"->",
"activeElement",
"==",
"'item'",
")",
"{",
"$",
"this",
"->",
"setToActive",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"this",
"->",... | Sets the item as active | [
"Sets",
"the",
"item",
"as",
"active"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Item.php#L228-L245 |
artkonekt/menu | src/Item.php | Item.data | public function data(...$args)
{
if (isset($args[0]) && is_array($args[0])) {
$this->data = array_merge($this->data, array_change_key_case($args[0]));
// Cascade data to item's children if cascade_data option is enabled
if ($this->menu->config->cascadeData) {
$this->cascadeData(...$args);
}
return $this;
} elseif (isset($args[0]) && isset($args[1])) {
$this->data[strtolower($args[0])] = $args[1];
// Cascade data to item's children if cascade_data option is enabled
if ($this->menu->config->cascadeData) {
$this->cascadeData(...$args);
}
return $this;
} elseif (isset($args[0])) {
return isset($this->data[$args[0]]) ? $this->data[$args[0]] : null;
}
return $this->data;
} | php | public function data(...$args)
{
if (isset($args[0]) && is_array($args[0])) {
$this->data = array_merge($this->data, array_change_key_case($args[0]));
// Cascade data to item's children if cascade_data option is enabled
if ($this->menu->config->cascadeData) {
$this->cascadeData(...$args);
}
return $this;
} elseif (isset($args[0]) && isset($args[1])) {
$this->data[strtolower($args[0])] = $args[1];
// Cascade data to item's children if cascade_data option is enabled
if ($this->menu->config->cascadeData) {
$this->cascadeData(...$args);
}
return $this;
} elseif (isset($args[0])) {
return isset($this->data[$args[0]]) ? $this->data[$args[0]] : null;
}
return $this->data;
} | [
"public",
"function",
"data",
"(",
"...",
"$",
"args",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"args",
"[",
"0",
"]",
")",
"&&",
"is_array",
"(",
"$",
"args",
"[",
"0",
"]",
")",
")",
"{",
"$",
"this",
"->",
"data",
"=",
"array_merge",
"(",
"... | Set or get items's meta data
@param array $args
@return mixed | [
"Set",
"or",
"get",
"items",
"s",
"meta",
"data"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Item.php#L269-L292 |
artkonekt/menu | src/Item.php | Item.hasProperty | public function hasProperty($property)
{
return
property_exists($this, $property)
||
$this->hasAttribute($property)
||
$this->hasData($property);
} | php | public function hasProperty($property)
{
return
property_exists($this, $property)
||
$this->hasAttribute($property)
||
$this->hasData($property);
} | [
"public",
"function",
"hasProperty",
"(",
"$",
"property",
")",
"{",
"return",
"property_exists",
"(",
"$",
"this",
",",
"$",
"property",
")",
"||",
"$",
"this",
"->",
"hasAttribute",
"(",
"$",
"property",
")",
"||",
"$",
"this",
"->",
"hasData",
"(",
... | Check if property exists either in the class or the meta collection
@param string $property
@return bool | [
"Check",
"if",
"property",
"exists",
"either",
"in",
"the",
"class",
"or",
"the",
"meta",
"collection"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Item.php#L335-L343 |
artkonekt/menu | src/Item.php | Item.setToActive | protected function setToActive()
{
$this->attributes['class'] = Utils::addHtmlClass(
array_get($this->attributes, 'class'),
$this->menu->config->activeClass
);
$this->isActive = true;
return $this;
} | php | protected function setToActive()
{
$this->attributes['class'] = Utils::addHtmlClass(
array_get($this->attributes, 'class'),
$this->menu->config->activeClass
);
$this->isActive = true;
return $this;
} | [
"protected",
"function",
"setToActive",
"(",
")",
"{",
"$",
"this",
"->",
"attributes",
"[",
"'class'",
"]",
"=",
"Utils",
"::",
"addHtmlClass",
"(",
"array_get",
"(",
"$",
"this",
"->",
"attributes",
",",
"'class'",
")",
",",
"$",
"this",
"->",
"menu",
... | Make the item active
@return Item | [
"Make",
"the",
"item",
"active"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Item.php#L380-L389 |
artkonekt/menu | src/Item.php | Item.currentUrlMatches | protected function currentUrlMatches()
{
if ($this->url() == Request::url()) { // If URLs are equal, always return true
return true;
}
if ($this->activeUrlPattern) { // If pattern was set, see if it matches
$pattern = ltrim(preg_replace('/\/\*/', '(/.*)?', $this->activeUrlPattern), '/');
return preg_match("@^{$pattern}\z@", Request::path());
}
return false; // No match
} | php | protected function currentUrlMatches()
{
if ($this->url() == Request::url()) { // If URLs are equal, always return true
return true;
}
if ($this->activeUrlPattern) { // If pattern was set, see if it matches
$pattern = ltrim(preg_replace('/\/\*/', '(/.*)?', $this->activeUrlPattern), '/');
return preg_match("@^{$pattern}\z@", Request::path());
}
return false; // No match
} | [
"protected",
"function",
"currentUrlMatches",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"url",
"(",
")",
"==",
"Request",
"::",
"url",
"(",
")",
")",
"{",
"// If URLs are equal, always return true",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
... | Returns whether the current URL matches this link's URL
@return bool | [
"Returns",
"whether",
"the",
"current",
"URL",
"matches",
"this",
"link",
"s",
"URL"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Item.php#L396-L408 |
artkonekt/menu | src/Repository.php | Repository.create | public function create($name, $options = [])
{
if ($this->menus->has($name)) {
throw new MenuAlreadyExistsException("Can not create menu named `$name` because it already exists");
}
$this->menus->put($name, $instance = MenuFactory::create($name, $options));
return $instance;
} | php | public function create($name, $options = [])
{
if ($this->menus->has($name)) {
throw new MenuAlreadyExistsException("Can not create menu named `$name` because it already exists");
}
$this->menus->put($name, $instance = MenuFactory::create($name, $options));
return $instance;
} | [
"public",
"function",
"create",
"(",
"$",
"name",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"menus",
"->",
"has",
"(",
"$",
"name",
")",
")",
"{",
"throw",
"new",
"MenuAlreadyExistsException",
"(",
"\"Can not create me... | Create a new menu instance
@param string $name The name of the menu
@param array $options Set of options
@see processOptions() method
@return Menu
@throws MenuAlreadyExistsException | [
"Create",
"a",
"new",
"menu",
"instance"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Repository.php#L49-L58 |
artkonekt/menu | src/Traits/Renderable.php | Renderable.render | public function render(string $rendererName = null)
{
$renderer = app(sprintf('konekt.menu.renderer.%s.%s',
snake_case(class_basename(static::class)),
$rendererName ?: $this->renderer
));
return $renderer->render($this);
} | php | public function render(string $rendererName = null)
{
$renderer = app(sprintf('konekt.menu.renderer.%s.%s',
snake_case(class_basename(static::class)),
$rendererName ?: $this->renderer
));
return $renderer->render($this);
} | [
"public",
"function",
"render",
"(",
"string",
"$",
"rendererName",
"=",
"null",
")",
"{",
"$",
"renderer",
"=",
"app",
"(",
"sprintf",
"(",
"'konekt.menu.renderer.%s.%s'",
",",
"snake_case",
"(",
"class_basename",
"(",
"static",
"::",
"class",
")",
")",
","... | @param string $rendererName
@return string | [
"@param",
"string",
"$rendererName"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Traits/Renderable.php#L25-L33 |
artkonekt/menu | src/Utils.php | Utils.addHtmlClass | public static function addHtmlClass($existingClasses, $classToAdd)
{
if (empty($existingClasses)) {
return $classToAdd;
}
$classes = trim(trim($existingClasses) . ' ' . trim($classToAdd));
return implode(' ', array_unique(explode(' ', $classes)));
} | php | public static function addHtmlClass($existingClasses, $classToAdd)
{
if (empty($existingClasses)) {
return $classToAdd;
}
$classes = trim(trim($existingClasses) . ' ' . trim($classToAdd));
return implode(' ', array_unique(explode(' ', $classes)));
} | [
"public",
"static",
"function",
"addHtmlClass",
"(",
"$",
"existingClasses",
",",
"$",
"classToAdd",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"existingClasses",
")",
")",
"{",
"return",
"$",
"classToAdd",
";",
"}",
"$",
"classes",
"=",
"trim",
"(",
"trim"... | Adds a new class to an existing set of classes.
Examples.:
- addHtmlClass('nav-link', 'active') turns "nav-link" into "nav-link active"
- addHtmlClass('nav-link active', 'active') -> 'nav-link active' // smart, eh?
- addHtmlClass('active', 'active') -> 'active' // no duplicates
- addHtmlClass('active active', 'active') -> 'active' // it even heals duplicates
@param $existingClasses
@param $classToAdd
@return mixed|string | [
"Adds",
"a",
"new",
"class",
"to",
"an",
"existing",
"set",
"of",
"classes",
".",
"Examples",
".",
":",
"-",
"addHtmlClass",
"(",
"nav",
"-",
"link",
"active",
")",
"turns",
"nav",
"-",
"link",
"into",
"nav",
"-",
"link",
"active",
"-",
"addHtmlClass",... | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Utils.php#L30-L39 |
artkonekt/menu | src/Utils.php | Utils.attrsToHtml | public static function attrsToHtml(array $attributes)
{
$attrs = [];
foreach ($attributes as $key => $value) {
$element = is_numeric($key) ?
(string)$value :
(is_null($value) ? (string)$key : $key . '="' . e($value) . '"');
if (!empty($element)) {
$attrs[] = $element;
}
}
return count($attrs) ? ' ' . implode(' ', $attrs) : '';
} | php | public static function attrsToHtml(array $attributes)
{
$attrs = [];
foreach ($attributes as $key => $value) {
$element = is_numeric($key) ?
(string)$value :
(is_null($value) ? (string)$key : $key . '="' . e($value) . '"');
if (!empty($element)) {
$attrs[] = $element;
}
}
return count($attrs) ? ' ' . implode(' ', $attrs) : '';
} | [
"public",
"static",
"function",
"attrsToHtml",
"(",
"array",
"$",
"attributes",
")",
"{",
"$",
"attrs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"element",
"=",
"is_numeric",
"(",
"$"... | Converts attributes to html string.
Eg.: ['disabled', ['src' => 'img.png']] -> ' disabled src="img.png"'
@param array $attributes
@return string | [
"Converts",
"attributes",
"to",
"html",
"string",
".",
"Eg",
".",
":",
"[",
"disabled",
"[",
"src",
"=",
">",
"img",
".",
"png",
"]]",
"-",
">",
"disabled",
"src",
"=",
"img",
".",
"png"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Utils.php#L61-L75 |
artkonekt/menu | src/Menu.php | Menu.addItem | public function addItem($name, $title, $options = [])
{
$options = is_string($options) ? ['url' => $options] : $options;
$item = new Item($this, $name, $title, $options);
$this->items->addItem($item);
return $item;
} | php | public function addItem($name, $title, $options = [])
{
$options = is_string($options) ? ['url' => $options] : $options;
$item = new Item($this, $name, $title, $options);
$this->items->addItem($item);
return $item;
} | [
"public",
"function",
"addItem",
"(",
"$",
"name",
",",
"$",
"title",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"is_string",
"(",
"$",
"options",
")",
"?",
"[",
"'url'",
"=>",
"$",
"options",
"]",
":",
"$",
"options",
";"... | Adds an item to the menu
@param string $name
@param string $title
@param string|array $options
@return Item | [
"Adds",
"an",
"item",
"to",
"the",
"menu"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Menu.php#L64-L71 |
artkonekt/menu | src/Menu.php | Menu.removeItem | public function removeItem(string $name, $removeChildren = true)
{
if ($removeChildren) {
if ($item = $this->getItem($name)) {
$item->children()->each(function ($item) {
$this->removeItem($item->name);
});
}
}
return $this->items->remove($name);
} | php | public function removeItem(string $name, $removeChildren = true)
{
if ($removeChildren) {
if ($item = $this->getItem($name)) {
$item->children()->each(function ($item) {
$this->removeItem($item->name);
});
}
}
return $this->items->remove($name);
} | [
"public",
"function",
"removeItem",
"(",
"string",
"$",
"name",
",",
"$",
"removeChildren",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"removeChildren",
")",
"{",
"if",
"(",
"$",
"item",
"=",
"$",
"this",
"->",
"getItem",
"(",
"$",
"name",
")",
")",
"{... | Remove a menu item by name
@param string $name
@param bool $removeChildren
@return bool Returns true if item(s) was/were removed, false if failed | [
"Remove",
"a",
"menu",
"item",
"by",
"name"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Menu.php#L91-L102 |
artkonekt/menu | src/Link.php | Link.activate | public function activate()
{
$this->isActive = true;
$this->attributes['class'] = Utils::addHtmlClass(
array_get($this->attributes, 'class', ''),
$this->activeClass
);
return $this;
} | php | public function activate()
{
$this->isActive = true;
$this->attributes['class'] = Utils::addHtmlClass(
array_get($this->attributes, 'class', ''),
$this->activeClass
);
return $this;
} | [
"public",
"function",
"activate",
"(",
")",
"{",
"$",
"this",
"->",
"isActive",
"=",
"true",
";",
"$",
"this",
"->",
"attributes",
"[",
"'class'",
"]",
"=",
"Utils",
"::",
"addHtmlClass",
"(",
"array_get",
"(",
"$",
"this",
"->",
"attributes",
",",
"'c... | Make the anchor active
@return static | [
"Make",
"the",
"anchor",
"active"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Link.php#L49-L58 |
artkonekt/menu | src/Link.php | Link.url | public function url()
{
if (!is_null($this->href)) {
return $this->href;
} elseif (isset($this->path['url'])) {
return $this->getUrl();
} elseif (isset($this->path['route'])) {
return $this->getRoute();
} elseif (isset($this->path['action'])) {
return $this->getControllerAction();
}
return null;
} | php | public function url()
{
if (!is_null($this->href)) {
return $this->href;
} elseif (isset($this->path['url'])) {
return $this->getUrl();
} elseif (isset($this->path['route'])) {
return $this->getRoute();
} elseif (isset($this->path['action'])) {
return $this->getControllerAction();
}
return null;
} | [
"public",
"function",
"url",
"(",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"href",
")",
")",
"{",
"return",
"$",
"this",
"->",
"href",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"this",
"->",
"path",
"[",
"'url'",
"]",
")",... | Return the URL for the link
@return string|null | [
"Return",
"the",
"URL",
"for",
"the",
"link"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Link.php#L79-L92 |
artkonekt/menu | src/Link.php | Link.getUrl | protected function getUrl()
{
$url = $this->path['url'];
$uri = is_array($url) ? $url[0] : $url;
$params = is_array($url) ? array_slice($url, 1) : null;
if (Utils::isAbsoluteUrl($uri)) {
return $uri;
}
return url($uri, $params);
} | php | protected function getUrl()
{
$url = $this->path['url'];
$uri = is_array($url) ? $url[0] : $url;
$params = is_array($url) ? array_slice($url, 1) : null;
if (Utils::isAbsoluteUrl($uri)) {
return $uri;
}
return url($uri, $params);
} | [
"protected",
"function",
"getUrl",
"(",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"path",
"[",
"'url'",
"]",
";",
"$",
"uri",
"=",
"is_array",
"(",
"$",
"url",
")",
"?",
"$",
"url",
"[",
"0",
"]",
":",
"$",
"url",
";",
"$",
"params",
"=",... | Get the action for "url" option.
@return string | [
"Get",
"the",
"action",
"for",
"url",
"option",
"."
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Link.php#L118-L130 |
artkonekt/menu | src/Link.php | Link.getRoute | protected function getRoute()
{
$route = $this->path['route'];
if (is_array($route)) {
return route($route[0], array_slice($route, 1));
}
return route($route);
} | php | protected function getRoute()
{
$route = $this->path['route'];
if (is_array($route)) {
return route($route[0], array_slice($route, 1));
}
return route($route);
} | [
"protected",
"function",
"getRoute",
"(",
")",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"path",
"[",
"'route'",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"route",
")",
")",
"{",
"return",
"route",
"(",
"$",
"route",
"[",
"0",
"]",
",",
"array_... | Get the url for a "route" option.
@return string | [
"Get",
"the",
"url",
"for",
"a",
"route",
"option",
"."
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Link.php#L137-L145 |
artkonekt/menu | src/Link.php | Link.getControllerAction | protected function getControllerAction()
{
$action = $this->path['action'];
if (is_array($action)) {
return action($action[0], array_slice($action, 1));
}
return action($action);
} | php | protected function getControllerAction()
{
$action = $this->path['action'];
if (is_array($action)) {
return action($action[0], array_slice($action, 1));
}
return action($action);
} | [
"protected",
"function",
"getControllerAction",
"(",
")",
"{",
"$",
"action",
"=",
"$",
"this",
"->",
"path",
"[",
"'action'",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"action",
")",
")",
"{",
"return",
"action",
"(",
"$",
"action",
"[",
"0",
"]",
... | Get the url for an "action" option
@return string | [
"Get",
"the",
"url",
"for",
"an",
"action",
"option"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/Link.php#L152-L160 |
artkonekt/menu | src/MenuFactory.php | MenuFactory.create | public static function create(string $name, array $options = [])
{
$menu = new Menu($name, new MenuConfiguration($options));
if (array_key_exists('share', $options)) {
if (is_bool($options['share'])) { // we should also handle if 'share' => false is passed
if (true === $options['share']) { // but only actually share if true
View::share($menu->name, $menu);
}
} else {
View::share((string)$options['share'], $menu);
}
}
return $menu;
} | php | public static function create(string $name, array $options = [])
{
$menu = new Menu($name, new MenuConfiguration($options));
if (array_key_exists('share', $options)) {
if (is_bool($options['share'])) { // we should also handle if 'share' => false is passed
if (true === $options['share']) { // but only actually share if true
View::share($menu->name, $menu);
}
} else {
View::share((string)$options['share'], $menu);
}
}
return $menu;
} | [
"public",
"static",
"function",
"create",
"(",
"string",
"$",
"name",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"menu",
"=",
"new",
"Menu",
"(",
"$",
"name",
",",
"new",
"MenuConfiguration",
"(",
"$",
"options",
")",
")",
";",
"if... | @param string $name
@param array $options
@return Menu | [
"@param",
"string",
"$name",
"@param",
"array",
"$options"
] | train | https://github.com/artkonekt/menu/blob/3b8649f41cce09c61bf84cfecc71727d41171dd3/src/MenuFactory.php#L25-L40 |
bugsnag/bugsnag-psr-logger | src/BugsnagLogger.php | BugsnagLogger.setNotifyLevel | public function setNotifyLevel($notifyLevel)
{
if (!in_array($notifyLevel, $this->getLogLevelOrder())) {
syslog(LOG_WARNING, 'Bugsnag Warning: Invalid notify level supplied to Bugsnag Logger');
} else {
$this->notifyLevel = $notifyLevel;
}
} | php | public function setNotifyLevel($notifyLevel)
{
if (!in_array($notifyLevel, $this->getLogLevelOrder())) {
syslog(LOG_WARNING, 'Bugsnag Warning: Invalid notify level supplied to Bugsnag Logger');
} else {
$this->notifyLevel = $notifyLevel;
}
} | [
"public",
"function",
"setNotifyLevel",
"(",
"$",
"notifyLevel",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"notifyLevel",
",",
"$",
"this",
"->",
"getLogLevelOrder",
"(",
")",
")",
")",
"{",
"syslog",
"(",
"LOG_WARNING",
",",
"'Bugsnag Warning: Invalid... | Set the notifyLevel of the logger, as defined in Psr\Log\LogLevel.
@param string $notifyLevel
@return void | [
"Set",
"the",
"notifyLevel",
"of",
"the",
"logger",
"as",
"defined",
"in",
"Psr",
"\\",
"Log",
"\\",
"LogLevel",
"."
] | train | https://github.com/bugsnag/bugsnag-psr-logger/blob/257967ef831353279489b1696e36f6d76a733c5b/src/BugsnagLogger.php#L48-L55 |
bugsnag/bugsnag-psr-logger | src/BugsnagLogger.php | BugsnagLogger.log | public function log($level, $message, array $context = [])
{
$title = 'Log '.$level;
if (isset($context['title'])) {
$title = $context['title'];
unset($context['title']);
}
$exception = null;
if (isset($context['exception']) && ($context['exception'] instanceof Exception || $context['exception'] instanceof Throwable)) {
$exception = $context['exception'];
unset($context['exception']);
} elseif ($message instanceof Exception || $message instanceof Throwable) {
$exception = $message;
}
// Below theshold, leave a breadcrumb but don't send a notification
if (!$this->aboveLevel($level, $this->notifyLevel)) {
if ($exception !== null) {
$title = get_class($exception);
$data = ['name' => $title, 'message' => $exception->getMessage()];
} else {
$data = ['message' => $message];
}
$metaData = array_merge($data, $context);
$this->client->leaveBreadcrumb($title, 'log', array_filter($metaData));
return;
}
$severityReason = [
'type' => 'log',
'attributes' => [
'level' => $level,
],
];
if ($exception !== null) {
$report = Report::fromPHPThrowable($this->client->getConfig(), $exception);
} else {
$report = Report::fromNamedError($this->client->getConfig(), $title, $this->formatMessage($message));
}
$report->setMetaData($context);
$report->setSeverity($this->getSeverity($level));
$report->setSeverityReason($severityReason);
$this->client->notify($report);
} | php | public function log($level, $message, array $context = [])
{
$title = 'Log '.$level;
if (isset($context['title'])) {
$title = $context['title'];
unset($context['title']);
}
$exception = null;
if (isset($context['exception']) && ($context['exception'] instanceof Exception || $context['exception'] instanceof Throwable)) {
$exception = $context['exception'];
unset($context['exception']);
} elseif ($message instanceof Exception || $message instanceof Throwable) {
$exception = $message;
}
// Below theshold, leave a breadcrumb but don't send a notification
if (!$this->aboveLevel($level, $this->notifyLevel)) {
if ($exception !== null) {
$title = get_class($exception);
$data = ['name' => $title, 'message' => $exception->getMessage()];
} else {
$data = ['message' => $message];
}
$metaData = array_merge($data, $context);
$this->client->leaveBreadcrumb($title, 'log', array_filter($metaData));
return;
}
$severityReason = [
'type' => 'log',
'attributes' => [
'level' => $level,
],
];
if ($exception !== null) {
$report = Report::fromPHPThrowable($this->client->getConfig(), $exception);
} else {
$report = Report::fromNamedError($this->client->getConfig(), $title, $this->formatMessage($message));
}
$report->setMetaData($context);
$report->setSeverity($this->getSeverity($level));
$report->setSeverityReason($severityReason);
$this->client->notify($report);
} | [
"public",
"function",
"log",
"(",
"$",
"level",
",",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"title",
"=",
"'Log '",
".",
"$",
"level",
";",
"if",
"(",
"isset",
"(",
"$",
"context",
"[",
"'title'",
"]",
")",
... | Log a message to the logs.
@param string $level
@param mixed $message
@param array $context
@return void | [
"Log",
"a",
"message",
"to",
"the",
"logs",
"."
] | train | https://github.com/bugsnag/bugsnag-psr-logger/blob/257967ef831353279489b1696e36f6d76a733c5b/src/BugsnagLogger.php#L66-L116 |
bugsnag/bugsnag-psr-logger | src/BugsnagLogger.php | BugsnagLogger.aboveLevel | protected function aboveLevel($level, $base)
{
$levelOrder = $this->getLogLevelOrder();
$baseIndex = array_search($base, $levelOrder);
$levelIndex = array_search($level, $levelOrder);
return $levelIndex >= $baseIndex;
} | php | protected function aboveLevel($level, $base)
{
$levelOrder = $this->getLogLevelOrder();
$baseIndex = array_search($base, $levelOrder);
$levelIndex = array_search($level, $levelOrder);
return $levelIndex >= $baseIndex;
} | [
"protected",
"function",
"aboveLevel",
"(",
"$",
"level",
",",
"$",
"base",
")",
"{",
"$",
"levelOrder",
"=",
"$",
"this",
"->",
"getLogLevelOrder",
"(",
")",
";",
"$",
"baseIndex",
"=",
"array_search",
"(",
"$",
"base",
",",
"$",
"levelOrder",
")",
";... | Checks whether the selected level is above another level.
@param string $level
@param string $base
@return bool | [
"Checks",
"whether",
"the",
"selected",
"level",
"is",
"above",
"another",
"level",
"."
] | train | https://github.com/bugsnag/bugsnag-psr-logger/blob/257967ef831353279489b1696e36f6d76a733c5b/src/BugsnagLogger.php#L126-L133 |
thephpleague/plates | src/Engine.php | Engine.createWithConfig | public static function createWithConfig(array $config = []) {
$plates = new self();
$plates->register(new PlatesExtension());
$plates->register(new Extension\Data\DataExtension());
$plates->register(new Extension\Path\PathExtension());
$plates->register(new Extension\RenderContext\RenderContextExtension());
$plates->register(new Extension\LayoutSections\LayoutSectionsExtension());
$plates->register(new Extension\Folders\FoldersExtension());
$plates->addConfig($config);
return $plates;
} | php | public static function createWithConfig(array $config = []) {
$plates = new self();
$plates->register(new PlatesExtension());
$plates->register(new Extension\Data\DataExtension());
$plates->register(new Extension\Path\PathExtension());
$plates->register(new Extension\RenderContext\RenderContextExtension());
$plates->register(new Extension\LayoutSections\LayoutSectionsExtension());
$plates->register(new Extension\Folders\FoldersExtension());
$plates->addConfig($config);
return $plates;
} | [
"public",
"static",
"function",
"createWithConfig",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"plates",
"=",
"new",
"self",
"(",
")",
";",
"$",
"plates",
"->",
"register",
"(",
"new",
"PlatesExtension",
"(",
")",
")",
";",
"$",
"plat... | Create a configured engine and pass in an array to configure after extension registration | [
"Create",
"a",
"configured",
"engine",
"and",
"pass",
"in",
"an",
"array",
"to",
"configure",
"after",
"extension",
"registration"
] | train | https://github.com/thephpleague/plates/blob/97034759c6bce6ebcae020785eab01cec7fc9ebf/src/Engine.php#L23-L36 |
thephpleague/plates | src/Template.php | Template.fork | public function fork($name, array $data = [], array $attributes = []) {
return new self(
$name,
$data,
$attributes,
null,
$this->reference
);
} | php | public function fork($name, array $data = [], array $attributes = []) {
return new self(
$name,
$data,
$attributes,
null,
$this->reference
);
} | [
"public",
"function",
"fork",
"(",
"$",
"name",
",",
"array",
"$",
"data",
"=",
"[",
"]",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"name",
",",
"$",
"data",
",",
"$",
"attributes",
",",
"null",
... | Create a new template based off of this current one | [
"Create",
"a",
"new",
"template",
"based",
"off",
"of",
"this",
"current",
"one"
] | train | https://github.com/thephpleague/plates/blob/97034759c6bce6ebcae020785eab01cec7fc9ebf/src/Template.php#L67-L75 |
mark-gerarts/automapper-plus | src/Configuration/Options.php | Options.default | public static function default(): Options
{
$options = new static;
$options->skipConstructor();
$options->setPropertyAccessor(new PropertyAccessor());
$options->setDefaultMappingOperation(new DefaultMappingOperation());
$options->setNameResolver(new NameResolver());
$options->registerObjectCrate(\stdClass::class);
return $options;
} | php | public static function default(): Options
{
$options = new static;
$options->skipConstructor();
$options->setPropertyAccessor(new PropertyAccessor());
$options->setDefaultMappingOperation(new DefaultMappingOperation());
$options->setNameResolver(new NameResolver());
$options->registerObjectCrate(\stdClass::class);
return $options;
} | [
"public",
"static",
"function",
"default",
"(",
")",
":",
"Options",
"{",
"$",
"options",
"=",
"new",
"static",
";",
"$",
"options",
"->",
"skipConstructor",
"(",
")",
";",
"$",
"options",
"->",
"setPropertyAccessor",
"(",
"new",
"PropertyAccessor",
"(",
"... | @return Options
Note: the skipConstructor default will be replaced by dontSkipConstructor
in the next major release. | [
"@return",
"Options"
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/Configuration/Options.php#L94-L104 |
mark-gerarts/automapper-plus | src/AutoMapper.php | AutoMapper.doMap | protected function doMap(
$source,
$destination,
MappingInterface $mapping,
array $context = []
) {
$propertyNames = $mapping->getTargetProperties($destination, $source);
foreach ($propertyNames as $propertyName) {
$mappingOperation = $mapping->getMappingOperationFor($propertyName);
if ($mappingOperation instanceof MapperAwareOperation) {
$mappingOperation->setMapper($this);
}
if ($mappingOperation instanceof ContextAwareOperation) {
$mappingOperation->setContext($context);
}
$mappingOperation->mapProperty(
$propertyName,
$source,
$destination
);
}
return $destination;
} | php | protected function doMap(
$source,
$destination,
MappingInterface $mapping,
array $context = []
) {
$propertyNames = $mapping->getTargetProperties($destination, $source);
foreach ($propertyNames as $propertyName) {
$mappingOperation = $mapping->getMappingOperationFor($propertyName);
if ($mappingOperation instanceof MapperAwareOperation) {
$mappingOperation->setMapper($this);
}
if ($mappingOperation instanceof ContextAwareOperation) {
$mappingOperation->setContext($context);
}
$mappingOperation->mapProperty(
$propertyName,
$source,
$destination
);
}
return $destination;
} | [
"protected",
"function",
"doMap",
"(",
"$",
"source",
",",
"$",
"destination",
",",
"MappingInterface",
"$",
"mapping",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"propertyNames",
"=",
"$",
"mapping",
"->",
"getTargetProperties",
"(",
"$",... | Performs the actual transferring of properties.
@param $source
@param $destination
@param MappingInterface $mapping
@param array $context
@return mixed
The destination object with mapped properties. | [
"Performs",
"the",
"actual",
"transferring",
"of",
"properties",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/AutoMapper.php#L137-L162 |
mark-gerarts/automapper-plus | src/AutoMapper.php | AutoMapper.getCustomMapper | private function getCustomMapper(MappingInterface $mapping): ?MapperInterface
{
$customMapper = $mapping->getCustomMapper();
if ($customMapper instanceof MapperAwareOperation) {
$customMapper->setMapper($this);
}
return $customMapper;
} | php | private function getCustomMapper(MappingInterface $mapping): ?MapperInterface
{
$customMapper = $mapping->getCustomMapper();
if ($customMapper instanceof MapperAwareOperation) {
$customMapper->setMapper($this);
}
return $customMapper;
} | [
"private",
"function",
"getCustomMapper",
"(",
"MappingInterface",
"$",
"mapping",
")",
":",
"?",
"MapperInterface",
"{",
"$",
"customMapper",
"=",
"$",
"mapping",
"->",
"getCustomMapper",
"(",
")",
";",
"if",
"(",
"$",
"customMapper",
"instanceof",
"MapperAware... | @param MappingInterface $mapping
@return MapperInterface|null | [
"@param",
"MappingInterface",
"$mapping"
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/AutoMapper.php#L202-L211 |
mark-gerarts/automapper-plus | src/MappingOperation/DefaultMappingOperation.php | DefaultMappingOperation.getSourcePropertyName | protected function getSourcePropertyName(string $propertyName): string
{
return $this->nameResolver->getSourcePropertyName(
$propertyName,
$this,
$this->options
);
} | php | protected function getSourcePropertyName(string $propertyName): string
{
return $this->nameResolver->getSourcePropertyName(
$propertyName,
$this,
$this->options
);
} | [
"protected",
"function",
"getSourcePropertyName",
"(",
"string",
"$",
"propertyName",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"nameResolver",
"->",
"getSourcePropertyName",
"(",
"$",
"propertyName",
",",
"$",
"this",
",",
"$",
"this",
"->",
"opti... | Returns the name of the property we should fetch from the source object.
@param string $propertyName
@return string | [
"Returns",
"the",
"name",
"of",
"the",
"property",
"we",
"should",
"fetch",
"from",
"the",
"source",
"object",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/MappingOperation/DefaultMappingOperation.php#L144-L151 |
mark-gerarts/automapper-plus | src/MappingOperation/Operation.php | Operation.mapTo | public static function mapTo(
string $destinationClass,
bool $sourceIsObjectArray = false,
array $context = []
): MapTo {
return new MapTo($destinationClass, $sourceIsObjectArray, $context);
} | php | public static function mapTo(
string $destinationClass,
bool $sourceIsObjectArray = false,
array $context = []
): MapTo {
return new MapTo($destinationClass, $sourceIsObjectArray, $context);
} | [
"public",
"static",
"function",
"mapTo",
"(",
"string",
"$",
"destinationClass",
",",
"bool",
"$",
"sourceIsObjectArray",
"=",
"false",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
":",
"MapTo",
"{",
"return",
"new",
"MapTo",
"(",
"$",
"destinationCla... | Map a property to a class.
@param string $destinationClass
@param bool $sourceIsObjectArray
Indicates whether or not an array as source value should be treated as
a collection of elements, or as an array representing an object.
@param array $context
Arbitrary values that will be passed the the mapper as context. See
MapperInterface::nap() as well.
@return MapTo | [
"Map",
"a",
"property",
"to",
"a",
"class",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/MappingOperation/Operation.php#L74-L80 |
mark-gerarts/automapper-plus | src/Configuration/AutoMapperConfig.php | AutoMapperConfig.getMostSpecificCandidate | protected function getMostSpecificCandidate(
array $candidates,
string $sourceClassName,
string $destinationClassName
): ?MappingInterface {
$lowestDistance = PHP_INT_MAX;
$selectedCandidate = null;
/** @var MappingInterface $candidate */
foreach($candidates as $candidate) {
$sourceDistance = $this->getClassDistance(
$sourceClassName,
$candidate->getSourceClassName()
);
$destinationDistance = $this->getClassDistance(
$destinationClassName,
$candidate->getDestinationClassName()
);
$distance = $sourceDistance + $destinationDistance;
if ($distance < $lowestDistance) {
$lowestDistance = $distance;
$selectedCandidate = $candidate;
}
}
return $selectedCandidate;
} | php | protected function getMostSpecificCandidate(
array $candidates,
string $sourceClassName,
string $destinationClassName
): ?MappingInterface {
$lowestDistance = PHP_INT_MAX;
$selectedCandidate = null;
/** @var MappingInterface $candidate */
foreach($candidates as $candidate) {
$sourceDistance = $this->getClassDistance(
$sourceClassName,
$candidate->getSourceClassName()
);
$destinationDistance = $this->getClassDistance(
$destinationClassName,
$candidate->getDestinationClassName()
);
$distance = $sourceDistance + $destinationDistance;
if ($distance < $lowestDistance) {
$lowestDistance = $distance;
$selectedCandidate = $candidate;
}
}
return $selectedCandidate;
} | [
"protected",
"function",
"getMostSpecificCandidate",
"(",
"array",
"$",
"candidates",
",",
"string",
"$",
"sourceClassName",
",",
"string",
"$",
"destinationClassName",
")",
":",
"?",
"MappingInterface",
"{",
"$",
"lowestDistance",
"=",
"PHP_INT_MAX",
";",
"$",
"s... | Searches the most specific candidate in the list. This means the mapping
that is closest to the given source and destination in the inheritance
chain.
@param array $candidates
@param string $sourceClassName
@param string $destinationClassName
@return MappingInterface|null | [
"Searches",
"the",
"most",
"specific",
"candidate",
"in",
"the",
"list",
".",
"This",
"means",
"the",
"mapping",
"that",
"is",
"closest",
"to",
"the",
"given",
"source",
"and",
"destination",
"in",
"the",
"inheritance",
"chain",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/Configuration/AutoMapperConfig.php#L119-L145 |
mark-gerarts/automapper-plus | src/Configuration/AutoMapperConfig.php | AutoMapperConfig.getClassDistance | protected function getClassDistance(
string $childClass,
string $parentClass
): int {
if ($childClass === $parentClass) {
return 0;
}
$result = 0;
$childParents = class_parents($childClass, true);
foreach($childParents as $childParent) {
$result++;
if ($childParent === $parentClass) {
return $result;
}
}
// We'll treat implementing an interface as having a greater class
// distance. This because we want a concrete implementation to be more
// specific than an interface. For example, suppose we have:
// - FooInterface
// - FooClass, implementing the above interface
// If a mapping has been registered for both of these, we want the
// mapper to pick the mapping registered for FooClass, since this is
// more specific.
$interfaces = class_implements($childClass);
if (\in_array($parentClass, $interfaces, true)) {
return ++$result;
}
// @todo: use a domain specific exception.
throw new \Exception(
'This error should have never be thrown.
This could only happen if given childClass is not a child of the given parentClass'
);
} | php | protected function getClassDistance(
string $childClass,
string $parentClass
): int {
if ($childClass === $parentClass) {
return 0;
}
$result = 0;
$childParents = class_parents($childClass, true);
foreach($childParents as $childParent) {
$result++;
if ($childParent === $parentClass) {
return $result;
}
}
// We'll treat implementing an interface as having a greater class
// distance. This because we want a concrete implementation to be more
// specific than an interface. For example, suppose we have:
// - FooInterface
// - FooClass, implementing the above interface
// If a mapping has been registered for both of these, we want the
// mapper to pick the mapping registered for FooClass, since this is
// more specific.
$interfaces = class_implements($childClass);
if (\in_array($parentClass, $interfaces, true)) {
return ++$result;
}
// @todo: use a domain specific exception.
throw new \Exception(
'This error should have never be thrown.
This could only happen if given childClass is not a child of the given parentClass'
);
} | [
"protected",
"function",
"getClassDistance",
"(",
"string",
"$",
"childClass",
",",
"string",
"$",
"parentClass",
")",
":",
"int",
"{",
"if",
"(",
"$",
"childClass",
"===",
"$",
"parentClass",
")",
"{",
"return",
"0",
";",
"}",
"$",
"result",
"=",
"0",
... | Returns the distance in the inheritance chain between 2 classes.
@param string $childClass
@param string $parentClass
@return int | [
"Returns",
"the",
"distance",
"in",
"the",
"inheritance",
"chain",
"between",
"2",
"classes",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/Configuration/AutoMapperConfig.php#L154-L189 |
mark-gerarts/automapper-plus | src/PropertyAccessor/PropertyAccessor.php | PropertyAccessor.getPrivate | protected function getPrivate($object, string $propertyName)
{
$objectArray = (array) $object;
foreach ($objectArray as $name => $value) {
if (substr($name, - \strlen($propertyName) - 1) === "\x00" . $propertyName) {
return $value;
}
}
return null;
} | php | protected function getPrivate($object, string $propertyName)
{
$objectArray = (array) $object;
foreach ($objectArray as $name => $value) {
if (substr($name, - \strlen($propertyName) - 1) === "\x00" . $propertyName) {
return $value;
}
}
return null;
} | [
"protected",
"function",
"getPrivate",
"(",
"$",
"object",
",",
"string",
"$",
"propertyName",
")",
"{",
"$",
"objectArray",
"=",
"(",
"array",
")",
"$",
"object",
";",
"foreach",
"(",
"$",
"objectArray",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{"... | Abuses PHP's internal representation of properties when casting an object
to an array.
@param $object
@param string $propertyName
@return mixed | [
"Abuses",
"PHP",
"s",
"internal",
"representation",
"of",
"properties",
"when",
"casting",
"an",
"object",
"to",
"an",
"array",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/PropertyAccessor/PropertyAccessor.php#L78-L88 |
mark-gerarts/automapper-plus | src/PropertyAccessor/PropertyAccessor.php | PropertyAccessor.isPublic | private function isPublic($object, string $propertyName): bool
{
$objectArray = (array) $object;
return array_key_exists($propertyName, $objectArray);
} | php | private function isPublic($object, string $propertyName): bool
{
$objectArray = (array) $object;
return array_key_exists($propertyName, $objectArray);
} | [
"private",
"function",
"isPublic",
"(",
"$",
"object",
",",
"string",
"$",
"propertyName",
")",
":",
"bool",
"{",
"$",
"objectArray",
"=",
"(",
"array",
")",
"$",
"object",
";",
"return",
"array_key_exists",
"(",
"$",
"propertyName",
",",
"$",
"objectArray... | Checks if the given property is public.
@param $object
@param string $propertyName
@return bool | [
"Checks",
"if",
"the",
"given",
"property",
"is",
"public",
"."
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/PropertyAccessor/PropertyAccessor.php#L120-L125 |
mark-gerarts/automapper-plus | src/Configuration/Mapping.php | Mapping.getTargetProperties | public function getTargetProperties($targetObject, $sourceObject): array
{
// We use the property accessor defined on the config, because the one
// in this mapping's Options might have been overridden to be the
// object crate implementation.
$propertyAccessor = $this->autoMapperConfig->getOptions()->getPropertyAccessor();
if (!$this->options->isObjectCrate($this->destinationClassName)) {
$properties = $propertyAccessor->getPropertyNames($targetObject);
return array_values($properties);
}
$sourceProperties = $propertyAccessor->getPropertyNames($sourceObject);
$sourceProperties = array_values($sourceProperties);
if (!$this->options->shouldConvertName()) {
return $sourceProperties;
}
$nameConverter = function (string $sourceProperty): string {
return NameConverter::convert(
$this->options->getSourceMemberNamingConvention(),
$this->options->getDestinationMemberNamingConvention(),
$sourceProperty
);
};
return array_map($nameConverter, $sourceProperties);
} | php | public function getTargetProperties($targetObject, $sourceObject): array
{
// We use the property accessor defined on the config, because the one
// in this mapping's Options might have been overridden to be the
// object crate implementation.
$propertyAccessor = $this->autoMapperConfig->getOptions()->getPropertyAccessor();
if (!$this->options->isObjectCrate($this->destinationClassName)) {
$properties = $propertyAccessor->getPropertyNames($targetObject);
return array_values($properties);
}
$sourceProperties = $propertyAccessor->getPropertyNames($sourceObject);
$sourceProperties = array_values($sourceProperties);
if (!$this->options->shouldConvertName()) {
return $sourceProperties;
}
$nameConverter = function (string $sourceProperty): string {
return NameConverter::convert(
$this->options->getSourceMemberNamingConvention(),
$this->options->getDestinationMemberNamingConvention(),
$sourceProperty
);
};
return array_map($nameConverter, $sourceProperties);
} | [
"public",
"function",
"getTargetProperties",
"(",
"$",
"targetObject",
",",
"$",
"sourceObject",
")",
":",
"array",
"{",
"// We use the property accessor defined on the config, because the one",
"// in this mapping's Options might have been overridden to be the",
"// object crate imple... | @inheritdoc
@todo: move this logic to a separate class. | [
"@inheritdoc"
] | train | https://github.com/mark-gerarts/automapper-plus/blob/fd62a849b7f0076cb8ae41313b2ad11223f932bf/src/Configuration/Mapping.php#L204-L230 |
nategood/commando | src/Commando/Util/Terminal.php | Terminal.tput | private static function tput($default, $param = 'cols')
{
$test = exec('tput ' . $param . ' 2>/dev/null');
if (empty($test))
return $default;
$result = intval(exec('tput ' . $param));
return empty($result) ? $default : $result;
} | php | private static function tput($default, $param = 'cols')
{
$test = exec('tput ' . $param . ' 2>/dev/null');
if (empty($test))
return $default;
$result = intval(exec('tput ' . $param));
return empty($result) ? $default : $result;
} | [
"private",
"static",
"function",
"tput",
"(",
"$",
"default",
",",
"$",
"param",
"=",
"'cols'",
")",
"{",
"$",
"test",
"=",
"exec",
"(",
"'tput '",
".",
"$",
"param",
".",
"' 2>/dev/null'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"test",
")",
")",
... | Sadly if you attempt to redirect stderr, e.g. "tput cols 2>/dev/null"
tput does not return the expected values. As a result, to prevent tput
from writing to stderr, we first check the exit code and call it again
to get the value :-(.
@param int $default
@param string $param
@return int | [
"Sadly",
"if",
"you",
"attempt",
"to",
"redirect",
"stderr",
"e",
".",
"g",
".",
"tput",
"cols",
"2",
">",
"/",
"dev",
"/",
"null",
"tput",
"does",
"not",
"return",
"the",
"expected",
"values",
".",
"As",
"a",
"result",
"to",
"prevent",
"tput",
"from... | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Util/Terminal.php#L51-L58 |
nategood/commando | src/Commando/Util/Terminal.php | Terminal.wrap | public static function wrap($text, $left_margin = 0, $right_margin = 0,
$width = null)
{
if (empty($width)) {
$width = self::getWidth();
}
$width = $width - abs($left_margin) - abs($right_margin);
$margin = str_repeat(' ', $left_margin);
return $margin . wordwrap($text, $width, PHP_EOL . $margin);
} | php | public static function wrap($text, $left_margin = 0, $right_margin = 0,
$width = null)
{
if (empty($width)) {
$width = self::getWidth();
}
$width = $width - abs($left_margin) - abs($right_margin);
$margin = str_repeat(' ', $left_margin);
return $margin . wordwrap($text, $width, PHP_EOL . $margin);
} | [
"public",
"static",
"function",
"wrap",
"(",
"$",
"text",
",",
"$",
"left_margin",
"=",
"0",
",",
"$",
"right_margin",
"=",
"0",
",",
"$",
"width",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"width",
")",
")",
"{",
"$",
"width",
"=",
... | Wrap text for printing
@param string $text
@param int $left_margin
@param int $right_margin
@param int $width attempts to use current terminal width by default
@return string | [
"Wrap",
"text",
"for",
"printing"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Util/Terminal.php#L68-L77 |
nategood/commando | src/Commando/Util/Terminal.php | Terminal.pad | public static function pad($text, $width, $pad = ' ', $mode = STR_PAD_RIGHT)
{
$width = strlen($text) - mb_strlen($text, 'UTF-8') + $width;
return str_pad($text, $width, $pad, $mode);
} | php | public static function pad($text, $width, $pad = ' ', $mode = STR_PAD_RIGHT)
{
$width = strlen($text) - mb_strlen($text, 'UTF-8') + $width;
return str_pad($text, $width, $pad, $mode);
} | [
"public",
"static",
"function",
"pad",
"(",
"$",
"text",
",",
"$",
"width",
",",
"$",
"pad",
"=",
"' '",
",",
"$",
"mode",
"=",
"STR_PAD_RIGHT",
")",
"{",
"$",
"width",
"=",
"strlen",
"(",
"$",
"text",
")",
"-",
"mb_strlen",
"(",
"$",
"text",
","... | A UT8 compatible string pad
@param string $text
@param int $width
@param string $pad
@param int $mode
@return string | [
"A",
"UT8",
"compatible",
"string",
"pad"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Util/Terminal.php#L102-L106 |
nategood/commando | src/Commando/Option.php | Option.setFileRequirements | public function setFileRequirements($require_exists = true, $allow_globbing = true)
{
$this->file = true;
$this->file_require_exists = $require_exists;
$this->file_allow_globbing = $allow_globbing;
} | php | public function setFileRequirements($require_exists = true, $allow_globbing = true)
{
$this->file = true;
$this->file_require_exists = $require_exists;
$this->file_allow_globbing = $allow_globbing;
} | [
"public",
"function",
"setFileRequirements",
"(",
"$",
"require_exists",
"=",
"true",
",",
"$",
"allow_globbing",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"true",
";",
"$",
"this",
"->",
"file_require_exists",
"=",
"$",
"require_exists",
";",
... | Require that the argument is a file. This will
make sure the argument is a valid file, will expand
the file path provided to a full path (e.g. map relative
paths), and in the case where $allow_globbing is set,
supports file globbing and returns an array of matching
files.
@param bool $require_exists
@param bool $allow_globbing
@return void
@throws \Exception if the file does not exists | [
"Require",
"that",
"the",
"argument",
"is",
"a",
"file",
".",
"This",
"will",
"make",
"sure",
"the",
"argument",
"is",
"a",
"valid",
"file",
"will",
"expand",
"the",
"file",
"path",
"provided",
"to",
"a",
"full",
"path",
"(",
"e",
".",
"g",
".",
"map... | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Option.php#L148-L153 |
nategood/commando | src/Commando/Option.php | Option.setNeeds | public function setNeeds($option)
{
if (!is_array($option)) {
$option = array($option);
}
foreach ($option as $opt) {
$this->needs[] = $opt;
}
return $this;
} | php | public function setNeeds($option)
{
if (!is_array($option)) {
$option = array($option);
}
foreach ($option as $opt) {
$this->needs[] = $opt;
}
return $this;
} | [
"public",
"function",
"setNeeds",
"(",
"$",
"option",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"option",
")",
")",
"{",
"$",
"option",
"=",
"array",
"(",
"$",
"option",
")",
";",
"}",
"foreach",
"(",
"$",
"option",
"as",
"$",
"opt",
")",
... | Set an option as required
@param string $option Option name
@return Option | [
"Set",
"an",
"option",
"as",
"required"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Option.php#L181-L190 |
nategood/commando | src/Commando/Option.php | Option.hasNeeds | public function hasNeeds($optionsList)
{
$needs = $this->getNeeds();
$definedOptions = array_keys($optionsList);
$notFound = array();
foreach ($needs as $need) {
if (!in_array($need, $definedOptions)) {
// The needed option has not been defined as a valid flag.
$notFound[] = $need;
} elseif (!$optionsList[$need]->getValue()) {
// The needed option has been defined as a valid flag, but was
// not pased in by the user.
$notFound[] = $need;
}
}
return (empty($notFound)) ? true : $notFound;
} | php | public function hasNeeds($optionsList)
{
$needs = $this->getNeeds();
$definedOptions = array_keys($optionsList);
$notFound = array();
foreach ($needs as $need) {
if (!in_array($need, $definedOptions)) {
// The needed option has not been defined as a valid flag.
$notFound[] = $need;
} elseif (!$optionsList[$need]->getValue()) {
// The needed option has been defined as a valid flag, but was
// not pased in by the user.
$notFound[] = $need;
}
}
return (empty($notFound)) ? true : $notFound;
} | [
"public",
"function",
"hasNeeds",
"(",
"$",
"optionsList",
")",
"{",
"$",
"needs",
"=",
"$",
"this",
"->",
"getNeeds",
"(",
")",
";",
"$",
"definedOptions",
"=",
"array_keys",
"(",
"$",
"optionsList",
")",
";",
"$",
"notFound",
"=",
"array",
"(",
")",
... | Check to see if requirements list for option are met
@param array $optionsList Set of current options defined
@return boolean|array True if requirements met, array if not found | [
"Check",
"to",
"see",
"if",
"requirements",
"list",
"for",
"option",
"are",
"met"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Option.php#L371-L389 |
nategood/commando | src/Commando/Command.php | Command._flag | private function _flag($option, $name)
{
if (isset($name) && is_numeric($name))
throw new \Exception('Attempted to reference flag with a numeric index');
return $this->_option($option, $name);
} | php | private function _flag($option, $name)
{
if (isset($name) && is_numeric($name))
throw new \Exception('Attempted to reference flag with a numeric index');
return $this->_option($option, $name);
} | [
"private",
"function",
"_flag",
"(",
"$",
"option",
",",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"name",
")",
"&&",
"is_numeric",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"'Attempted to reference flag with a numeric ... | @param Option|null $option
@param string $name
@return Option
@throws \Exception
Like _option but only for named flags
@throws \Exception | [
"@param",
"Option|null",
"$option",
"@param",
"string",
"$name",
"@return",
"Option",
"@throws",
"\\",
"Exception"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L238-L243 |
nategood/commando | src/Commando/Command.php | Command._argument | private function _argument($option, $index = null)
{
if (isset($index) && !is_numeric($index))
throw new \Exception('Attempted to reference argument with a string name');
return $this->_option($option, $index);
} | php | private function _argument($option, $index = null)
{
if (isset($index) && !is_numeric($index))
throw new \Exception('Attempted to reference argument with a string name');
return $this->_option($option, $index);
} | [
"private",
"function",
"_argument",
"(",
"$",
"option",
",",
"$",
"index",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"index",
")",
"&&",
"!",
"is_numeric",
"(",
"$",
"index",
")",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"'Attempted to... | @param Option|null $option
@param int $index [optional] only used when referencing an existing option
@return Option
@throws \Exception
Like _option but only for anonymous arguments | [
"@param",
"Option|null",
"$option",
"@param",
"int",
"$index",
"[",
"optional",
"]",
"only",
"used",
"when",
"referencing",
"an",
"existing",
"option",
"@return",
"Option",
"@throws",
"\\",
"Exception"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L253-L258 |
nategood/commando | src/Commando/Command.php | Command.error | public function error(\Exception $e)
{
if ($this->beep_on_error === true) {
\Commando\Util\Terminal::beep();
}
if ($this->trap_errors !== true) {
throw $e;
}
$color = new \Colors\Color();
$error = sprintf('ERROR: %s ', $e->getMessage());
echo $color($error)->bg('red')->bold()->white() . PHP_EOL;
exit(1);
} | php | public function error(\Exception $e)
{
if ($this->beep_on_error === true) {
\Commando\Util\Terminal::beep();
}
if ($this->trap_errors !== true) {
throw $e;
}
$color = new \Colors\Color();
$error = sprintf('ERROR: %s ', $e->getMessage());
echo $color($error)->bg('red')->bold()->white() . PHP_EOL;
exit(1);
} | [
"public",
"function",
"error",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"beep_on_error",
"===",
"true",
")",
"{",
"\\",
"Commando",
"\\",
"Util",
"\\",
"Terminal",
"::",
"beep",
"(",
")",
";",
"}",
"if",
"(",
"$",
... | @param \Exception $e
@throws \Exception | [
"@param",
"\\",
"Exception",
"$e"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L543-L557 |
nategood/commando | src/Commando/Command.php | Command._parseOption | private function _parseOption($token)
{
$matches = array();
if (substr($token, 0, 1) === '-' && !preg_match('/(?P<hyphen>\-{1,2})(?P<name>[a-z][a-z0-9_-]*)/i', $token, $matches)) {
throw new \Exception(sprintf('Unable to parse option %s: Invalid syntax', $token));
}
if (!empty($matches['hyphen'])) {
$type = (strlen($matches['hyphen']) === 1) ?
self::OPTION_TYPE_SHORT:
self::OPTION_TYPE_VERBOSE;
return array($matches['name'], $type);
}
return array($token, self::OPTION_TYPE_ARGUMENT);
} | php | private function _parseOption($token)
{
$matches = array();
if (substr($token, 0, 1) === '-' && !preg_match('/(?P<hyphen>\-{1,2})(?P<name>[a-z][a-z0-9_-]*)/i', $token, $matches)) {
throw new \Exception(sprintf('Unable to parse option %s: Invalid syntax', $token));
}
if (!empty($matches['hyphen'])) {
$type = (strlen($matches['hyphen']) === 1) ?
self::OPTION_TYPE_SHORT:
self::OPTION_TYPE_VERBOSE;
return array($matches['name'], $type);
}
return array($token, self::OPTION_TYPE_ARGUMENT);
} | [
"private",
"function",
"_parseOption",
"(",
"$",
"token",
")",
"{",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"if",
"(",
"substr",
"(",
"$",
"token",
",",
"0",
",",
"1",
")",
"===",
"'-'",
"&&",
"!",
"preg_match",
"(",
"'/(?P<hyphen>\\-{1,2})(?P<nam... | @param string $token
@return array [option name/value, OPTION_TYPE_*]
@throws \Exception | [
"@param",
"string",
"$token"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L574-L590 |
nategood/commando | src/Commando/Command.php | Command.getArgumentValues | public function getArgumentValues()
{
$this->parseIfNotParsed();
return array_map(function(Option $argument) {
return $argument->getValue();
}, $this->arguments);
} | php | public function getArgumentValues()
{
$this->parseIfNotParsed();
return array_map(function(Option $argument) {
return $argument->getValue();
}, $this->arguments);
} | [
"public",
"function",
"getArgumentValues",
"(",
")",
"{",
"$",
"this",
"->",
"parseIfNotParsed",
"(",
")",
";",
"return",
"array_map",
"(",
"function",
"(",
"Option",
"$",
"argument",
")",
"{",
"return",
"$",
"argument",
"->",
"getValue",
"(",
")",
";",
... | @return array of argument values only
If your command was `php filename -f flagvalue argument1 argument2`
`getArguments` would return array("argument1", "argument2"); | [
"@return",
"array",
"of",
"argument",
"values",
"only"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L640-L646 |
nategood/commando | src/Commando/Command.php | Command.getFlagValues | public function getFlagValues()
{
$this->parseIfNotParsed();
return array_map(function(Option $flag) {
return $flag->getValue();
}, $this->dedupeFlags());
} | php | public function getFlagValues()
{
$this->parseIfNotParsed();
return array_map(function(Option $flag) {
return $flag->getValue();
}, $this->dedupeFlags());
} | [
"public",
"function",
"getFlagValues",
"(",
")",
"{",
"$",
"this",
"->",
"parseIfNotParsed",
"(",
")",
";",
"return",
"array_map",
"(",
"function",
"(",
"Option",
"$",
"flag",
")",
"{",
"return",
"$",
"flag",
"->",
"getValue",
"(",
")",
";",
"}",
",",
... | @return array of flag values only
If your command was `php filename -f flagvalue argument1 argument2`
`getFlags` would return array("-f" => "flagvalue"); | [
"@return",
"array",
"of",
"flag",
"values",
"only"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L654-L660 |
nategood/commando | src/Commando/Command.php | Command.offsetGet | public function offsetGet($offset)
{
// Support implicit/lazy parsing
$this->parseIfNotParsed();
if (!isset($this->options[$offset])) {
return null; // follows normal php convention
}
return $this->options[$offset]->getValue();
} | php | public function offsetGet($offset)
{
// Support implicit/lazy parsing
$this->parseIfNotParsed();
if (!isset($this->options[$offset])) {
return null; // follows normal php convention
}
return $this->options[$offset]->getValue();
} | [
"public",
"function",
"offsetGet",
"(",
"$",
"offset",
")",
"{",
"// Support implicit/lazy parsing",
"$",
"this",
"->",
"parseIfNotParsed",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"$",
"offset",
"]",
")",
")",
"{",... | @param string $offset
@see \ArrayAccess
@return mixed | [
"@param",
"string",
"$offset"
] | train | https://github.com/nategood/commando/blob/bf0f579de672503f78d997da3fe2fad0d42380e7/src/Commando/Command.php#L814-L822 |
jormin/laravel-ddoc | src/Controllers/DDocController.php | DDocController.initTablesData | private function initTablesData()
{
//获取数据库表名称列表
$tables = DB::select('SHOW TABLE STATUS ');
foreach ($tables as $key => $table) {
//获取改表的所有字段信息
$columns = DB::select("SHOW FULL FIELDS FROM `".$table->Name."`");
$table->columns = $columns;
$tables[$key] = $table;
}
return $tables;
} | php | private function initTablesData()
{
//获取数据库表名称列表
$tables = DB::select('SHOW TABLE STATUS ');
foreach ($tables as $key => $table) {
//获取改表的所有字段信息
$columns = DB::select("SHOW FULL FIELDS FROM `".$table->Name."`");
$table->columns = $columns;
$tables[$key] = $table;
}
return $tables;
} | [
"private",
"function",
"initTablesData",
"(",
")",
"{",
"//获取数据库表名称列表",
"$",
"tables",
"=",
"DB",
"::",
"select",
"(",
"'SHOW TABLE STATUS '",
")",
";",
"foreach",
"(",
"$",
"tables",
"as",
"$",
"key",
"=>",
"$",
"table",
")",
"{",
"//获取改表的所有字段信息",
"$",
... | 读取数据库信息 | [
"读取数据库信息"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Controllers/DDocController.php#L18-L29 |
jormin/laravel-ddoc | src/Controllers/DDocController.php | DDocController.addFileToZip | private function addFileToZip($path, $zip) {
$handler = opendir(public_path($path));
while (($filename = readdir($handler)) !== false) {
if (!in_array($filename,array('.','..','.DS_Store'))) {
if (is_dir($path . "/" . $filename)) {
$this->addFileToZip($path . "/" . $filename, $zip);
} else { //将文件加入zip对象
$fullname = public_path($path) . "/" . $filename;
$localname = str_replace('vendor/laravel-ddoc/','','/'.$path.'/'.$filename);
$zip->addFile($fullname,$localname);
}
}
}
@closedir($path);
} | php | private function addFileToZip($path, $zip) {
$handler = opendir(public_path($path));
while (($filename = readdir($handler)) !== false) {
if (!in_array($filename,array('.','..','.DS_Store'))) {
if (is_dir($path . "/" . $filename)) {
$this->addFileToZip($path . "/" . $filename, $zip);
} else { //将文件加入zip对象
$fullname = public_path($path) . "/" . $filename;
$localname = str_replace('vendor/laravel-ddoc/','','/'.$path.'/'.$filename);
$zip->addFile($fullname,$localname);
}
}
}
@closedir($path);
} | [
"private",
"function",
"addFileToZip",
"(",
"$",
"path",
",",
"$",
"zip",
")",
"{",
"$",
"handler",
"=",
"opendir",
"(",
"public_path",
"(",
"$",
"path",
")",
")",
";",
"while",
"(",
"(",
"$",
"filename",
"=",
"readdir",
"(",
"$",
"handler",
")",
"... | 添加文件夹
@param $path
@param $zip | [
"添加文件夹"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Controllers/DDocController.php#L110-L124 |
jormin/laravel-ddoc | src/Controllers/DDocController.php | DDocController.getMdContent | private function getMdContent()
{
$tables = $this->initTablesData();
$content = "## 数据字典\n";
foreach ($tables as $table){
$content .= $this->tableName($table);
}
$content .= "\n";
foreach ($tables as $key => $table){
$content .= $this->tableDetail($key, $table);
}
return $content;
} | php | private function getMdContent()
{
$tables = $this->initTablesData();
$content = "## 数据字典\n";
foreach ($tables as $table){
$content .= $this->tableName($table);
}
$content .= "\n";
foreach ($tables as $key => $table){
$content .= $this->tableDetail($key, $table);
}
return $content;
} | [
"private",
"function",
"getMdContent",
"(",
")",
"{",
"$",
"tables",
"=",
"$",
"this",
"->",
"initTablesData",
"(",
")",
";",
"$",
"content",
"=",
"\"## 数据字典\\n\";",
"",
"foreach",
"(",
"$",
"tables",
"as",
"$",
"table",
")",
"{",
"$",
"content",
".=",... | md 内容
@param $table | [
"md",
"内容"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Controllers/DDocController.php#L131-L143 |
jormin/laravel-ddoc | src/DDocServiceProvider.php | DDocServiceProvider.boot | public function boot()
{
// 发布配置文件
$this->publishes([
__DIR__.'/../config/laravel-ddoc.php' => config_path('laravel-ddoc.php'),
]);
// 发布视图文件
$this->loadViewsFrom(__DIR__.'/../resources/views', 'ddoc');
$this->publishes([
__DIR__.'/../resources/views' => base_path('resources/views/vendor/laravel-ddoc'),
]);
// 发布资源文件
$this->publishes([
__DIR__.'/../public/' => public_path(''),
]);
// 注册路由
if ((method_exists($this->app, 'routesAreCached') && !$this->app->routesAreCached())
|| $this->isLumen()) {
require __DIR__.'/routes.php';
}
} | php | public function boot()
{
// 发布配置文件
$this->publishes([
__DIR__.'/../config/laravel-ddoc.php' => config_path('laravel-ddoc.php'),
]);
// 发布视图文件
$this->loadViewsFrom(__DIR__.'/../resources/views', 'ddoc');
$this->publishes([
__DIR__.'/../resources/views' => base_path('resources/views/vendor/laravel-ddoc'),
]);
// 发布资源文件
$this->publishes([
__DIR__.'/../public/' => public_path(''),
]);
// 注册路由
if ((method_exists($this->app, 'routesAreCached') && !$this->app->routesAreCached())
|| $this->isLumen()) {
require __DIR__.'/routes.php';
}
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"// 发布配置文件",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/../config/laravel-ddoc.php'",
"=>",
"config_path",
"(",
"'laravel-ddoc.php'",
")",
",",
"]",
")",
";",
"// 发布视图文件",
"$",
"this",
"->",
"loa... | Perform post-registration booting of services.
@return void | [
"Perform",
"post",
"-",
"registration",
"booting",
"of",
"services",
"."
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/DDocServiceProvider.php#L16-L36 |
jormin/laravel-ddoc | src/Lib/simple_html_dom.php | simple_html_dom_node.outertext | function outertext()
{
global $debug_object;
if (is_object($debug_object))
{
$text = '';
if ($this->tag == 'text')
{
if (!empty($this->text))
{
$text = " with text: " . $this->text;
}
}
$debug_object->debug_log(1, 'Innertext of tag: ' . $this->tag . $text);
}
if ($this->tag==='root') return $this->innertext();
// trigger callback
if ($this->dom && $this->dom->callback!==null)
{
call_user_func_array($this->dom->callback, array($this));
}
if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
// render begin tag
if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
{
$ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
} else {
$ret = "";
}
// render inner text
if (isset($this->_[HDOM_INFO_INNER]))
{
// If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added.
if ($this->tag != "br")
{
$ret .= $this->_[HDOM_INFO_INNER];
}
} else {
if ($this->nodes)
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->outertext());
}
}
}
// render end tag
if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
$ret .= '</'.$this->tag.'>';
return $ret;
} | php | function outertext()
{
global $debug_object;
if (is_object($debug_object))
{
$text = '';
if ($this->tag == 'text')
{
if (!empty($this->text))
{
$text = " with text: " . $this->text;
}
}
$debug_object->debug_log(1, 'Innertext of tag: ' . $this->tag . $text);
}
if ($this->tag==='root') return $this->innertext();
// trigger callback
if ($this->dom && $this->dom->callback!==null)
{
call_user_func_array($this->dom->callback, array($this));
}
if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
// render begin tag
if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
{
$ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
} else {
$ret = "";
}
// render inner text
if (isset($this->_[HDOM_INFO_INNER]))
{
// If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added.
if ($this->tag != "br")
{
$ret .= $this->_[HDOM_INFO_INNER];
}
} else {
if ($this->nodes)
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->outertext());
}
}
}
// render end tag
if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
$ret .= '</'.$this->tag.'>';
return $ret;
} | [
"function",
"outertext",
"(",
")",
"{",
"global",
"$",
"debug_object",
";",
"if",
"(",
"is_object",
"(",
"$",
"debug_object",
")",
")",
"{",
"$",
"text",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"tag",
"==",
"'text'",
")",
"{",
"if",
"(",
"!... | get dom node's outer text (with tag) | [
"get",
"dom",
"node",
"s",
"outer",
"text",
"(",
"with",
"tag",
")"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Lib/simple_html_dom.php#L367-L424 |
jormin/laravel-ddoc | src/Lib/simple_html_dom.php | simple_html_dom_node.text | function text()
{
if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
switch ($this->nodetype)
{
case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
case HDOM_TYPE_COMMENT: return '';
case HDOM_TYPE_UNKNOWN: return '';
}
if (strcasecmp($this->tag, 'script')===0) return '';
if (strcasecmp($this->tag, 'style')===0) return '';
$ret = '';
// In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL.
// NOTE: This indicates that there is a problem where it's set to NULL without a clear happening.
// WHY is this happening?
if (!is_null($this->nodes))
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->text());
}
// If this node is a span... add a space at the end of it so multiple spans don't run into each other. This is plaintext after all.
if ($this->tag == "span")
{
$ret .= $this->dom->default_span_text;
}
}
return $ret;
} | php | function text()
{
if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
switch ($this->nodetype)
{
case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
case HDOM_TYPE_COMMENT: return '';
case HDOM_TYPE_UNKNOWN: return '';
}
if (strcasecmp($this->tag, 'script')===0) return '';
if (strcasecmp($this->tag, 'style')===0) return '';
$ret = '';
// In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL.
// NOTE: This indicates that there is a problem where it's set to NULL without a clear happening.
// WHY is this happening?
if (!is_null($this->nodes))
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->text());
}
// If this node is a span... add a space at the end of it so multiple spans don't run into each other. This is plaintext after all.
if ($this->tag == "span")
{
$ret .= $this->dom->default_span_text;
}
}
return $ret;
} | [
"function",
"text",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_",
"[",
"HDOM_INFO_INNER",
"]",
")",
")",
"return",
"$",
"this",
"->",
"_",
"[",
"HDOM_INFO_INNER",
"]",
";",
"switch",
"(",
"$",
"this",
"->",
"nodetype",
")",
"{",
... | get dom node's plain text | [
"get",
"dom",
"node",
"s",
"plain",
"text"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Lib/simple_html_dom.php#L427-L459 |
jormin/laravel-ddoc | src/Lib/simple_html_dom.php | simple_html_dom_node.makeup | function makeup()
{
// text, comment, unknown
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
$ret = '<'.$this->tag;
$i = -1;
foreach ($this->attr as $key=>$val)
{
++$i;
// skip removed attribute
if ($val===null || $val===false)
continue;
$ret .= $this->_[HDOM_INFO_SPACE][$i][0];
//no value attr: nowrap, checked selected...
if ($val===true)
$ret .= $key;
else {
switch ($this->_[HDOM_INFO_QUOTE][$i])
{
case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
case HDOM_QUOTE_SINGLE: $quote = '\''; break;
default: $quote = '';
}
$ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
}
}
$ret = $this->dom->restore_noise($ret);
return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
} | php | function makeup()
{
// text, comment, unknown
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
$ret = '<'.$this->tag;
$i = -1;
foreach ($this->attr as $key=>$val)
{
++$i;
// skip removed attribute
if ($val===null || $val===false)
continue;
$ret .= $this->_[HDOM_INFO_SPACE][$i][0];
//no value attr: nowrap, checked selected...
if ($val===true)
$ret .= $key;
else {
switch ($this->_[HDOM_INFO_QUOTE][$i])
{
case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
case HDOM_QUOTE_SINGLE: $quote = '\''; break;
default: $quote = '';
}
$ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
}
}
$ret = $this->dom->restore_noise($ret);
return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
} | [
"function",
"makeup",
"(",
")",
"{",
"// text, comment, unknown\r",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"_",
"[",
"HDOM_INFO_TEXT",
"]",
")",
")",
"return",
"$",
"this",
"->",
"dom",
"->",
"restore_noise",
"(",
"$",
"this",
"->",
"_",
"[",
"HDO... | build node's text with tag | [
"build",
"node",
"s",
"text",
"with",
"tag"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Lib/simple_html_dom.php#L470-L502 |
jormin/laravel-ddoc | src/Lib/simple_html_dom.php | simple_html_dom_node.find | function find($selector, $idx=null, $lowercase=false)
{
$selectors = $this->parse_selector($selector);
if (($count=count($selectors))===0) return array();
$found_keys = array();
// find each selector
for ($c=0; $c<$count; ++$c)
{
// The change on the below line was documented on the sourceforge code tracker id 2788009
// used to be: if (($levle=count($selectors[0]))===0) return array();
if (($levle=count($selectors[$c]))===0) return array();
if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
$head = array($this->_[HDOM_INFO_BEGIN]=>1);
// handle descendant selectors, no recursive!
for ($l=0; $l<$levle; ++$l)
{
$ret = array();
foreach ($head as $k=>$v)
{
$n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
//PaperG - Pass this optional parameter on to the seek function.
$n->seek($selectors[$c][$l], $ret, $lowercase);
}
$head = $ret;
}
foreach ($head as $k=>$v)
{
if (!isset($found_keys[$k]))
{
$found_keys[$k] = 1;
}
}
}
// sort keys
ksort($found_keys);
$found = array();
foreach ($found_keys as $k=>$v)
$found[] = $this->dom->nodes[$k];
// return nth-element or array
if (is_null($idx)) return $found;
else if ($idx<0) $idx = count($found) + $idx;
return (isset($found[$idx])) ? $found[$idx] : null;
} | php | function find($selector, $idx=null, $lowercase=false)
{
$selectors = $this->parse_selector($selector);
if (($count=count($selectors))===0) return array();
$found_keys = array();
// find each selector
for ($c=0; $c<$count; ++$c)
{
// The change on the below line was documented on the sourceforge code tracker id 2788009
// used to be: if (($levle=count($selectors[0]))===0) return array();
if (($levle=count($selectors[$c]))===0) return array();
if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
$head = array($this->_[HDOM_INFO_BEGIN]=>1);
// handle descendant selectors, no recursive!
for ($l=0; $l<$levle; ++$l)
{
$ret = array();
foreach ($head as $k=>$v)
{
$n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
//PaperG - Pass this optional parameter on to the seek function.
$n->seek($selectors[$c][$l], $ret, $lowercase);
}
$head = $ret;
}
foreach ($head as $k=>$v)
{
if (!isset($found_keys[$k]))
{
$found_keys[$k] = 1;
}
}
}
// sort keys
ksort($found_keys);
$found = array();
foreach ($found_keys as $k=>$v)
$found[] = $this->dom->nodes[$k];
// return nth-element or array
if (is_null($idx)) return $found;
else if ($idx<0) $idx = count($found) + $idx;
return (isset($found[$idx])) ? $found[$idx] : null;
} | [
"function",
"find",
"(",
"$",
"selector",
",",
"$",
"idx",
"=",
"null",
",",
"$",
"lowercase",
"=",
"false",
")",
"{",
"$",
"selectors",
"=",
"$",
"this",
"->",
"parse_selector",
"(",
"$",
"selector",
")",
";",
"if",
"(",
"(",
"$",
"count",
"=",
... | PaperG - added ability for find to lowercase the value of the selector. | [
"PaperG",
"-",
"added",
"ability",
"for",
"find",
"to",
"lowercase",
"the",
"value",
"of",
"the",
"selector",
"."
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Lib/simple_html_dom.php#L506-L555 |
jormin/laravel-ddoc | src/Lib/simple_html_dom.php | simple_html_dom_node.seek | protected function seek($selector, &$ret, $lowercase=false)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
list($tag, $key, $val, $exp, $no_key) = $selector;
// xpath index
if ($tag && $key && is_numeric($key))
{
$count = 0;
foreach ($this->children as $c)
{
if ($tag==='*' || $tag===$c->tag) {
if (++$count==$key) {
$ret[$c->_[HDOM_INFO_BEGIN]] = 1;
return;
}
}
}
return;
}
$end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
if ($end==0) {
$parent = $this->parent;
while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
$end -= 1;
$parent = $parent->parent;
}
$end += $parent->_[HDOM_INFO_END];
}
for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
$node = $this->dom->nodes[$i];
$pass = true;
if ($tag==='*' && !$key) {
if (in_array($node, $this->children, true))
$ret[$i] = 1;
continue;
}
// compare tag
if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
// compare key
if ($pass && $key) {
if ($no_key) {
if (isset($node->attr[$key])) $pass=false;
} else {
if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
}
}
// compare value
if ($pass && $key && $val && $val!=='*') {
// If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
if ($key == "plaintext") {
// $node->plaintext actually returns $node->text();
$nodeKeyValue = $node->text();
} else {
// this is a normal search, we want the value of that attribute of the tag.
$nodeKeyValue = $node->attr[$key];
}
if (is_object($debug_object)) {$debug_object->debug_log(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}
//PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
if ($lowercase) {
$check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
} else {
$check = $this->match($exp, $val, $nodeKeyValue);
}
if (is_object($debug_object)) {$debug_object->debug_log(2, "after match: " . ($check ? "true" : "false"));}
// handle multiple class
if (!$check && strcasecmp($key, 'class')===0) {
foreach (explode(' ',$node->attr[$key]) as $k) {
// Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
if (!empty($k)) {
if ($lowercase) {
$check = $this->match($exp, strtolower($val), strtolower($k));
} else {
$check = $this->match($exp, $val, $k);
}
if ($check) break;
}
}
}
if (!$check) $pass = false;
}
if ($pass) $ret[$i] = 1;
unset($node);
}
// It's passed by reference so this is actually what this function returns.
if (is_object($debug_object)) {$debug_object->debug_log(1, "EXIT - ret: ", $ret);}
} | php | protected function seek($selector, &$ret, $lowercase=false)
{
global $debug_object;
if (is_object($debug_object)) { $debug_object->debug_log_entry(1); }
list($tag, $key, $val, $exp, $no_key) = $selector;
// xpath index
if ($tag && $key && is_numeric($key))
{
$count = 0;
foreach ($this->children as $c)
{
if ($tag==='*' || $tag===$c->tag) {
if (++$count==$key) {
$ret[$c->_[HDOM_INFO_BEGIN]] = 1;
return;
}
}
}
return;
}
$end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
if ($end==0) {
$parent = $this->parent;
while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
$end -= 1;
$parent = $parent->parent;
}
$end += $parent->_[HDOM_INFO_END];
}
for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
$node = $this->dom->nodes[$i];
$pass = true;
if ($tag==='*' && !$key) {
if (in_array($node, $this->children, true))
$ret[$i] = 1;
continue;
}
// compare tag
if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
// compare key
if ($pass && $key) {
if ($no_key) {
if (isset($node->attr[$key])) $pass=false;
} else {
if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
}
}
// compare value
if ($pass && $key && $val && $val!=='*') {
// If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
if ($key == "plaintext") {
// $node->plaintext actually returns $node->text();
$nodeKeyValue = $node->text();
} else {
// this is a normal search, we want the value of that attribute of the tag.
$nodeKeyValue = $node->attr[$key];
}
if (is_object($debug_object)) {$debug_object->debug_log(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}
//PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
if ($lowercase) {
$check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
} else {
$check = $this->match($exp, $val, $nodeKeyValue);
}
if (is_object($debug_object)) {$debug_object->debug_log(2, "after match: " . ($check ? "true" : "false"));}
// handle multiple class
if (!$check && strcasecmp($key, 'class')===0) {
foreach (explode(' ',$node->attr[$key]) as $k) {
// Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
if (!empty($k)) {
if ($lowercase) {
$check = $this->match($exp, strtolower($val), strtolower($k));
} else {
$check = $this->match($exp, $val, $k);
}
if ($check) break;
}
}
}
if (!$check) $pass = false;
}
if ($pass) $ret[$i] = 1;
unset($node);
}
// It's passed by reference so this is actually what this function returns.
if (is_object($debug_object)) {$debug_object->debug_log(1, "EXIT - ret: ", $ret);}
} | [
"protected",
"function",
"seek",
"(",
"$",
"selector",
",",
"&",
"$",
"ret",
",",
"$",
"lowercase",
"=",
"false",
")",
"{",
"global",
"$",
"debug_object",
";",
"if",
"(",
"is_object",
"(",
"$",
"debug_object",
")",
")",
"{",
"$",
"debug_object",
"->",
... | PaperG - added parameter to allow for case insensitive testing of the value of a selector. | [
"PaperG",
"-",
"added",
"parameter",
"to",
"allow",
"for",
"case",
"insensitive",
"testing",
"of",
"the",
"value",
"of",
"a",
"selector",
"."
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Lib/simple_html_dom.php#L559-L654 |
jormin/laravel-ddoc | src/Lib/simple_html_dom.php | simple_html_dom.load | function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
global $debug_object;
// prepare
$this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
// strip out cdata
$this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
// strip out comments
$this->remove_noise("'<!--(.*?)-->'is");
// Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
// Script tags removal now preceeds style tag removal.
// strip out <script> tags
$this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
$this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
// strip out <style> tags
$this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
$this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
// strip out preformatted tags
$this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
// strip out server side scripts
$this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
// strip smarty scripts
$this->remove_noise("'(\{\w)(.*?)(\})'s", true);
// parsing
while ($this->parse());
// end
$this->root->_[HDOM_INFO_END] = $this->cursor;
$this->parse_charset();
// make load function chainable
return $this;
} | php | function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
global $debug_object;
// prepare
$this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
// strip out cdata
$this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
// strip out comments
$this->remove_noise("'<!--(.*?)-->'is");
// Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
// Script tags removal now preceeds style tag removal.
// strip out <script> tags
$this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
$this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
// strip out <style> tags
$this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
$this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
// strip out preformatted tags
$this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
// strip out server side scripts
$this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
// strip smarty scripts
$this->remove_noise("'(\{\w)(.*?)(\})'s", true);
// parsing
while ($this->parse());
// end
$this->root->_[HDOM_INFO_END] = $this->cursor;
$this->parse_charset();
// make load function chainable
return $this;
} | [
"function",
"load",
"(",
"$",
"str",
",",
"$",
"lowercase",
"=",
"true",
",",
"$",
"stripRN",
"=",
"true",
",",
"$",
"defaultBRText",
"=",
"DEFAULT_BR_TEXT",
",",
"$",
"defaultSpanText",
"=",
"DEFAULT_SPAN_TEXT",
")",
"{",
"global",
"$",
"debug_object",
";... | load html from string | [
"load",
"html",
"from",
"string"
] | train | https://github.com/jormin/laravel-ddoc/blob/0c6cab6c247cbb599bf15fcc6253cbeae48493c4/src/Lib/simple_html_dom.php#L1057-L1091 |
craftcms/element-api | src/PaginatorAdapter.php | PaginatorAdapter.getUrl | public function getUrl($page)
{
$request = Craft::$app->getRequest();
// Get the query string params without the path or `pattern`
parse_str($request->getQueryString(), $params);
$pathParam = Craft::$app->getConfig()->getGeneral()->pathParam;
unset($params[$pathParam], $params['pattern']);
// Return the URL with the page param
$params[$this->pageParam] = $page;
return UrlHelper::url($request->getPathInfo(), $params);
} | php | public function getUrl($page)
{
$request = Craft::$app->getRequest();
// Get the query string params without the path or `pattern`
parse_str($request->getQueryString(), $params);
$pathParam = Craft::$app->getConfig()->getGeneral()->pathParam;
unset($params[$pathParam], $params['pattern']);
// Return the URL with the page param
$params[$this->pageParam] = $page;
return UrlHelper::url($request->getPathInfo(), $params);
} | [
"public",
"function",
"getUrl",
"(",
"$",
"page",
")",
"{",
"$",
"request",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getRequest",
"(",
")",
";",
"// Get the query string params without the path or `pattern`",
"parse_str",
"(",
"$",
"request",
"->",
"getQueryString",... | Get the url for the given page.
@param int $page
@return string | [
"Get",
"the",
"url",
"for",
"the",
"given",
"page",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/PaginatorAdapter.php#L129-L141 |
craftcms/element-api | src/PaginatorAdapter.php | PaginatorAdapter._currentPage | private function _currentPage(): int
{
$currentPage = Craft::$app->getRequest()->getQueryParam($this->pageParam, 1);
if (is_numeric($currentPage) && $currentPage > $this->totalPages) {
$currentPage = $this->totalPages > 0 ? $this->totalPages : 1;
} else if (!is_numeric($currentPage) || $currentPage < 0) {
$currentPage = 1;
}
return (int)$currentPage;
} | php | private function _currentPage(): int
{
$currentPage = Craft::$app->getRequest()->getQueryParam($this->pageParam, 1);
if (is_numeric($currentPage) && $currentPage > $this->totalPages) {
$currentPage = $this->totalPages > 0 ? $this->totalPages : 1;
} else if (!is_numeric($currentPage) || $currentPage < 0) {
$currentPage = 1;
}
return (int)$currentPage;
} | [
"private",
"function",
"_currentPage",
"(",
")",
":",
"int",
"{",
"$",
"currentPage",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getRequest",
"(",
")",
"->",
"getQueryParam",
"(",
"$",
"this",
"->",
"pageParam",
",",
"1",
")",
";",
"if",
"(",
"is_numeric",... | Determines the current page.
@return integer | [
"Determines",
"the",
"current",
"page",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/PaginatorAdapter.php#L148-L159 |
craftcms/element-api | src/resources/ElementResource.php | ElementResource.getTransformer | protected function getTransformer()
{
if (is_callable($this->transformer) || $this->transformer instanceof TransformerAbstract) {
return $this->transformer;
}
return Craft::createObject($this->transformer);
} | php | protected function getTransformer()
{
if (is_callable($this->transformer) || $this->transformer instanceof TransformerAbstract) {
return $this->transformer;
}
return Craft::createObject($this->transformer);
} | [
"protected",
"function",
"getTransformer",
"(",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"transformer",
")",
"||",
"$",
"this",
"->",
"transformer",
"instanceof",
"TransformerAbstract",
")",
"{",
"return",
"$",
"this",
"->",
"transformer",
... | Returns the transformer based on the given endpoint
@return callable|TransformerAbstract | [
"Returns",
"the",
"transformer",
"based",
"on",
"the",
"given",
"endpoint"
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/resources/ElementResource.php#L176-L183 |
craftcms/element-api | src/Plugin.php | Plugin.getDefaultResourceAdapterConfig | public function getDefaultResourceAdapterConfig(): array
{
if ($this->_defaultResourceAdapterConfig !== null) {
return $this->_defaultResourceAdapterConfig;
}
return $this->_defaultResourceAdapterConfig = $this->getSettings()->defaults;
} | php | public function getDefaultResourceAdapterConfig(): array
{
if ($this->_defaultResourceAdapterConfig !== null) {
return $this->_defaultResourceAdapterConfig;
}
return $this->_defaultResourceAdapterConfig = $this->getSettings()->defaults;
} | [
"public",
"function",
"getDefaultResourceAdapterConfig",
"(",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"_defaultResourceAdapterConfig",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"_defaultResourceAdapterConfig",
";",
"}",
"return",
"$",
"... | Returns the default endpoint configuration.
@return array | [
"Returns",
"the",
"default",
"endpoint",
"configuration",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/Plugin.php#L60-L67 |
craftcms/element-api | src/Plugin.php | Plugin.registerUrlRules | public function registerUrlRules(RegisterUrlRulesEvent $event)
{
foreach ($this->getSettings()->endpoints as $pattern => $config) {
$event->rules[$pattern] = [
'route' => 'element-api',
'defaults' => ['pattern' => $pattern],
];
}
} | php | public function registerUrlRules(RegisterUrlRulesEvent $event)
{
foreach ($this->getSettings()->endpoints as $pattern => $config) {
$event->rules[$pattern] = [
'route' => 'element-api',
'defaults' => ['pattern' => $pattern],
];
}
} | [
"public",
"function",
"registerUrlRules",
"(",
"RegisterUrlRulesEvent",
"$",
"event",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"getSettings",
"(",
")",
"->",
"endpoints",
"as",
"$",
"pattern",
"=>",
"$",
"config",
")",
"{",
"$",
"event",
"->",
"rules",... | Registers the site URL rules.
@param RegisterUrlRulesEvent $event | [
"Registers",
"the",
"site",
"URL",
"rules",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/Plugin.php#L74-L82 |
craftcms/element-api | src/Plugin.php | Plugin.createResource | public function createResource($config): ResourceInterface
{
if ($config instanceof ResourceInterface) {
return $config;
}
if ($config instanceof ResourceAdapterInterface) {
return $config->getResource();
}
if (!isset($config['class'])) {
// Default to ElementResourceAdapter
$config['class'] = ElementResource::class;
}
/** @var ResourceInterface|ResourceAdapterInterface $resource */
$resource = Craft::createObject($config);
if ($resource instanceof ResourceAdapterInterface) {
$resource = $resource->getResource();
}
return $resource;
} | php | public function createResource($config): ResourceInterface
{
if ($config instanceof ResourceInterface) {
return $config;
}
if ($config instanceof ResourceAdapterInterface) {
return $config->getResource();
}
if (!isset($config['class'])) {
// Default to ElementResourceAdapter
$config['class'] = ElementResource::class;
}
/** @var ResourceInterface|ResourceAdapterInterface $resource */
$resource = Craft::createObject($config);
if ($resource instanceof ResourceAdapterInterface) {
$resource = $resource->getResource();
}
return $resource;
} | [
"public",
"function",
"createResource",
"(",
"$",
"config",
")",
":",
"ResourceInterface",
"{",
"if",
"(",
"$",
"config",
"instanceof",
"ResourceInterface",
")",
"{",
"return",
"$",
"config",
";",
"}",
"if",
"(",
"$",
"config",
"instanceof",
"ResourceAdapterIn... | Creates a Fractal resource based on the given config.
@param array|ResourceInterface|ResourceAdapterInterface
@return ResourceInterface | [
"Creates",
"a",
"Fractal",
"resource",
"based",
"on",
"the",
"given",
"config",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/Plugin.php#L90-L113 |
craftcms/element-api | src/controllers/DefaultController.php | DefaultController.actionIndex | public function actionIndex(string $pattern): Response
{
/** @var Response $response */
$response = Craft::$app->getResponse();
$jsonOptions = null;
$pretty = false;
$cache = false;
$statusCode = 200;
$statusText = null;
try {
$plugin = Plugin::getInstance();
$config = $plugin->getEndpoint($pattern);
$request = Craft::$app->getRequest();
$siteId = Craft::$app->getSites()->getCurrentSite()->id;
if (is_callable($config)) {
$params = Craft::$app->getUrlManager()->getRouteParams();
$config = $this->_callWithParams($config, $params);
}
if (is_array($config)) {
// Merge in the defaults
$config = array_merge($plugin->getDefaultResourceAdapterConfig(), $config);
}
// Before anything else, check the cache
$cache = ArrayHelper::remove($config, 'cache', false);
if ($cache) {
$cacheKey = 'elementapi:'.$siteId.':'.$request->getPathInfo().':'.$request->getQueryStringWithoutPath();
$cacheService = Craft::$app->getCache();
if (($cachedContent = $cacheService->get($cacheKey)) !== false) {
// Set the JSON headers
(new JsonResponseFormatter())->format($response);
// Set the cached JSON on the response and return
$response->format = Response::FORMAT_RAW;
$response->content = $cachedContent;
return $response;
}
}
// Extract config settings that aren't meant for createResource()
$serializer = ArrayHelper::remove($config, 'serializer');
$jsonOptions = ArrayHelper::remove($config, 'jsonOptions', JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$pretty = ArrayHelper::remove($config, 'pretty', false);
$includes = ArrayHelper::remove($config, 'includes', []);
$excludes = ArrayHelper::remove($config, 'excludes', []);
// Generate all transforms immediately
Craft::$app->getConfig()->getGeneral()->generateTransformsBeforePageLoad = true;
// Get the data resource
try {
$resource = $plugin->createResource($config);
} catch (\Throwable $e) {
throw new NotFoundHttpException($e->getMessage() ?: Craft::t('element-api', 'Resource not found'), 0, $e);
}
// Load Fractal
$fractal = new Manager();
// Serialize the data
if (!$serializer instanceof SerializerAbstract) {
switch ($serializer) {
case 'dataArray':
$serializer = new DataArraySerializer();
break;
case 'jsonApi':
$serializer = new JsonApiSerializer();
break;
case 'jsonFeed':
$serializer = new JsonFeedV1Serializer();
break;
default:
$serializer = new ArraySerializer();
}
}
$fractal->setSerializer($serializer);
// Parse includes/excludes
$fractal->parseIncludes($includes);
$fractal->parseExcludes($excludes);
$data = $fractal->createData($resource);
// Fire a 'beforeSendData' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SEND_DATA)) {
$this->trigger(self::EVENT_BEFORE_SEND_DATA, new DataEvent([
'data' => $data,
]));
}
$data = $data->toArray();
} catch (\Throwable $e) {
$data = [
'error' => [
'code' => $e instanceof HttpException ? $e->statusCode : $e->getCode(),
'message' => $e->getMessage(),
]
];
$statusCode = $e instanceof HttpException ? $e->statusCode : 500;
$statusText = $e->getMessage();
}
// Create a JSON response formatter with custom options
$formatter = new JsonResponseFormatter([
'encodeOptions' => $jsonOptions,
'prettyPrint' => $pretty,
]);
// Manually format the response ahead of time, so we can access and cache the JSON
$response->data = $data;
$formatter->format($response);
$response->data = null;
$response->format = Response::FORMAT_RAW;
// Cache it?
if ($cache) {
if ($cache !== true) {
$expire = ConfigHelper::durationInSeconds($cache);
} else {
$expire = null;
}
/** @noinspection PhpUndefinedVariableInspection */
$cacheService->set($cacheKey, $response->content, $expire);
}
// Don't double-encode the data
$response->format = Response::FORMAT_RAW;
$response->setStatusCode($statusCode, $statusText);
return $response;
} | php | public function actionIndex(string $pattern): Response
{
/** @var Response $response */
$response = Craft::$app->getResponse();
$jsonOptions = null;
$pretty = false;
$cache = false;
$statusCode = 200;
$statusText = null;
try {
$plugin = Plugin::getInstance();
$config = $plugin->getEndpoint($pattern);
$request = Craft::$app->getRequest();
$siteId = Craft::$app->getSites()->getCurrentSite()->id;
if (is_callable($config)) {
$params = Craft::$app->getUrlManager()->getRouteParams();
$config = $this->_callWithParams($config, $params);
}
if (is_array($config)) {
// Merge in the defaults
$config = array_merge($plugin->getDefaultResourceAdapterConfig(), $config);
}
// Before anything else, check the cache
$cache = ArrayHelper::remove($config, 'cache', false);
if ($cache) {
$cacheKey = 'elementapi:'.$siteId.':'.$request->getPathInfo().':'.$request->getQueryStringWithoutPath();
$cacheService = Craft::$app->getCache();
if (($cachedContent = $cacheService->get($cacheKey)) !== false) {
// Set the JSON headers
(new JsonResponseFormatter())->format($response);
// Set the cached JSON on the response and return
$response->format = Response::FORMAT_RAW;
$response->content = $cachedContent;
return $response;
}
}
// Extract config settings that aren't meant for createResource()
$serializer = ArrayHelper::remove($config, 'serializer');
$jsonOptions = ArrayHelper::remove($config, 'jsonOptions', JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$pretty = ArrayHelper::remove($config, 'pretty', false);
$includes = ArrayHelper::remove($config, 'includes', []);
$excludes = ArrayHelper::remove($config, 'excludes', []);
// Generate all transforms immediately
Craft::$app->getConfig()->getGeneral()->generateTransformsBeforePageLoad = true;
// Get the data resource
try {
$resource = $plugin->createResource($config);
} catch (\Throwable $e) {
throw new NotFoundHttpException($e->getMessage() ?: Craft::t('element-api', 'Resource not found'), 0, $e);
}
// Load Fractal
$fractal = new Manager();
// Serialize the data
if (!$serializer instanceof SerializerAbstract) {
switch ($serializer) {
case 'dataArray':
$serializer = new DataArraySerializer();
break;
case 'jsonApi':
$serializer = new JsonApiSerializer();
break;
case 'jsonFeed':
$serializer = new JsonFeedV1Serializer();
break;
default:
$serializer = new ArraySerializer();
}
}
$fractal->setSerializer($serializer);
// Parse includes/excludes
$fractal->parseIncludes($includes);
$fractal->parseExcludes($excludes);
$data = $fractal->createData($resource);
// Fire a 'beforeSendData' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SEND_DATA)) {
$this->trigger(self::EVENT_BEFORE_SEND_DATA, new DataEvent([
'data' => $data,
]));
}
$data = $data->toArray();
} catch (\Throwable $e) {
$data = [
'error' => [
'code' => $e instanceof HttpException ? $e->statusCode : $e->getCode(),
'message' => $e->getMessage(),
]
];
$statusCode = $e instanceof HttpException ? $e->statusCode : 500;
$statusText = $e->getMessage();
}
// Create a JSON response formatter with custom options
$formatter = new JsonResponseFormatter([
'encodeOptions' => $jsonOptions,
'prettyPrint' => $pretty,
]);
// Manually format the response ahead of time, so we can access and cache the JSON
$response->data = $data;
$formatter->format($response);
$response->data = null;
$response->format = Response::FORMAT_RAW;
// Cache it?
if ($cache) {
if ($cache !== true) {
$expire = ConfigHelper::durationInSeconds($cache);
} else {
$expire = null;
}
/** @noinspection PhpUndefinedVariableInspection */
$cacheService->set($cacheKey, $response->content, $expire);
}
// Don't double-encode the data
$response->format = Response::FORMAT_RAW;
$response->setStatusCode($statusCode, $statusText);
return $response;
} | [
"public",
"function",
"actionIndex",
"(",
"string",
"$",
"pattern",
")",
":",
"Response",
"{",
"/** @var Response $response */",
"$",
"response",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getResponse",
"(",
")",
";",
"$",
"jsonOptions",
"=",
"null",
";",
"$",
... | Returns the requested elements as JSON.
@param string $pattern The endpoint URL pattern that was matched
@return Response
@throws InvalidConfigException
@throws NotFoundHttpException | [
"Returns",
"the",
"requested",
"elements",
"as",
"JSON",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/controllers/DefaultController.php#L66-L201 |
craftcms/element-api | src/controllers/DefaultController.php | DefaultController._callWithParams | private function _callWithParams($func, $params)
{
if (empty($params)) {
return $func();
}
$ref = new ReflectionFunction($func);
$args = [];
foreach ($ref->getParameters() as $param) {
$name = $param->getName();
if (isset($params[$name])) {
if ($param->isArray()) {
$args[] = is_array($params[$name]) ? $params[$name] : [$params[$name]];
} else if (!is_array($params[$name])) {
$args[] = $params[$name];
} else {
return false;
}
} else if ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
return false;
}
}
return $ref->invokeArgs($args);
} | php | private function _callWithParams($func, $params)
{
if (empty($params)) {
return $func();
}
$ref = new ReflectionFunction($func);
$args = [];
foreach ($ref->getParameters() as $param) {
$name = $param->getName();
if (isset($params[$name])) {
if ($param->isArray()) {
$args[] = is_array($params[$name]) ? $params[$name] : [$params[$name]];
} else if (!is_array($params[$name])) {
$args[] = $params[$name];
} else {
return false;
}
} else if ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
return false;
}
}
return $ref->invokeArgs($args);
} | [
"private",
"function",
"_callWithParams",
"(",
"$",
"func",
",",
"$",
"params",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"params",
")",
")",
"{",
"return",
"$",
"func",
"(",
")",
";",
"}",
"$",
"ref",
"=",
"new",
"ReflectionFunction",
"(",
"$",
"fun... | Calls a given function. If any params are given, they will be mapped to the function's arguments.
@param callable $func The function to call
@param array $params Any params that should be mapped to function arguments
@return mixed The result of the function | [
"Calls",
"a",
"given",
"function",
".",
"If",
"any",
"params",
"are",
"given",
"they",
"will",
"be",
"mapped",
"to",
"the",
"function",
"s",
"arguments",
"."
] | train | https://github.com/craftcms/element-api/blob/10499abe5d88a8efa66a37b6cf187a435e970120/src/controllers/DefaultController.php#L213-L241 |
willdurand/BazingaJsTranslationBundle | DependencyInjection/BazingaJsTranslationExtension.php | BazingaJsTranslationExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$configuration = new Configuration($container->getParameter('kernel.debug'));
$config = $processor->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$loader->load('controllers.xml');
$container
->getDefinition('bazinga.jstranslation.controller')
->replaceArgument(5, $config['locale_fallback'])
->replaceArgument(6, $config['default_domain'])
->replaceArgument(7, $config['http_cache_time']);
// Add fallback locale to active locales if missing
if ($config['active_locales'] && !in_array($config['locale_fallback'], $config['active_locales'])) {
array_push($config['active_locales'], $config['locale_fallback']);
}
$container
->getDefinition('bazinga.jstranslation.translation_dumper')
->replaceArgument(3, $config['locale_fallback'])
->replaceArgument(4, $config['default_domain'])
->replaceArgument(5, $config['active_locales'])
->replaceArgument(6, $config['active_domains']);
} | php | public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$configuration = new Configuration($container->getParameter('kernel.debug'));
$config = $processor->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$loader->load('controllers.xml');
$container
->getDefinition('bazinga.jstranslation.controller')
->replaceArgument(5, $config['locale_fallback'])
->replaceArgument(6, $config['default_domain'])
->replaceArgument(7, $config['http_cache_time']);
// Add fallback locale to active locales if missing
if ($config['active_locales'] && !in_array($config['locale_fallback'], $config['active_locales'])) {
array_push($config['active_locales'], $config['locale_fallback']);
}
$container
->getDefinition('bazinga.jstranslation.translation_dumper')
->replaceArgument(3, $config['locale_fallback'])
->replaceArgument(4, $config['default_domain'])
->replaceArgument(5, $config['active_locales'])
->replaceArgument(6, $config['active_domains']);
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"processor",
"=",
"new",
"Processor",
"(",
")",
";",
"$",
"configuration",
"=",
"new",
"Configuration",
"(",
"$",
"container",
"->",
"getP... | Load configuration. | [
"Load",
"configuration",
"."
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/DependencyInjection/BazingaJsTranslationExtension.php#L20-L47 |
willdurand/BazingaJsTranslationBundle | Controller/Controller.php | Controller.addLoader | public function addLoader($id, $loader)
{
if (!array_key_exists($id, $this->loaders)) {
$this->loaders[$id] = $loader;
}
} | php | public function addLoader($id, $loader)
{
if (!array_key_exists($id, $this->loaders)) {
$this->loaders[$id] = $loader;
}
} | [
"public",
"function",
"addLoader",
"(",
"$",
"id",
",",
"$",
"loader",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"id",
",",
"$",
"this",
"->",
"loaders",
")",
")",
"{",
"$",
"this",
"->",
"loaders",
"[",
"$",
"id",
"]",
"=",
"$",
... | Add a translation loader if it does not exist.
@param string $id The loader id.
@param LoaderInterface $loader A translation loader. | [
"Add",
"a",
"translation",
"loader",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/Controller/Controller.php#L100-L105 |
willdurand/BazingaJsTranslationBundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$builder = new TreeBuilder();
$builder->root('bazinga_js_translation')
->fixXmlConfig('active_locale')
->fixXmlConfig('active_domain')
->children()
->scalarNode('locale_fallback')->defaultValue('en')->end()
->scalarNode('default_domain')->defaultValue('messages')->end()
->scalarNode('http_cache_time')->defaultValue('86400')->end()
->arrayNode('active_locales')
->prototype('scalar')
->end()
->end()
->arrayNode('active_domains')
->prototype('scalar')
->end()
->end()
->end();
return $builder;
} | php | public function getConfigTreeBuilder()
{
$builder = new TreeBuilder();
$builder->root('bazinga_js_translation')
->fixXmlConfig('active_locale')
->fixXmlConfig('active_domain')
->children()
->scalarNode('locale_fallback')->defaultValue('en')->end()
->scalarNode('default_domain')->defaultValue('messages')->end()
->scalarNode('http_cache_time')->defaultValue('86400')->end()
->arrayNode('active_locales')
->prototype('scalar')
->end()
->end()
->arrayNode('active_domains')
->prototype('scalar')
->end()
->end()
->end();
return $builder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"builder",
"=",
"new",
"TreeBuilder",
"(",
")",
";",
"$",
"builder",
"->",
"root",
"(",
"'bazinga_js_translation'",
")",
"->",
"fixXmlConfig",
"(",
"'active_locale'",
")",
"->",
"fixXmlConfig",
... | Generates the configuration tree builder.
@return TreeBuilder The tree builder | [
"Generates",
"the",
"configuration",
"tree",
"builder",
"."
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/DependencyInjection/Configuration.php#L18-L40 |
willdurand/BazingaJsTranslationBundle | Dumper/TranslationDumper.php | TranslationDumper.dump | public function dump(
$target = 'web/js',
$pattern = self::DEFAULT_TRANSLATION_PATTERN,
array $formats = array(),
\stdClass $merge = null
) {
$availableFormats = array('js', 'json');
$parts = array_filter(explode('/', $pattern));
$this->filesystem->remove($target. '/' . current($parts));
foreach ($formats as $format) {
if (!in_array($format, $availableFormats)) {
throw new \RuntimeException('The ' . $format . ' format is not available. Use only: ' . implode(', ', $availableFormats) . '.');
}
}
if (empty($formats)) {
$formats = $availableFormats;
}
$this->dumpConfig($pattern, $formats, $target);
if ($merge && $merge->domains) {
$this->dumpTranslationsPerLocale($pattern, $formats, $target);
} else {
$this->dumpTranslationsPerDomain($pattern, $formats, $target);
}
} | php | public function dump(
$target = 'web/js',
$pattern = self::DEFAULT_TRANSLATION_PATTERN,
array $formats = array(),
\stdClass $merge = null
) {
$availableFormats = array('js', 'json');
$parts = array_filter(explode('/', $pattern));
$this->filesystem->remove($target. '/' . current($parts));
foreach ($formats as $format) {
if (!in_array($format, $availableFormats)) {
throw new \RuntimeException('The ' . $format . ' format is not available. Use only: ' . implode(', ', $availableFormats) . '.');
}
}
if (empty($formats)) {
$formats = $availableFormats;
}
$this->dumpConfig($pattern, $formats, $target);
if ($merge && $merge->domains) {
$this->dumpTranslationsPerLocale($pattern, $formats, $target);
} else {
$this->dumpTranslationsPerDomain($pattern, $formats, $target);
}
} | [
"public",
"function",
"dump",
"(",
"$",
"target",
"=",
"'web/js'",
",",
"$",
"pattern",
"=",
"self",
"::",
"DEFAULT_TRANSLATION_PATTERN",
",",
"array",
"$",
"formats",
"=",
"array",
"(",
")",
",",
"\\",
"stdClass",
"$",
"merge",
"=",
"null",
")",
"{",
... | Dump all translation files.
@param string $target Target directory.
@param string $pattern route path
@param string[] $formats Formats to generate.
@param \stdClass $merge Merge options. | [
"Dump",
"all",
"translation",
"files",
"."
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/Dumper/TranslationDumper.php#L120-L148 |
willdurand/BazingaJsTranslationBundle | Finder/TranslationFinder.php | TranslationFinder.getTranslationFilesFromConfiguration | private function getTranslationFilesFromConfiguration($domain, $locale)
{
$filteredFilenames = array();
foreach ($this->translationFilesByLocale as $localeFromConfig => $resourceFilePaths) {
foreach ($resourceFilePaths as $filename) {
list($currentDomain, $currentLocale) = explode('.', basename($filename), 3);
if ($currentDomain === $domain && $currentLocale === $locale) {
$filteredFilenames[] = $filename;
}
}
}
return $filteredFilenames;
} | php | private function getTranslationFilesFromConfiguration($domain, $locale)
{
$filteredFilenames = array();
foreach ($this->translationFilesByLocale as $localeFromConfig => $resourceFilePaths) {
foreach ($resourceFilePaths as $filename) {
list($currentDomain, $currentLocale) = explode('.', basename($filename), 3);
if ($currentDomain === $domain && $currentLocale === $locale) {
$filteredFilenames[] = $filename;
}
}
}
return $filteredFilenames;
} | [
"private",
"function",
"getTranslationFilesFromConfiguration",
"(",
"$",
"domain",
",",
"$",
"locale",
")",
"{",
"$",
"filteredFilenames",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"translationFilesByLocale",
"as",
"$",
"localeFromConfig",
... | @param string $domain
@param string $locale
@return array all translation file names loaded from the FrameworkBundle | [
"@param",
"string",
"$domain",
"@param",
"string",
"$locale"
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/Finder/TranslationFinder.php#L76-L90 |
willdurand/BazingaJsTranslationBundle | Command/DumpCommand.php | DumpCommand.configure | protected function configure()
{
$this
->setName('bazinga:js-translation:dump')
->setDefinition(array(
new InputArgument(
'target',
InputArgument::OPTIONAL,
'Override the target directory to dump JS translation files in.'
),
))
->setDescription('Dumps all JS translation files to the filesystem')
->addOption(
'pattern',
null,
InputOption::VALUE_REQUIRED,
'The route pattern: e.g. "/translations/{domain}.{_format}"',
TranslationDumper::DEFAULT_TRANSLATION_PATTERN
)
->addOption(
'format',
null,
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'If set, only the passed formats will be generated',
array()
)
->addOption(
'merge-domains',
null,
InputOption::VALUE_NONE,
'If set, all domains will be merged into a single file per language'
);
} | php | protected function configure()
{
$this
->setName('bazinga:js-translation:dump')
->setDefinition(array(
new InputArgument(
'target',
InputArgument::OPTIONAL,
'Override the target directory to dump JS translation files in.'
),
))
->setDescription('Dumps all JS translation files to the filesystem')
->addOption(
'pattern',
null,
InputOption::VALUE_REQUIRED,
'The route pattern: e.g. "/translations/{domain}.{_format}"',
TranslationDumper::DEFAULT_TRANSLATION_PATTERN
)
->addOption(
'format',
null,
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'If set, only the passed formats will be generated',
array()
)
->addOption(
'merge-domains',
null,
InputOption::VALUE_NONE,
'If set, all domains will be merged into a single file per language'
);
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'bazinga:js-translation:dump'",
")",
"->",
"setDefinition",
"(",
"array",
"(",
"new",
"InputArgument",
"(",
"'target'",
",",
"InputArgument",
"::",
"OPTIONAL",
",",
"'Overri... | {@inheritDoc} | [
"{"
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/Command/DumpCommand.php#L48-L80 |
willdurand/BazingaJsTranslationBundle | Command/DumpCommand.php | DumpCommand.initialize | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
$this->targetPath = $input->getArgument('target') ?: sprintf('%s/../web/js', $this->kernelRootDir);
} | php | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
$this->targetPath = $input->getArgument('target') ?: sprintf('%s/../web/js', $this->kernelRootDir);
} | [
"protected",
"function",
"initialize",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"parent",
"::",
"initialize",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"this",
"->",
"targetPath",
"=",
"$",
"input",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/Command/DumpCommand.php#L85-L90 |
willdurand/BazingaJsTranslationBundle | Command/DumpCommand.php | DumpCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$formats = $input->getOption('format');
$merge = (object) array(
'domains' => $input->getOption('merge-domains')
);
if (!is_dir($dir = dirname($this->targetPath))) {
$output->writeln('<info>[dir+]</info> ' . $dir);
if (false === @mkdir($dir, 0777, true)) {
throw new \RuntimeException('Unable to create directory ' . $dir);
}
}
$output->writeln(sprintf(
'Installing translation files in <comment>%s</comment> directory',
$this->targetPath
));
$this->dumper->dump($this->targetPath, $input->getOption('pattern'), $formats, $merge);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$formats = $input->getOption('format');
$merge = (object) array(
'domains' => $input->getOption('merge-domains')
);
if (!is_dir($dir = dirname($this->targetPath))) {
$output->writeln('<info>[dir+]</info> ' . $dir);
if (false === @mkdir($dir, 0777, true)) {
throw new \RuntimeException('Unable to create directory ' . $dir);
}
}
$output->writeln(sprintf(
'Installing translation files in <comment>%s</comment> directory',
$this->targetPath
));
$this->dumper->dump($this->targetPath, $input->getOption('pattern'), $formats, $merge);
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"formats",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'format'",
")",
";",
"$",
"merge",
"=",
"(",
"object",
")",
"array",
"("... | {@inheritDoc} | [
"{"
] | train | https://github.com/willdurand/BazingaJsTranslationBundle/blob/9c80406dd4cc195f1f835a52e038fb80a96563b2/Command/DumpCommand.php#L95-L115 |
wp-cli/profile-command | inc/class-formatter.php | Formatter.display_items | public function display_items( $items, $include_total = true, $order, $orderby ) {
if ( 'table' === $this->args['format'] && empty( $this->args['field'] ) ) {
$this->show_table( $order, $orderby, $items, $this->args['fields'], $include_total );
} else {
$this->formatter->display_items( $items );
}
} | php | public function display_items( $items, $include_total = true, $order, $orderby ) {
if ( 'table' === $this->args['format'] && empty( $this->args['field'] ) ) {
$this->show_table( $order, $orderby, $items, $this->args['fields'], $include_total );
} else {
$this->formatter->display_items( $items );
}
} | [
"public",
"function",
"display_items",
"(",
"$",
"items",
",",
"$",
"include_total",
"=",
"true",
",",
"$",
"order",
",",
"$",
"orderby",
")",
"{",
"if",
"(",
"'table'",
"===",
"$",
"this",
"->",
"args",
"[",
"'format'",
"]",
"&&",
"empty",
"(",
"$",... | Display multiple items according to the output arguments.
@param array $items | [
"Display",
"multiple",
"items",
"according",
"to",
"the",
"output",
"arguments",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-formatter.php#L45-L51 |
wp-cli/profile-command | inc/class-formatter.php | Formatter.compare_float | private function compare_float( $a, $b ) {
$a = number_format( $a, 4 );
$b = number_format( $b, 4 );
if ( 0 === $a - $b ) {
return 0;
} elseif ( $a - $b < 0 ) {
return -1;
} else {
return 1;
}
} | php | private function compare_float( $a, $b ) {
$a = number_format( $a, 4 );
$b = number_format( $b, 4 );
if ( 0 === $a - $b ) {
return 0;
} elseif ( $a - $b < 0 ) {
return -1;
} else {
return 1;
}
} | [
"private",
"function",
"compare_float",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"$",
"a",
"=",
"number_format",
"(",
"$",
"a",
",",
"4",
")",
";",
"$",
"b",
"=",
"number_format",
"(",
"$",
"b",
",",
"4",
")",
";",
"if",
"(",
"0",
"===",
"$",
... | Function to compare floats.
@param double $a Floating number.
@param double $b Floating number. | [
"Function",
"to",
"compare",
"floats",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-formatter.php#L59-L69 |
wp-cli/profile-command | inc/class-formatter.php | Formatter.show_table | private function show_table( $order, $orderby, $items, $fields, $include_total ) {
$table = new \cli\Table();
$enabled = \cli\Colors::shouldColorize();
if ( $enabled ) {
\cli\Colors::disable( true );
}
$table->setHeaders( $fields );
$totals = array_fill( 0, count( $fields ), null );
if ( ! is_null( $this->total_cell_index ) ) {
$totals[ $this->total_cell_index ] = 'total (' . count( $items ) . ')';
}
if ( $orderby ) {
usort(
$items,
function( $a, $b ) use ( $order, $orderby ) {
list( $first, $second ) = 'ASC' === $order ? array( $a, $b ) : array( $b, $a );
if ( is_numeric( $first->$orderby ) && is_numeric( $second->$orderby ) ) {
return $this->compare_float( $first->$orderby, $second->$orderby );
}
return strcmp( $first->$orderby, $second->$orderby );
}
);
}
$location_index = array_search( 'location', $fields );
foreach ( $items as $item ) {
$values = array_values( \WP_CLI\Utils\pick_fields( $item, $fields ) );
foreach ( $values as $i => $value ) {
if ( ! is_null( $this->total_cell_index ) && $this->total_cell_index === $i ) {
continue;
}
// Ignore 'location' for hook profiling
if ( false !== $location_index && $location_index === $i ) {
continue;
}
if ( null === $totals[ $i ] ) {
if ( stripos( $fields[ $i ], '_ratio' ) ) {
$totals[ $i ] = array();
} else {
$totals[ $i ] = 0;
}
}
if ( stripos( $fields[ $i ], '_ratio' ) ) {
if ( ! is_null( $value ) ) {
$totals[ $i ][] = $value;
}
} else {
$totals[ $i ] += $value;
}
if ( stripos( $fields[ $i ], '_time' ) || 'time' === $fields[ $i ] ) {
$values[ $i ] = round( $value, 4 ) . 's';
}
}
$table->addRow( $values );
}
if ( $include_total ) {
foreach ( $totals as $i => $value ) {
if ( null === $value ) {
continue;
}
if ( stripos( $fields[ $i ], '_time' ) || 'time' === $fields[ $i ] ) {
$totals[ $i ] = round( $value, 4 ) . 's';
}
if ( is_array( $value ) ) {
if ( ! empty( $value ) ) {
$totals[ $i ] = round( ( array_sum( $value ) / count( $value ) ), 2 ) . '%';
} else {
$totals[ $i ] = null;
}
}
}
$table->setFooters( $totals );
}
foreach ( $table->getDisplayLines() as $line ) {
\WP_CLI::line( $line );
}
if ( $enabled ) {
\cli\Colors::enable( true );
}
} | php | private function show_table( $order, $orderby, $items, $fields, $include_total ) {
$table = new \cli\Table();
$enabled = \cli\Colors::shouldColorize();
if ( $enabled ) {
\cli\Colors::disable( true );
}
$table->setHeaders( $fields );
$totals = array_fill( 0, count( $fields ), null );
if ( ! is_null( $this->total_cell_index ) ) {
$totals[ $this->total_cell_index ] = 'total (' . count( $items ) . ')';
}
if ( $orderby ) {
usort(
$items,
function( $a, $b ) use ( $order, $orderby ) {
list( $first, $second ) = 'ASC' === $order ? array( $a, $b ) : array( $b, $a );
if ( is_numeric( $first->$orderby ) && is_numeric( $second->$orderby ) ) {
return $this->compare_float( $first->$orderby, $second->$orderby );
}
return strcmp( $first->$orderby, $second->$orderby );
}
);
}
$location_index = array_search( 'location', $fields );
foreach ( $items as $item ) {
$values = array_values( \WP_CLI\Utils\pick_fields( $item, $fields ) );
foreach ( $values as $i => $value ) {
if ( ! is_null( $this->total_cell_index ) && $this->total_cell_index === $i ) {
continue;
}
// Ignore 'location' for hook profiling
if ( false !== $location_index && $location_index === $i ) {
continue;
}
if ( null === $totals[ $i ] ) {
if ( stripos( $fields[ $i ], '_ratio' ) ) {
$totals[ $i ] = array();
} else {
$totals[ $i ] = 0;
}
}
if ( stripos( $fields[ $i ], '_ratio' ) ) {
if ( ! is_null( $value ) ) {
$totals[ $i ][] = $value;
}
} else {
$totals[ $i ] += $value;
}
if ( stripos( $fields[ $i ], '_time' ) || 'time' === $fields[ $i ] ) {
$values[ $i ] = round( $value, 4 ) . 's';
}
}
$table->addRow( $values );
}
if ( $include_total ) {
foreach ( $totals as $i => $value ) {
if ( null === $value ) {
continue;
}
if ( stripos( $fields[ $i ], '_time' ) || 'time' === $fields[ $i ] ) {
$totals[ $i ] = round( $value, 4 ) . 's';
}
if ( is_array( $value ) ) {
if ( ! empty( $value ) ) {
$totals[ $i ] = round( ( array_sum( $value ) / count( $value ) ), 2 ) . '%';
} else {
$totals[ $i ] = null;
}
}
}
$table->setFooters( $totals );
}
foreach ( $table->getDisplayLines() as $line ) {
\WP_CLI::line( $line );
}
if ( $enabled ) {
\cli\Colors::enable( true );
}
} | [
"private",
"function",
"show_table",
"(",
"$",
"order",
",",
"$",
"orderby",
",",
"$",
"items",
",",
"$",
"fields",
",",
"$",
"include_total",
")",
"{",
"$",
"table",
"=",
"new",
"\\",
"cli",
"\\",
"Table",
"(",
")",
";",
"$",
"enabled",
"=",
"\\",... | Show items in a \cli\Table.
@param array $items
@param array $fields | [
"Show",
"items",
"in",
"a",
"\\",
"cli",
"\\",
"Table",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-formatter.php#L77-L166 |
wp-cli/profile-command | inc/class-logger.php | Logger.start | public function start() {
global $wpdb, $wp_object_cache;
$this->start_time = microtime( true );
$this->query_offset = ! empty( $wpdb->queries ) ? count( $wpdb->queries ) : 0;
if ( false === ( $key = array_search( $this, self::$active_loggers ) ) ) {
self::$active_loggers[] = $this;
}
$this->cache_hit_offset = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$this->cache_miss_offset = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
} | php | public function start() {
global $wpdb, $wp_object_cache;
$this->start_time = microtime( true );
$this->query_offset = ! empty( $wpdb->queries ) ? count( $wpdb->queries ) : 0;
if ( false === ( $key = array_search( $this, self::$active_loggers ) ) ) {
self::$active_loggers[] = $this;
}
$this->cache_hit_offset = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$this->cache_miss_offset = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
} | [
"public",
"function",
"start",
"(",
")",
"{",
"global",
"$",
"wpdb",
",",
"$",
"wp_object_cache",
";",
"$",
"this",
"->",
"start_time",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"this",
"->",
"query_offset",
"=",
"!",
"empty",
"(",
"$",
"wpdb",
"... | Start this logger | [
"Start",
"this",
"logger"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-logger.php#L37-L46 |
wp-cli/profile-command | inc/class-logger.php | Logger.stop | public function stop() {
global $wpdb, $wp_object_cache;
if ( ! is_null( $this->start_time ) ) {
$this->time += microtime( true ) - $this->start_time;
}
if ( ! is_null( $this->query_offset ) && isset( $wpdb ) && ! empty( $wpdb->queries ) ) {
for ( $i = $this->query_offset; $i < count( $wpdb->queries ); $i++ ) {
$this->query_time += $wpdb->queries[ $i ][1];
$this->query_count++;
}
}
if ( ! is_null( $this->cache_hit_offset ) && ! is_null( $this->cache_miss_offset ) && isset( $wp_object_cache ) ) {
$cache_hits = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$cache_misses = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
$this->cache_hits = $cache_hits - $this->cache_hit_offset;
$this->cache_misses = $cache_misses - $this->cache_miss_offset;
$cache_total = $this->cache_hits + $this->cache_misses;
if ( $cache_total ) {
$ratio = ( $this->cache_hits / $cache_total ) * 100;
$this->cache_ratio = round( $ratio, 2 ) . '%';
}
}
$this->start_time = null;
$this->query_offset = null;
$this->cache_hit_offset = null;
$this->cache_miss_offset = null;
if ( false !== ( $key = array_search( $this, self::$active_loggers ) ) ) {
unset( self::$active_loggers[ $key ] );
}
} | php | public function stop() {
global $wpdb, $wp_object_cache;
if ( ! is_null( $this->start_time ) ) {
$this->time += microtime( true ) - $this->start_time;
}
if ( ! is_null( $this->query_offset ) && isset( $wpdb ) && ! empty( $wpdb->queries ) ) {
for ( $i = $this->query_offset; $i < count( $wpdb->queries ); $i++ ) {
$this->query_time += $wpdb->queries[ $i ][1];
$this->query_count++;
}
}
if ( ! is_null( $this->cache_hit_offset ) && ! is_null( $this->cache_miss_offset ) && isset( $wp_object_cache ) ) {
$cache_hits = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$cache_misses = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
$this->cache_hits = $cache_hits - $this->cache_hit_offset;
$this->cache_misses = $cache_misses - $this->cache_miss_offset;
$cache_total = $this->cache_hits + $this->cache_misses;
if ( $cache_total ) {
$ratio = ( $this->cache_hits / $cache_total ) * 100;
$this->cache_ratio = round( $ratio, 2 ) . '%';
}
}
$this->start_time = null;
$this->query_offset = null;
$this->cache_hit_offset = null;
$this->cache_miss_offset = null;
if ( false !== ( $key = array_search( $this, self::$active_loggers ) ) ) {
unset( self::$active_loggers[ $key ] );
}
} | [
"public",
"function",
"stop",
"(",
")",
"{",
"global",
"$",
"wpdb",
",",
"$",
"wp_object_cache",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"start_time",
")",
")",
"{",
"$",
"this",
"->",
"time",
"+=",
"microtime",
"(",
"true",
")",
"-... | Stop this logger | [
"Stop",
"this",
"logger"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-logger.php#L58-L90 |
wp-cli/profile-command | inc/class-logger.php | Logger.start_hook_timer | public function start_hook_timer() {
$this->hook_count++;
// Timer already running means a subhook has been called
if ( ! is_null( $this->hook_start_time ) ) {
$this->hook_depth++;
} else {
$this->hook_start_time = microtime( true );
}
} | php | public function start_hook_timer() {
$this->hook_count++;
// Timer already running means a subhook has been called
if ( ! is_null( $this->hook_start_time ) ) {
$this->hook_depth++;
} else {
$this->hook_start_time = microtime( true );
}
} | [
"public",
"function",
"start_hook_timer",
"(",
")",
"{",
"$",
"this",
"->",
"hook_count",
"++",
";",
"// Timer already running means a subhook has been called",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"hook_start_time",
")",
")",
"{",
"$",
"this",
"->... | Start this logger's hook timer | [
"Start",
"this",
"logger",
"s",
"hook",
"timer"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-logger.php#L95-L103 |
wp-cli/profile-command | inc/class-logger.php | Logger.stop_hook_timer | public function stop_hook_timer() {
if ( $this->hook_depth ) {
$this->hook_depth--;
} else {
if ( ! is_null( $this->hook_start_time ) ) {
$this->hook_time += microtime( true ) - $this->hook_start_time;
}
$this->hook_start_time = null;
}
} | php | public function stop_hook_timer() {
if ( $this->hook_depth ) {
$this->hook_depth--;
} else {
if ( ! is_null( $this->hook_start_time ) ) {
$this->hook_time += microtime( true ) - $this->hook_start_time;
}
$this->hook_start_time = null;
}
} | [
"public",
"function",
"stop_hook_timer",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hook_depth",
")",
"{",
"$",
"this",
"->",
"hook_depth",
"--",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"hook_start_time",
")",
")"... | Stop this logger's hook timer | [
"Stop",
"this",
"logger",
"s",
"hook",
"timer"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-logger.php#L108-L117 |
wp-cli/profile-command | inc/class-logger.php | Logger.stop_request_timer | public function stop_request_timer() {
if ( ! is_null( $this->request_start_time ) ) {
$this->request_time += microtime( true ) - $this->request_start_time;
}
$this->request_start_time = null;
} | php | public function stop_request_timer() {
if ( ! is_null( $this->request_start_time ) ) {
$this->request_time += microtime( true ) - $this->request_start_time;
}
$this->request_start_time = null;
} | [
"public",
"function",
"stop_request_timer",
"(",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"request_start_time",
")",
")",
"{",
"$",
"this",
"->",
"request_time",
"+=",
"microtime",
"(",
"true",
")",
"-",
"$",
"this",
"->",
"request_st... | Stop this logger's request timer | [
"Stop",
"this",
"logger",
"s",
"request",
"timer"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-logger.php#L130-L135 |
wp-cli/profile-command | inc/class-command.php | Command.stage | public function stage( $args, $assoc_args ) {
global $wpdb;
$focus = Utils\get_flag_value( $assoc_args, 'all', isset( $args[0] ) ? $args[0] : null );
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
$valid_stages = array( 'bootstrap', 'main_query', 'template' );
if ( $focus && ( true !== $focus && ! in_array( $focus, $valid_stages, true ) ) ) {
WP_CLI::error( 'Invalid stage. Must be one of ' . implode( ', ', $valid_stages ) . ', or use --all.' );
}
$profiler = new Profiler( 'stage', $focus );
$profiler->run();
if ( $focus ) {
$base = array(
'hook',
'callback_count',
);
$metrics = array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'request_time',
'request_count',
);
} else {
$base = array(
'stage',
);
$metrics = array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'hook_time',
'hook_count',
'request_time',
'request_count',
);
}
$fields = array_merge( $base, $metrics );
$formatter = new Formatter( $assoc_args, $fields );
$loggers = $profiler->get_loggers();
if ( Utils\get_flag_value( $assoc_args, 'spotlight' ) ) {
$loggers = self::shine_spotlight( $loggers, $metrics );
}
$formatter->display_items( $loggers, true, $order, $orderby );
} | php | public function stage( $args, $assoc_args ) {
global $wpdb;
$focus = Utils\get_flag_value( $assoc_args, 'all', isset( $args[0] ) ? $args[0] : null );
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
$valid_stages = array( 'bootstrap', 'main_query', 'template' );
if ( $focus && ( true !== $focus && ! in_array( $focus, $valid_stages, true ) ) ) {
WP_CLI::error( 'Invalid stage. Must be one of ' . implode( ', ', $valid_stages ) . ', or use --all.' );
}
$profiler = new Profiler( 'stage', $focus );
$profiler->run();
if ( $focus ) {
$base = array(
'hook',
'callback_count',
);
$metrics = array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'request_time',
'request_count',
);
} else {
$base = array(
'stage',
);
$metrics = array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'hook_time',
'hook_count',
'request_time',
'request_count',
);
}
$fields = array_merge( $base, $metrics );
$formatter = new Formatter( $assoc_args, $fields );
$loggers = $profiler->get_loggers();
if ( Utils\get_flag_value( $assoc_args, 'spotlight' ) ) {
$loggers = self::shine_spotlight( $loggers, $metrics );
}
$formatter->display_items( $loggers, true, $order, $orderby );
} | [
"public",
"function",
"stage",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"global",
"$",
"wpdb",
";",
"$",
"focus",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'all'",
",",
"isset",
"(",
"$",
"args",
"[",
"0",
"]",
... | Profile each stage of the WordPress load process (bootstrap, main_query, template).
When WordPress handles a request from a browser, it’s essentially
executing as one long PHP script. `wp profile stage` breaks the script
into three stages:
* **bootstrap** is where WordPress is setting itself up, loading plugins
and the main theme, and firing the `init` hook.
* **main_query** is how WordPress transforms the request (e.g. `/2016/10/21/moms-birthday/`)
into the primary WP_Query.
* **template** is where WordPress determines which theme template to
render based on the main query, and renders it.
```
# `wp profile stage` gives an overview of each stage.
$ wp profile stage --fields=stage,time,cache_ratio
+------------+---------+-------------+
| stage | time | cache_ratio |
+------------+---------+-------------+
| bootstrap | 0.7994s | 93.21% |
| main_query | 0.0123s | 94.29% |
| template | 0.792s | 91.23% |
+------------+---------+-------------+
| total (3) | 1.6037s | 92.91% |
+------------+---------+-------------+
# Then, dive into hooks for each stage with `wp profile stage <stage>`
$ wp profile stage bootstrap --fields=hook,time,cache_ratio --spotlight
+--------------------------+---------+-------------+
| hook | time | cache_ratio |
+--------------------------+---------+-------------+
| muplugins_loaded:before | 0.2335s | 40% |
| muplugins_loaded | 0.0007s | 50% |
| plugins_loaded:before | 0.2792s | 77.63% |
| plugins_loaded | 0.1502s | 100% |
| after_setup_theme:before | 0.068s | 100% |
| init | 0.2643s | 96.88% |
| wp_loaded:after | 0.0377s | |
+--------------------------+---------+-------------+
| total (7) | 1.0335s | 77.42% |
+--------------------------+---------+-------------+
```
## OPTIONS
[<stage>]
: Drill down into a specific stage.
[--all]
: Expand upon all stages.
[--spotlight]
: Filter out logs with zero-ish values from the set.
[--url=<url>]
: Execute a request against a specified URL. Defaults to the home URL.
[--fields=<fields>]
: Limit the output to specific fields. Default is all fields.
[--format=<format>]
: Render output in a particular format.
---
default: table
options:
- table
- json
- yaml
- csv
---
[--order=<order>]
: Ascending or Descending order.
---
default: ASC
options:
- ASC
- DESC
---
[--orderby=<orderby>]
: Order by fields.
@when before_wp_load | [
"Profile",
"each",
"stage",
"of",
"the",
"WordPress",
"load",
"process",
"(",
"bootstrap",
"main_query",
"template",
")",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-command.php#L96-L152 |
wp-cli/profile-command | inc/class-command.php | Command.hook | public function hook( $args, $assoc_args ) {
$focus = Utils\get_flag_value( $assoc_args, 'all', isset( $args[0] ) ? $args[0] : null );
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
$profiler = new Profiler( 'hook', $focus );
$profiler->run();
// 'shutdown' won't actually fire until script completion
// but we can mock it
if ( 'shutdown' === $focus ) {
do_action( 'shutdown' );
remove_all_actions( 'shutdown' );
}
if ( $focus ) {
$base = array( 'callback', 'location' );
} else {
$base = array( 'hook', 'callback_count' );
}
$metrics = array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'request_time',
'request_count',
);
$fields = array_merge( $base, $metrics );
$formatter = new Formatter( $assoc_args, $fields );
$loggers = $profiler->get_loggers();
if ( Utils\get_flag_value( $assoc_args, 'spotlight' ) ) {
$loggers = self::shine_spotlight( $loggers, $metrics );
}
$formatter->display_items( $loggers, true, $order, $orderby );
} | php | public function hook( $args, $assoc_args ) {
$focus = Utils\get_flag_value( $assoc_args, 'all', isset( $args[0] ) ? $args[0] : null );
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
$profiler = new Profiler( 'hook', $focus );
$profiler->run();
// 'shutdown' won't actually fire until script completion
// but we can mock it
if ( 'shutdown' === $focus ) {
do_action( 'shutdown' );
remove_all_actions( 'shutdown' );
}
if ( $focus ) {
$base = array( 'callback', 'location' );
} else {
$base = array( 'hook', 'callback_count' );
}
$metrics = array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'request_time',
'request_count',
);
$fields = array_merge( $base, $metrics );
$formatter = new Formatter( $assoc_args, $fields );
$loggers = $profiler->get_loggers();
if ( Utils\get_flag_value( $assoc_args, 'spotlight' ) ) {
$loggers = self::shine_spotlight( $loggers, $metrics );
}
$formatter->display_items( $loggers, true, $order, $orderby );
} | [
"public",
"function",
"hook",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"focus",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'all'",
",",
"isset",
"(",
"$",
"args",
"[",
"0",
"]",
")",
"?",
"$",
"args",
"[",
... | Profile key metrics for WordPress hooks (actions and filters).
In order to profile callbacks on a specific hook, the action or filter
will need to execute during the course of the request.
## OPTIONS
[<hook>]
: Drill into key metrics of callbacks on a specific WordPress hook.
[--all]
: Profile callbacks for all WordPress hooks.
[--spotlight]
: Filter out logs with zero-ish values from the set.
[--url=<url>]
: Execute a request against a specified URL. Defaults to the home URL.
[--fields=<fields>]
: Display one or more fields.
[--format=<format>]
: Render output in a particular format.
---
default: table
options:
- table
- json
- yaml
- csv
---
[--order=<order>]
: Ascending or Descending order.
---
default: ASC
options:
- ASC
- DESC
---
[--orderby=<orderby>]
: Order by fields.
@when before_wp_load | [
"Profile",
"key",
"metrics",
"for",
"WordPress",
"hooks",
"(",
"actions",
"and",
"filters",
")",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-command.php#L202-L241 |
wp-cli/profile-command | inc/class-command.php | Command.eval_ | public function eval_( $args, $assoc_args ) {
$statement = $args[0];
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
self::profile_eval_ish(
$assoc_args,
function() use ( $statement ) {
eval( $statement ); // phpcs:ignore Squiz.PHP.Eval.Discouraged -- no other way oround here
},
$order,
$orderby
);
} | php | public function eval_( $args, $assoc_args ) {
$statement = $args[0];
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
self::profile_eval_ish(
$assoc_args,
function() use ( $statement ) {
eval( $statement ); // phpcs:ignore Squiz.PHP.Eval.Discouraged -- no other way oround here
},
$order,
$orderby
);
} | [
"public",
"function",
"eval_",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"statement",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"order",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'order'",
",",
"'ASC'",
")",
... | Profile arbitrary code execution.
Code execution happens after WordPress has loaded entirely, which means
you can use any utilities defined in WordPress, active plugins, or the
current theme.
## OPTIONS
<php-code>
: The code to execute, as a string.
[--hook[=<hook>]]
: Focus on key metrics for all hooks, or callbacks on a specific hook.
[--fields=<fields>]
: Display one or more fields.
[--format=<format>]
: Render output in a particular format.
---
default: table
options:
- table
- json
- yaml
- csv
---
[--order=<order>]
: Ascending or Descending order.
---
default: ASC
options:
- ASC
- DESC
---
[--orderby=<orderby>]
: Order by fields.
@subcommand eval | [
"Profile",
"arbitrary",
"code",
"execution",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-command.php#L286-L300 |
wp-cli/profile-command | inc/class-command.php | Command.eval_file | public function eval_file( $args, $assoc_args ) {
$file = $args[0];
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
if ( ! file_exists( $file ) ) {
WP_CLI::error( "'$file' does not exist." );
}
self::profile_eval_ish(
$assoc_args,
function() use ( $file ) {
self::include_file( $file );
},
$order,
$orderby
);
} | php | public function eval_file( $args, $assoc_args ) {
$file = $args[0];
$order = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$orderby = Utils\get_flag_value( $assoc_args, 'orderby', null );
if ( ! file_exists( $file ) ) {
WP_CLI::error( "'$file' does not exist." );
}
self::profile_eval_ish(
$assoc_args,
function() use ( $file ) {
self::include_file( $file );
},
$order,
$orderby
);
} | [
"public",
"function",
"eval_file",
"(",
"$",
"args",
",",
"$",
"assoc_args",
")",
"{",
"$",
"file",
"=",
"$",
"args",
"[",
"0",
"]",
";",
"$",
"order",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args",
",",
"'order'",
",",
"'ASC'",
")",
... | Profile execution of an arbitrary file.
File execution happens after WordPress has loaded entirely, which means
you can use any utilities defined in WordPress, active plugins, or the
current theme.
## OPTIONS
<file>
: The path to the PHP file to execute and profile.
[--hook[=<hook>]]
: Focus on key metrics for all hooks, or callbacks on a specific hook.
[--fields=<fields>]
: Display one or more fields.
[--format=<format>]
: Render output in a particular format.
---
default: table
options:
- table
- json
- yaml
- csv
---
[--order=<order>]
: Ascending or Descending order.
---
default: ASC
options:
- ASC
- DESC
---
[--orderby=<orderby>]
: Order by fields.
@subcommand eval-file | [
"Profile",
"execution",
"of",
"an",
"arbitrary",
"file",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-command.php#L345-L364 |
wp-cli/profile-command | inc/class-command.php | Command.profile_eval_ish | private static function profile_eval_ish( $assoc_args, $profile_callback, $order = 'ASC', $orderby = null ) {
$hook = Utils\get_flag_value( $assoc_args, 'hook' );
$type = $focus = false;
$fields = array();
if ( $hook ) {
$type = 'hook';
if ( true !== $hook ) {
$focus = $hook;
$fields[] = 'callback';
$fields[] = 'location';
} else {
$fields[] = 'hook';
}
}
$profiler = new Profiler( $type, $focus );
$profiler->run();
if ( $hook ) {
$profile_callback();
$loggers = $profiler->get_loggers();
} else {
$logger = new Logger();
$logger->start();
$profile_callback();
$logger->stop();
$loggers = array( $logger );
}
$fields = array_merge(
$fields,
array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'request_time',
'request_count',
)
);
$formatter = new Formatter( $assoc_args, $fields );
$formatter->display_items( $loggers, false, $order, $orderby );
} | php | private static function profile_eval_ish( $assoc_args, $profile_callback, $order = 'ASC', $orderby = null ) {
$hook = Utils\get_flag_value( $assoc_args, 'hook' );
$type = $focus = false;
$fields = array();
if ( $hook ) {
$type = 'hook';
if ( true !== $hook ) {
$focus = $hook;
$fields[] = 'callback';
$fields[] = 'location';
} else {
$fields[] = 'hook';
}
}
$profiler = new Profiler( $type, $focus );
$profiler->run();
if ( $hook ) {
$profile_callback();
$loggers = $profiler->get_loggers();
} else {
$logger = new Logger();
$logger->start();
$profile_callback();
$logger->stop();
$loggers = array( $logger );
}
$fields = array_merge(
$fields,
array(
'time',
'query_time',
'query_count',
'cache_ratio',
'cache_hits',
'cache_misses',
'request_time',
'request_count',
)
);
$formatter = new Formatter( $assoc_args, $fields );
$formatter->display_items( $loggers, false, $order, $orderby );
} | [
"private",
"static",
"function",
"profile_eval_ish",
"(",
"$",
"assoc_args",
",",
"$",
"profile_callback",
",",
"$",
"order",
"=",
"'ASC'",
",",
"$",
"orderby",
"=",
"null",
")",
"{",
"$",
"hook",
"=",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"assoc_args... | Profile an eval or eval-file statement. | [
"Profile",
"an",
"eval",
"or",
"eval",
"-",
"file",
"statement",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-command.php#L369-L410 |
wp-cli/profile-command | inc/class-command.php | Command.shine_spotlight | private static function shine_spotlight( $loggers, $metrics ) {
foreach ( $loggers as $k => $logger ) {
$non_zero = false;
foreach ( $metrics as $metric ) {
switch ( $metric ) {
// 100% cache ratio is fine by us
case 'cache_ratio':
case 'cache_hits':
case 'cache_misses':
if ( $logger->cache_ratio && '100%' !== $logger->cache_ratio ) {
$non_zero = true;
}
break;
case 'time':
case 'query_time':
if ( $logger->$metric > 0.01 ) {
$non_zero = true;
}
break;
default:
if ( $logger->$metric ) {
$non_zero = true;
}
break;
}
}
if ( ! $non_zero ) {
unset( $loggers[ $k ] );
}
}
return $loggers;
} | php | private static function shine_spotlight( $loggers, $metrics ) {
foreach ( $loggers as $k => $logger ) {
$non_zero = false;
foreach ( $metrics as $metric ) {
switch ( $metric ) {
// 100% cache ratio is fine by us
case 'cache_ratio':
case 'cache_hits':
case 'cache_misses':
if ( $logger->cache_ratio && '100%' !== $logger->cache_ratio ) {
$non_zero = true;
}
break;
case 'time':
case 'query_time':
if ( $logger->$metric > 0.01 ) {
$non_zero = true;
}
break;
default:
if ( $logger->$metric ) {
$non_zero = true;
}
break;
}
}
if ( ! $non_zero ) {
unset( $loggers[ $k ] );
}
}
return $loggers;
} | [
"private",
"static",
"function",
"shine_spotlight",
"(",
"$",
"loggers",
",",
"$",
"metrics",
")",
"{",
"foreach",
"(",
"$",
"loggers",
"as",
"$",
"k",
"=>",
"$",
"logger",
")",
"{",
"$",
"non_zero",
"=",
"false",
";",
"foreach",
"(",
"$",
"metrics",
... | Filter loggers with zero-ish values.
@param array $loggers
@param array $metrics
@return array | [
"Filter",
"loggers",
"with",
"zero",
"-",
"ish",
"values",
"."
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-command.php#L428-L461 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.run | public function run() {
WP_CLI::add_wp_hook(
'muplugins_loaded',
function() {
if ( $url = WP_CLI::get_runner()->config['url'] ) {
WP_CLI::set_url( trailingslashit( $url ) );
} else {
WP_CLI::set_url( home_url( '/' ) );
}
}
);
WP_CLI::add_hook(
'after_wp_config_load',
function() {
if ( defined( 'SAVEQUERIES' ) && ! SAVEQUERIES ) {
WP_CLI::error( "'SAVEQUERIES' is defined as false, and must be true. Please check your wp-config.php" );
}
if ( ! defined( 'SAVEQUERIES' ) ) {
define( 'SAVEQUERIES', true );
}
}
);
if ( 'hook' === $this->type
&& ':before' === substr( $this->focus, -7, 7 ) ) {
$stage_hooks = array();
foreach ( $this->stage_hooks as $hooks ) {
$stage_hooks = array_merge( $stage_hooks, $hooks );
}
$end_hook = substr( $this->focus, 0, -7 );
$key = array_search( $end_hook, $stage_hooks );
if ( isset( $stage_hooks[ $key - 1 ] ) ) {
$start_hook = $stage_hooks[ $key - 1 ];
WP_CLI::add_wp_hook( $start_hook, array( $this, 'wp_tick_profile_begin' ), 9999 );
} else {
WP_CLI::add_hook( 'after_wp_config_load', array( $this, 'wp_tick_profile_begin' ) );
}
WP_CLI::add_wp_hook( $end_hook, array( $this, 'wp_tick_profile_end' ), -9999 );
} elseif ( 'hook' === $this->type
&& ':after' === substr( $this->focus, -6, 6 ) ) {
$start_hook = substr( $this->focus, 0, -6 );
WP_CLI::add_wp_hook( $start_hook, array( $this, 'wp_tick_profile_begin' ), 9999 );
} else {
WP_CLI::add_wp_hook( 'all', array( $this, 'wp_hook_begin' ) );
}
WP_CLI::add_wp_hook( 'pre_http_request', array( $this, 'wp_request_begin' ) );
WP_CLI::add_wp_hook( 'http_api_debug', array( $this, 'wp_request_end' ) );
$this->load_wordpress_with_template();
} | php | public function run() {
WP_CLI::add_wp_hook(
'muplugins_loaded',
function() {
if ( $url = WP_CLI::get_runner()->config['url'] ) {
WP_CLI::set_url( trailingslashit( $url ) );
} else {
WP_CLI::set_url( home_url( '/' ) );
}
}
);
WP_CLI::add_hook(
'after_wp_config_load',
function() {
if ( defined( 'SAVEQUERIES' ) && ! SAVEQUERIES ) {
WP_CLI::error( "'SAVEQUERIES' is defined as false, and must be true. Please check your wp-config.php" );
}
if ( ! defined( 'SAVEQUERIES' ) ) {
define( 'SAVEQUERIES', true );
}
}
);
if ( 'hook' === $this->type
&& ':before' === substr( $this->focus, -7, 7 ) ) {
$stage_hooks = array();
foreach ( $this->stage_hooks as $hooks ) {
$stage_hooks = array_merge( $stage_hooks, $hooks );
}
$end_hook = substr( $this->focus, 0, -7 );
$key = array_search( $end_hook, $stage_hooks );
if ( isset( $stage_hooks[ $key - 1 ] ) ) {
$start_hook = $stage_hooks[ $key - 1 ];
WP_CLI::add_wp_hook( $start_hook, array( $this, 'wp_tick_profile_begin' ), 9999 );
} else {
WP_CLI::add_hook( 'after_wp_config_load', array( $this, 'wp_tick_profile_begin' ) );
}
WP_CLI::add_wp_hook( $end_hook, array( $this, 'wp_tick_profile_end' ), -9999 );
} elseif ( 'hook' === $this->type
&& ':after' === substr( $this->focus, -6, 6 ) ) {
$start_hook = substr( $this->focus, 0, -6 );
WP_CLI::add_wp_hook( $start_hook, array( $this, 'wp_tick_profile_begin' ), 9999 );
} else {
WP_CLI::add_wp_hook( 'all', array( $this, 'wp_hook_begin' ) );
}
WP_CLI::add_wp_hook( 'pre_http_request', array( $this, 'wp_request_begin' ) );
WP_CLI::add_wp_hook( 'http_api_debug', array( $this, 'wp_request_end' ) );
$this->load_wordpress_with_template();
} | [
"public",
"function",
"run",
"(",
")",
"{",
"WP_CLI",
"::",
"add_wp_hook",
"(",
"'muplugins_loaded'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"$",
"url",
"=",
"WP_CLI",
"::",
"get_runner",
"(",
")",
"->",
"config",
"[",
"'url'",
"]",
")",
"{",
"WP... | Run the profiler against WordPress | [
"Run",
"the",
"profiler",
"against",
"WordPress"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L77-L124 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.wp_tick_profile_begin | public function wp_tick_profile_begin( $value = null ) {
if ( version_compare( PHP_VERSION, '7.0.0' ) >= 0 ) {
WP_CLI::error( 'Profiling intermediate hooks is broken in PHP 7, see https://bugs.php.net/bug.php?id=72966' );
}
// Disable opcode optimizers. These "optimize" calls out of the stack
// and hide calls from the tick handler and backtraces.
// Copied from P3 Profiler
if ( extension_loaded( 'xcache' ) ) {
@ini_set( 'xcache.optimizer', false ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
} elseif ( extension_loaded( 'apc' ) ) {
@ini_set( 'apc.optimization', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
apc_clear_cache();
} elseif ( extension_loaded( 'eaccelerator' ) ) {
@ini_set( 'eaccelerator.optimizer', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
if ( function_exists( 'eaccelerator_optimizer' ) ) {
@eaccelerator_optimizer( false ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- disabling eaccelerator on runtime can faild
}
} elseif ( extension_loaded( 'Zend Optimizer+' ) ) {
@ini_set( 'zend_optimizerplus.optimization_level', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
}
register_tick_function( array( $this, 'handle_function_tick' ) );
declare( ticks = 1 );
return $value;
} | php | public function wp_tick_profile_begin( $value = null ) {
if ( version_compare( PHP_VERSION, '7.0.0' ) >= 0 ) {
WP_CLI::error( 'Profiling intermediate hooks is broken in PHP 7, see https://bugs.php.net/bug.php?id=72966' );
}
// Disable opcode optimizers. These "optimize" calls out of the stack
// and hide calls from the tick handler and backtraces.
// Copied from P3 Profiler
if ( extension_loaded( 'xcache' ) ) {
@ini_set( 'xcache.optimizer', false ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
} elseif ( extension_loaded( 'apc' ) ) {
@ini_set( 'apc.optimization', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
apc_clear_cache();
} elseif ( extension_loaded( 'eaccelerator' ) ) {
@ini_set( 'eaccelerator.optimizer', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
if ( function_exists( 'eaccelerator_optimizer' ) ) {
@eaccelerator_optimizer( false ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- disabling eaccelerator on runtime can faild
}
} elseif ( extension_loaded( 'Zend Optimizer+' ) ) {
@ini_set( 'zend_optimizerplus.optimization_level', 0 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- ini_set can be disabled on server.
}
register_tick_function( array( $this, 'handle_function_tick' ) );
declare( ticks = 1 );
return $value;
} | [
"public",
"function",
"wp_tick_profile_begin",
"(",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"version_compare",
"(",
"PHP_VERSION",
",",
"'7.0.0'",
")",
">=",
"0",
")",
"{",
"WP_CLI",
"::",
"error",
"(",
"'Profiling intermediate hooks is broken in PHP 7, se... | Start profiling function calls on the end of this filter | [
"Start",
"profiling",
"function",
"calls",
"on",
"the",
"end",
"of",
"this",
"filter"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L129-L155 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.wp_hook_begin | public function wp_hook_begin() {
foreach ( Logger::$active_loggers as $logger ) {
$logger->start_hook_timer();
}
$current_filter = current_filter();
if ( ( 'stage' === $this->type && in_array( $current_filter, $this->current_stage_hooks ) )
|| ( 'hook' === $this->type && ! $this->focus ) ) {
$pseudo_hook = "{$current_filter}:before";
if ( isset( $this->loggers[ $pseudo_hook ] ) ) {
$this->loggers[ $pseudo_hook ]->stop();
}
$callback_count = 0;
$callbacks = self::get_filter_callbacks( $current_filter );
if ( false !== $callbacks ) {
foreach ( $callbacks as $priority => $cbs ) {
$callback_count += count( $cbs );
}
}
$this->loggers[ $current_filter ] = new Logger(
array(
'hook' => $current_filter,
'callback_count' => $callback_count,
)
);
$this->loggers[ $current_filter ]->start();
}
if ( 0 === $this->filter_depth
&& ! is_null( $this->previous_filter_callbacks ) ) {
self::set_filter_callbacks( $this->previous_filter, $this->previous_filter_callbacks );
$this->previous_filter_callbacks = null;
}
if ( 'hook' === $this->type
&& 0 === $this->filter_depth
&& ( $current_filter === $this->focus || true === $this->focus ) ) {
$this->wrap_current_filter_callbacks( $current_filter );
}
$this->filter_depth++;
WP_CLI::add_wp_hook( $current_filter, array( $this, 'wp_hook_end' ), 9999 );
} | php | public function wp_hook_begin() {
foreach ( Logger::$active_loggers as $logger ) {
$logger->start_hook_timer();
}
$current_filter = current_filter();
if ( ( 'stage' === $this->type && in_array( $current_filter, $this->current_stage_hooks ) )
|| ( 'hook' === $this->type && ! $this->focus ) ) {
$pseudo_hook = "{$current_filter}:before";
if ( isset( $this->loggers[ $pseudo_hook ] ) ) {
$this->loggers[ $pseudo_hook ]->stop();
}
$callback_count = 0;
$callbacks = self::get_filter_callbacks( $current_filter );
if ( false !== $callbacks ) {
foreach ( $callbacks as $priority => $cbs ) {
$callback_count += count( $cbs );
}
}
$this->loggers[ $current_filter ] = new Logger(
array(
'hook' => $current_filter,
'callback_count' => $callback_count,
)
);
$this->loggers[ $current_filter ]->start();
}
if ( 0 === $this->filter_depth
&& ! is_null( $this->previous_filter_callbacks ) ) {
self::set_filter_callbacks( $this->previous_filter, $this->previous_filter_callbacks );
$this->previous_filter_callbacks = null;
}
if ( 'hook' === $this->type
&& 0 === $this->filter_depth
&& ( $current_filter === $this->focus || true === $this->focus ) ) {
$this->wrap_current_filter_callbacks( $current_filter );
}
$this->filter_depth++;
WP_CLI::add_wp_hook( $current_filter, array( $this, 'wp_hook_end' ), 9999 );
} | [
"public",
"function",
"wp_hook_begin",
"(",
")",
"{",
"foreach",
"(",
"Logger",
"::",
"$",
"active_loggers",
"as",
"$",
"logger",
")",
"{",
"$",
"logger",
"->",
"start_hook_timer",
"(",
")",
";",
"}",
"$",
"current_filter",
"=",
"current_filter",
"(",
")",... | Profiling verbosity at the beginning of every action and filter | [
"Profiling",
"verbosity",
"at",
"the",
"beginning",
"of",
"every",
"action",
"and",
"filter"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L169-L213 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.wrap_current_filter_callbacks | private function wrap_current_filter_callbacks( $current_filter ) {
$callbacks = self::get_filter_callbacks( $current_filter );
if ( false === $callbacks ) {
return;
}
$this->previous_filter = $current_filter;
$this->previous_filter_callbacks = $callbacks;
foreach ( $callbacks as $priority => $priority_callbacks ) {
foreach ( $priority_callbacks as $i => $the_ ) {
$callbacks[ $priority ][ $i ] = array(
'function' => function() use ( $the_, $i ) {
if ( ! isset( $this->loggers[ $i ] ) ) {
$this->loggers[ $i ] = new Logger(
array(
'callback' => $the_['function'],
)
);
}
$this->loggers[ $i ]->start();
$value = call_user_func_array( $the_['function'], func_get_args() );
$this->loggers[ $i ]->stop();
return $value;
},
'accepted_args' => $the_['accepted_args'],
);
}
}
self::set_filter_callbacks( $current_filter, $callbacks );
} | php | private function wrap_current_filter_callbacks( $current_filter ) {
$callbacks = self::get_filter_callbacks( $current_filter );
if ( false === $callbacks ) {
return;
}
$this->previous_filter = $current_filter;
$this->previous_filter_callbacks = $callbacks;
foreach ( $callbacks as $priority => $priority_callbacks ) {
foreach ( $priority_callbacks as $i => $the_ ) {
$callbacks[ $priority ][ $i ] = array(
'function' => function() use ( $the_, $i ) {
if ( ! isset( $this->loggers[ $i ] ) ) {
$this->loggers[ $i ] = new Logger(
array(
'callback' => $the_['function'],
)
);
}
$this->loggers[ $i ]->start();
$value = call_user_func_array( $the_['function'], func_get_args() );
$this->loggers[ $i ]->stop();
return $value;
},
'accepted_args' => $the_['accepted_args'],
);
}
}
self::set_filter_callbacks( $current_filter, $callbacks );
} | [
"private",
"function",
"wrap_current_filter_callbacks",
"(",
"$",
"current_filter",
")",
"{",
"$",
"callbacks",
"=",
"self",
"::",
"get_filter_callbacks",
"(",
"$",
"current_filter",
")",
";",
"if",
"(",
"false",
"===",
"$",
"callbacks",
")",
"{",
"return",
";... | Wrap current filter callbacks with a timer | [
"Wrap",
"current",
"filter",
"callbacks",
"with",
"a",
"timer"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L218-L248 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.wp_hook_end | public function wp_hook_end( $filter_value = null ) {
foreach ( Logger::$active_loggers as $logger ) {
$logger->stop_hook_timer();
}
$current_filter = current_filter();
if ( ( 'stage' === $this->type && in_array( $current_filter, $this->current_stage_hooks ) )
|| ( 'hook' === $this->type && ! $this->focus ) ) {
$this->loggers[ $current_filter ]->stop();
if ( 'stage' === $this->type ) {
$key = array_search( $current_filter, $this->current_stage_hooks );
if ( false !== $key && isset( $this->current_stage_hooks[ $key + 1 ] ) ) {
$pseudo_hook = "{$this->current_stage_hooks[$key+1]}:before";
} else {
$pseudo_hook = "{$this->current_stage_hooks[$key]}:after";
$this->running_hook = $pseudo_hook;
}
$this->loggers[ $pseudo_hook ] = new Logger( array( 'hook' => $pseudo_hook ) );
$this->loggers[ $pseudo_hook ]->start();
}
}
$this->filter_depth--;
return $filter_value;
} | php | public function wp_hook_end( $filter_value = null ) {
foreach ( Logger::$active_loggers as $logger ) {
$logger->stop_hook_timer();
}
$current_filter = current_filter();
if ( ( 'stage' === $this->type && in_array( $current_filter, $this->current_stage_hooks ) )
|| ( 'hook' === $this->type && ! $this->focus ) ) {
$this->loggers[ $current_filter ]->stop();
if ( 'stage' === $this->type ) {
$key = array_search( $current_filter, $this->current_stage_hooks );
if ( false !== $key && isset( $this->current_stage_hooks[ $key + 1 ] ) ) {
$pseudo_hook = "{$this->current_stage_hooks[$key+1]}:before";
} else {
$pseudo_hook = "{$this->current_stage_hooks[$key]}:after";
$this->running_hook = $pseudo_hook;
}
$this->loggers[ $pseudo_hook ] = new Logger( array( 'hook' => $pseudo_hook ) );
$this->loggers[ $pseudo_hook ]->start();
}
}
$this->filter_depth--;
return $filter_value;
} | [
"public",
"function",
"wp_hook_end",
"(",
"$",
"filter_value",
"=",
"null",
")",
"{",
"foreach",
"(",
"Logger",
"::",
"$",
"active_loggers",
"as",
"$",
"logger",
")",
"{",
"$",
"logger",
"->",
"stop_hook_timer",
"(",
")",
";",
"}",
"$",
"current_filter",
... | Profiling verbosity at the end of every action and filter | [
"Profiling",
"verbosity",
"at",
"the",
"end",
"of",
"every",
"action",
"and",
"filter"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L253-L279 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.handle_function_tick | public function handle_function_tick() {
global $wpdb, $wp_object_cache;
if ( ! is_null( $this->tick_callback ) ) {
$time = microtime( true ) - $this->tick_start_time;
$callback_hash = md5( serialize( $this->tick_callback . $this->tick_location ) );
if ( ! isset( $this->loggers[ $callback_hash ] ) ) {
$this->loggers[ $callback_hash ] = array(
'callback' => $this->tick_callback,
'location' => $this->tick_location,
'time' => 0,
'query_time' => 0,
'query_count' => 0,
'cache_hits' => 0,
'cache_misses' => 0,
'cache_ratio' => null,
);
}
$this->loggers[ $callback_hash ]['time'] += $time;
if ( isset( $wpdb ) ) {
for ( $i = $this->tick_query_offset; $i < count( $wpdb->queries ); $i++ ) {
$this->loggers[ $callback_hash ]['query_time'] += $wpdb->queries[ $i ][1];
$this->loggers[ $callback_hash ]['query_count']++;
}
}
if ( isset( $wp_object_cache ) ) {
$hits = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$misses = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
$this->loggers[ $callback_hash ]['cache_hits'] = ( $hits - $this->tick_cache_hit_offset ) + $this->loggers[ $callback_hash ]['cache_hits'];
$this->loggers[ $callback_hash ]['cache_misses'] = ( $misses - $this->tick_cache_miss_offset ) + $this->loggers[ $callback_hash ]['cache_misses'];
$total = $this->loggers[ $callback_hash ]['cache_hits'] + $this->loggers[ $callback_hash ]['cache_misses'];
if ( $total ) {
$ratio = ( $this->loggers[ $callback_hash ]['cache_hits'] / $total ) * 100;
$this->loggers[ $callback_hash ]['cache_ratio'] = round( $ratio, 2 ) . '%';
}
}
}
$bt = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT, 2 );
$frame = $bt[0];
if ( isset( $bt[1] ) ) {
$frame = $bt[1];
}
$callback = $location = '';
if ( in_array( strtolower( $frame['function'] ), array( 'include', 'require', 'include_once', 'require_once' ) ) ) {
$callback = $frame['function'] . " '" . $frame['args'][0] . "'";
} elseif ( isset( $frame['object'] ) && method_exists( $frame['object'], $frame['function'] ) ) {
$callback = get_class( $frame['object'] ) . '->' . $frame['function'] . '()';
} elseif ( isset( $frame['class'] ) && method_exists( $frame['class'], $frame['function'] ) ) {
$callback = $frame['class'] . '::' . $frame['function'] . '()';
} elseif ( ! empty( $frame['function'] ) && function_exists( $frame['function'] ) ) {
$callback = $frame['function'] . '()';
} elseif ( '__lambda_func' == $frame['function'] || '{closure}' == $frame['function'] ) {
$callback = 'function(){}';
}
if ( 'runcommand\Profile\Profiler->wp_tick_profile_begin()' === $callback ) {
$this->tick_callback = null;
return;
}
if ( isset( $frame['file'] ) ) {
$location = $frame['file'];
if ( isset( $frame['line'] ) ) {
$location .= ':' . $frame['line'];
}
}
$this->tick_callback = $callback;
$this->tick_location = $location;
$this->tick_start_time = microtime( true );
$this->tick_query_offset = ! empty( $wpdb->queries ) ? count( $wpdb->queries ) : 0;
$this->tick_cache_hit_offset = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$this->tick_cache_miss_offset = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
} | php | public function handle_function_tick() {
global $wpdb, $wp_object_cache;
if ( ! is_null( $this->tick_callback ) ) {
$time = microtime( true ) - $this->tick_start_time;
$callback_hash = md5( serialize( $this->tick_callback . $this->tick_location ) );
if ( ! isset( $this->loggers[ $callback_hash ] ) ) {
$this->loggers[ $callback_hash ] = array(
'callback' => $this->tick_callback,
'location' => $this->tick_location,
'time' => 0,
'query_time' => 0,
'query_count' => 0,
'cache_hits' => 0,
'cache_misses' => 0,
'cache_ratio' => null,
);
}
$this->loggers[ $callback_hash ]['time'] += $time;
if ( isset( $wpdb ) ) {
for ( $i = $this->tick_query_offset; $i < count( $wpdb->queries ); $i++ ) {
$this->loggers[ $callback_hash ]['query_time'] += $wpdb->queries[ $i ][1];
$this->loggers[ $callback_hash ]['query_count']++;
}
}
if ( isset( $wp_object_cache ) ) {
$hits = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$misses = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
$this->loggers[ $callback_hash ]['cache_hits'] = ( $hits - $this->tick_cache_hit_offset ) + $this->loggers[ $callback_hash ]['cache_hits'];
$this->loggers[ $callback_hash ]['cache_misses'] = ( $misses - $this->tick_cache_miss_offset ) + $this->loggers[ $callback_hash ]['cache_misses'];
$total = $this->loggers[ $callback_hash ]['cache_hits'] + $this->loggers[ $callback_hash ]['cache_misses'];
if ( $total ) {
$ratio = ( $this->loggers[ $callback_hash ]['cache_hits'] / $total ) * 100;
$this->loggers[ $callback_hash ]['cache_ratio'] = round( $ratio, 2 ) . '%';
}
}
}
$bt = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT, 2 );
$frame = $bt[0];
if ( isset( $bt[1] ) ) {
$frame = $bt[1];
}
$callback = $location = '';
if ( in_array( strtolower( $frame['function'] ), array( 'include', 'require', 'include_once', 'require_once' ) ) ) {
$callback = $frame['function'] . " '" . $frame['args'][0] . "'";
} elseif ( isset( $frame['object'] ) && method_exists( $frame['object'], $frame['function'] ) ) {
$callback = get_class( $frame['object'] ) . '->' . $frame['function'] . '()';
} elseif ( isset( $frame['class'] ) && method_exists( $frame['class'], $frame['function'] ) ) {
$callback = $frame['class'] . '::' . $frame['function'] . '()';
} elseif ( ! empty( $frame['function'] ) && function_exists( $frame['function'] ) ) {
$callback = $frame['function'] . '()';
} elseif ( '__lambda_func' == $frame['function'] || '{closure}' == $frame['function'] ) {
$callback = 'function(){}';
}
if ( 'runcommand\Profile\Profiler->wp_tick_profile_begin()' === $callback ) {
$this->tick_callback = null;
return;
}
if ( isset( $frame['file'] ) ) {
$location = $frame['file'];
if ( isset( $frame['line'] ) ) {
$location .= ':' . $frame['line'];
}
}
$this->tick_callback = $callback;
$this->tick_location = $location;
$this->tick_start_time = microtime( true );
$this->tick_query_offset = ! empty( $wpdb->queries ) ? count( $wpdb->queries ) : 0;
$this->tick_cache_hit_offset = ! empty( $wp_object_cache->cache_hits ) ? $wp_object_cache->cache_hits : 0;
$this->tick_cache_miss_offset = ! empty( $wp_object_cache->cache_misses ) ? $wp_object_cache->cache_misses : 0;
} | [
"public",
"function",
"handle_function_tick",
"(",
")",
"{",
"global",
"$",
"wpdb",
",",
"$",
"wp_object_cache",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"tick_callback",
")",
")",
"{",
"$",
"time",
"=",
"microtime",
"(",
"true",
")",
"-... | Handle the tick of a function | [
"Handle",
"the",
"tick",
"of",
"a",
"function"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L284-L363 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.wp_request_begin | public function wp_request_begin( $filter_value = null ) {
foreach ( Logger::$active_loggers as $logger ) {
$logger->start_request_timer();
}
return $filter_value;
} | php | public function wp_request_begin( $filter_value = null ) {
foreach ( Logger::$active_loggers as $logger ) {
$logger->start_request_timer();
}
return $filter_value;
} | [
"public",
"function",
"wp_request_begin",
"(",
"$",
"filter_value",
"=",
"null",
")",
"{",
"foreach",
"(",
"Logger",
"::",
"$",
"active_loggers",
"as",
"$",
"logger",
")",
"{",
"$",
"logger",
"->",
"start_request_timer",
"(",
")",
";",
"}",
"return",
"$",
... | Profiling request time for any active Loggers | [
"Profiling",
"request",
"time",
"for",
"any",
"active",
"Loggers"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L368-L373 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.wp_request_end | public function wp_request_end( $filter_value = null ) {
foreach ( Logger::$active_loggers as $logger ) {
$logger->stop_request_timer();
}
return $filter_value;
} | php | public function wp_request_end( $filter_value = null ) {
foreach ( Logger::$active_loggers as $logger ) {
$logger->stop_request_timer();
}
return $filter_value;
} | [
"public",
"function",
"wp_request_end",
"(",
"$",
"filter_value",
"=",
"null",
")",
"{",
"foreach",
"(",
"Logger",
"::",
"$",
"active_loggers",
"as",
"$",
"logger",
")",
"{",
"$",
"logger",
"->",
"stop_request_timer",
"(",
")",
";",
"}",
"return",
"$",
"... | Profiling request time for any active Loggers | [
"Profiling",
"request",
"time",
"for",
"any",
"active",
"Loggers"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L378-L383 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.load_wordpress_with_template | private function load_wordpress_with_template() {
// WordPress already ran once.
if ( function_exists( 'add_filter' ) ) {
return;
}
if ( 'stage' === $this->type && true === $this->focus ) {
$hooks = array();
foreach ( $this->stage_hooks as $stage_hook ) {
$hooks = array_merge( $hooks, $stage_hook );
}
$this->set_stage_hooks( $hooks );
}
if ( 'stage' === $this->type ) {
if ( 'bootstrap' === $this->focus ) {
$this->set_stage_hooks( $this->stage_hooks['bootstrap'] );
} elseif ( ! $this->focus ) {
$logger = new Logger( array( 'stage' => 'bootstrap' ) );
$logger->start();
}
}
WP_CLI::get_runner()->load_wordpress();
if ( $this->running_hook ) {
$this->loggers[ $this->running_hook ]->stop();
$this->running_hook = null;
}
if ( 'hook' === $this->type && 'wp_loaded:after' === $this->focus ) {
$this->wp_tick_profile_end();
}
if ( 'stage' === $this->type && ! $this->focus ) {
$logger->stop();
$this->loggers[] = $logger;
}
// Set up main_query main WordPress query.
if ( 'stage' === $this->type ) {
if ( 'main_query' === $this->focus ) {
$this->set_stage_hooks( $this->stage_hooks['main_query'] );
} elseif ( ! $this->focus ) {
$logger = new Logger( array( 'stage' => 'main_query' ) );
$logger->start();
}
}
wp();
if ( $this->running_hook ) {
$this->loggers[ $this->running_hook ]->stop();
$this->running_hook = null;
}
if ( 'hook' === $this->type && 'wp:after' === $this->focus ) {
$this->wp_tick_profile_end();
}
if ( 'stage' === $this->type && ! $this->focus ) {
$logger->stop();
$this->loggers[] = $logger;
}
define( 'WP_USE_THEMES', true );
// Template is normally loaded in global scope, so we need to replicate
foreach ( $GLOBALS as $key => $value ) {
global ${$key}; // phpcs:ignore PHPCompatibility.PHP.ForbiddenGlobalVariableVariable.NonBareVariableFound -- Syntax is updated to compatible with php 5 and 7.
}
// Load the theme template.
if ( 'stage' === $this->type ) {
if ( 'template' === $this->focus ) {
$this->set_stage_hooks( $this->stage_hooks['template'] );
} elseif ( ! $this->focus ) {
$logger = new Logger( array( 'stage' => 'template' ) );
$logger->start();
}
}
ob_start();
require_once( ABSPATH . WPINC . '/template-loader.php' );
ob_get_clean();
if ( $this->running_hook ) {
$this->loggers[ $this->running_hook ]->stop();
$this->running_hook = null;
}
if ( 'hook' === $this->type && 'wp_footer:after' === $this->focus ) {
$this->wp_tick_profile_end();
}
if ( 'stage' === $this->type && ! $this->focus ) {
$logger->stop();
$this->loggers[] = $logger;
}
} | php | private function load_wordpress_with_template() {
// WordPress already ran once.
if ( function_exists( 'add_filter' ) ) {
return;
}
if ( 'stage' === $this->type && true === $this->focus ) {
$hooks = array();
foreach ( $this->stage_hooks as $stage_hook ) {
$hooks = array_merge( $hooks, $stage_hook );
}
$this->set_stage_hooks( $hooks );
}
if ( 'stage' === $this->type ) {
if ( 'bootstrap' === $this->focus ) {
$this->set_stage_hooks( $this->stage_hooks['bootstrap'] );
} elseif ( ! $this->focus ) {
$logger = new Logger( array( 'stage' => 'bootstrap' ) );
$logger->start();
}
}
WP_CLI::get_runner()->load_wordpress();
if ( $this->running_hook ) {
$this->loggers[ $this->running_hook ]->stop();
$this->running_hook = null;
}
if ( 'hook' === $this->type && 'wp_loaded:after' === $this->focus ) {
$this->wp_tick_profile_end();
}
if ( 'stage' === $this->type && ! $this->focus ) {
$logger->stop();
$this->loggers[] = $logger;
}
// Set up main_query main WordPress query.
if ( 'stage' === $this->type ) {
if ( 'main_query' === $this->focus ) {
$this->set_stage_hooks( $this->stage_hooks['main_query'] );
} elseif ( ! $this->focus ) {
$logger = new Logger( array( 'stage' => 'main_query' ) );
$logger->start();
}
}
wp();
if ( $this->running_hook ) {
$this->loggers[ $this->running_hook ]->stop();
$this->running_hook = null;
}
if ( 'hook' === $this->type && 'wp:after' === $this->focus ) {
$this->wp_tick_profile_end();
}
if ( 'stage' === $this->type && ! $this->focus ) {
$logger->stop();
$this->loggers[] = $logger;
}
define( 'WP_USE_THEMES', true );
// Template is normally loaded in global scope, so we need to replicate
foreach ( $GLOBALS as $key => $value ) {
global ${$key}; // phpcs:ignore PHPCompatibility.PHP.ForbiddenGlobalVariableVariable.NonBareVariableFound -- Syntax is updated to compatible with php 5 and 7.
}
// Load the theme template.
if ( 'stage' === $this->type ) {
if ( 'template' === $this->focus ) {
$this->set_stage_hooks( $this->stage_hooks['template'] );
} elseif ( ! $this->focus ) {
$logger = new Logger( array( 'stage' => 'template' ) );
$logger->start();
}
}
ob_start();
require_once( ABSPATH . WPINC . '/template-loader.php' );
ob_get_clean();
if ( $this->running_hook ) {
$this->loggers[ $this->running_hook ]->stop();
$this->running_hook = null;
}
if ( 'hook' === $this->type && 'wp_footer:after' === $this->focus ) {
$this->wp_tick_profile_end();
}
if ( 'stage' === $this->type && ! $this->focus ) {
$logger->stop();
$this->loggers[] = $logger;
}
} | [
"private",
"function",
"load_wordpress_with_template",
"(",
")",
"{",
"// WordPress already ran once.",
"if",
"(",
"function_exists",
"(",
"'add_filter'",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"'stage'",
"===",
"$",
"this",
"->",
"type",
"&&",
"true",
... | Runs through the entirety of the WP bootstrap process | [
"Runs",
"through",
"the",
"entirety",
"of",
"the",
"WP",
"bootstrap",
"process"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L388-L477 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.get_name_location_from_callback | private static function get_name_location_from_callback( $callback ) {
$name = $location = '';
$reflection = false;
if ( is_array( $callback ) && is_object( $callback[0] ) ) {
$reflection = new \ReflectionMethod( $callback[0], $callback[1] );
$name = get_class( $callback[0] ) . '->' . $callback[1] . '()';
} elseif ( is_array( $callback ) && method_exists( $callback[0], $callback[1] ) ) {
$reflection = new \ReflectionMethod( $callback[0], $callback[1] );
$name = $callback[0] . '::' . $callback[1] . '()';
} elseif ( is_object( $callback ) && is_a( $callback, 'Closure' ) ) {
$reflection = new \ReflectionFunction( $callback );
$name = 'function(){}';
} elseif ( is_string( $callback ) && function_exists( $callback ) ) {
$reflection = new \ReflectionFunction( $callback );
$name = $callback . '()';
}
if ( $reflection ) {
$location = $reflection->getFileName() . ':' . $reflection->getStartLine();
}
return array( $name, $location );
} | php | private static function get_name_location_from_callback( $callback ) {
$name = $location = '';
$reflection = false;
if ( is_array( $callback ) && is_object( $callback[0] ) ) {
$reflection = new \ReflectionMethod( $callback[0], $callback[1] );
$name = get_class( $callback[0] ) . '->' . $callback[1] . '()';
} elseif ( is_array( $callback ) && method_exists( $callback[0], $callback[1] ) ) {
$reflection = new \ReflectionMethod( $callback[0], $callback[1] );
$name = $callback[0] . '::' . $callback[1] . '()';
} elseif ( is_object( $callback ) && is_a( $callback, 'Closure' ) ) {
$reflection = new \ReflectionFunction( $callback );
$name = 'function(){}';
} elseif ( is_string( $callback ) && function_exists( $callback ) ) {
$reflection = new \ReflectionFunction( $callback );
$name = $callback . '()';
}
if ( $reflection ) {
$location = $reflection->getFileName() . ':' . $reflection->getStartLine();
}
return array( $name, $location );
} | [
"private",
"static",
"function",
"get_name_location_from_callback",
"(",
"$",
"callback",
")",
"{",
"$",
"name",
"=",
"$",
"location",
"=",
"''",
";",
"$",
"reflection",
"=",
"false",
";",
"if",
"(",
"is_array",
"(",
"$",
"callback",
")",
"&&",
"is_object"... | Get a human-readable name from a callback | [
"Get",
"a",
"human",
"-",
"readable",
"name",
"from",
"a",
"callback"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L482-L502 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.get_short_location | private static function get_short_location( $location ) {
$abspath = rtrim( realpath( ABSPATH ), '/' ) . '/';
if ( defined( 'WP_PLUGIN_DIR' ) && 0 === stripos( $location, WP_PLUGIN_DIR ) ) {
$location = str_replace( trailingslashit( WP_PLUGIN_DIR ), '', $location );
} elseif ( defined( 'WPMU_PLUGIN_DIR' ) && 0 === stripos( $location, WPMU_PLUGIN_DIR ) ) {
$location = str_replace( trailingslashit( dirname( WPMU_PLUGIN_DIR ) ), '', $location );
} elseif ( function_exists( 'get_theme_root' ) && 0 === stripos( $location, get_theme_root() ) ) {
$location = str_replace( trailingslashit( get_theme_root() ), '', $location );
} elseif ( 0 === stripos( $location, $abspath . 'wp-admin/' ) ) {
$location = str_replace( $abspath, '', $location );
} elseif ( 0 === stripos( $location, $abspath . 'wp-includes/' ) ) {
$location = str_replace( $abspath, '', $location );
}
return $location;
} | php | private static function get_short_location( $location ) {
$abspath = rtrim( realpath( ABSPATH ), '/' ) . '/';
if ( defined( 'WP_PLUGIN_DIR' ) && 0 === stripos( $location, WP_PLUGIN_DIR ) ) {
$location = str_replace( trailingslashit( WP_PLUGIN_DIR ), '', $location );
} elseif ( defined( 'WPMU_PLUGIN_DIR' ) && 0 === stripos( $location, WPMU_PLUGIN_DIR ) ) {
$location = str_replace( trailingslashit( dirname( WPMU_PLUGIN_DIR ) ), '', $location );
} elseif ( function_exists( 'get_theme_root' ) && 0 === stripos( $location, get_theme_root() ) ) {
$location = str_replace( trailingslashit( get_theme_root() ), '', $location );
} elseif ( 0 === stripos( $location, $abspath . 'wp-admin/' ) ) {
$location = str_replace( $abspath, '', $location );
} elseif ( 0 === stripos( $location, $abspath . 'wp-includes/' ) ) {
$location = str_replace( $abspath, '', $location );
}
return $location;
} | [
"private",
"static",
"function",
"get_short_location",
"(",
"$",
"location",
")",
"{",
"$",
"abspath",
"=",
"rtrim",
"(",
"realpath",
"(",
"ABSPATH",
")",
",",
"'/'",
")",
".",
"'/'",
";",
"if",
"(",
"defined",
"(",
"'WP_PLUGIN_DIR'",
")",
"&&",
"0",
"... | Get the short location from the full location
@param string $location
@return string | [
"Get",
"the",
"short",
"location",
"from",
"the",
"full",
"location"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L510-L524 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.set_stage_hooks | private function set_stage_hooks( $hooks ) {
$this->current_stage_hooks = $hooks;
$pseudo_hook = "{$hooks[0]}:before";
$this->loggers[ $pseudo_hook ] = new Logger( array( 'hook' => $pseudo_hook ) );
$this->loggers[ $pseudo_hook ]->start();
} | php | private function set_stage_hooks( $hooks ) {
$this->current_stage_hooks = $hooks;
$pseudo_hook = "{$hooks[0]}:before";
$this->loggers[ $pseudo_hook ] = new Logger( array( 'hook' => $pseudo_hook ) );
$this->loggers[ $pseudo_hook ]->start();
} | [
"private",
"function",
"set_stage_hooks",
"(",
"$",
"hooks",
")",
"{",
"$",
"this",
"->",
"current_stage_hooks",
"=",
"$",
"hooks",
";",
"$",
"pseudo_hook",
"=",
"\"{$hooks[0]}:before\"",
";",
"$",
"this",
"->",
"loggers",
"[",
"$",
"pseudo_hook",
"]",
"=",
... | Set the hooks for the current stage | [
"Set",
"the",
"hooks",
"for",
"the",
"current",
"stage"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L529-L534 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.get_filter_callbacks | private static function get_filter_callbacks( $filter ) {
global $wp_filter;
if ( ! isset( $wp_filter[ $filter ] ) ) {
return false;
}
if ( is_a( $wp_filter[ $filter ], 'WP_Hook' ) ) {
$callbacks = $wp_filter[ $filter ]->callbacks;
} else {
$callbacks = $wp_filter[ $filter ];
}
if ( is_array( $callbacks ) ) {
return $callbacks;
}
return false;
} | php | private static function get_filter_callbacks( $filter ) {
global $wp_filter;
if ( ! isset( $wp_filter[ $filter ] ) ) {
return false;
}
if ( is_a( $wp_filter[ $filter ], 'WP_Hook' ) ) {
$callbacks = $wp_filter[ $filter ]->callbacks;
} else {
$callbacks = $wp_filter[ $filter ];
}
if ( is_array( $callbacks ) ) {
return $callbacks;
}
return false;
} | [
"private",
"static",
"function",
"get_filter_callbacks",
"(",
"$",
"filter",
")",
"{",
"global",
"$",
"wp_filter",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"wp_filter",
"[",
"$",
"filter",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"i... | Get the callbacks for a given filter
@param string
@return array|false | [
"Get",
"the",
"callbacks",
"for",
"a",
"given",
"filter"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L542-L558 |
wp-cli/profile-command | inc/class-profiler.php | Profiler.set_filter_callbacks | private static function set_filter_callbacks( $filter, $callbacks ) {
global $wp_filter;
if ( ! isset( $wp_filter[ $filter ] ) && class_exists( 'WP_Hook' ) ) {
$wp_filter[ $filter ] = new \WP_Hook;
}
if ( is_a( $wp_filter[ $filter ], 'WP_Hook' ) ) {
$wp_filter[ $filter ]->callbacks = $callbacks;
} else {
$wp_filter[ $filter ] = $callbacks;
}
} | php | private static function set_filter_callbacks( $filter, $callbacks ) {
global $wp_filter;
if ( ! isset( $wp_filter[ $filter ] ) && class_exists( 'WP_Hook' ) ) {
$wp_filter[ $filter ] = new \WP_Hook;
}
if ( is_a( $wp_filter[ $filter ], 'WP_Hook' ) ) {
$wp_filter[ $filter ]->callbacks = $callbacks;
} else {
$wp_filter[ $filter ] = $callbacks;
}
} | [
"private",
"static",
"function",
"set_filter_callbacks",
"(",
"$",
"filter",
",",
"$",
"callbacks",
")",
"{",
"global",
"$",
"wp_filter",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"wp_filter",
"[",
"$",
"filter",
"]",
")",
"&&",
"class_exists",
"(",
"'WP_H... | Set the callbacks for a given filter
@param string $filter
@param mixed $callbacks | [
"Set",
"the",
"callbacks",
"for",
"a",
"given",
"filter"
] | train | https://github.com/wp-cli/profile-command/blob/0d3365290059c321e9943d3d407c44dfffd450c7/inc/class-profiler.php#L566-L578 |
theofidry/AliceDataFixtures | src/Loader/SimpleLoader.php | SimpleLoader.load | public function load(array $fixturesFiles, array $parameters = [], array $objects = [], PurgeMode $purgeMode = null): array
{
$this->logger->info('Loading fixtures.');
return $this->filesLoader->loadFiles($fixturesFiles, $parameters, $objects)->getObjects();
} | php | public function load(array $fixturesFiles, array $parameters = [], array $objects = [], PurgeMode $purgeMode = null): array
{
$this->logger->info('Loading fixtures.');
return $this->filesLoader->loadFiles($fixturesFiles, $parameters, $objects)->getObjects();
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"fixturesFiles",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"array",
"$",
"objects",
"=",
"[",
"]",
",",
"PurgeMode",
"$",
"purgeMode",
"=",
"null",
")",
":",
"array",
"{",
"$",
"this",
"->",... | Loads each file one after another.
{@inheritdoc} | [
"Loads",
"each",
"file",
"one",
"after",
"another",
"."
] | train | https://github.com/theofidry/AliceDataFixtures/blob/6fac234c054f053e3b1de66f00d7cb3c6f6d3058/src/Loader/SimpleLoader.php#L49-L54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.