repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
list | docstring
stringlengths 3
47.2k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
rfussien/leboncoin-crawler | src/Helper/Encoding.php | Encoding.toAscii | public static function toAscii($string)
{
$alnumPattern = '/^[a-zA-Z0-9 ]+$/';
$string = iconv(
mb_detect_encoding($string),
'ASCII//TRANSLIT',
$string
);
$ret = array_map(function ($chr) use ($alnumPattern) {
if (preg_match($alnumPattern, $chr)) {
return $chr;
}
return '';
}, str_split($string));
return implode($ret);
} | php | public static function toAscii($string)
{
$alnumPattern = '/^[a-zA-Z0-9 ]+$/';
$string = iconv(
mb_detect_encoding($string),
'ASCII//TRANSLIT',
$string
);
$ret = array_map(function ($chr) use ($alnumPattern) {
if (preg_match($alnumPattern, $chr)) {
return $chr;
}
return '';
}, str_split($string));
return implode($ret);
} | [
"public",
"static",
"function",
"toAscii",
"(",
"$",
"string",
")",
"{",
"$",
"alnumPattern",
"=",
"'/^[a-zA-Z0-9 ]+$/'",
";",
"$",
"string",
"=",
"iconv",
"(",
"mb_detect_encoding",
"(",
"$",
"string",
")",
",",
"'ASCII//TRANSLIT'",
",",
"$",
"string",
")",
";",
"$",
"ret",
"=",
"array_map",
"(",
"function",
"(",
"$",
"chr",
")",
"use",
"(",
"$",
"alnumPattern",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"alnumPattern",
",",
"$",
"chr",
")",
")",
"{",
"return",
"$",
"chr",
";",
"}",
"return",
"''",
";",
"}",
",",
"str_split",
"(",
"$",
"string",
")",
")",
";",
"return",
"implode",
"(",
"$",
"ret",
")",
";",
"}"
]
| Replace accent and remove unknown chars
@param string $string
@return string | [
"Replace",
"accent",
"and",
"remove",
"unknown",
"chars"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Helper/Encoding.php#L13-L31 | train |
rfussien/leboncoin-crawler | src/Crawler/CrawlerAbstract.php | CrawlerAbstract.getFieldValue | protected function getFieldValue(
Crawler $node,
$defaultValue,
$callback = null,
$funcName = 'text',
$funcParam = ''
) {
if ($callback == null) {
$callback = function ($value) {
return (new DefaultSanitizer)->clean($value);
};
}
if ($node->count()) {
return $callback($node->$funcName($funcParam));
}
return $defaultValue;
} | php | protected function getFieldValue(
Crawler $node,
$defaultValue,
$callback = null,
$funcName = 'text',
$funcParam = ''
) {
if ($callback == null) {
$callback = function ($value) {
return (new DefaultSanitizer)->clean($value);
};
}
if ($node->count()) {
return $callback($node->$funcName($funcParam));
}
return $defaultValue;
} | [
"protected",
"function",
"getFieldValue",
"(",
"Crawler",
"$",
"node",
",",
"$",
"defaultValue",
",",
"$",
"callback",
"=",
"null",
",",
"$",
"funcName",
"=",
"'text'",
",",
"$",
"funcParam",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"callback",
"==",
"null",
")",
"{",
"$",
"callback",
"=",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"(",
"new",
"DefaultSanitizer",
")",
"->",
"clean",
"(",
"$",
"value",
")",
";",
"}",
";",
"}",
"if",
"(",
"$",
"node",
"->",
"count",
"(",
")",
")",
"{",
"return",
"$",
"callback",
"(",
"$",
"node",
"->",
"$",
"funcName",
"(",
"$",
"funcParam",
")",
")",
";",
"}",
"return",
"$",
"defaultValue",
";",
"}"
]
| Return the field's value
@param Crawler $node
@param mixed $defaultValue
@param \Closure $callback
@param string $funcName
@param string $funcParam
@return mixed | [
"Return",
"the",
"field",
"s",
"value"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/CrawlerAbstract.php#L71-L89 | train |
rfussien/leboncoin-crawler | src/Crawler/SearchResultCrawler.php | SearchResultCrawler.getNbAds | public function getNbAds()
{
$nbAds = $this->node
->filter('a.tabsSwitch span.tabsSwitchNumbers')
->first();
if ($nbAds->count()) {
$nbAds = preg_replace('/\s+/', '', $nbAds->text());
return (int) $nbAds;
}
return 0;
} | php | public function getNbAds()
{
$nbAds = $this->node
->filter('a.tabsSwitch span.tabsSwitchNumbers')
->first();
if ($nbAds->count()) {
$nbAds = preg_replace('/\s+/', '', $nbAds->text());
return (int) $nbAds;
}
return 0;
} | [
"public",
"function",
"getNbAds",
"(",
")",
"{",
"$",
"nbAds",
"=",
"$",
"this",
"->",
"node",
"->",
"filter",
"(",
"'a.tabsSwitch span.tabsSwitchNumbers'",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"$",
"nbAds",
"->",
"count",
"(",
")",
")",
"{",
"$",
"nbAds",
"=",
"preg_replace",
"(",
"'/\\s+/'",
",",
"''",
",",
"$",
"nbAds",
"->",
"text",
"(",
")",
")",
";",
"return",
"(",
"int",
")",
"$",
"nbAds",
";",
"}",
"return",
"0",
";",
"}"
]
| Return the total number of ads of the search
@return int | [
"Return",
"the",
"total",
"number",
"of",
"ads",
"of",
"the",
"search"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/SearchResultCrawler.php#L32-L44 | train |
rfussien/leboncoin-crawler | src/Crawler/SearchResultCrawler.php | SearchResultCrawler.getAds | public function getAds()
{
$ads = array();
$this->node->filter('[itemtype="http://schema.org/Offer"]')
->each(function ($node) use (&$ads) {
$ad = (new SearchResultAdCrawler(
$node,
$node->filter('a')->attr('href')
))->getAll();
$ads [$ad['id']] = $ad;
});
return $ads;
} | php | public function getAds()
{
$ads = array();
$this->node->filter('[itemtype="http://schema.org/Offer"]')
->each(function ($node) use (&$ads) {
$ad = (new SearchResultAdCrawler(
$node,
$node->filter('a')->attr('href')
))->getAll();
$ads [$ad['id']] = $ad;
});
return $ads;
} | [
"public",
"function",
"getAds",
"(",
")",
"{",
"$",
"ads",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"node",
"->",
"filter",
"(",
"'[itemtype=\"http://schema.org/Offer\"]'",
")",
"->",
"each",
"(",
"function",
"(",
"$",
"node",
")",
"use",
"(",
"&",
"$",
"ads",
")",
"{",
"$",
"ad",
"=",
"(",
"new",
"SearchResultAdCrawler",
"(",
"$",
"node",
",",
"$",
"node",
"->",
"filter",
"(",
"'a'",
")",
"->",
"attr",
"(",
"'href'",
")",
")",
")",
"->",
"getAll",
"(",
")",
";",
"$",
"ads",
"[",
"$",
"ad",
"[",
"'id'",
"]",
"]",
"=",
"$",
"ad",
";",
"}",
")",
";",
"return",
"$",
"ads",
";",
"}"
]
| Get an array containing the ads of the current result page
@return array | [
"Get",
"an",
"array",
"containing",
"the",
"ads",
"of",
"the",
"current",
"result",
"page"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/SearchResultCrawler.php#L75-L90 | train |
rfussien/leboncoin-crawler | src/Crawler/AdCrawler.php | AdCrawler.getAll | public function getAll()
{
return array_merge(
[
'id' => $this->getUrlParser()->getId(),
'category' => $this->getUrlParser()->getCategory(),
],
$this->getPictures(),
$this->getProperties(),
$this->getDescription()
);
} | php | public function getAll()
{
return array_merge(
[
'id' => $this->getUrlParser()->getId(),
'category' => $this->getUrlParser()->getCategory(),
],
$this->getPictures(),
$this->getProperties(),
$this->getDescription()
);
} | [
"public",
"function",
"getAll",
"(",
")",
"{",
"return",
"array_merge",
"(",
"[",
"'id'",
"=>",
"$",
"this",
"->",
"getUrlParser",
"(",
")",
"->",
"getId",
"(",
")",
",",
"'category'",
"=>",
"$",
"this",
"->",
"getUrlParser",
"(",
")",
"->",
"getCategory",
"(",
")",
",",
"]",
",",
"$",
"this",
"->",
"getPictures",
"(",
")",
",",
"$",
"this",
"->",
"getProperties",
"(",
")",
",",
"$",
"this",
"->",
"getDescription",
"(",
")",
")",
";",
"}"
]
| Return a full ad information
@return array | [
"Return",
"a",
"full",
"ad",
"information"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/AdCrawler.php#L38-L49 | train |
rfussien/leboncoin-crawler | src/Crawler/AdCrawler.php | AdCrawler.getPictures | public function getPictures(Crawler $node = null)
{
$node = $node ?: $this->node;
$images = [
'images_thumbs' => [],
'images' => [],
];
$node
->filter('.adview_main script')
->each(function (Crawler $crawler) use (&$images) {
if (preg_match_all(
'#//img.+.leboncoin.fr/.*\.jpg#',
$crawler->html(),
$matches
)) {
foreach ($matches[0] as $image) {
if (preg_match('/thumb/', $image)) {
array_push(
$images['images_thumbs'],
(string) Http::createFromString($image)
->withScheme($this->sheme)
);
continue;
}
array_push(
$images['images'],
(string) Http::createFromString($image)
->withScheme($this->sheme)
);
}
}
});
return $images;
} | php | public function getPictures(Crawler $node = null)
{
$node = $node ?: $this->node;
$images = [
'images_thumbs' => [],
'images' => [],
];
$node
->filter('.adview_main script')
->each(function (Crawler $crawler) use (&$images) {
if (preg_match_all(
'#//img.+.leboncoin.fr/.*\.jpg#',
$crawler->html(),
$matches
)) {
foreach ($matches[0] as $image) {
if (preg_match('/thumb/', $image)) {
array_push(
$images['images_thumbs'],
(string) Http::createFromString($image)
->withScheme($this->sheme)
);
continue;
}
array_push(
$images['images'],
(string) Http::createFromString($image)
->withScheme($this->sheme)
);
}
}
});
return $images;
} | [
"public",
"function",
"getPictures",
"(",
"Crawler",
"$",
"node",
"=",
"null",
")",
"{",
"$",
"node",
"=",
"$",
"node",
"?",
":",
"$",
"this",
"->",
"node",
";",
"$",
"images",
"=",
"[",
"'images_thumbs'",
"=>",
"[",
"]",
",",
"'images'",
"=>",
"[",
"]",
",",
"]",
";",
"$",
"node",
"->",
"filter",
"(",
"'.adview_main script'",
")",
"->",
"each",
"(",
"function",
"(",
"Crawler",
"$",
"crawler",
")",
"use",
"(",
"&",
"$",
"images",
")",
"{",
"if",
"(",
"preg_match_all",
"(",
"'#//img.+.leboncoin.fr/.*\\.jpg#'",
",",
"$",
"crawler",
"->",
"html",
"(",
")",
",",
"$",
"matches",
")",
")",
"{",
"foreach",
"(",
"$",
"matches",
"[",
"0",
"]",
"as",
"$",
"image",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/thumb/'",
",",
"$",
"image",
")",
")",
"{",
"array_push",
"(",
"$",
"images",
"[",
"'images_thumbs'",
"]",
",",
"(",
"string",
")",
"Http",
"::",
"createFromString",
"(",
"$",
"image",
")",
"->",
"withScheme",
"(",
"$",
"this",
"->",
"sheme",
")",
")",
";",
"continue",
";",
"}",
"array_push",
"(",
"$",
"images",
"[",
"'images'",
"]",
",",
"(",
"string",
")",
"Http",
"::",
"createFromString",
"(",
"$",
"image",
")",
"->",
"withScheme",
"(",
"$",
"this",
"->",
"sheme",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"$",
"images",
";",
"}"
]
| Return an array with the Thumbs pictures url
@param Crawler $node
@return array | [
"Return",
"an",
"array",
"with",
"the",
"Thumbs",
"pictures",
"url"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/AdCrawler.php#L57-L95 | train |
rfussien/leboncoin-crawler | src/Crawler/AdCrawler.php | AdCrawler.getDescription | public function getDescription(Crawler $node = null)
{
$node = $node ?: $this->node;
return [
'description' => $this->getFieldValue(
$node->filter("p[itemprop=description]"),
null
),
];
} | php | public function getDescription(Crawler $node = null)
{
$node = $node ?: $this->node;
return [
'description' => $this->getFieldValue(
$node->filter("p[itemprop=description]"),
null
),
];
} | [
"public",
"function",
"getDescription",
"(",
"Crawler",
"$",
"node",
"=",
"null",
")",
"{",
"$",
"node",
"=",
"$",
"node",
"?",
":",
"$",
"this",
"->",
"node",
";",
"return",
"[",
"'description'",
"=>",
"$",
"this",
"->",
"getFieldValue",
"(",
"$",
"node",
"->",
"filter",
"(",
"\"p[itemprop=description]\"",
")",
",",
"null",
")",
",",
"]",
";",
"}"
]
| Return the description
@param Crawler $node
@return string | [
"Return",
"the",
"description"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/AdCrawler.php#L139-L149 | train |
rfussien/leboncoin-crawler | src/Crawler/AdCrawler.php | AdCrawler.sanitize | private function sanitize($key, $value)
{
$key = (new KeySanitizer)->clean($key);
if ($key == 'ville') {
return [
'ville' => (new CitySanitizer)->clean($value),
'cp' => (new CpSanitizer)->clean($value),
];
}
$filteClass = 'Lbc\\Filter\\' . ucfirst($key) . 'Sanitizer';
if (!class_exists($filteClass)) {
$filteClass = 'Lbc\\Filter\\DefaultSanitizer';
}
return [
$key => call_user_func_array([(new $filteClass), 'clean'], [$value]),
];
} | php | private function sanitize($key, $value)
{
$key = (new KeySanitizer)->clean($key);
if ($key == 'ville') {
return [
'ville' => (new CitySanitizer)->clean($value),
'cp' => (new CpSanitizer)->clean($value),
];
}
$filteClass = 'Lbc\\Filter\\' . ucfirst($key) . 'Sanitizer';
if (!class_exists($filteClass)) {
$filteClass = 'Lbc\\Filter\\DefaultSanitizer';
}
return [
$key => call_user_func_array([(new $filteClass), 'clean'], [$value]),
];
} | [
"private",
"function",
"sanitize",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"key",
"=",
"(",
"new",
"KeySanitizer",
")",
"->",
"clean",
"(",
"$",
"key",
")",
";",
"if",
"(",
"$",
"key",
"==",
"'ville'",
")",
"{",
"return",
"[",
"'ville'",
"=>",
"(",
"new",
"CitySanitizer",
")",
"->",
"clean",
"(",
"$",
"value",
")",
",",
"'cp'",
"=>",
"(",
"new",
"CpSanitizer",
")",
"->",
"clean",
"(",
"$",
"value",
")",
",",
"]",
";",
"}",
"$",
"filteClass",
"=",
"'Lbc\\\\Filter\\\\'",
".",
"ucfirst",
"(",
"$",
"key",
")",
".",
"'Sanitizer'",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"filteClass",
")",
")",
"{",
"$",
"filteClass",
"=",
"'Lbc\\\\Filter\\\\DefaultSanitizer'",
";",
"}",
"return",
"[",
"$",
"key",
"=>",
"call_user_func_array",
"(",
"[",
"(",
"new",
"$",
"filteClass",
")",
",",
"'clean'",
"]",
",",
"[",
"$",
"value",
"]",
")",
",",
"]",
";",
"}"
]
| Transform the properties name into a snake_case string and sanitize
the value
@param string $key
@param string $value
@return string | [
"Transform",
"the",
"properties",
"name",
"into",
"a",
"snake_case",
"string",
"and",
"sanitize",
"the",
"value"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/AdCrawler.php#L159-L179 | train |
rfussien/leboncoin-crawler | src/Parser/SearchResultUrlParser.php | SearchResultUrlParser.next | public function next()
{
if ((int) $this->current()->query->getValue('o') >= $this->nbPages) {
return null;
}
return $this->getIndexUrl(+1);
} | php | public function next()
{
if ((int) $this->current()->query->getValue('o') >= $this->nbPages) {
return null;
}
return $this->getIndexUrl(+1);
} | [
"public",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"(",
"int",
")",
"$",
"this",
"->",
"current",
"(",
")",
"->",
"query",
"->",
"getValue",
"(",
"'o'",
")",
">=",
"$",
"this",
"->",
"nbPages",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"getIndexUrl",
"(",
"+",
"1",
")",
";",
"}"
]
| Return the next page URL or null if non.
@return UriInterface | [
"Return",
"the",
"next",
"page",
"URL",
"or",
"null",
"if",
"non",
"."
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Parser/SearchResultUrlParser.php#L60-L67 | train |
rfussien/leboncoin-crawler | src/Parser/SearchResultUrlParser.php | SearchResultUrlParser.getNav | public function getNav()
{
return [
'page' => (int) $this->current()->query->getValue('o'),
'links' => [
'current' => (string) $this->current(),
'previous' => (string) $this->previous(),
'next' => (string) $this->next(),
]
];
} | php | public function getNav()
{
return [
'page' => (int) $this->current()->query->getValue('o'),
'links' => [
'current' => (string) $this->current(),
'previous' => (string) $this->previous(),
'next' => (string) $this->next(),
]
];
} | [
"public",
"function",
"getNav",
"(",
")",
"{",
"return",
"[",
"'page'",
"=>",
"(",
"int",
")",
"$",
"this",
"->",
"current",
"(",
")",
"->",
"query",
"->",
"getValue",
"(",
"'o'",
")",
",",
"'links'",
"=>",
"[",
"'current'",
"=>",
"(",
"string",
")",
"$",
"this",
"->",
"current",
"(",
")",
",",
"'previous'",
"=>",
"(",
"string",
")",
"$",
"this",
"->",
"previous",
"(",
")",
",",
"'next'",
"=>",
"(",
"string",
")",
"$",
"this",
"->",
"next",
"(",
")",
",",
"]",
"]",
";",
"}"
]
| Return a meta array containing the nav links and the page
@return array | [
"Return",
"a",
"meta",
"array",
"containing",
"the",
"nav",
"links",
"and",
"the",
"page"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Parser/SearchResultUrlParser.php#L101-L111 | train |
rfussien/leboncoin-crawler | src/Parser/SearchResultUrlParser.php | SearchResultUrlParser.getSearchArea | public function getSearchArea()
{
if ($this->current()->path->getSegment(3) === 'occasions') {
return 'toute la france';
}
if ($this->current()->path->getSegment(3) === 'bonnes_affaires') {
return 'regions voisines';
}
return $this->current()->path->getSegment(2);
} | php | public function getSearchArea()
{
if ($this->current()->path->getSegment(3) === 'occasions') {
return 'toute la france';
}
if ($this->current()->path->getSegment(3) === 'bonnes_affaires') {
return 'regions voisines';
}
return $this->current()->path->getSegment(2);
} | [
"public",
"function",
"getSearchArea",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"current",
"(",
")",
"->",
"path",
"->",
"getSegment",
"(",
"3",
")",
"===",
"'occasions'",
")",
"{",
"return",
"'toute la france'",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"current",
"(",
")",
"->",
"path",
"->",
"getSegment",
"(",
"3",
")",
"===",
"'bonnes_affaires'",
")",
"{",
"return",
"'regions voisines'",
";",
"}",
"return",
"$",
"this",
"->",
"current",
"(",
")",
"->",
"path",
"->",
"getSegment",
"(",
"2",
")",
";",
"}"
]
| Return the search area
@return string | [
"Return",
"the",
"search",
"area"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Parser/SearchResultUrlParser.php#L134-L145 | train |
rfussien/leboncoin-crawler | src/Crawler/SearchResultAdCrawler.php | SearchResultAdCrawler.getPrice | public function getPrice()
{
return $this->getFieldValue(
$this->node->filter('*[itemprop=price]'),
0,
function ($value) {
return (new PrixSanitizer)->clean($value);
}
);
} | php | public function getPrice()
{
return $this->getFieldValue(
$this->node->filter('*[itemprop=price]'),
0,
function ($value) {
return (new PrixSanitizer)->clean($value);
}
);
} | [
"public",
"function",
"getPrice",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"getFieldValue",
"(",
"$",
"this",
"->",
"node",
"->",
"filter",
"(",
"'*[itemprop=price]'",
")",
",",
"0",
",",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"(",
"new",
"PrixSanitizer",
")",
"->",
"clean",
"(",
"$",
"value",
")",
";",
"}",
")",
";",
"}"
]
| Return the price
@return int | [
"Return",
"the",
"price"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/SearchResultAdCrawler.php#L56-L65 | train |
rfussien/leboncoin-crawler | src/Crawler/SearchResultAdCrawler.php | SearchResultAdCrawler.getThumb | public function getThumb()
{
$image = $this->node
->filter('.item_imagePic .lazyload[data-imgsrc]')
->first();
if (0 === $image->count()) {
return null;
}
$src = $image
->attr('data-imgsrc');
return (string)Http::createFromString($src)->withScheme('https');
} | php | public function getThumb()
{
$image = $this->node
->filter('.item_imagePic .lazyload[data-imgsrc]')
->first();
if (0 === $image->count()) {
return null;
}
$src = $image
->attr('data-imgsrc');
return (string)Http::createFromString($src)->withScheme('https');
} | [
"public",
"function",
"getThumb",
"(",
")",
"{",
"$",
"image",
"=",
"$",
"this",
"->",
"node",
"->",
"filter",
"(",
"'.item_imagePic .lazyload[data-imgsrc]'",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"0",
"===",
"$",
"image",
"->",
"count",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"src",
"=",
"$",
"image",
"->",
"attr",
"(",
"'data-imgsrc'",
")",
";",
"return",
"(",
"string",
")",
"Http",
"::",
"createFromString",
"(",
"$",
"src",
")",
"->",
"withScheme",
"(",
"'https'",
")",
";",
"}"
]
| Return the thumb picture url
@return null|string | [
"Return",
"the",
"thumb",
"picture",
"url"
]
| 1ff5abced9392d24a759f6c8b5170e90d2e1ddb2 | https://github.com/rfussien/leboncoin-crawler/blob/1ff5abced9392d24a759f6c8b5170e90d2e1ddb2/src/Crawler/SearchResultAdCrawler.php#L95-L109 | train |
SRLabs/Centaur | src/Controllers/RoleController.php | RoleController.index | public function index()
{
$roles = $this->roleRepository->createModel()->all();
$userRoleIds = Sentinel::getUser()->roles()->pluck('id');
return view('Centaur::roles.index')
->with('userRoleIds', $userRoleIds)
->with('roles', $roles);
} | php | public function index()
{
$roles = $this->roleRepository->createModel()->all();
$userRoleIds = Sentinel::getUser()->roles()->pluck('id');
return view('Centaur::roles.index')
->with('userRoleIds', $userRoleIds)
->with('roles', $roles);
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"roles",
"=",
"$",
"this",
"->",
"roleRepository",
"->",
"createModel",
"(",
")",
"->",
"all",
"(",
")",
";",
"$",
"userRoleIds",
"=",
"Sentinel",
"::",
"getUser",
"(",
")",
"->",
"roles",
"(",
")",
"->",
"pluck",
"(",
"'id'",
")",
";",
"return",
"view",
"(",
"'Centaur::roles.index'",
")",
"->",
"with",
"(",
"'userRoleIds'",
",",
"$",
"userRoleIds",
")",
"->",
"with",
"(",
"'roles'",
",",
"$",
"roles",
")",
";",
"}"
]
| Display a listing of the roles.
@return \Illuminate\Http\Response | [
"Display",
"a",
"listing",
"of",
"the",
"roles",
"."
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/RoleController.php#L30-L38 | train |
SRLabs/Centaur | src/Controllers/UserController.php | UserController.destroy | public function destroy(Request $request, $id)
{
// Fetch the user object
//$id = $this->decode($hash);
$user = $this->userRepository->findById($id);
// Check to be sure user cannot delete himself
if (Sentinel::getUser()->id == $user->id) {
$message = "You cannot remove yourself!";
if ($request->expectsJson()) {
return response()->json($message, 422);
}
session()->flash('error', $message);
return redirect()->route('users.index');
}
// Remove the user
$user->delete();
// All done
$message = "{$user->email} has been removed.";
if ($request->expectsJson()) {
return response()->json([$message], 200);
}
session()->flash('success', $message);
return redirect()->route('users.index');
} | php | public function destroy(Request $request, $id)
{
// Fetch the user object
//$id = $this->decode($hash);
$user = $this->userRepository->findById($id);
// Check to be sure user cannot delete himself
if (Sentinel::getUser()->id == $user->id) {
$message = "You cannot remove yourself!";
if ($request->expectsJson()) {
return response()->json($message, 422);
}
session()->flash('error', $message);
return redirect()->route('users.index');
}
// Remove the user
$user->delete();
// All done
$message = "{$user->email} has been removed.";
if ($request->expectsJson()) {
return response()->json([$message], 200);
}
session()->flash('success', $message);
return redirect()->route('users.index');
} | [
"public",
"function",
"destroy",
"(",
"Request",
"$",
"request",
",",
"$",
"id",
")",
"{",
"// Fetch the user object",
"//$id = $this->decode($hash);",
"$",
"user",
"=",
"$",
"this",
"->",
"userRepository",
"->",
"findById",
"(",
"$",
"id",
")",
";",
"// Check to be sure user cannot delete himself",
"if",
"(",
"Sentinel",
"::",
"getUser",
"(",
")",
"->",
"id",
"==",
"$",
"user",
"->",
"id",
")",
"{",
"$",
"message",
"=",
"\"You cannot remove yourself!\"",
";",
"if",
"(",
"$",
"request",
"->",
"expectsJson",
"(",
")",
")",
"{",
"return",
"response",
"(",
")",
"->",
"json",
"(",
"$",
"message",
",",
"422",
")",
";",
"}",
"session",
"(",
")",
"->",
"flash",
"(",
"'error'",
",",
"$",
"message",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"route",
"(",
"'users.index'",
")",
";",
"}",
"// Remove the user",
"$",
"user",
"->",
"delete",
"(",
")",
";",
"// All done",
"$",
"message",
"=",
"\"{$user->email} has been removed.\"",
";",
"if",
"(",
"$",
"request",
"->",
"expectsJson",
"(",
")",
")",
"{",
"return",
"response",
"(",
")",
"->",
"json",
"(",
"[",
"$",
"message",
"]",
",",
"200",
")",
";",
"}",
"session",
"(",
")",
"->",
"flash",
"(",
"'success'",
",",
"$",
"message",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"route",
"(",
"'users.index'",
")",
";",
"}"
]
| Remove the specified user from storage.
@param string $hash
@return \Illuminate\Http\Response | [
"Remove",
"the",
"specified",
"user",
"from",
"storage",
"."
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/UserController.php#L206-L235 | train |
SRLabs/Centaur | src/Controllers/Auth/PasswordController.php | PasswordController.postRequest | public function postRequest(Request $request)
{
// Validate the form data
$result = $this->validate($request, [
'email' => 'required|email|max:255'
]);
// Fetch the user in question
$user = Sentinel::findUserByCredentials(['email' => $request->get('email')]);
// Only send them an email if they have a valid, inactive account
if ($user) {
// Generate a new code
$reminder = Reminder::create($user);
// Send the email
$code = $reminder->code;
$email = $user->email;
Mail::to($email)->queue(new CentaurPasswordReset($code));
}
$message = 'Instructions for changing your password will be sent to your email address if it is associated with a valid account.';
if ($request->expectsJson()) {
return response()->json(['message' => $message, 'code' => $code], 200);
}
Session::flash('success', $message);
return redirect()->route('dashboard');
} | php | public function postRequest(Request $request)
{
// Validate the form data
$result = $this->validate($request, [
'email' => 'required|email|max:255'
]);
// Fetch the user in question
$user = Sentinel::findUserByCredentials(['email' => $request->get('email')]);
// Only send them an email if they have a valid, inactive account
if ($user) {
// Generate a new code
$reminder = Reminder::create($user);
// Send the email
$code = $reminder->code;
$email = $user->email;
Mail::to($email)->queue(new CentaurPasswordReset($code));
}
$message = 'Instructions for changing your password will be sent to your email address if it is associated with a valid account.';
if ($request->expectsJson()) {
return response()->json(['message' => $message, 'code' => $code], 200);
}
Session::flash('success', $message);
return redirect()->route('dashboard');
} | [
"public",
"function",
"postRequest",
"(",
"Request",
"$",
"request",
")",
"{",
"// Validate the form data",
"$",
"result",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"request",
",",
"[",
"'email'",
"=>",
"'required|email|max:255'",
"]",
")",
";",
"// Fetch the user in question",
"$",
"user",
"=",
"Sentinel",
"::",
"findUserByCredentials",
"(",
"[",
"'email'",
"=>",
"$",
"request",
"->",
"get",
"(",
"'email'",
")",
"]",
")",
";",
"// Only send them an email if they have a valid, inactive account",
"if",
"(",
"$",
"user",
")",
"{",
"// Generate a new code",
"$",
"reminder",
"=",
"Reminder",
"::",
"create",
"(",
"$",
"user",
")",
";",
"// Send the email",
"$",
"code",
"=",
"$",
"reminder",
"->",
"code",
";",
"$",
"email",
"=",
"$",
"user",
"->",
"email",
";",
"Mail",
"::",
"to",
"(",
"$",
"email",
")",
"->",
"queue",
"(",
"new",
"CentaurPasswordReset",
"(",
"$",
"code",
")",
")",
";",
"}",
"$",
"message",
"=",
"'Instructions for changing your password will be sent to your email address if it is associated with a valid account.'",
";",
"if",
"(",
"$",
"request",
"->",
"expectsJson",
"(",
")",
")",
"{",
"return",
"response",
"(",
")",
"->",
"json",
"(",
"[",
"'message'",
"=>",
"$",
"message",
",",
"'code'",
"=>",
"$",
"code",
"]",
",",
"200",
")",
";",
"}",
"Session",
"::",
"flash",
"(",
"'success'",
",",
"$",
"message",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"route",
"(",
"'dashboard'",
")",
";",
"}"
]
| Send a password reset link
@return Response|Redirect | [
"Send",
"a",
"password",
"reset",
"link"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/PasswordController.php#L45-L74 | train |
SRLabs/Centaur | src/Controllers/Auth/PasswordController.php | PasswordController.getReset | public function getReset(Request $request, $code)
{
// Is this a valid code?
if (!$this->validatePasswordResetCode($code)) {
// This route will not be accessed via ajax;
// no need for a json response
Session::flash('error', 'Invalid or expired password reset code; please request a new link.');
return redirect()->route('dashboard');
}
return view('Centaur::auth.password')
->with('code', $code);
} | php | public function getReset(Request $request, $code)
{
// Is this a valid code?
if (!$this->validatePasswordResetCode($code)) {
// This route will not be accessed via ajax;
// no need for a json response
Session::flash('error', 'Invalid or expired password reset code; please request a new link.');
return redirect()->route('dashboard');
}
return view('Centaur::auth.password')
->with('code', $code);
} | [
"public",
"function",
"getReset",
"(",
"Request",
"$",
"request",
",",
"$",
"code",
")",
"{",
"// Is this a valid code?",
"if",
"(",
"!",
"$",
"this",
"->",
"validatePasswordResetCode",
"(",
"$",
"code",
")",
")",
"{",
"// This route will not be accessed via ajax;",
"// no need for a json response",
"Session",
"::",
"flash",
"(",
"'error'",
",",
"'Invalid or expired password reset code; please request a new link.'",
")",
";",
"return",
"redirect",
"(",
")",
"->",
"route",
"(",
"'dashboard'",
")",
";",
"}",
"return",
"view",
"(",
"'Centaur::auth.password'",
")",
"->",
"with",
"(",
"'code'",
",",
"$",
"code",
")",
";",
"}"
]
| Show the password reset form if the reset code is valid
@param Request $request
@param string $code
@return View | [
"Show",
"the",
"password",
"reset",
"form",
"if",
"the",
"reset",
"code",
"is",
"valid"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/PasswordController.php#L83-L95 | train |
SRLabs/Centaur | src/Controllers/Auth/PasswordController.php | PasswordController.postReset | public function postReset(Request $request, $code)
{
// Validate the form data
$result = $this->validate($request, [
'password' => 'required|confirmed|min:6',
]);
// Attempt the password reset
$result = $this->authManager->resetPassword($code, $request->get('password'));
if ($result->isFailure()) {
return $result->dispatch();
}
// Return the appropriate response
return $result->dispatch(route('auth.login.form'));
} | php | public function postReset(Request $request, $code)
{
// Validate the form data
$result = $this->validate($request, [
'password' => 'required|confirmed|min:6',
]);
// Attempt the password reset
$result = $this->authManager->resetPassword($code, $request->get('password'));
if ($result->isFailure()) {
return $result->dispatch();
}
// Return the appropriate response
return $result->dispatch(route('auth.login.form'));
} | [
"public",
"function",
"postReset",
"(",
"Request",
"$",
"request",
",",
"$",
"code",
")",
"{",
"// Validate the form data",
"$",
"result",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"request",
",",
"[",
"'password'",
"=>",
"'required|confirmed|min:6'",
",",
"]",
")",
";",
"// Attempt the password reset",
"$",
"result",
"=",
"$",
"this",
"->",
"authManager",
"->",
"resetPassword",
"(",
"$",
"code",
",",
"$",
"request",
"->",
"get",
"(",
"'password'",
")",
")",
";",
"if",
"(",
"$",
"result",
"->",
"isFailure",
"(",
")",
")",
"{",
"return",
"$",
"result",
"->",
"dispatch",
"(",
")",
";",
"}",
"// Return the appropriate response",
"return",
"$",
"result",
"->",
"dispatch",
"(",
"route",
"(",
"'auth.login.form'",
")",
")",
";",
"}"
]
| Process a password reset form submission
@param Request $request
@param string $code
@return Response|Redirect | [
"Process",
"a",
"password",
"reset",
"form",
"submission"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/PasswordController.php#L103-L119 | train |
SRLabs/Centaur | src/Replies/Reply.php | Reply.has | public function has($key)
{
if ($key == 'message') {
return !empty($this->message);
}
if ($key == 'exception') {
return !is_null($this->exception);
}
return array_key_exists($key, $this->payload);
} | php | public function has($key)
{
if ($key == 'message') {
return !empty($this->message);
}
if ($key == 'exception') {
return !is_null($this->exception);
}
return array_key_exists($key, $this->payload);
} | [
"public",
"function",
"has",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"key",
"==",
"'message'",
")",
"{",
"return",
"!",
"empty",
"(",
"$",
"this",
"->",
"message",
")",
";",
"}",
"if",
"(",
"$",
"key",
"==",
"'exception'",
")",
"{",
"return",
"!",
"is_null",
"(",
"$",
"this",
"->",
"exception",
")",
";",
"}",
"return",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"payload",
")",
";",
"}"
]
| Determine if a value exists within this object
@param string $key
@return void | [
"Determine",
"if",
"a",
"value",
"exists",
"within",
"this",
"object"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Replies/Reply.php#L127-L138 | train |
SRLabs/Centaur | src/Replies/Reply.php | Reply.remove | public function remove($key)
{
if ($key == 'message') {
$this->message = '';
}
if ($key == 'exception') {
$this->exception = null;
}
if (array_key_exists($key, $this->payload)) {
unset($this->payload[$key]);
}
} | php | public function remove($key)
{
if ($key == 'message') {
$this->message = '';
}
if ($key == 'exception') {
$this->exception = null;
}
if (array_key_exists($key, $this->payload)) {
unset($this->payload[$key]);
}
} | [
"public",
"function",
"remove",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"$",
"key",
"==",
"'message'",
")",
"{",
"$",
"this",
"->",
"message",
"=",
"''",
";",
"}",
"if",
"(",
"$",
"key",
"==",
"'exception'",
")",
"{",
"$",
"this",
"->",
"exception",
"=",
"null",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"payload",
")",
")",
"{",
"unset",
"(",
"$",
"this",
"->",
"payload",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}"
]
| Unset a payload array key => value
@param string $key
@return void | [
"Unset",
"a",
"payload",
"array",
"key",
"=",
">",
"value"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Replies/Reply.php#L145-L158 | train |
SRLabs/Centaur | src/Replies/Reply.php | Reply.toArray | public function toArray()
{
$dispatch = [];
$dispatch['status'] = $this->statusCode;
if ($this->hasMessage()) {
$dispatch['message'] = $this->message;
}
if ($this->hasPayload()) {
$dispatch = array_merge($dispatch, $this->payload);
}
return $dispatch;
} | php | public function toArray()
{
$dispatch = [];
$dispatch['status'] = $this->statusCode;
if ($this->hasMessage()) {
$dispatch['message'] = $this->message;
}
if ($this->hasPayload()) {
$dispatch = array_merge($dispatch, $this->payload);
}
return $dispatch;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"dispatch",
"=",
"[",
"]",
";",
"$",
"dispatch",
"[",
"'status'",
"]",
"=",
"$",
"this",
"->",
"statusCode",
";",
"if",
"(",
"$",
"this",
"->",
"hasMessage",
"(",
")",
")",
"{",
"$",
"dispatch",
"[",
"'message'",
"]",
"=",
"$",
"this",
"->",
"message",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"hasPayload",
"(",
")",
")",
"{",
"$",
"dispatch",
"=",
"array_merge",
"(",
"$",
"dispatch",
",",
"$",
"this",
"->",
"payload",
")",
";",
"}",
"return",
"$",
"dispatch",
";",
"}"
]
| Convert the dispatch object to an array
@return array | [
"Convert",
"the",
"dispatch",
"object",
"to",
"an",
"array"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Replies/Reply.php#L189-L203 | train |
SRLabs/Centaur | src/CentaurServiceProvider.php | CentaurServiceProvider.registerArtisanCommands | private function registerArtisanCommands()
{
// Register the Scaffold command
$this->app->singleton('centaur.scaffold', function ($app) {
return new CentaurScaffold(
$app->make('files')
);
});
$this->commands('centaur.scaffold');
// Register the Spruce command
$this->app->singleton('centaur.spruce', function ($app) {
return new CentaurSpruce(
$app->make('files')
);
});
$this->commands('centaur.spruce');
} | php | private function registerArtisanCommands()
{
// Register the Scaffold command
$this->app->singleton('centaur.scaffold', function ($app) {
return new CentaurScaffold(
$app->make('files')
);
});
$this->commands('centaur.scaffold');
// Register the Spruce command
$this->app->singleton('centaur.spruce', function ($app) {
return new CentaurSpruce(
$app->make('files')
);
});
$this->commands('centaur.spruce');
} | [
"private",
"function",
"registerArtisanCommands",
"(",
")",
"{",
"// Register the Scaffold command",
"$",
"this",
"->",
"app",
"->",
"singleton",
"(",
"'centaur.scaffold'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"new",
"CentaurScaffold",
"(",
"$",
"app",
"->",
"make",
"(",
"'files'",
")",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"commands",
"(",
"'centaur.scaffold'",
")",
";",
"// Register the Spruce command",
"$",
"this",
"->",
"app",
"->",
"singleton",
"(",
"'centaur.spruce'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"return",
"new",
"CentaurSpruce",
"(",
"$",
"app",
"->",
"make",
"(",
"'files'",
")",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"commands",
"(",
"'centaur.spruce'",
")",
";",
"}"
]
| Register the Artisan Commands | [
"Register",
"the",
"Artisan",
"Commands"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/CentaurServiceProvider.php#L84-L101 | train |
SRLabs/Centaur | src/Controllers/Auth/SessionController.php | SessionController.postLogin | public function postLogin(Request $request)
{
// Validate the Form Data
$result = $this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
// Assemble Login Credentials
$credentials = [
'email' => trim($request->get('email')),
'password' => $request->get('password'),
];
$remember = (bool)$request->get('remember', false);
// Attempt the Login
$result = $this->authManager->authenticate($credentials, $remember);
// Return the appropriate response
$path = session()->pull('url.intended', route('dashboard'));
return $result->dispatch($path);
} | php | public function postLogin(Request $request)
{
// Validate the Form Data
$result = $this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
// Assemble Login Credentials
$credentials = [
'email' => trim($request->get('email')),
'password' => $request->get('password'),
];
$remember = (bool)$request->get('remember', false);
// Attempt the Login
$result = $this->authManager->authenticate($credentials, $remember);
// Return the appropriate response
$path = session()->pull('url.intended', route('dashboard'));
return $result->dispatch($path);
} | [
"public",
"function",
"postLogin",
"(",
"Request",
"$",
"request",
")",
"{",
"// Validate the Form Data",
"$",
"result",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"request",
",",
"[",
"'email'",
"=>",
"'required'",
",",
"'password'",
"=>",
"'required'",
"]",
")",
";",
"// Assemble Login Credentials",
"$",
"credentials",
"=",
"[",
"'email'",
"=>",
"trim",
"(",
"$",
"request",
"->",
"get",
"(",
"'email'",
")",
")",
",",
"'password'",
"=>",
"$",
"request",
"->",
"get",
"(",
"'password'",
")",
",",
"]",
";",
"$",
"remember",
"=",
"(",
"bool",
")",
"$",
"request",
"->",
"get",
"(",
"'remember'",
",",
"false",
")",
";",
"// Attempt the Login",
"$",
"result",
"=",
"$",
"this",
"->",
"authManager",
"->",
"authenticate",
"(",
"$",
"credentials",
",",
"$",
"remember",
")",
";",
"// Return the appropriate response",
"$",
"path",
"=",
"session",
"(",
")",
"->",
"pull",
"(",
"'url.intended'",
",",
"route",
"(",
"'dashboard'",
")",
")",
";",
"return",
"$",
"result",
"->",
"dispatch",
"(",
"$",
"path",
")",
";",
"}"
]
| Handle a Login Request
@return Response|Redirect | [
"Handle",
"a",
"Login",
"Request"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/SessionController.php#L40-L61 | train |
SRLabs/Centaur | src/Controllers/Auth/SessionController.php | SessionController.getLogout | public function getLogout(Request $request)
{
// Terminate the user's current session. Passing true as the
// second parameter kills all of the user's active sessions.
$result = $this->authManager->logout(null, null);
// Return the appropriate response
return $result->dispatch(route('dashboard'));
} | php | public function getLogout(Request $request)
{
// Terminate the user's current session. Passing true as the
// second parameter kills all of the user's active sessions.
$result = $this->authManager->logout(null, null);
// Return the appropriate response
return $result->dispatch(route('dashboard'));
} | [
"public",
"function",
"getLogout",
"(",
"Request",
"$",
"request",
")",
"{",
"// Terminate the user's current session. Passing true as the",
"// second parameter kills all of the user's active sessions.",
"$",
"result",
"=",
"$",
"this",
"->",
"authManager",
"->",
"logout",
"(",
"null",
",",
"null",
")",
";",
"// Return the appropriate response",
"return",
"$",
"result",
"->",
"dispatch",
"(",
"route",
"(",
"'dashboard'",
")",
")",
";",
"}"
]
| Handle a Logout Request
@return Response|Redirect | [
"Handle",
"a",
"Logout",
"Request"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/SessionController.php#L67-L75 | train |
SRLabs/Centaur | src/Controllers/Auth/RegistrationController.php | RegistrationController.getActivate | public function getActivate(Request $request, $code)
{
// Attempt the registration
$result = $this->authManager->activate($code);
if ($result->isFailure()) {
// Normally an exception would trigger a redirect()->back() However,
// because they get here via direct link, back() will take them
// to "/"; I would prefer they be sent to the login page.
$result->setRedirectUrl(route('auth.login.form'));
return $result->dispatch();
}
// Ask the user to check their email for the activation link
$result->setMessage('Registration complete. You may now log in.');
// There is no need to send the payload data to the end user
$result->clearPayload();
// Return the appropriate response
return $result->dispatch(route('dashboard'));
} | php | public function getActivate(Request $request, $code)
{
// Attempt the registration
$result = $this->authManager->activate($code);
if ($result->isFailure()) {
// Normally an exception would trigger a redirect()->back() However,
// because they get here via direct link, back() will take them
// to "/"; I would prefer they be sent to the login page.
$result->setRedirectUrl(route('auth.login.form'));
return $result->dispatch();
}
// Ask the user to check their email for the activation link
$result->setMessage('Registration complete. You may now log in.');
// There is no need to send the payload data to the end user
$result->clearPayload();
// Return the appropriate response
return $result->dispatch(route('dashboard'));
} | [
"public",
"function",
"getActivate",
"(",
"Request",
"$",
"request",
",",
"$",
"code",
")",
"{",
"// Attempt the registration",
"$",
"result",
"=",
"$",
"this",
"->",
"authManager",
"->",
"activate",
"(",
"$",
"code",
")",
";",
"if",
"(",
"$",
"result",
"->",
"isFailure",
"(",
")",
")",
"{",
"// Normally an exception would trigger a redirect()->back() However,",
"// because they get here via direct link, back() will take them",
"// to \"/\"; I would prefer they be sent to the login page.",
"$",
"result",
"->",
"setRedirectUrl",
"(",
"route",
"(",
"'auth.login.form'",
")",
")",
";",
"return",
"$",
"result",
"->",
"dispatch",
"(",
")",
";",
"}",
"// Ask the user to check their email for the activation link",
"$",
"result",
"->",
"setMessage",
"(",
"'Registration complete. You may now log in.'",
")",
";",
"// There is no need to send the payload data to the end user",
"$",
"result",
"->",
"clearPayload",
"(",
")",
";",
"// Return the appropriate response",
"return",
"$",
"result",
"->",
"dispatch",
"(",
"route",
"(",
"'dashboard'",
")",
")",
";",
"}"
]
| Activate a user if they have provided the correct code
@param string $code
@return Response|Redirect | [
"Activate",
"a",
"user",
"if",
"they",
"have",
"provided",
"the",
"correct",
"code"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/RegistrationController.php#L87-L108 | train |
SRLabs/Centaur | src/Controllers/Auth/RegistrationController.php | RegistrationController.postResend | public function postResend(Request $request)
{
// Validate the form data
$result = $this->validate($request, [
'email' => 'required|email|max:255'
]);
// Fetch the user in question
$user = Sentinel::findUserByCredentials(['email' => $request->get('email')]);
// Only send them an email if they have a valid, inactive account
if (!Activation::completed($user)) {
// Generate a new code
$activation = Activation::create($user);
// Send the email
$code = $activation->getCode();
$email = $user->email;
Mail::to($email)->queue(new CentaurWelcomeEmail($email, $code, 'Account Activation Instructions'));
}
$message = 'New instructions will be sent to that email address if it is associated with a inactive account.';
if ($request->expectsJson()) {
return response()->json(['message' => $message], 200);
}
Session::flash('success', $message);
return redirect('/dashboard');
} | php | public function postResend(Request $request)
{
// Validate the form data
$result = $this->validate($request, [
'email' => 'required|email|max:255'
]);
// Fetch the user in question
$user = Sentinel::findUserByCredentials(['email' => $request->get('email')]);
// Only send them an email if they have a valid, inactive account
if (!Activation::completed($user)) {
// Generate a new code
$activation = Activation::create($user);
// Send the email
$code = $activation->getCode();
$email = $user->email;
Mail::to($email)->queue(new CentaurWelcomeEmail($email, $code, 'Account Activation Instructions'));
}
$message = 'New instructions will be sent to that email address if it is associated with a inactive account.';
if ($request->expectsJson()) {
return response()->json(['message' => $message], 200);
}
Session::flash('success', $message);
return redirect('/dashboard');
} | [
"public",
"function",
"postResend",
"(",
"Request",
"$",
"request",
")",
"{",
"// Validate the form data",
"$",
"result",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"request",
",",
"[",
"'email'",
"=>",
"'required|email|max:255'",
"]",
")",
";",
"// Fetch the user in question",
"$",
"user",
"=",
"Sentinel",
"::",
"findUserByCredentials",
"(",
"[",
"'email'",
"=>",
"$",
"request",
"->",
"get",
"(",
"'email'",
")",
"]",
")",
";",
"// Only send them an email if they have a valid, inactive account",
"if",
"(",
"!",
"Activation",
"::",
"completed",
"(",
"$",
"user",
")",
")",
"{",
"// Generate a new code",
"$",
"activation",
"=",
"Activation",
"::",
"create",
"(",
"$",
"user",
")",
";",
"// Send the email",
"$",
"code",
"=",
"$",
"activation",
"->",
"getCode",
"(",
")",
";",
"$",
"email",
"=",
"$",
"user",
"->",
"email",
";",
"Mail",
"::",
"to",
"(",
"$",
"email",
")",
"->",
"queue",
"(",
"new",
"CentaurWelcomeEmail",
"(",
"$",
"email",
",",
"$",
"code",
",",
"'Account Activation Instructions'",
")",
")",
";",
"}",
"$",
"message",
"=",
"'New instructions will be sent to that email address if it is associated with a inactive account.'",
";",
"if",
"(",
"$",
"request",
"->",
"expectsJson",
"(",
")",
")",
"{",
"return",
"response",
"(",
")",
"->",
"json",
"(",
"[",
"'message'",
"=>",
"$",
"message",
"]",
",",
"200",
")",
";",
"}",
"Session",
"::",
"flash",
"(",
"'success'",
",",
"$",
"message",
")",
";",
"return",
"redirect",
"(",
"'/dashboard'",
")",
";",
"}"
]
| Handle a resend activation request
@return Response|Redirect | [
"Handle",
"a",
"resend",
"activation",
"request"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/Controllers/Auth/RegistrationController.php#L123-L152 | train |
SRLabs/Centaur | src/AuthManager.php | AuthManager.authenticate | public function authenticate($credentials, $remember = false, $login = true)
{
try {
$user = $this->sentinel->authenticate($credentials, $remember, $login);
} catch (Exception $e) {
return $this->returnException($e);
}
if ($user) {
$message = request()->expectsJson() ?
$this->translate('session_initated', 'You have been authenticated.') : null;
return new SuccessReply($message);
}
$message = $this->translate('failed_authorization', 'Access denied due to invalid credentials.');
return new FailureReply($message);
} | php | public function authenticate($credentials, $remember = false, $login = true)
{
try {
$user = $this->sentinel->authenticate($credentials, $remember, $login);
} catch (Exception $e) {
return $this->returnException($e);
}
if ($user) {
$message = request()->expectsJson() ?
$this->translate('session_initated', 'You have been authenticated.') : null;
return new SuccessReply($message);
}
$message = $this->translate('failed_authorization', 'Access denied due to invalid credentials.');
return new FailureReply($message);
} | [
"public",
"function",
"authenticate",
"(",
"$",
"credentials",
",",
"$",
"remember",
"=",
"false",
",",
"$",
"login",
"=",
"true",
")",
"{",
"try",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"sentinel",
"->",
"authenticate",
"(",
"$",
"credentials",
",",
"$",
"remember",
",",
"$",
"login",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"returnException",
"(",
"$",
"e",
")",
";",
"}",
"if",
"(",
"$",
"user",
")",
"{",
"$",
"message",
"=",
"request",
"(",
")",
"->",
"expectsJson",
"(",
")",
"?",
"$",
"this",
"->",
"translate",
"(",
"'session_initated'",
",",
"'You have been authenticated.'",
")",
":",
"null",
";",
"return",
"new",
"SuccessReply",
"(",
"$",
"message",
")",
";",
"}",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"'failed_authorization'",
",",
"'Access denied due to invalid credentials.'",
")",
";",
"return",
"new",
"FailureReply",
"(",
"$",
"message",
")",
";",
"}"
]
| Attempt to authenticate a user
@param array $credentials
@param boolean $remember
@param boolean $login
@return Reply | [
"Attempt",
"to",
"authenticate",
"a",
"user"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/AuthManager.php#L38-L54 | train |
SRLabs/Centaur | src/AuthManager.php | AuthManager.logout | public function logout(UserInterface $user = null, $everywhere = false)
{
try {
$user = $this->sentinel->logout($user, $everywhere);
} catch (Exception $e) {
return $this->returnException($e);
}
if (!$this->sentinel->check()) {
$message = $this->translate('user_logout', 'You have been logged out');
return new SuccessReply($message);
}
$message = $this->translate('generic_problem', 'There was a problem. Please contact a site administrator.');
return new FailureReply($message);
} | php | public function logout(UserInterface $user = null, $everywhere = false)
{
try {
$user = $this->sentinel->logout($user, $everywhere);
} catch (Exception $e) {
return $this->returnException($e);
}
if (!$this->sentinel->check()) {
$message = $this->translate('user_logout', 'You have been logged out');
return new SuccessReply($message);
}
$message = $this->translate('generic_problem', 'There was a problem. Please contact a site administrator.');
return new FailureReply($message);
} | [
"public",
"function",
"logout",
"(",
"UserInterface",
"$",
"user",
"=",
"null",
",",
"$",
"everywhere",
"=",
"false",
")",
"{",
"try",
"{",
"$",
"user",
"=",
"$",
"this",
"->",
"sentinel",
"->",
"logout",
"(",
"$",
"user",
",",
"$",
"everywhere",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"returnException",
"(",
"$",
"e",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"sentinel",
"->",
"check",
"(",
")",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"'user_logout'",
",",
"'You have been logged out'",
")",
";",
"return",
"new",
"SuccessReply",
"(",
"$",
"message",
")",
";",
"}",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"'generic_problem'",
",",
"'There was a problem. Please contact a site administrator.'",
")",
";",
"return",
"new",
"FailureReply",
"(",
"$",
"message",
")",
";",
"}"
]
| Terminate a user's session. If no user is provided, the currently active
user will be signed out.
@param UserInterface|null $user
@param boolean $everywhere
@return Reply | [
"Terminate",
"a",
"user",
"s",
"session",
".",
"If",
"no",
"user",
"is",
"provided",
"the",
"currently",
"active",
"user",
"will",
"be",
"signed",
"out",
"."
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/AuthManager.php#L63-L78 | train |
SRLabs/Centaur | src/AuthManager.php | AuthManager.activate | public function activate($code)
{
try {
// Attempt to fetch the user via the activation code
$activation = $this->activations
->createModel()
->newQuery()
->where('code', $code)
->where('completed', false)
->where('created_at', '>', Carbon::now()->subSeconds(259200))
->first();
if (!$activation) {
$message = $this->translate("activation_problem", "Invalid or expired activation code.");
throw new InvalidArgumentException($message);
}
$user = $this->sentinel->findUserById($activation->user_id);
// Complete the user's activation
$this->activations->complete($user, $code);
// While we are here, lets remove any expired activations
$this->activations->removeExpired();
} catch (Exception $e) {
return $this->returnException($e);
}
if ($user) {
$message = $this->translate("activation_success", "Activation successful.");
return new SuccessReply($message);
}
$message = $this->translate('activation_failed', 'There was a problem activating your account.');
return new FailureReply($message);
} | php | public function activate($code)
{
try {
// Attempt to fetch the user via the activation code
$activation = $this->activations
->createModel()
->newQuery()
->where('code', $code)
->where('completed', false)
->where('created_at', '>', Carbon::now()->subSeconds(259200))
->first();
if (!$activation) {
$message = $this->translate("activation_problem", "Invalid or expired activation code.");
throw new InvalidArgumentException($message);
}
$user = $this->sentinel->findUserById($activation->user_id);
// Complete the user's activation
$this->activations->complete($user, $code);
// While we are here, lets remove any expired activations
$this->activations->removeExpired();
} catch (Exception $e) {
return $this->returnException($e);
}
if ($user) {
$message = $this->translate("activation_success", "Activation successful.");
return new SuccessReply($message);
}
$message = $this->translate('activation_failed', 'There was a problem activating your account.');
return new FailureReply($message);
} | [
"public",
"function",
"activate",
"(",
"$",
"code",
")",
"{",
"try",
"{",
"// Attempt to fetch the user via the activation code",
"$",
"activation",
"=",
"$",
"this",
"->",
"activations",
"->",
"createModel",
"(",
")",
"->",
"newQuery",
"(",
")",
"->",
"where",
"(",
"'code'",
",",
"$",
"code",
")",
"->",
"where",
"(",
"'completed'",
",",
"false",
")",
"->",
"where",
"(",
"'created_at'",
",",
"'>'",
",",
"Carbon",
"::",
"now",
"(",
")",
"->",
"subSeconds",
"(",
"259200",
")",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"$",
"activation",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"\"activation_problem\"",
",",
"\"Invalid or expired activation code.\"",
")",
";",
"throw",
"new",
"InvalidArgumentException",
"(",
"$",
"message",
")",
";",
"}",
"$",
"user",
"=",
"$",
"this",
"->",
"sentinel",
"->",
"findUserById",
"(",
"$",
"activation",
"->",
"user_id",
")",
";",
"// Complete the user's activation",
"$",
"this",
"->",
"activations",
"->",
"complete",
"(",
"$",
"user",
",",
"$",
"code",
")",
";",
"// While we are here, lets remove any expired activations",
"$",
"this",
"->",
"activations",
"->",
"removeExpired",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"returnException",
"(",
"$",
"e",
")",
";",
"}",
"if",
"(",
"$",
"user",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"\"activation_success\"",
",",
"\"Activation successful.\"",
")",
";",
"return",
"new",
"SuccessReply",
"(",
"$",
"message",
")",
";",
"}",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"'activation_failed'",
",",
"'There was a problem activating your account.'",
")",
";",
"return",
"new",
"FailureReply",
"(",
"$",
"message",
")",
";",
"}"
]
| Activate a user based on the provided activation code
@param string $code
@return Reply | [
"Activate",
"a",
"user",
"based",
"on",
"the",
"provided",
"activation",
"code"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/AuthManager.php#L117-L151 | train |
SRLabs/Centaur | src/AuthManager.php | AuthManager.resetPassword | public function resetPassword($code, $password)
{
try {
// Attempt to fetch the user via the activation code
$reminder = $this->reminders
->createModel()
->newQuery()
->where('code', $code)
->where('completed', false)
->where('created_at', '>', Carbon::now()->subSeconds(259200))
->first();
if (!$reminder) {
$message = $this->translate("password_reset_problem", "Invalid or expired password reset code; please request a new link.");
throw new InvalidArgumentException($message);
}
$user = $this->sentinel->findUserById($reminder->user_id);
// Complete the user's password reminder
$this->reminders->complete($user, $code, $password);
// While we are here, lets remove any expired reminders
$this->reminders->removeExpired();
} catch (Exception $e) {
return $this->returnException($e);
}
if ($user) {
$message = $this->translate("password_reset_success", "Password reset successful.");
return new SuccessReply($message);
}
$message = $this->translate('password_reset_failed', 'There was a problem reseting your password.');
return new FailureReply($message);
} | php | public function resetPassword($code, $password)
{
try {
// Attempt to fetch the user via the activation code
$reminder = $this->reminders
->createModel()
->newQuery()
->where('code', $code)
->where('completed', false)
->where('created_at', '>', Carbon::now()->subSeconds(259200))
->first();
if (!$reminder) {
$message = $this->translate("password_reset_problem", "Invalid or expired password reset code; please request a new link.");
throw new InvalidArgumentException($message);
}
$user = $this->sentinel->findUserById($reminder->user_id);
// Complete the user's password reminder
$this->reminders->complete($user, $code, $password);
// While we are here, lets remove any expired reminders
$this->reminders->removeExpired();
} catch (Exception $e) {
return $this->returnException($e);
}
if ($user) {
$message = $this->translate("password_reset_success", "Password reset successful.");
return new SuccessReply($message);
}
$message = $this->translate('password_reset_failed', 'There was a problem reseting your password.');
return new FailureReply($message);
} | [
"public",
"function",
"resetPassword",
"(",
"$",
"code",
",",
"$",
"password",
")",
"{",
"try",
"{",
"// Attempt to fetch the user via the activation code",
"$",
"reminder",
"=",
"$",
"this",
"->",
"reminders",
"->",
"createModel",
"(",
")",
"->",
"newQuery",
"(",
")",
"->",
"where",
"(",
"'code'",
",",
"$",
"code",
")",
"->",
"where",
"(",
"'completed'",
",",
"false",
")",
"->",
"where",
"(",
"'created_at'",
",",
"'>'",
",",
"Carbon",
"::",
"now",
"(",
")",
"->",
"subSeconds",
"(",
"259200",
")",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"$",
"reminder",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"\"password_reset_problem\"",
",",
"\"Invalid or expired password reset code; please request a new link.\"",
")",
";",
"throw",
"new",
"InvalidArgumentException",
"(",
"$",
"message",
")",
";",
"}",
"$",
"user",
"=",
"$",
"this",
"->",
"sentinel",
"->",
"findUserById",
"(",
"$",
"reminder",
"->",
"user_id",
")",
";",
"// Complete the user's password reminder",
"$",
"this",
"->",
"reminders",
"->",
"complete",
"(",
"$",
"user",
",",
"$",
"code",
",",
"$",
"password",
")",
";",
"// While we are here, lets remove any expired reminders",
"$",
"this",
"->",
"reminders",
"->",
"removeExpired",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"returnException",
"(",
"$",
"e",
")",
";",
"}",
"if",
"(",
"$",
"user",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"\"password_reset_success\"",
",",
"\"Password reset successful.\"",
")",
";",
"return",
"new",
"SuccessReply",
"(",
"$",
"message",
")",
";",
"}",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"'password_reset_failed'",
",",
"'There was a problem reseting your password.'",
")",
";",
"return",
"new",
"FailureReply",
"(",
"$",
"message",
")",
";",
"}"
]
| Attempt a password reset
@param string $code
@param string $password
@return Reply | [
"Attempt",
"a",
"password",
"reset"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/AuthManager.php#L159-L193 | train |
SRLabs/Centaur | src/AuthManager.php | AuthManager.returnException | protected function returnException(Exception $e)
{
$key = snake_case(class_basename($e));
$message = $this->translate($key, $e->getMessage());
return new ExceptionReply($message, [], $e);
} | php | protected function returnException(Exception $e)
{
$key = snake_case(class_basename($e));
$message = $this->translate($key, $e->getMessage());
return new ExceptionReply($message, [], $e);
} | [
"protected",
"function",
"returnException",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"key",
"=",
"snake_case",
"(",
"class_basename",
"(",
"$",
"e",
")",
")",
";",
"$",
"message",
"=",
"$",
"this",
"->",
"translate",
"(",
"$",
"key",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"return",
"new",
"ExceptionReply",
"(",
"$",
"message",
",",
"[",
"]",
",",
"$",
"e",
")",
";",
"}"
]
| Return any caught exceptions in a ExceptionDispatch DTO
@param Exception $e
@return ExcpetionDispatch | [
"Return",
"any",
"caught",
"exceptions",
"in",
"a",
"ExceptionDispatch",
"DTO"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/AuthManager.php#L200-L206 | train |
SRLabs/Centaur | src/AuthManager.php | AuthManager.translate | protected function translate($key, $message)
{
$key = 'centaur.' . $key;
if (Lang::has($key)) {
$message = trans($key);
}
return $message;
} | php | protected function translate($key, $message)
{
$key = 'centaur.' . $key;
if (Lang::has($key)) {
$message = trans($key);
}
return $message;
} | [
"protected",
"function",
"translate",
"(",
"$",
"key",
",",
"$",
"message",
")",
"{",
"$",
"key",
"=",
"'centaur.'",
".",
"$",
"key",
";",
"if",
"(",
"Lang",
"::",
"has",
"(",
"$",
"key",
")",
")",
"{",
"$",
"message",
"=",
"trans",
"(",
"$",
"key",
")",
";",
"}",
"return",
"$",
"message",
";",
"}"
]
| Helper method for facilitating string translation
@param string $key
@param string $message
@return string | [
"Helper",
"method",
"for",
"facilitating",
"string",
"translation"
]
| 261761166c63b49202edd5caf859139cdbb91af5 | https://github.com/SRLabs/Centaur/blob/261761166c63b49202edd5caf859139cdbb91af5/src/AuthManager.php#L214-L223 | train |
ivome/graphql-relay-php | src/Node/Plural.php | Plural.pluralIdentifyingRootField | public static function pluralIdentifyingRootField(array $config)
{
$inputArgs = [];
$argName = self::getArrayValue($config, 'argName');
$inputArgs[$argName] = [
'type' => Type::nonNull(
Type::listOf(
Type::nonNull(self::getArrayValue($config, 'inputType'))
)
)
];
return [
'description' => isset($config['description']) ? $config['description'] : null,
'type' => Type::listOf(self::getArrayValue($config, 'outputType')),
'args' => $inputArgs,
'resolve' => function ($obj, $args, $context, ResolveInfo $info) use ($argName, $config) {
$inputs = $args[$argName];
return array_map(function($input) use ($config, $context, $info) {
return call_user_func(self::getArrayValue($config, 'resolveSingleInput'), $input, $context, $info);
}, $inputs);
}
];
} | php | public static function pluralIdentifyingRootField(array $config)
{
$inputArgs = [];
$argName = self::getArrayValue($config, 'argName');
$inputArgs[$argName] = [
'type' => Type::nonNull(
Type::listOf(
Type::nonNull(self::getArrayValue($config, 'inputType'))
)
)
];
return [
'description' => isset($config['description']) ? $config['description'] : null,
'type' => Type::listOf(self::getArrayValue($config, 'outputType')),
'args' => $inputArgs,
'resolve' => function ($obj, $args, $context, ResolveInfo $info) use ($argName, $config) {
$inputs = $args[$argName];
return array_map(function($input) use ($config, $context, $info) {
return call_user_func(self::getArrayValue($config, 'resolveSingleInput'), $input, $context, $info);
}, $inputs);
}
];
} | [
"public",
"static",
"function",
"pluralIdentifyingRootField",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"inputArgs",
"=",
"[",
"]",
";",
"$",
"argName",
"=",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'argName'",
")",
";",
"$",
"inputArgs",
"[",
"$",
"argName",
"]",
"=",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"Type",
"::",
"listOf",
"(",
"Type",
"::",
"nonNull",
"(",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'inputType'",
")",
")",
")",
")",
"]",
";",
"return",
"[",
"'description'",
"=>",
"isset",
"(",
"$",
"config",
"[",
"'description'",
"]",
")",
"?",
"$",
"config",
"[",
"'description'",
"]",
":",
"null",
",",
"'type'",
"=>",
"Type",
"::",
"listOf",
"(",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'outputType'",
")",
")",
",",
"'args'",
"=>",
"$",
"inputArgs",
",",
"'resolve'",
"=>",
"function",
"(",
"$",
"obj",
",",
"$",
"args",
",",
"$",
"context",
",",
"ResolveInfo",
"$",
"info",
")",
"use",
"(",
"$",
"argName",
",",
"$",
"config",
")",
"{",
"$",
"inputs",
"=",
"$",
"args",
"[",
"$",
"argName",
"]",
";",
"return",
"array_map",
"(",
"function",
"(",
"$",
"input",
")",
"use",
"(",
"$",
"config",
",",
"$",
"context",
",",
"$",
"info",
")",
"{",
"return",
"call_user_func",
"(",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'resolveSingleInput'",
")",
",",
"$",
"input",
",",
"$",
"context",
",",
"$",
"info",
")",
";",
"}",
",",
"$",
"inputs",
")",
";",
"}",
"]",
";",
"}"
]
| Returns configuration for Plural identifying root field
type PluralIdentifyingRootFieldConfig = {
argName: string,
inputType: GraphQLInputType,
outputType: GraphQLOutputType,
resolveSingleInput: (input: any, info: GraphQLResolveInfo) => ?any,
description?: ?string,
};
@param array $config
@return array | [
"Returns",
"configuration",
"for",
"Plural",
"identifying",
"root",
"field"
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Node/Plural.php#L29-L52 | train |
ivome/graphql-relay-php | src/Connection/Connection.php | Connection.createConnectionType | public static function createConnectionType(array $config)
{
if (!array_key_exists('nodeType', $config)){
throw new \InvalidArgumentException('Connection config needs to have at least a node definition');
}
$nodeType = $config['nodeType'];
$name = array_key_exists('name', $config) ? $config['name'] : $nodeType->name;
$connectionFields = array_key_exists('connectionFields', $config) ? $config['connectionFields'] : [];
$edgeType = array_key_exists('edgeType', $config) ? $config['edgeType'] : null;
$connectionType = new ObjectType([
'name' => $name . 'Connection',
'description' => 'A connection to a list of items.',
'fields' => function() use ($edgeType, $connectionFields, $config) {
return array_merge([
'pageInfo' => [
'type' => Type::nonNull(self::pageInfoType()),
'description' => 'Information to aid in pagination.'
],
'edges' => [
'type' => Type::listOf($edgeType ?: self::createEdgeType($config)),
'description' => 'Information to aid in pagination'
]
], self::resolveMaybeThunk($connectionFields));
}
]);
return $connectionType;
} | php | public static function createConnectionType(array $config)
{
if (!array_key_exists('nodeType', $config)){
throw new \InvalidArgumentException('Connection config needs to have at least a node definition');
}
$nodeType = $config['nodeType'];
$name = array_key_exists('name', $config) ? $config['name'] : $nodeType->name;
$connectionFields = array_key_exists('connectionFields', $config) ? $config['connectionFields'] : [];
$edgeType = array_key_exists('edgeType', $config) ? $config['edgeType'] : null;
$connectionType = new ObjectType([
'name' => $name . 'Connection',
'description' => 'A connection to a list of items.',
'fields' => function() use ($edgeType, $connectionFields, $config) {
return array_merge([
'pageInfo' => [
'type' => Type::nonNull(self::pageInfoType()),
'description' => 'Information to aid in pagination.'
],
'edges' => [
'type' => Type::listOf($edgeType ?: self::createEdgeType($config)),
'description' => 'Information to aid in pagination'
]
], self::resolveMaybeThunk($connectionFields));
}
]);
return $connectionType;
} | [
"public",
"static",
"function",
"createConnectionType",
"(",
"array",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'nodeType'",
",",
"$",
"config",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Connection config needs to have at least a node definition'",
")",
";",
"}",
"$",
"nodeType",
"=",
"$",
"config",
"[",
"'nodeType'",
"]",
";",
"$",
"name",
"=",
"array_key_exists",
"(",
"'name'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'name'",
"]",
":",
"$",
"nodeType",
"->",
"name",
";",
"$",
"connectionFields",
"=",
"array_key_exists",
"(",
"'connectionFields'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'connectionFields'",
"]",
":",
"[",
"]",
";",
"$",
"edgeType",
"=",
"array_key_exists",
"(",
"'edgeType'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'edgeType'",
"]",
":",
"null",
";",
"$",
"connectionType",
"=",
"new",
"ObjectType",
"(",
"[",
"'name'",
"=>",
"$",
"name",
".",
"'Connection'",
",",
"'description'",
"=>",
"'A connection to a list of items.'",
",",
"'fields'",
"=>",
"function",
"(",
")",
"use",
"(",
"$",
"edgeType",
",",
"$",
"connectionFields",
",",
"$",
"config",
")",
"{",
"return",
"array_merge",
"(",
"[",
"'pageInfo'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"self",
"::",
"pageInfoType",
"(",
")",
")",
",",
"'description'",
"=>",
"'Information to aid in pagination.'",
"]",
",",
"'edges'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"listOf",
"(",
"$",
"edgeType",
"?",
":",
"self",
"::",
"createEdgeType",
"(",
"$",
"config",
")",
")",
",",
"'description'",
"=>",
"'Information to aid in pagination'",
"]",
"]",
",",
"self",
"::",
"resolveMaybeThunk",
"(",
"$",
"connectionFields",
")",
")",
";",
"}",
"]",
")",
";",
"return",
"$",
"connectionType",
";",
"}"
]
| Returns a GraphQLObjectType for a connection with the given name,
and whose nodes are of the specified type.
@return ObjectType | [
"Returns",
"a",
"GraphQLObjectType",
"for",
"a",
"connection",
"with",
"the",
"given",
"name",
"and",
"whose",
"nodes",
"are",
"of",
"the",
"specified",
"type",
"."
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Connection/Connection.php#L87-L115 | train |
ivome/graphql-relay-php | src/Connection/Connection.php | Connection.createEdgeType | public static function createEdgeType(array $config)
{
if (!array_key_exists('nodeType', $config)){
throw new \InvalidArgumentException('Edge config needs to have at least a node definition');
}
$nodeType = $config['nodeType'];
$name = array_key_exists('name', $config) ? $config['name'] : $nodeType->name;
$edgeFields = array_key_exists('edgeFields', $config) ? $config['edgeFields'] : [];
$resolveNode = array_key_exists('resolveNode', $config) ? $config['resolveNode'] : null;
$resolveCursor = array_key_exists('resolveCursor', $config) ? $config['resolveCursor'] : null;
$edgeType = new ObjectType(array_merge([
'name' => $name . 'Edge',
'description' => 'An edge in a connection',
'fields' => function() use ($nodeType, $resolveNode, $resolveCursor, $edgeFields) {
return array_merge([
'node' => [
'type' => $nodeType,
'resolve' => $resolveNode,
'description' => 'The item at the end of the edge'
],
'cursor' => [
'type' => Type::nonNull(Type::string()),
'resolve' => $resolveCursor,
'description' => 'A cursor for use in pagination'
]
], self::resolveMaybeThunk($edgeFields));
}
]));
return $edgeType;
} | php | public static function createEdgeType(array $config)
{
if (!array_key_exists('nodeType', $config)){
throw new \InvalidArgumentException('Edge config needs to have at least a node definition');
}
$nodeType = $config['nodeType'];
$name = array_key_exists('name', $config) ? $config['name'] : $nodeType->name;
$edgeFields = array_key_exists('edgeFields', $config) ? $config['edgeFields'] : [];
$resolveNode = array_key_exists('resolveNode', $config) ? $config['resolveNode'] : null;
$resolveCursor = array_key_exists('resolveCursor', $config) ? $config['resolveCursor'] : null;
$edgeType = new ObjectType(array_merge([
'name' => $name . 'Edge',
'description' => 'An edge in a connection',
'fields' => function() use ($nodeType, $resolveNode, $resolveCursor, $edgeFields) {
return array_merge([
'node' => [
'type' => $nodeType,
'resolve' => $resolveNode,
'description' => 'The item at the end of the edge'
],
'cursor' => [
'type' => Type::nonNull(Type::string()),
'resolve' => $resolveCursor,
'description' => 'A cursor for use in pagination'
]
], self::resolveMaybeThunk($edgeFields));
}
]));
return $edgeType;
} | [
"public",
"static",
"function",
"createEdgeType",
"(",
"array",
"$",
"config",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'nodeType'",
",",
"$",
"config",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Edge config needs to have at least a node definition'",
")",
";",
"}",
"$",
"nodeType",
"=",
"$",
"config",
"[",
"'nodeType'",
"]",
";",
"$",
"name",
"=",
"array_key_exists",
"(",
"'name'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'name'",
"]",
":",
"$",
"nodeType",
"->",
"name",
";",
"$",
"edgeFields",
"=",
"array_key_exists",
"(",
"'edgeFields'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'edgeFields'",
"]",
":",
"[",
"]",
";",
"$",
"resolveNode",
"=",
"array_key_exists",
"(",
"'resolveNode'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'resolveNode'",
"]",
":",
"null",
";",
"$",
"resolveCursor",
"=",
"array_key_exists",
"(",
"'resolveCursor'",
",",
"$",
"config",
")",
"?",
"$",
"config",
"[",
"'resolveCursor'",
"]",
":",
"null",
";",
"$",
"edgeType",
"=",
"new",
"ObjectType",
"(",
"array_merge",
"(",
"[",
"'name'",
"=>",
"$",
"name",
".",
"'Edge'",
",",
"'description'",
"=>",
"'An edge in a connection'",
",",
"'fields'",
"=>",
"function",
"(",
")",
"use",
"(",
"$",
"nodeType",
",",
"$",
"resolveNode",
",",
"$",
"resolveCursor",
",",
"$",
"edgeFields",
")",
"{",
"return",
"array_merge",
"(",
"[",
"'node'",
"=>",
"[",
"'type'",
"=>",
"$",
"nodeType",
",",
"'resolve'",
"=>",
"$",
"resolveNode",
",",
"'description'",
"=>",
"'The item at the end of the edge'",
"]",
",",
"'cursor'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"Type",
"::",
"string",
"(",
")",
")",
",",
"'resolve'",
"=>",
"$",
"resolveCursor",
",",
"'description'",
"=>",
"'A cursor for use in pagination'",
"]",
"]",
",",
"self",
"::",
"resolveMaybeThunk",
"(",
"$",
"edgeFields",
")",
")",
";",
"}",
"]",
")",
")",
";",
"return",
"$",
"edgeType",
";",
"}"
]
| Returns a GraphQLObjectType for an edge with the given name,
and whose nodes are of the specified type.
@param array $config
@return ObjectType | [
"Returns",
"a",
"GraphQLObjectType",
"for",
"an",
"edge",
"with",
"the",
"given",
"name",
"and",
"whose",
"nodes",
"are",
"of",
"the",
"specified",
"type",
"."
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Connection/Connection.php#L124-L155 | train |
ivome/graphql-relay-php | src/Connection/Connection.php | Connection.pageInfoType | public static function pageInfoType()
{
if (self::$pageInfoType === null){
self::$pageInfoType = new ObjectType([
'name' => 'PageInfo',
'description' => 'Information about pagination in a connection.',
'fields' => [
'hasNextPage' => [
'type' => Type::nonNull(Type::boolean()),
'description' => 'When paginating forwards, are there more items?'
],
'hasPreviousPage' => [
'type' => Type::nonNull(Type::boolean()),
'description' => 'When paginating backwards, are there more items?'
],
'startCursor' => [
'type' => Type::string(),
'description' => 'When paginating backwards, the cursor to continue.'
],
'endCursor' => [
'type' => Type::string(),
'description' => 'When paginating forwards, the cursor to continue.'
]
]
]);
}
return self::$pageInfoType;
} | php | public static function pageInfoType()
{
if (self::$pageInfoType === null){
self::$pageInfoType = new ObjectType([
'name' => 'PageInfo',
'description' => 'Information about pagination in a connection.',
'fields' => [
'hasNextPage' => [
'type' => Type::nonNull(Type::boolean()),
'description' => 'When paginating forwards, are there more items?'
],
'hasPreviousPage' => [
'type' => Type::nonNull(Type::boolean()),
'description' => 'When paginating backwards, are there more items?'
],
'startCursor' => [
'type' => Type::string(),
'description' => 'When paginating backwards, the cursor to continue.'
],
'endCursor' => [
'type' => Type::string(),
'description' => 'When paginating forwards, the cursor to continue.'
]
]
]);
}
return self::$pageInfoType;
} | [
"public",
"static",
"function",
"pageInfoType",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"pageInfoType",
"===",
"null",
")",
"{",
"self",
"::",
"$",
"pageInfoType",
"=",
"new",
"ObjectType",
"(",
"[",
"'name'",
"=>",
"'PageInfo'",
",",
"'description'",
"=>",
"'Information about pagination in a connection.'",
",",
"'fields'",
"=>",
"[",
"'hasNextPage'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"Type",
"::",
"boolean",
"(",
")",
")",
",",
"'description'",
"=>",
"'When paginating forwards, are there more items?'",
"]",
",",
"'hasPreviousPage'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"Type",
"::",
"boolean",
"(",
")",
")",
",",
"'description'",
"=>",
"'When paginating backwards, are there more items?'",
"]",
",",
"'startCursor'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"string",
"(",
")",
",",
"'description'",
"=>",
"'When paginating backwards, the cursor to continue.'",
"]",
",",
"'endCursor'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"string",
"(",
")",
",",
"'description'",
"=>",
"'When paginating forwards, the cursor to continue.'",
"]",
"]",
"]",
")",
";",
"}",
"return",
"self",
"::",
"$",
"pageInfoType",
";",
"}"
]
| The common page info type used by all connections.
@return ObjectType | [
"The",
"common",
"page",
"info",
"type",
"used",
"by",
"all",
"connections",
"."
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Connection/Connection.php#L162-L189 | train |
ivome/graphql-relay-php | src/Node/Node.php | Node.nodeDefinitions | public static function nodeDefinitions(callable $idFetcher, callable $typeResolver = null) {
$nodeInterface = new InterfaceType([
'name' => 'Node',
'description' => 'An object with an ID',
'fields' => [
'id' => [
'type' => Type::nonNull(Type::id()),
'description' => 'The id of the object',
]
],
'resolveType' => $typeResolver
]);
$nodeField = [
'name' => 'node',
'description' => 'Fetches an object given its ID',
'type' => $nodeInterface,
'args' => [
'id' => [
'type' => Type::nonNull(Type::id()),
'description' => 'The ID of an object'
]
],
'resolve' => function ($obj, $args, $context, $info) use ($idFetcher) {
return $idFetcher($args['id'], $context, $info);
}
];
return [
'nodeInterface' => $nodeInterface,
'nodeField' => $nodeField
];
} | php | public static function nodeDefinitions(callable $idFetcher, callable $typeResolver = null) {
$nodeInterface = new InterfaceType([
'name' => 'Node',
'description' => 'An object with an ID',
'fields' => [
'id' => [
'type' => Type::nonNull(Type::id()),
'description' => 'The id of the object',
]
],
'resolveType' => $typeResolver
]);
$nodeField = [
'name' => 'node',
'description' => 'Fetches an object given its ID',
'type' => $nodeInterface,
'args' => [
'id' => [
'type' => Type::nonNull(Type::id()),
'description' => 'The ID of an object'
]
],
'resolve' => function ($obj, $args, $context, $info) use ($idFetcher) {
return $idFetcher($args['id'], $context, $info);
}
];
return [
'nodeInterface' => $nodeInterface,
'nodeField' => $nodeField
];
} | [
"public",
"static",
"function",
"nodeDefinitions",
"(",
"callable",
"$",
"idFetcher",
",",
"callable",
"$",
"typeResolver",
"=",
"null",
")",
"{",
"$",
"nodeInterface",
"=",
"new",
"InterfaceType",
"(",
"[",
"'name'",
"=>",
"'Node'",
",",
"'description'",
"=>",
"'An object with an ID'",
",",
"'fields'",
"=>",
"[",
"'id'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"Type",
"::",
"id",
"(",
")",
")",
",",
"'description'",
"=>",
"'The id of the object'",
",",
"]",
"]",
",",
"'resolveType'",
"=>",
"$",
"typeResolver",
"]",
")",
";",
"$",
"nodeField",
"=",
"[",
"'name'",
"=>",
"'node'",
",",
"'description'",
"=>",
"'Fetches an object given its ID'",
",",
"'type'",
"=>",
"$",
"nodeInterface",
",",
"'args'",
"=>",
"[",
"'id'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"Type",
"::",
"id",
"(",
")",
")",
",",
"'description'",
"=>",
"'The ID of an object'",
"]",
"]",
",",
"'resolve'",
"=>",
"function",
"(",
"$",
"obj",
",",
"$",
"args",
",",
"$",
"context",
",",
"$",
"info",
")",
"use",
"(",
"$",
"idFetcher",
")",
"{",
"return",
"$",
"idFetcher",
"(",
"$",
"args",
"[",
"'id'",
"]",
",",
"$",
"context",
",",
"$",
"info",
")",
";",
"}",
"]",
";",
"return",
"[",
"'nodeInterface'",
"=>",
"$",
"nodeInterface",
",",
"'nodeField'",
"=>",
"$",
"nodeField",
"]",
";",
"}"
]
| Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a field config for a `node` root field.
If the typeResolver is omitted, object resolution on the interface will be
handled with the `isTypeOf` method on object types, as with any GraphQL
interface without a provided `resolveType` method.
@param callable $idFetcher
@param callable $typeResolver
@return array | [
"Given",
"a",
"function",
"to",
"map",
"from",
"an",
"ID",
"to",
"an",
"underlying",
"object",
"and",
"a",
"function",
"to",
"map",
"from",
"an",
"underlying",
"object",
"to",
"the",
"concrete",
"GraphQLObjectType",
"it",
"corresponds",
"to",
"constructs",
"a",
"Node",
"interface",
"that",
"objects",
"can",
"implement",
"and",
"a",
"field",
"config",
"for",
"a",
"node",
"root",
"field",
"."
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Node/Node.php#L31-L63 | train |
ivome/graphql-relay-php | src/Connection/ArrayConnection.php | ArrayConnection.cursorToOffset | public static function cursorToOffset($cursor)
{
$offset = substr(base64_decode($cursor), strlen(self::PREFIX));
if (is_numeric($offset)){
return intval($offset);
} else {
return null;
}
} | php | public static function cursorToOffset($cursor)
{
$offset = substr(base64_decode($cursor), strlen(self::PREFIX));
if (is_numeric($offset)){
return intval($offset);
} else {
return null;
}
} | [
"public",
"static",
"function",
"cursorToOffset",
"(",
"$",
"cursor",
")",
"{",
"$",
"offset",
"=",
"substr",
"(",
"base64_decode",
"(",
"$",
"cursor",
")",
",",
"strlen",
"(",
"self",
"::",
"PREFIX",
")",
")",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"offset",
")",
")",
"{",
"return",
"intval",
"(",
"$",
"offset",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
]
| Rederives the offset from the cursor string. | [
"Rederives",
"the",
"offset",
"from",
"the",
"cursor",
"string",
"."
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Connection/ArrayConnection.php#L26-L34 | train |
ivome/graphql-relay-php | src/Mutation/Mutation.php | Mutation.mutationWithClientMutationId | public static function mutationWithClientMutationId(array $config)
{
$name = self::getArrayValue($config, 'name');
$inputFields = self::getArrayValue($config, 'inputFields');
$outputFields = self::getArrayValue($config, 'outputFields');
$mutateAndGetPayload = self::getArrayValue($config, 'mutateAndGetPayload');
$augmentedInputFields = function() use ($inputFields) {
$inputFieldsResolved = self::resolveMaybeThunk($inputFields);
return array_merge($inputFieldsResolved !== null ? $inputFieldsResolved : [], [
'clientMutationId' => [
'type' => Type::string()
]
]);
};
$augmentedOutputFields = function () use ($outputFields) {
$outputFieldsResolved = self::resolveMaybeThunk($outputFields);
return array_merge($outputFieldsResolved !== null ? $outputFieldsResolved : [], [
'clientMutationId' => [
'type' => Type::string()
]
]);
};
$outputType = new ObjectType([
'name' => $name . 'Payload',
'fields' => $augmentedOutputFields
]);
$inputType = new InputObjectType([
'name' => $name . 'Input',
'fields' => $augmentedInputFields
]);
$definition = [
'type' => $outputType,
'args' => [
'input' => [
'type' => Type::nonNull($inputType)
]
],
'resolve' => function ($query, $args, $context, ResolveInfo $info) use ($mutateAndGetPayload) {
$payload = call_user_func($mutateAndGetPayload, $args['input'], $context, $info);
$payload['clientMutationId'] = isset($args['input']['clientMutationId']) ? $args['input']['clientMutationId'] : null;
return $payload;
}
];
if (array_key_exists('description', $config)){
$definition['description'] = $config['description'];
}
if (array_key_exists('deprecationReason', $config)){
$definition['deprecationReason'] = $config['deprecationReason'];
}
return $definition;
} | php | public static function mutationWithClientMutationId(array $config)
{
$name = self::getArrayValue($config, 'name');
$inputFields = self::getArrayValue($config, 'inputFields');
$outputFields = self::getArrayValue($config, 'outputFields');
$mutateAndGetPayload = self::getArrayValue($config, 'mutateAndGetPayload');
$augmentedInputFields = function() use ($inputFields) {
$inputFieldsResolved = self::resolveMaybeThunk($inputFields);
return array_merge($inputFieldsResolved !== null ? $inputFieldsResolved : [], [
'clientMutationId' => [
'type' => Type::string()
]
]);
};
$augmentedOutputFields = function () use ($outputFields) {
$outputFieldsResolved = self::resolveMaybeThunk($outputFields);
return array_merge($outputFieldsResolved !== null ? $outputFieldsResolved : [], [
'clientMutationId' => [
'type' => Type::string()
]
]);
};
$outputType = new ObjectType([
'name' => $name . 'Payload',
'fields' => $augmentedOutputFields
]);
$inputType = new InputObjectType([
'name' => $name . 'Input',
'fields' => $augmentedInputFields
]);
$definition = [
'type' => $outputType,
'args' => [
'input' => [
'type' => Type::nonNull($inputType)
]
],
'resolve' => function ($query, $args, $context, ResolveInfo $info) use ($mutateAndGetPayload) {
$payload = call_user_func($mutateAndGetPayload, $args['input'], $context, $info);
$payload['clientMutationId'] = isset($args['input']['clientMutationId']) ? $args['input']['clientMutationId'] : null;
return $payload;
}
];
if (array_key_exists('description', $config)){
$definition['description'] = $config['description'];
}
if (array_key_exists('deprecationReason', $config)){
$definition['deprecationReason'] = $config['deprecationReason'];
}
return $definition;
} | [
"public",
"static",
"function",
"mutationWithClientMutationId",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"name",
"=",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'name'",
")",
";",
"$",
"inputFields",
"=",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'inputFields'",
")",
";",
"$",
"outputFields",
"=",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'outputFields'",
")",
";",
"$",
"mutateAndGetPayload",
"=",
"self",
"::",
"getArrayValue",
"(",
"$",
"config",
",",
"'mutateAndGetPayload'",
")",
";",
"$",
"augmentedInputFields",
"=",
"function",
"(",
")",
"use",
"(",
"$",
"inputFields",
")",
"{",
"$",
"inputFieldsResolved",
"=",
"self",
"::",
"resolveMaybeThunk",
"(",
"$",
"inputFields",
")",
";",
"return",
"array_merge",
"(",
"$",
"inputFieldsResolved",
"!==",
"null",
"?",
"$",
"inputFieldsResolved",
":",
"[",
"]",
",",
"[",
"'clientMutationId'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"string",
"(",
")",
"]",
"]",
")",
";",
"}",
";",
"$",
"augmentedOutputFields",
"=",
"function",
"(",
")",
"use",
"(",
"$",
"outputFields",
")",
"{",
"$",
"outputFieldsResolved",
"=",
"self",
"::",
"resolveMaybeThunk",
"(",
"$",
"outputFields",
")",
";",
"return",
"array_merge",
"(",
"$",
"outputFieldsResolved",
"!==",
"null",
"?",
"$",
"outputFieldsResolved",
":",
"[",
"]",
",",
"[",
"'clientMutationId'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"string",
"(",
")",
"]",
"]",
")",
";",
"}",
";",
"$",
"outputType",
"=",
"new",
"ObjectType",
"(",
"[",
"'name'",
"=>",
"$",
"name",
".",
"'Payload'",
",",
"'fields'",
"=>",
"$",
"augmentedOutputFields",
"]",
")",
";",
"$",
"inputType",
"=",
"new",
"InputObjectType",
"(",
"[",
"'name'",
"=>",
"$",
"name",
".",
"'Input'",
",",
"'fields'",
"=>",
"$",
"augmentedInputFields",
"]",
")",
";",
"$",
"definition",
"=",
"[",
"'type'",
"=>",
"$",
"outputType",
",",
"'args'",
"=>",
"[",
"'input'",
"=>",
"[",
"'type'",
"=>",
"Type",
"::",
"nonNull",
"(",
"$",
"inputType",
")",
"]",
"]",
",",
"'resolve'",
"=>",
"function",
"(",
"$",
"query",
",",
"$",
"args",
",",
"$",
"context",
",",
"ResolveInfo",
"$",
"info",
")",
"use",
"(",
"$",
"mutateAndGetPayload",
")",
"{",
"$",
"payload",
"=",
"call_user_func",
"(",
"$",
"mutateAndGetPayload",
",",
"$",
"args",
"[",
"'input'",
"]",
",",
"$",
"context",
",",
"$",
"info",
")",
";",
"$",
"payload",
"[",
"'clientMutationId'",
"]",
"=",
"isset",
"(",
"$",
"args",
"[",
"'input'",
"]",
"[",
"'clientMutationId'",
"]",
")",
"?",
"$",
"args",
"[",
"'input'",
"]",
"[",
"'clientMutationId'",
"]",
":",
"null",
";",
"return",
"$",
"payload",
";",
"}",
"]",
";",
"if",
"(",
"array_key_exists",
"(",
"'description'",
",",
"$",
"config",
")",
")",
"{",
"$",
"definition",
"[",
"'description'",
"]",
"=",
"$",
"config",
"[",
"'description'",
"]",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'deprecationReason'",
",",
"$",
"config",
")",
")",
"{",
"$",
"definition",
"[",
"'deprecationReason'",
"]",
"=",
"$",
"config",
"[",
"'deprecationReason'",
"]",
";",
"}",
"return",
"$",
"definition",
";",
"}"
]
| Returns a GraphQLFieldConfig for the mutation described by the
provided MutationConfig.
A description of a mutation consumable by mutationWithClientMutationId
to create a GraphQLFieldConfig for that mutation.
The inputFields and outputFields should not include `clientMutationId`,
as this will be provided automatically.
An input object will be created containing the input fields, and an
object will be created containing the output fields.
mutateAndGetPayload will receieve an Object with a key for each
input field, and it should return an Object with a key for each
output field. It may return synchronously, or return a Promise.
type MutationConfig = {
name: string,
description?: string,
deprecationReason?: string,
inputFields: InputObjectConfigFieldMap,
outputFields: GraphQLFieldConfigMap,
mutateAndGetPayload: mutationFn,
} | [
"Returns",
"a",
"GraphQLFieldConfig",
"for",
"the",
"mutation",
"described",
"by",
"the",
"provided",
"MutationConfig",
"."
]
| b227c17e79564d147db2162329f5bdbe19192313 | https://github.com/ivome/graphql-relay-php/blob/b227c17e79564d147db2162329f5bdbe19192313/src/Mutation/Mutation.php#L43-L98 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/Product.php | Product.create | public function create($type, $set, $sku, $productData, $storeView = null)
{
return $this->__createAction('catalog_product.create', func_get_args());
} | php | public function create($type, $set, $sku, $productData, $storeView = null)
{
return $this->__createAction('catalog_product.create', func_get_args());
} | [
"public",
"function",
"create",
"(",
"$",
"type",
",",
"$",
"set",
",",
"$",
"sku",
",",
"$",
"productData",
",",
"$",
"storeView",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'catalog_product.create'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to create a new product and return ID of the created product.
@param string $type
@param string $set
@param string $sku
@param array $productData
@param string $storeView
@return ActionInterface | [
"Allows",
"you",
"to",
"create",
"a",
"new",
"product",
"and",
"return",
"ID",
"of",
"the",
"created",
"product",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/Product.php#L40-L43 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/Product.php | Product.setSpecialPrice | public function setSpecialPrice(
$productId,
$specialPrice,
$fromDate,
$toDate,
$storeView = null,
$productIdentifierType = null
) {
return $this->__createAction('catalog_product.setSpecialPrice', func_get_args());
} | php | public function setSpecialPrice(
$productId,
$specialPrice,
$fromDate,
$toDate,
$storeView = null,
$productIdentifierType = null
) {
return $this->__createAction('catalog_product.setSpecialPrice', func_get_args());
} | [
"public",
"function",
"setSpecialPrice",
"(",
"$",
"productId",
",",
"$",
"specialPrice",
",",
"$",
"fromDate",
",",
"$",
"toDate",
",",
"$",
"storeView",
"=",
"null",
",",
"$",
"productIdentifierType",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'catalog_product.setSpecialPrice'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to set the product special price.
@param string $productId
@param string $specialPrice
@param string $fromDate
@param string $toDate
@param string $storeView
@param string $productIdentifierType
@return ActionInterface | [
"Allows",
"you",
"to",
"set",
"the",
"product",
"special",
"price",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/Product.php#L139-L148 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/Product.php | Product.update | public function update($productId, $productData, $storeView = null, $identifierType = null)
{
return $this->__createAction('catalog_product.update', func_get_args());
} | php | public function update($productId, $productData, $storeView = null, $identifierType = null)
{
return $this->__createAction('catalog_product.update', func_get_args());
} | [
"public",
"function",
"update",
"(",
"$",
"productId",
",",
"$",
"productData",
",",
"$",
"storeView",
"=",
"null",
",",
"$",
"identifierType",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'catalog_product.update'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to update the required product.
Note that you should specify only those parameters which you want to be updated.
@param string $productId
@param array $productData
@param string $storeView
@param string $identifierType
@return ActionInterface | [
"Allows",
"you",
"to",
"update",
"the",
"required",
"product",
".",
"Note",
"that",
"you",
"should",
"specify",
"only",
"those",
"parameters",
"which",
"you",
"want",
"to",
"be",
"updated",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/Product.php#L161-L164 | train |
smalot/magento-client | src/Smalot/Magento/Order/OrderShipment.php | OrderShipment.addComment | public function addComment($shipmentIncrementId, $comment = null, $email = null, $includeInEmail = null)
{
return $this->__createAction('order_shipment.addComment', func_get_args());
} | php | public function addComment($shipmentIncrementId, $comment = null, $email = null, $includeInEmail = null)
{
return $this->__createAction('order_shipment.addComment', func_get_args());
} | [
"public",
"function",
"addComment",
"(",
"$",
"shipmentIncrementId",
",",
"$",
"comment",
"=",
"null",
",",
"$",
"email",
"=",
"null",
",",
"$",
"includeInEmail",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'order_shipment.addComment'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to add a new comment to the order shipment.
@param string $shipmentIncrementId
@param string $comment
@param string $email
@param string $includeInEmail
@return ActionInterface | [
"Allows",
"you",
"to",
"add",
"a",
"new",
"comment",
"to",
"the",
"order",
"shipment",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Order/OrderShipment.php#L39-L42 | train |
smalot/magento-client | src/Smalot/Magento/Order/OrderShipment.php | OrderShipment.create | public function create($orderIncrementId, $itemsQty = null, $comment = null, $email = null, $includeComment = null)
{
return $this->__createAction('order_shipment.create', func_get_args());
} | php | public function create($orderIncrementId, $itemsQty = null, $comment = null, $email = null, $includeComment = null)
{
return $this->__createAction('order_shipment.create', func_get_args());
} | [
"public",
"function",
"create",
"(",
"$",
"orderIncrementId",
",",
"$",
"itemsQty",
"=",
"null",
",",
"$",
"comment",
"=",
"null",
",",
"$",
"email",
"=",
"null",
",",
"$",
"includeComment",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'order_shipment.create'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to create a new shipment for an order.
@param string $orderIncrementId
@param string $itemsQty
@param string $comment
@param int $email
@param int $includeComment
@return ActionInterface | [
"Allows",
"you",
"to",
"create",
"a",
"new",
"shipment",
"for",
"an",
"order",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Order/OrderShipment.php#L70-L73 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/ProductDownloadableLink.php | ProductDownloadableLink.add | public function add($productId, $resource, $resourceType, $store = null, $identifierType = null)
{
return $this->__createAction('product_downloadable_link.add', func_get_args());
} | php | public function add($productId, $resource, $resourceType, $store = null, $identifierType = null)
{
return $this->__createAction('product_downloadable_link.add', func_get_args());
} | [
"public",
"function",
"add",
"(",
"$",
"productId",
",",
"$",
"resource",
",",
"$",
"resourceType",
",",
"$",
"store",
"=",
"null",
",",
"$",
"identifierType",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'product_downloadable_link.add'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to add a new link to a downloadable product.
@param string $productId
@param array $resource
@param string $resourceType
@param string $store
@param string $identifierType
@return ActionInterface | [
"Allows",
"you",
"to",
"add",
"a",
"new",
"link",
"to",
"a",
"downloadable",
"product",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/ProductDownloadableLink.php#L44-L47 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/ProductAttributeSet.php | ProductAttributeSet.attributeAdd | public function attributeAdd($attributeId, $attributeSetId, $attributeGroupId = null, $sortOrder = null)
{
return $this->__createAction('product_attribute_set.attributeAdd', func_get_args());
} | php | public function attributeAdd($attributeId, $attributeSetId, $attributeGroupId = null, $sortOrder = null)
{
return $this->__createAction('product_attribute_set.attributeAdd', func_get_args());
} | [
"public",
"function",
"attributeAdd",
"(",
"$",
"attributeId",
",",
"$",
"attributeSetId",
",",
"$",
"attributeGroupId",
"=",
"null",
",",
"$",
"sortOrder",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'product_attribute_set.attributeAdd'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to add an existing attribute to an attribute set.
@param string $attributeId
@param string $attributeSetId
@param string $attributeGroupId
@param string $sortOrder
@return ActionInterface | [
"Allows",
"you",
"to",
"add",
"an",
"existing",
"attribute",
"to",
"an",
"attribute",
"set",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/ProductAttributeSet.php#L39-L42 | train |
smalot/magento-client | src/Smalot/Magento/Order/OrderCreditMemo.php | OrderCreditMemo.addComment | public function addComment($creditmemoIncrementId, $comment = null, $notifyCustomer = null, $includeComment = null)
{
return $this->__createAction('order_creditmemo.addComment', func_get_args());
} | php | public function addComment($creditmemoIncrementId, $comment = null, $notifyCustomer = null, $includeComment = null)
{
return $this->__createAction('order_creditmemo.addComment', func_get_args());
} | [
"public",
"function",
"addComment",
"(",
"$",
"creditmemoIncrementId",
",",
"$",
"comment",
"=",
"null",
",",
"$",
"notifyCustomer",
"=",
"null",
",",
"$",
"includeComment",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'order_creditmemo.addComment'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to add a new comment to an existing credit memo.
Email notification can be sent to the user email.
@param string $creditmemoIncrementId
@param string $comment
@param string $notifyCustomer
@param string $includeComment
@return ActionInterface | [
"Allows",
"you",
"to",
"add",
"a",
"new",
"comment",
"to",
"an",
"existing",
"credit",
"memo",
".",
"Email",
"notification",
"can",
"be",
"sent",
"to",
"the",
"user",
"email",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Order/OrderCreditMemo.php#L40-L43 | train |
smalot/magento-client | src/Smalot/Magento/Order/OrderCreditMemo.php | OrderCreditMemo.create | public function create(
$orderIncrementId,
$creditmemoData = null,
$comment = null,
$notifyCustomer = null,
$includeComment = null,
$refundToStoreCreditAmount = null
) {
return $this->__createAction('order_creditmemo.create', func_get_args());
} | php | public function create(
$orderIncrementId,
$creditmemoData = null,
$comment = null,
$notifyCustomer = null,
$includeComment = null,
$refundToStoreCreditAmount = null
) {
return $this->__createAction('order_creditmemo.create', func_get_args());
} | [
"public",
"function",
"create",
"(",
"$",
"orderIncrementId",
",",
"$",
"creditmemoData",
"=",
"null",
",",
"$",
"comment",
"=",
"null",
",",
"$",
"notifyCustomer",
"=",
"null",
",",
"$",
"includeComment",
"=",
"null",
",",
"$",
"refundToStoreCreditAmount",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'order_creditmemo.create'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to create a new credit memo for the invoiced order.
Comments can be added and an email notification can be sent to the user email.
@param string $orderIncrementId
@param array $creditmemoData
@param string $comment
@param int $notifyCustomer
@param int $includeComment
@param string $refundToStoreCreditAmount
@return ActionInterface | [
"Allows",
"you",
"to",
"create",
"a",
"new",
"credit",
"memo",
"for",
"the",
"invoiced",
"order",
".",
"Comments",
"can",
"be",
"added",
"and",
"an",
"email",
"notification",
"can",
"be",
"sent",
"to",
"the",
"user",
"email",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Order/OrderCreditMemo.php#L70-L79 | train |
smalot/magento-client | src/Smalot/Magento/Order/OrderInvoice.php | OrderInvoice.addComment | public function addComment($invoiceIncrementId, $comment = null, $email = null, $includeComment = null)
{
return $this->__createAction('order_invoice.addComment', func_get_args());
} | php | public function addComment($invoiceIncrementId, $comment = null, $email = null, $includeComment = null)
{
return $this->__createAction('order_invoice.addComment', func_get_args());
} | [
"public",
"function",
"addComment",
"(",
"$",
"invoiceIncrementId",
",",
"$",
"comment",
"=",
"null",
",",
"$",
"email",
"=",
"null",
",",
"$",
"includeComment",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'order_invoice.addComment'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to add a new comment to the order invoice.
@param string $invoiceIncrementId
@param string $comment
@param int $email
@param int $includeComment
@return ActionInterface | [
"Allows",
"you",
"to",
"add",
"a",
"new",
"comment",
"to",
"the",
"order",
"invoice",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Order/OrderInvoice.php#L39-L42 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/Category.php | Category.assignProduct | public function assignProduct($categoryId, $productId, $position = null, $identifierType = null)
{
return $this->__createAction('catalog_category.assignProduct', func_get_args());
} | php | public function assignProduct($categoryId, $productId, $position = null, $identifierType = null)
{
return $this->__createAction('catalog_category.assignProduct', func_get_args());
} | [
"public",
"function",
"assignProduct",
"(",
"$",
"categoryId",
",",
"$",
"productId",
",",
"$",
"position",
"=",
"null",
",",
"$",
"identifierType",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'catalog_category.assignProduct'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Assign a product to the required category.
@param int $categoryId
@param string $productId
@param string $position
@param string $identifierType
@return ActionInterface | [
"Assign",
"a",
"product",
"to",
"the",
"required",
"category",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/Category.php#L51-L54 | train |
smalot/magento-client | src/Smalot/Magento/Catalog/ProductLink.php | ProductLink.update | public function update($type, $productId, $linkedProductId, $data, $identifierType = null)
{
return $this->__createAction('catalog_product_link.update', func_get_args());
} | php | public function update($type, $productId, $linkedProductId, $data, $identifierType = null)
{
return $this->__createAction('catalog_product_link.update', func_get_args());
} | [
"public",
"function",
"update",
"(",
"$",
"type",
",",
"$",
"productId",
",",
"$",
"linkedProductId",
",",
"$",
"data",
",",
"$",
"identifierType",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"__createAction",
"(",
"'catalog_product_link.update'",
",",
"func_get_args",
"(",
")",
")",
";",
"}"
]
| Allows you to update the product link.
@param string $type
@param string $productId
@param string $linkedProductId
@param array $data
@param string $identifierType
@return ActionInterface | [
"Allows",
"you",
"to",
"update",
"the",
"product",
"link",
"."
]
| 4630ae0502df8a7fd1e4aca41b92b050af62d113 | https://github.com/smalot/magento-client/blob/4630ae0502df8a7fd1e4aca41b92b050af62d113/src/Smalot/Magento/Catalog/ProductLink.php#L113-L116 | train |
vanilla/garden-cli | src/Table.php | Table.addCell | protected function addCell($text, $wrap = ['', '']) {
if ($this->currentRow === null) {
$this->row();
}
$i = count($this->currentRow);
$this->columnWidths[$i] = max(strlen($text), Cli::val($i, $this->columnWidths, 0)); // max column width
$this->currentRow[$i] = [$text, $wrap];
return $this;
} | php | protected function addCell($text, $wrap = ['', '']) {
if ($this->currentRow === null) {
$this->row();
}
$i = count($this->currentRow);
$this->columnWidths[$i] = max(strlen($text), Cli::val($i, $this->columnWidths, 0)); // max column width
$this->currentRow[$i] = [$text, $wrap];
return $this;
} | [
"protected",
"function",
"addCell",
"(",
"$",
"text",
",",
"$",
"wrap",
"=",
"[",
"''",
",",
"''",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"currentRow",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"row",
"(",
")",
";",
"}",
"$",
"i",
"=",
"count",
"(",
"$",
"this",
"->",
"currentRow",
")",
";",
"$",
"this",
"->",
"columnWidths",
"[",
"$",
"i",
"]",
"=",
"max",
"(",
"strlen",
"(",
"$",
"text",
")",
",",
"Cli",
"::",
"val",
"(",
"$",
"i",
",",
"$",
"this",
"->",
"columnWidths",
",",
"0",
")",
")",
";",
"// max column width",
"$",
"this",
"->",
"currentRow",
"[",
"$",
"i",
"]",
"=",
"[",
"$",
"text",
",",
"$",
"wrap",
"]",
";",
"return",
"$",
"this",
";",
"}"
]
| Add a cell to the table.
@param string $text The text of the cell.
@param array $wrap A two element array used to wrap the text in the cell.
@return $this | [
"Add",
"a",
"cell",
"to",
"the",
"table",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Table.php#L110-L120 | train |
vanilla/garden-cli | src/Table.php | Table.row | public function row() {
$this->rows[] = [];
$this->currentRow =& $this->rows[count($this->rows) - 1];
return $this;
} | php | public function row() {
$this->rows[] = [];
$this->currentRow =& $this->rows[count($this->rows) - 1];
return $this;
} | [
"public",
"function",
"row",
"(",
")",
"{",
"$",
"this",
"->",
"rows",
"[",
"]",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"currentRow",
"=",
"&",
"$",
"this",
"->",
"rows",
"[",
"count",
"(",
"$",
"this",
"->",
"rows",
")",
"-",
"1",
"]",
";",
"return",
"$",
"this",
";",
"}"
]
| Start a new row.
@return $this | [
"Start",
"a",
"new",
"row",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Table.php#L196-L200 | train |
vanilla/garden-cli | src/Table.php | Table.write | public function write() {
// Determine the width of the last column.
$columnWidths = array_sum($this->columnWidths);
$totalWidth = $this->indent + $columnWidths + $this->padding * (count($this->columnWidths) - 1);
$lastWidth = end($this->columnWidths) + $this->maxWidth - $totalWidth;
$lastWidth = max($lastWidth, 10); // min width of 10
$this->columnWidths[count($this->columnWidths) - 1] = $lastWidth;
// Loop through each row and write it.
foreach ($this->rows as $row) {
$rowLines = [];
$lineCount = 0;
// Split the cells into lines.
foreach ($row as $i => $cell) {
list($text,) = $cell;
$width = $this->columnWidths[$i];
$lines = Cli::breakLines($text, $width, $i < count($this->columnWidths) - 1);
$rowLines[] = $lines;
$lineCount = max($lineCount, count($lines));
}
// Write all of the lines.
for ($i = 0; $i < $lineCount; $i++) {
foreach ($rowLines as $j => $lines) {
$padding = $j === 0 ? $this->indent : $this->padding;
if (isset($lines[$i])) {
if ($this->formatOutput) {
if(isset($row[$j])) {
$wrap = $row[$j][1];
} else {
// if we're out of array, use the latest wraps
$wrap = $row[count($row)-1][1];
}
echo str_repeat(' ', $padding).$wrap[0].$lines[$i].$wrap[1];
} else {
echo str_repeat(' ', $padding).$lines[$i];
}
} elseif ($j < count($this->columnWidths) - 1) {
// This is an empty line. Write the spaces.
echo str_repeat(' ', $padding + $this->columnWidths[$j]);
}
}
echo PHP_EOL;
}
}
} | php | public function write() {
// Determine the width of the last column.
$columnWidths = array_sum($this->columnWidths);
$totalWidth = $this->indent + $columnWidths + $this->padding * (count($this->columnWidths) - 1);
$lastWidth = end($this->columnWidths) + $this->maxWidth - $totalWidth;
$lastWidth = max($lastWidth, 10); // min width of 10
$this->columnWidths[count($this->columnWidths) - 1] = $lastWidth;
// Loop through each row and write it.
foreach ($this->rows as $row) {
$rowLines = [];
$lineCount = 0;
// Split the cells into lines.
foreach ($row as $i => $cell) {
list($text,) = $cell;
$width = $this->columnWidths[$i];
$lines = Cli::breakLines($text, $width, $i < count($this->columnWidths) - 1);
$rowLines[] = $lines;
$lineCount = max($lineCount, count($lines));
}
// Write all of the lines.
for ($i = 0; $i < $lineCount; $i++) {
foreach ($rowLines as $j => $lines) {
$padding = $j === 0 ? $this->indent : $this->padding;
if (isset($lines[$i])) {
if ($this->formatOutput) {
if(isset($row[$j])) {
$wrap = $row[$j][1];
} else {
// if we're out of array, use the latest wraps
$wrap = $row[count($row)-1][1];
}
echo str_repeat(' ', $padding).$wrap[0].$lines[$i].$wrap[1];
} else {
echo str_repeat(' ', $padding).$lines[$i];
}
} elseif ($j < count($this->columnWidths) - 1) {
// This is an empty line. Write the spaces.
echo str_repeat(' ', $padding + $this->columnWidths[$j]);
}
}
echo PHP_EOL;
}
}
} | [
"public",
"function",
"write",
"(",
")",
"{",
"// Determine the width of the last column.",
"$",
"columnWidths",
"=",
"array_sum",
"(",
"$",
"this",
"->",
"columnWidths",
")",
";",
"$",
"totalWidth",
"=",
"$",
"this",
"->",
"indent",
"+",
"$",
"columnWidths",
"+",
"$",
"this",
"->",
"padding",
"*",
"(",
"count",
"(",
"$",
"this",
"->",
"columnWidths",
")",
"-",
"1",
")",
";",
"$",
"lastWidth",
"=",
"end",
"(",
"$",
"this",
"->",
"columnWidths",
")",
"+",
"$",
"this",
"->",
"maxWidth",
"-",
"$",
"totalWidth",
";",
"$",
"lastWidth",
"=",
"max",
"(",
"$",
"lastWidth",
",",
"10",
")",
";",
"// min width of 10",
"$",
"this",
"->",
"columnWidths",
"[",
"count",
"(",
"$",
"this",
"->",
"columnWidths",
")",
"-",
"1",
"]",
"=",
"$",
"lastWidth",
";",
"// Loop through each row and write it.",
"foreach",
"(",
"$",
"this",
"->",
"rows",
"as",
"$",
"row",
")",
"{",
"$",
"rowLines",
"=",
"[",
"]",
";",
"$",
"lineCount",
"=",
"0",
";",
"// Split the cells into lines.",
"foreach",
"(",
"$",
"row",
"as",
"$",
"i",
"=>",
"$",
"cell",
")",
"{",
"list",
"(",
"$",
"text",
",",
")",
"=",
"$",
"cell",
";",
"$",
"width",
"=",
"$",
"this",
"->",
"columnWidths",
"[",
"$",
"i",
"]",
";",
"$",
"lines",
"=",
"Cli",
"::",
"breakLines",
"(",
"$",
"text",
",",
"$",
"width",
",",
"$",
"i",
"<",
"count",
"(",
"$",
"this",
"->",
"columnWidths",
")",
"-",
"1",
")",
";",
"$",
"rowLines",
"[",
"]",
"=",
"$",
"lines",
";",
"$",
"lineCount",
"=",
"max",
"(",
"$",
"lineCount",
",",
"count",
"(",
"$",
"lines",
")",
")",
";",
"}",
"// Write all of the lines.",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"lineCount",
";",
"$",
"i",
"++",
")",
"{",
"foreach",
"(",
"$",
"rowLines",
"as",
"$",
"j",
"=>",
"$",
"lines",
")",
"{",
"$",
"padding",
"=",
"$",
"j",
"===",
"0",
"?",
"$",
"this",
"->",
"indent",
":",
"$",
"this",
"->",
"padding",
";",
"if",
"(",
"isset",
"(",
"$",
"lines",
"[",
"$",
"i",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"formatOutput",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"row",
"[",
"$",
"j",
"]",
")",
")",
"{",
"$",
"wrap",
"=",
"$",
"row",
"[",
"$",
"j",
"]",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"// if we're out of array, use the latest wraps",
"$",
"wrap",
"=",
"$",
"row",
"[",
"count",
"(",
"$",
"row",
")",
"-",
"1",
"]",
"[",
"1",
"]",
";",
"}",
"echo",
"str_repeat",
"(",
"' '",
",",
"$",
"padding",
")",
".",
"$",
"wrap",
"[",
"0",
"]",
".",
"$",
"lines",
"[",
"$",
"i",
"]",
".",
"$",
"wrap",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"echo",
"str_repeat",
"(",
"' '",
",",
"$",
"padding",
")",
".",
"$",
"lines",
"[",
"$",
"i",
"]",
";",
"}",
"}",
"elseif",
"(",
"$",
"j",
"<",
"count",
"(",
"$",
"this",
"->",
"columnWidths",
")",
"-",
"1",
")",
"{",
"// This is an empty line. Write the spaces.",
"echo",
"str_repeat",
"(",
"' '",
",",
"$",
"padding",
"+",
"$",
"this",
"->",
"columnWidths",
"[",
"$",
"j",
"]",
")",
";",
"}",
"}",
"echo",
"PHP_EOL",
";",
"}",
"}",
"}"
]
| Writes the final table. | [
"Writes",
"the",
"final",
"table",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Table.php#L205-L255 | train |
vanilla/garden-cli | src/Cli.php | Cli.breakLines | public static function breakLines($text, $width, $addSpaces = true) {
$rawLines = explode("\n", $text);
$lines = [];
foreach ($rawLines as $line) {
// Check to see if the line needs to be broken.
$sublines = static::breakString($line, $width, $addSpaces);
$lines = array_merge($lines, $sublines);
}
return $lines;
} | php | public static function breakLines($text, $width, $addSpaces = true) {
$rawLines = explode("\n", $text);
$lines = [];
foreach ($rawLines as $line) {
// Check to see if the line needs to be broken.
$sublines = static::breakString($line, $width, $addSpaces);
$lines = array_merge($lines, $sublines);
}
return $lines;
} | [
"public",
"static",
"function",
"breakLines",
"(",
"$",
"text",
",",
"$",
"width",
",",
"$",
"addSpaces",
"=",
"true",
")",
"{",
"$",
"rawLines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"text",
")",
";",
"$",
"lines",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"rawLines",
"as",
"$",
"line",
")",
"{",
"// Check to see if the line needs to be broken.",
"$",
"sublines",
"=",
"static",
"::",
"breakString",
"(",
"$",
"line",
",",
"$",
"width",
",",
"$",
"addSpaces",
")",
";",
"$",
"lines",
"=",
"array_merge",
"(",
"$",
"lines",
",",
"$",
"sublines",
")",
";",
"}",
"return",
"$",
"lines",
";",
"}"
]
| Breaks a cell into several lines according to a given width.
@param string $text The text of the cell.
@param int $width The width of the cell.
@param bool $addSpaces Whether or not to right-pad the cell with spaces.
@return array Returns an array of strings representing the lines in the cell. | [
"Breaks",
"a",
"cell",
"into",
"several",
"lines",
"according",
"to",
"a",
"given",
"width",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L141-L152 | train |
vanilla/garden-cli | src/Cli.php | Cli.breakString | protected static function breakString($line, $width, $addSpaces = true) {
$words = explode(' ', $line);
$result = [];
$line = '';
foreach ($words as $word) {
$candidate = trim($line.' '.$word);
// Check for a new line.
if (strlen($candidate) > $width) {
if ($line === '') {
// The word is longer than a line.
if ($addSpaces) {
$result[] = substr($candidate, 0, $width);
} else {
$result[] = $candidate;
}
} else {
if ($addSpaces) {
$line .= str_repeat(' ', $width - strlen($line));
}
// Start a new line.
$result[] = $line;
$line = $word;
}
} else {
$line = $candidate;
}
}
// Add the remaining line.
if ($line) {
if ($addSpaces) {
$line .= str_repeat(' ', $width - strlen($line));
}
// Start a new line.
$result[] = $line;
}
return $result;
} | php | protected static function breakString($line, $width, $addSpaces = true) {
$words = explode(' ', $line);
$result = [];
$line = '';
foreach ($words as $word) {
$candidate = trim($line.' '.$word);
// Check for a new line.
if (strlen($candidate) > $width) {
if ($line === '') {
// The word is longer than a line.
if ($addSpaces) {
$result[] = substr($candidate, 0, $width);
} else {
$result[] = $candidate;
}
} else {
if ($addSpaces) {
$line .= str_repeat(' ', $width - strlen($line));
}
// Start a new line.
$result[] = $line;
$line = $word;
}
} else {
$line = $candidate;
}
}
// Add the remaining line.
if ($line) {
if ($addSpaces) {
$line .= str_repeat(' ', $width - strlen($line));
}
// Start a new line.
$result[] = $line;
}
return $result;
} | [
"protected",
"static",
"function",
"breakString",
"(",
"$",
"line",
",",
"$",
"width",
",",
"$",
"addSpaces",
"=",
"true",
")",
"{",
"$",
"words",
"=",
"explode",
"(",
"' '",
",",
"$",
"line",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"line",
"=",
"''",
";",
"foreach",
"(",
"$",
"words",
"as",
"$",
"word",
")",
"{",
"$",
"candidate",
"=",
"trim",
"(",
"$",
"line",
".",
"' '",
".",
"$",
"word",
")",
";",
"// Check for a new line.",
"if",
"(",
"strlen",
"(",
"$",
"candidate",
")",
">",
"$",
"width",
")",
"{",
"if",
"(",
"$",
"line",
"===",
"''",
")",
"{",
"// The word is longer than a line.",
"if",
"(",
"$",
"addSpaces",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"substr",
"(",
"$",
"candidate",
",",
"0",
",",
"$",
"width",
")",
";",
"}",
"else",
"{",
"$",
"result",
"[",
"]",
"=",
"$",
"candidate",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"addSpaces",
")",
"{",
"$",
"line",
".=",
"str_repeat",
"(",
"' '",
",",
"$",
"width",
"-",
"strlen",
"(",
"$",
"line",
")",
")",
";",
"}",
"// Start a new line.",
"$",
"result",
"[",
"]",
"=",
"$",
"line",
";",
"$",
"line",
"=",
"$",
"word",
";",
"}",
"}",
"else",
"{",
"$",
"line",
"=",
"$",
"candidate",
";",
"}",
"}",
"// Add the remaining line.",
"if",
"(",
"$",
"line",
")",
"{",
"if",
"(",
"$",
"addSpaces",
")",
"{",
"$",
"line",
".=",
"str_repeat",
"(",
"' '",
",",
"$",
"width",
"-",
"strlen",
"(",
"$",
"line",
")",
")",
";",
"}",
"// Start a new line.",
"$",
"result",
"[",
"]",
"=",
"$",
"line",
";",
"}",
"return",
"$",
"result",
";",
"}"
]
| Breaks a line of text according to a given width.
@param string $line The text of the line.
@param int $width The width of the cell.
@param bool $addSpaces Whether or not to right pad the lines with spaces.
@return array Returns an array of lines, broken on word boundaries. | [
"Breaks",
"a",
"line",
"of",
"text",
"according",
"to",
"a",
"given",
"width",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L162-L204 | train |
vanilla/garden-cli | src/Cli.php | Cli.hasCommand | public function hasCommand($name = '') {
if ($name) {
return array_key_exists($name, $this->commandSchemas);
} else {
foreach ($this->commandSchemas as $pattern => $opts) {
if (strpos($pattern, '*') === false) {
return true;
}
}
return false;
}
} | php | public function hasCommand($name = '') {
if ($name) {
return array_key_exists($name, $this->commandSchemas);
} else {
foreach ($this->commandSchemas as $pattern => $opts) {
if (strpos($pattern, '*') === false) {
return true;
}
}
return false;
}
} | [
"public",
"function",
"hasCommand",
"(",
"$",
"name",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"name",
")",
"{",
"return",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"commandSchemas",
")",
";",
"}",
"else",
"{",
"foreach",
"(",
"$",
"this",
"->",
"commandSchemas",
"as",
"$",
"pattern",
"=>",
"$",
"opts",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"pattern",
",",
"'*'",
")",
"===",
"false",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"}"
]
| Determines whether or not the schema has a command.
@param string $name Check for the specific command name.
@return bool Returns true if the schema has a command. | [
"Determines",
"whether",
"or",
"not",
"the",
"schema",
"has",
"a",
"command",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L222-L233 | train |
vanilla/garden-cli | src/Cli.php | Cli.hasOptions | public function hasOptions($command = '') {
if ($command) {
$def = $this->getSchema($command);
return $this->hasOptionsDef($def);
} else {
foreach ($this->commandSchemas as $pattern => $def) {
if ($this->hasOptionsDef($def)) {
return true;
}
}
}
return false;
} | php | public function hasOptions($command = '') {
if ($command) {
$def = $this->getSchema($command);
return $this->hasOptionsDef($def);
} else {
foreach ($this->commandSchemas as $pattern => $def) {
if ($this->hasOptionsDef($def)) {
return true;
}
}
}
return false;
} | [
"public",
"function",
"hasOptions",
"(",
"$",
"command",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"command",
")",
"{",
"$",
"def",
"=",
"$",
"this",
"->",
"getSchema",
"(",
"$",
"command",
")",
";",
"return",
"$",
"this",
"->",
"hasOptionsDef",
"(",
"$",
"def",
")",
";",
"}",
"else",
"{",
"foreach",
"(",
"$",
"this",
"->",
"commandSchemas",
"as",
"$",
"pattern",
"=>",
"$",
"def",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasOptionsDef",
"(",
"$",
"def",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
]
| Determines whether a command has options.
@param string $command The name of the command or an empty string for any command.
@return bool Returns true if the command has options. False otherwise. | [
"Determines",
"whether",
"a",
"command",
"has",
"options",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L241-L253 | train |
vanilla/garden-cli | src/Cli.php | Cli.hasOptionsDef | protected function hasOptionsDef($commandDef) {
return count($commandDef) > 1 || (count($commandDef) > 0 && !isset($commandDef[Cli::META]));
} | php | protected function hasOptionsDef($commandDef) {
return count($commandDef) > 1 || (count($commandDef) > 0 && !isset($commandDef[Cli::META]));
} | [
"protected",
"function",
"hasOptionsDef",
"(",
"$",
"commandDef",
")",
"{",
"return",
"count",
"(",
"$",
"commandDef",
")",
">",
"1",
"||",
"(",
"count",
"(",
"$",
"commandDef",
")",
">",
"0",
"&&",
"!",
"isset",
"(",
"$",
"commandDef",
"[",
"Cli",
"::",
"META",
"]",
")",
")",
";",
"}"
]
| Determines whether or not a command definition has options.
@param array $commandDef The command definition as returned from {@link Cli::getSchema()}.
@return bool Returns true if the command def has options or false otherwise. | [
"Determines",
"whether",
"or",
"not",
"a",
"command",
"definition",
"has",
"options",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L261-L263 | train |
vanilla/garden-cli | src/Cli.php | Cli.hasArgs | public function hasArgs($command = '') {
$args = null;
if ($command) {
// Check to see if the specific command has args.
$def = $this->getSchema($command);
if (isset($def[Cli::META][Cli::ARGS])) {
$args = $def[Cli::META][Cli::ARGS];
}
} else {
foreach ($this->commandSchemas as $pattern => $def) {
if (isset($def[Cli::META][Cli::ARGS])) {
$args = $def[Cli::META][Cli::ARGS];
}
}
if (!empty($args)) {
return 1;
}
}
if (!$args || empty($args)) {
return 0;
}
foreach ($args as $arg) {
if (!Cli::val('required', $arg)) {
return 1;
}
}
return 2;
} | php | public function hasArgs($command = '') {
$args = null;
if ($command) {
// Check to see if the specific command has args.
$def = $this->getSchema($command);
if (isset($def[Cli::META][Cli::ARGS])) {
$args = $def[Cli::META][Cli::ARGS];
}
} else {
foreach ($this->commandSchemas as $pattern => $def) {
if (isset($def[Cli::META][Cli::ARGS])) {
$args = $def[Cli::META][Cli::ARGS];
}
}
if (!empty($args)) {
return 1;
}
}
if (!$args || empty($args)) {
return 0;
}
foreach ($args as $arg) {
if (!Cli::val('required', $arg)) {
return 1;
}
}
return 2;
} | [
"public",
"function",
"hasArgs",
"(",
"$",
"command",
"=",
"''",
")",
"{",
"$",
"args",
"=",
"null",
";",
"if",
"(",
"$",
"command",
")",
"{",
"// Check to see if the specific command has args.",
"$",
"def",
"=",
"$",
"this",
"->",
"getSchema",
"(",
"$",
"command",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"def",
"[",
"Cli",
"::",
"META",
"]",
"[",
"Cli",
"::",
"ARGS",
"]",
")",
")",
"{",
"$",
"args",
"=",
"$",
"def",
"[",
"Cli",
"::",
"META",
"]",
"[",
"Cli",
"::",
"ARGS",
"]",
";",
"}",
"}",
"else",
"{",
"foreach",
"(",
"$",
"this",
"->",
"commandSchemas",
"as",
"$",
"pattern",
"=>",
"$",
"def",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"def",
"[",
"Cli",
"::",
"META",
"]",
"[",
"Cli",
"::",
"ARGS",
"]",
")",
")",
"{",
"$",
"args",
"=",
"$",
"def",
"[",
"Cli",
"::",
"META",
"]",
"[",
"Cli",
"::",
"ARGS",
"]",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
")",
")",
"{",
"return",
"1",
";",
"}",
"}",
"if",
"(",
"!",
"$",
"args",
"||",
"empty",
"(",
"$",
"args",
")",
")",
"{",
"return",
"0",
";",
"}",
"foreach",
"(",
"$",
"args",
"as",
"$",
"arg",
")",
"{",
"if",
"(",
"!",
"Cli",
"::",
"val",
"(",
"'required'",
",",
"$",
"arg",
")",
")",
"{",
"return",
"1",
";",
"}",
"}",
"return",
"2",
";",
"}"
]
| Determines whether or not a command has args.
@param string $command The command name to check.
@return int Returns one of the following.
- 0: The command has no args.
- 1: The command has optional args.
- 2: The command has required args. | [
"Determines",
"whether",
"or",
"not",
"a",
"command",
"has",
"args",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L274-L304 | train |
vanilla/garden-cli | src/Cli.php | Cli.parse | public function parse($argv = null, $exit = true) {
$formatOutputBak = $this->formatOutput;
// Only format commands if we are exiting.
if (!$exit) {
$this->formatOutput = false;
}
if (!$exit) {
ob_start();
}
$args = $this->parseRaw($argv);
$hasCommand = $this->hasCommand();
if ($hasCommand && !$args->getCommand()) {
// If no command is given then write a list of commands.
$this->writeUsage($args);
$this->writeCommands();
$result = null;
} elseif ($args->getOpt('help') || $args->getOpt('?')) {
// Write the help.
$this->writeUsage($args);
$this->writeHelp($args->getCommand());
$result = null;
} else {
// Validate the arguments against the schema.
$validArgs = $this->validate($args);
$result = $validArgs;
}
if (!$exit) {
$this->formatOutput = $formatOutputBak;
$output = ob_get_clean();
if ($result === null) {
throw new \Exception(trim($output));
}
} elseif ($result === null) {
exit();
}
return $result;
} | php | public function parse($argv = null, $exit = true) {
$formatOutputBak = $this->formatOutput;
// Only format commands if we are exiting.
if (!$exit) {
$this->formatOutput = false;
}
if (!$exit) {
ob_start();
}
$args = $this->parseRaw($argv);
$hasCommand = $this->hasCommand();
if ($hasCommand && !$args->getCommand()) {
// If no command is given then write a list of commands.
$this->writeUsage($args);
$this->writeCommands();
$result = null;
} elseif ($args->getOpt('help') || $args->getOpt('?')) {
// Write the help.
$this->writeUsage($args);
$this->writeHelp($args->getCommand());
$result = null;
} else {
// Validate the arguments against the schema.
$validArgs = $this->validate($args);
$result = $validArgs;
}
if (!$exit) {
$this->formatOutput = $formatOutputBak;
$output = ob_get_clean();
if ($result === null) {
throw new \Exception(trim($output));
}
} elseif ($result === null) {
exit();
}
return $result;
} | [
"public",
"function",
"parse",
"(",
"$",
"argv",
"=",
"null",
",",
"$",
"exit",
"=",
"true",
")",
"{",
"$",
"formatOutputBak",
"=",
"$",
"this",
"->",
"formatOutput",
";",
"// Only format commands if we are exiting.",
"if",
"(",
"!",
"$",
"exit",
")",
"{",
"$",
"this",
"->",
"formatOutput",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"exit",
")",
"{",
"ob_start",
"(",
")",
";",
"}",
"$",
"args",
"=",
"$",
"this",
"->",
"parseRaw",
"(",
"$",
"argv",
")",
";",
"$",
"hasCommand",
"=",
"$",
"this",
"->",
"hasCommand",
"(",
")",
";",
"if",
"(",
"$",
"hasCommand",
"&&",
"!",
"$",
"args",
"->",
"getCommand",
"(",
")",
")",
"{",
"// If no command is given then write a list of commands.",
"$",
"this",
"->",
"writeUsage",
"(",
"$",
"args",
")",
";",
"$",
"this",
"->",
"writeCommands",
"(",
")",
";",
"$",
"result",
"=",
"null",
";",
"}",
"elseif",
"(",
"$",
"args",
"->",
"getOpt",
"(",
"'help'",
")",
"||",
"$",
"args",
"->",
"getOpt",
"(",
"'?'",
")",
")",
"{",
"// Write the help.",
"$",
"this",
"->",
"writeUsage",
"(",
"$",
"args",
")",
";",
"$",
"this",
"->",
"writeHelp",
"(",
"$",
"args",
"->",
"getCommand",
"(",
")",
")",
";",
"$",
"result",
"=",
"null",
";",
"}",
"else",
"{",
"// Validate the arguments against the schema.",
"$",
"validArgs",
"=",
"$",
"this",
"->",
"validate",
"(",
"$",
"args",
")",
";",
"$",
"result",
"=",
"$",
"validArgs",
";",
"}",
"if",
"(",
"!",
"$",
"exit",
")",
"{",
"$",
"this",
"->",
"formatOutput",
"=",
"$",
"formatOutputBak",
";",
"$",
"output",
"=",
"ob_get_clean",
"(",
")",
";",
"if",
"(",
"$",
"result",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"trim",
"(",
"$",
"output",
")",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"result",
"===",
"null",
")",
"{",
"exit",
"(",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
]
| Parses and validates a set of command line arguments the schema.
@param array $argv The command line arguments a form compatible with the global `$argv` variable.
Note that the `$argv` array must have at least one element and it must represent the path to the command that
invoked the command. This is used to write usage information.
@param bool $exit Whether to exit the application when there is an error or when writing help.
@return Args|null Returns an {@see Args} instance when a command should be executed
or `null` when one should not be executed.
@throws \Exception Throws an exception when {@link $exit} is false and the help or errors need to be displayed. | [
"Parses",
"and",
"validates",
"a",
"set",
"of",
"command",
"line",
"arguments",
"the",
"schema",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L328-L367 | train |
vanilla/garden-cli | src/Cli.php | Cli.getSchema | public function getSchema($command = '') {
$result = [];
foreach ($this->commandSchemas as $pattern => $opts) {
if (fnmatch($pattern, $command)) {
$result = array_replace_recursive($result, $opts);
}
}
return $result;
} | php | public function getSchema($command = '') {
$result = [];
foreach ($this->commandSchemas as $pattern => $opts) {
if (fnmatch($pattern, $command)) {
$result = array_replace_recursive($result, $opts);
}
}
return $result;
} | [
"public",
"function",
"getSchema",
"(",
"$",
"command",
"=",
"''",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"commandSchemas",
"as",
"$",
"pattern",
"=>",
"$",
"opts",
")",
"{",
"if",
"(",
"fnmatch",
"(",
"$",
"pattern",
",",
"$",
"command",
")",
")",
"{",
"$",
"result",
"=",
"array_replace_recursive",
"(",
"$",
"result",
",",
"$",
"opts",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
]
| Gets the full cli schema.
@param string $command The name of the command. This can be left blank if there is no command.
@return array Returns the schema that matches the command. | [
"Gets",
"the",
"full",
"cli",
"schema",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L669-L677 | train |
vanilla/garden-cli | src/Cli.php | Cli.arg | public function arg($name, $description, $required = false) {
$this->currentSchema[Cli::META][Cli::ARGS][$name] =
['description' => $description, 'required' => $required];
return $this;
} | php | public function arg($name, $description, $required = false) {
$this->currentSchema[Cli::META][Cli::ARGS][$name] =
['description' => $description, 'required' => $required];
return $this;
} | [
"public",
"function",
"arg",
"(",
"$",
"name",
",",
"$",
"description",
",",
"$",
"required",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"currentSchema",
"[",
"Cli",
"::",
"META",
"]",
"[",
"Cli",
"::",
"ARGS",
"]",
"[",
"$",
"name",
"]",
"=",
"[",
"'description'",
"=>",
"$",
"description",
",",
"'required'",
"=>",
"$",
"required",
"]",
";",
"return",
"$",
"this",
";",
"}"
]
| Define an arg on the current command.
@param string $name The name of the arg.
@param string $description The arg description.
@param bool $required Whether or not the arg is required.
@return $this | [
"Define",
"an",
"arg",
"on",
"the",
"current",
"command",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L744-L748 | train |
vanilla/garden-cli | src/Cli.php | Cli.command | public function command($pattern) {
if (!isset($this->commandSchemas[$pattern])) {
$this->commandSchemas[$pattern] = [Cli::META => []];
}
$this->currentSchema =& $this->commandSchemas[$pattern];
return $this;
} | php | public function command($pattern) {
if (!isset($this->commandSchemas[$pattern])) {
$this->commandSchemas[$pattern] = [Cli::META => []];
}
$this->currentSchema =& $this->commandSchemas[$pattern];
return $this;
} | [
"public",
"function",
"command",
"(",
"$",
"pattern",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"commandSchemas",
"[",
"$",
"pattern",
"]",
")",
")",
"{",
"$",
"this",
"->",
"commandSchemas",
"[",
"$",
"pattern",
"]",
"=",
"[",
"Cli",
"::",
"META",
"=>",
"[",
"]",
"]",
";",
"}",
"$",
"this",
"->",
"currentSchema",
"=",
"&",
"$",
"this",
"->",
"commandSchemas",
"[",
"$",
"pattern",
"]",
";",
"return",
"$",
"this",
";",
"}"
]
| Selects the current command schema name.
@param string $pattern The command pattern.
@return $this | [
"Selects",
"the",
"current",
"command",
"schema",
"name",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L756-L763 | train |
vanilla/garden-cli | src/Cli.php | Cli.isStrictBoolean | protected function isStrictBoolean($value, &$boolValue = null) {
if ($value === true || $value === false) {
$boolValue = $value;
return true;
} elseif (in_array($value, ['0', 'false', 'off', 'no'])) {
$boolValue = false;
return true;
} elseif (in_array($value, ['1', 'true', 'on', 'yes'])) {
$boolValue = true;
return true;
} else {
$boolValue = null;
return false;
}
} | php | protected function isStrictBoolean($value, &$boolValue = null) {
if ($value === true || $value === false) {
$boolValue = $value;
return true;
} elseif (in_array($value, ['0', 'false', 'off', 'no'])) {
$boolValue = false;
return true;
} elseif (in_array($value, ['1', 'true', 'on', 'yes'])) {
$boolValue = true;
return true;
} else {
$boolValue = null;
return false;
}
} | [
"protected",
"function",
"isStrictBoolean",
"(",
"$",
"value",
",",
"&",
"$",
"boolValue",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"true",
"||",
"$",
"value",
"===",
"false",
")",
"{",
"$",
"boolValue",
"=",
"$",
"value",
";",
"return",
"true",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"value",
",",
"[",
"'0'",
",",
"'false'",
",",
"'off'",
",",
"'no'",
"]",
")",
")",
"{",
"$",
"boolValue",
"=",
"false",
";",
"return",
"true",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"value",
",",
"[",
"'1'",
",",
"'true'",
",",
"'on'",
",",
"'yes'",
"]",
")",
")",
"{",
"$",
"boolValue",
"=",
"true",
";",
"return",
"true",
";",
"}",
"else",
"{",
"$",
"boolValue",
"=",
"null",
";",
"return",
"false",
";",
"}",
"}"
]
| Determine weather or not a value can be represented as a boolean.
This method is sort of like {@link Cli::validateType()} but requires a more strict check of a boolean value.
@param mixed $value The value to test.
@return bool | [
"Determine",
"weather",
"or",
"not",
"a",
"value",
"can",
"be",
"represented",
"as",
"a",
"boolean",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L774-L788 | train |
vanilla/garden-cli | src/Cli.php | Cli.schema | public function schema(array $schema) {
$parsed = static::parseSchema($schema);
$this->currentSchema = array_replace($this->currentSchema, $parsed);
} | php | public function schema(array $schema) {
$parsed = static::parseSchema($schema);
$this->currentSchema = array_replace($this->currentSchema, $parsed);
} | [
"public",
"function",
"schema",
"(",
"array",
"$",
"schema",
")",
"{",
"$",
"parsed",
"=",
"static",
"::",
"parseSchema",
"(",
"$",
"schema",
")",
";",
"$",
"this",
"->",
"currentSchema",
"=",
"array_replace",
"(",
"$",
"this",
"->",
"currentSchema",
",",
"$",
"parsed",
")",
";",
"}"
]
| Set the schema for a command.
The schema array uses a short syntax so that commands can be specified as quickly as possible.
This schema is the exact same as those provided to {@link Schema::create()}.
The basic format of the array is the following:
```
[
type:name[:shortCode][?],
type:name[:shortCode][?],
...
]
```
@param array $schema The schema array. | [
"Set",
"the",
"schema",
"for",
"a",
"command",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L807-L811 | train |
vanilla/garden-cli | src/Cli.php | Cli.guessFormatOutput | public static function guessFormatOutput($stream = STDOUT) {
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
return false;
} elseif (function_exists('posix_isatty')) {
try {
return @posix_isatty($stream);
} catch (\Throwable $ex) {
return false;
}
} else {
return true;
}
} | php | public static function guessFormatOutput($stream = STDOUT) {
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
return false;
} elseif (function_exists('posix_isatty')) {
try {
return @posix_isatty($stream);
} catch (\Throwable $ex) {
return false;
}
} else {
return true;
}
} | [
"public",
"static",
"function",
"guessFormatOutput",
"(",
"$",
"stream",
"=",
"STDOUT",
")",
"{",
"if",
"(",
"defined",
"(",
"'PHP_WINDOWS_VERSION_MAJOR'",
")",
")",
"{",
"return",
"false",
";",
"}",
"elseif",
"(",
"function_exists",
"(",
"'posix_isatty'",
")",
")",
"{",
"try",
"{",
"return",
"@",
"posix_isatty",
"(",
"$",
"stream",
")",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"ex",
")",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}"
]
| Guess whether or not to format the output with colors.
If the current environment is being redirected to a file then output should not be formatted. Also, Windows
machines do not support terminal colors so formatting should be suppressed on them too.
@param mixed The stream to interrogate for output format support.
@return bool Returns **true** if the output can be formatter or **false** otherwise. | [
"Guess",
"whether",
"or",
"not",
"to",
"format",
"the",
"output",
"with",
"colors",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L937-L949 | train |
vanilla/garden-cli | src/Cli.php | Cli.validateType | protected function validateType(&$value, $type, $name = '', $def = null) {
switch ($type) {
case 'boolean':
if (is_bool($value)) {
$valid = true;
} elseif ($value === 0) {
// 0 doesn't work well with in_array() so check it separately.
$value = false;
$valid = true;
} elseif (in_array($value, [null, '', '0', 'false', 'no', 'disabled'])) {
$value = false;
$valid = true;
} elseif (in_array($value, [1, '1', 'true', 'yes', 'enabled'])) {
$value = true;
$valid = true;
} else {
$valid = false;
}
break;
case 'integer':
if (is_numeric($value)) {
$value = (int)$value;
$valid = true;
} else {
$valid = false;
}
break;
case 'string':
$value = (string)$value;
$valid = true;
break;
default:
throw new \Exception("Unknown type: $type.", 400);
}
if (!$valid && $name) {
$short = static::val('short', (array)$def);
$nameStr = "--$name".($short ? " (-$short)" : '');
echo $this->red("The value of $nameStr is not a valid $type.".PHP_EOL);
}
return $valid;
} | php | protected function validateType(&$value, $type, $name = '', $def = null) {
switch ($type) {
case 'boolean':
if (is_bool($value)) {
$valid = true;
} elseif ($value === 0) {
// 0 doesn't work well with in_array() so check it separately.
$value = false;
$valid = true;
} elseif (in_array($value, [null, '', '0', 'false', 'no', 'disabled'])) {
$value = false;
$valid = true;
} elseif (in_array($value, [1, '1', 'true', 'yes', 'enabled'])) {
$value = true;
$valid = true;
} else {
$valid = false;
}
break;
case 'integer':
if (is_numeric($value)) {
$value = (int)$value;
$valid = true;
} else {
$valid = false;
}
break;
case 'string':
$value = (string)$value;
$valid = true;
break;
default:
throw new \Exception("Unknown type: $type.", 400);
}
if (!$valid && $name) {
$short = static::val('short', (array)$def);
$nameStr = "--$name".($short ? " (-$short)" : '');
echo $this->red("The value of $nameStr is not a valid $type.".PHP_EOL);
}
return $valid;
} | [
"protected",
"function",
"validateType",
"(",
"&",
"$",
"value",
",",
"$",
"type",
",",
"$",
"name",
"=",
"''",
",",
"$",
"def",
"=",
"null",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'boolean'",
":",
"if",
"(",
"is_bool",
"(",
"$",
"value",
")",
")",
"{",
"$",
"valid",
"=",
"true",
";",
"}",
"elseif",
"(",
"$",
"value",
"===",
"0",
")",
"{",
"// 0 doesn't work well with in_array() so check it separately.",
"$",
"value",
"=",
"false",
";",
"$",
"valid",
"=",
"true",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"value",
",",
"[",
"null",
",",
"''",
",",
"'0'",
",",
"'false'",
",",
"'no'",
",",
"'disabled'",
"]",
")",
")",
"{",
"$",
"value",
"=",
"false",
";",
"$",
"valid",
"=",
"true",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"value",
",",
"[",
"1",
",",
"'1'",
",",
"'true'",
",",
"'yes'",
",",
"'enabled'",
"]",
")",
")",
"{",
"$",
"value",
"=",
"true",
";",
"$",
"valid",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"valid",
"=",
"false",
";",
"}",
"break",
";",
"case",
"'integer'",
":",
"if",
"(",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"(",
"int",
")",
"$",
"value",
";",
"$",
"valid",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"valid",
"=",
"false",
";",
"}",
"break",
";",
"case",
"'string'",
":",
"$",
"value",
"=",
"(",
"string",
")",
"$",
"value",
";",
"$",
"valid",
"=",
"true",
";",
"break",
";",
"default",
":",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Unknown type: $type.\"",
",",
"400",
")",
";",
"}",
"if",
"(",
"!",
"$",
"valid",
"&&",
"$",
"name",
")",
"{",
"$",
"short",
"=",
"static",
"::",
"val",
"(",
"'short'",
",",
"(",
"array",
")",
"$",
"def",
")",
";",
"$",
"nameStr",
"=",
"\"--$name\"",
".",
"(",
"$",
"short",
"?",
"\" (-$short)\"",
":",
"''",
")",
";",
"echo",
"$",
"this",
"->",
"red",
"(",
"\"The value of $nameStr is not a valid $type.\"",
".",
"PHP_EOL",
")",
";",
"}",
"return",
"$",
"valid",
";",
"}"
]
| Validate the type of a value and coerce it into the proper type.
@param mixed &$value The value to validate.
@param string $type One of: bool, int, string.
@param string $name The name of the option if you want to print an error message.
@param array|null $def The option def if you want to print an error message.
@return bool Returns `true` if the value is the correct type.
@throws \Exception Throws an exception when {@see $type} is not a known value. | [
"Validate",
"the",
"type",
"of",
"a",
"value",
"and",
"coerce",
"it",
"into",
"the",
"proper",
"type",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L973-L1015 | train |
vanilla/garden-cli | src/Cli.php | Cli.writeCommands | protected function writeCommands() {
echo static::bold("COMMANDS").PHP_EOL;
$table = new Table();
foreach ($this->commandSchemas as $pattern => $schema) {
if (static::isCommand($pattern)) {
$table
->row()
->cell($pattern)
->cell(Cli::val('description', Cli::val(Cli::META, $schema), ''));
}
}
$table->write();
} | php | protected function writeCommands() {
echo static::bold("COMMANDS").PHP_EOL;
$table = new Table();
foreach ($this->commandSchemas as $pattern => $schema) {
if (static::isCommand($pattern)) {
$table
->row()
->cell($pattern)
->cell(Cli::val('description', Cli::val(Cli::META, $schema), ''));
}
}
$table->write();
} | [
"protected",
"function",
"writeCommands",
"(",
")",
"{",
"echo",
"static",
"::",
"bold",
"(",
"\"COMMANDS\"",
")",
".",
"PHP_EOL",
";",
"$",
"table",
"=",
"new",
"Table",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"commandSchemas",
"as",
"$",
"pattern",
"=>",
"$",
"schema",
")",
"{",
"if",
"(",
"static",
"::",
"isCommand",
"(",
"$",
"pattern",
")",
")",
"{",
"$",
"table",
"->",
"row",
"(",
")",
"->",
"cell",
"(",
"$",
"pattern",
")",
"->",
"cell",
"(",
"Cli",
"::",
"val",
"(",
"'description'",
",",
"Cli",
"::",
"val",
"(",
"Cli",
"::",
"META",
",",
"$",
"schema",
")",
",",
"''",
")",
")",
";",
"}",
"}",
"$",
"table",
"->",
"write",
"(",
")",
";",
"}"
]
| Writes a lis of all of the commands. | [
"Writes",
"a",
"lis",
"of",
"all",
"of",
"the",
"commands",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L1020-L1033 | train |
vanilla/garden-cli | src/Cli.php | Cli.writeSchemaHelp | protected function writeSchemaHelp($schema) {
// Write the command description.
$meta = Cli::val(Cli::META, $schema, []);
$description = Cli::val('description', $meta);
if ($description) {
echo implode("\n", Cli::breakLines($description, 80, false)).PHP_EOL.PHP_EOL;
}
unset($schema[Cli::META]);
// Add the help.
$schema['help'] = [
'description' => 'Display this help.',
'type' => 'boolean',
'short' => '?'
];
echo Cli::bold('OPTIONS').PHP_EOL;
ksort($schema);
$table = new Table();
$table->setFormatOutput($this->formatOutput);
foreach ($schema as $key => $definition) {
$table->row();
// Write the keys.
$keys = "--{$key}";
if ($shortKey = Cli::val('short', $definition, false)) {
$keys .= ", -$shortKey";
}
if (Cli::val('required', $definition)) {
$table->bold($keys);
} else {
$table->cell($keys);
}
// Write the description.
$table->cell(Cli::val('description', $definition, ''));
}
$table->write();
echo PHP_EOL;
$args = Cli::val(Cli::ARGS, $meta, []);
if (!empty($args)) {
echo Cli::bold('ARGUMENTS').PHP_EOL;
$table = new Table();
$table->setFormatOutput($this->formatOutput);
foreach ($args as $argName => $arg) {
$table->row();
if (Cli::val('required', $arg)) {
$table->bold($argName);
} else {
$table->cell($argName);
}
$table->cell(Cli::val('description', $arg, ''));
}
$table->write();
echo PHP_EOL;
}
} | php | protected function writeSchemaHelp($schema) {
// Write the command description.
$meta = Cli::val(Cli::META, $schema, []);
$description = Cli::val('description', $meta);
if ($description) {
echo implode("\n", Cli::breakLines($description, 80, false)).PHP_EOL.PHP_EOL;
}
unset($schema[Cli::META]);
// Add the help.
$schema['help'] = [
'description' => 'Display this help.',
'type' => 'boolean',
'short' => '?'
];
echo Cli::bold('OPTIONS').PHP_EOL;
ksort($schema);
$table = new Table();
$table->setFormatOutput($this->formatOutput);
foreach ($schema as $key => $definition) {
$table->row();
// Write the keys.
$keys = "--{$key}";
if ($shortKey = Cli::val('short', $definition, false)) {
$keys .= ", -$shortKey";
}
if (Cli::val('required', $definition)) {
$table->bold($keys);
} else {
$table->cell($keys);
}
// Write the description.
$table->cell(Cli::val('description', $definition, ''));
}
$table->write();
echo PHP_EOL;
$args = Cli::val(Cli::ARGS, $meta, []);
if (!empty($args)) {
echo Cli::bold('ARGUMENTS').PHP_EOL;
$table = new Table();
$table->setFormatOutput($this->formatOutput);
foreach ($args as $argName => $arg) {
$table->row();
if (Cli::val('required', $arg)) {
$table->bold($argName);
} else {
$table->cell($argName);
}
$table->cell(Cli::val('description', $arg, ''));
}
$table->write();
echo PHP_EOL;
}
} | [
"protected",
"function",
"writeSchemaHelp",
"(",
"$",
"schema",
")",
"{",
"// Write the command description.",
"$",
"meta",
"=",
"Cli",
"::",
"val",
"(",
"Cli",
"::",
"META",
",",
"$",
"schema",
",",
"[",
"]",
")",
";",
"$",
"description",
"=",
"Cli",
"::",
"val",
"(",
"'description'",
",",
"$",
"meta",
")",
";",
"if",
"(",
"$",
"description",
")",
"{",
"echo",
"implode",
"(",
"\"\\n\"",
",",
"Cli",
"::",
"breakLines",
"(",
"$",
"description",
",",
"80",
",",
"false",
")",
")",
".",
"PHP_EOL",
".",
"PHP_EOL",
";",
"}",
"unset",
"(",
"$",
"schema",
"[",
"Cli",
"::",
"META",
"]",
")",
";",
"// Add the help.",
"$",
"schema",
"[",
"'help'",
"]",
"=",
"[",
"'description'",
"=>",
"'Display this help.'",
",",
"'type'",
"=>",
"'boolean'",
",",
"'short'",
"=>",
"'?'",
"]",
";",
"echo",
"Cli",
"::",
"bold",
"(",
"'OPTIONS'",
")",
".",
"PHP_EOL",
";",
"ksort",
"(",
"$",
"schema",
")",
";",
"$",
"table",
"=",
"new",
"Table",
"(",
")",
";",
"$",
"table",
"->",
"setFormatOutput",
"(",
"$",
"this",
"->",
"formatOutput",
")",
";",
"foreach",
"(",
"$",
"schema",
"as",
"$",
"key",
"=>",
"$",
"definition",
")",
"{",
"$",
"table",
"->",
"row",
"(",
")",
";",
"// Write the keys.",
"$",
"keys",
"=",
"\"--{$key}\"",
";",
"if",
"(",
"$",
"shortKey",
"=",
"Cli",
"::",
"val",
"(",
"'short'",
",",
"$",
"definition",
",",
"false",
")",
")",
"{",
"$",
"keys",
".=",
"\", -$shortKey\"",
";",
"}",
"if",
"(",
"Cli",
"::",
"val",
"(",
"'required'",
",",
"$",
"definition",
")",
")",
"{",
"$",
"table",
"->",
"bold",
"(",
"$",
"keys",
")",
";",
"}",
"else",
"{",
"$",
"table",
"->",
"cell",
"(",
"$",
"keys",
")",
";",
"}",
"// Write the description.",
"$",
"table",
"->",
"cell",
"(",
"Cli",
"::",
"val",
"(",
"'description'",
",",
"$",
"definition",
",",
"''",
")",
")",
";",
"}",
"$",
"table",
"->",
"write",
"(",
")",
";",
"echo",
"PHP_EOL",
";",
"$",
"args",
"=",
"Cli",
"::",
"val",
"(",
"Cli",
"::",
"ARGS",
",",
"$",
"meta",
",",
"[",
"]",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
")",
")",
"{",
"echo",
"Cli",
"::",
"bold",
"(",
"'ARGUMENTS'",
")",
".",
"PHP_EOL",
";",
"$",
"table",
"=",
"new",
"Table",
"(",
")",
";",
"$",
"table",
"->",
"setFormatOutput",
"(",
"$",
"this",
"->",
"formatOutput",
")",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"argName",
"=>",
"$",
"arg",
")",
"{",
"$",
"table",
"->",
"row",
"(",
")",
";",
"if",
"(",
"Cli",
"::",
"val",
"(",
"'required'",
",",
"$",
"arg",
")",
")",
"{",
"$",
"table",
"->",
"bold",
"(",
"$",
"argName",
")",
";",
"}",
"else",
"{",
"$",
"table",
"->",
"cell",
"(",
"$",
"argName",
")",
";",
"}",
"$",
"table",
"->",
"cell",
"(",
"Cli",
"::",
"val",
"(",
"'description'",
",",
"$",
"arg",
",",
"''",
")",
")",
";",
"}",
"$",
"table",
"->",
"write",
"(",
")",
";",
"echo",
"PHP_EOL",
";",
"}",
"}"
]
| Writes the help for a given schema.
@param array $schema A command line scheme returned from {@see Cli::getSchema()}. | [
"Writes",
"the",
"help",
"for",
"a",
"given",
"schema",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L1050-L1117 | train |
vanilla/garden-cli | src/Cli.php | Cli.writeUsage | protected function writeUsage(Args $args) {
if ($filename = $args->getMeta('filename')) {
$schema = $this->getSchema($args->getCommand());
unset($schema[Cli::META]);
echo static::bold("usage: ").$filename;
if ($this->hasCommand()) {
if ($args->getCommand() && isset($this->commandSchemas[$args->getCommand()])) {
echo ' '.$args->getCommand();
} else {
echo ' <command>';
}
}
if ($this->hasOptions($args->getCommand())) {
echo " [<options>]";
}
if ($hasArgs = $this->hasArgs($args->getCommand())) {
echo $hasArgs === 2 ? " <args>" : " [<args>]";
}
echo PHP_EOL.PHP_EOL;
}
} | php | protected function writeUsage(Args $args) {
if ($filename = $args->getMeta('filename')) {
$schema = $this->getSchema($args->getCommand());
unset($schema[Cli::META]);
echo static::bold("usage: ").$filename;
if ($this->hasCommand()) {
if ($args->getCommand() && isset($this->commandSchemas[$args->getCommand()])) {
echo ' '.$args->getCommand();
} else {
echo ' <command>';
}
}
if ($this->hasOptions($args->getCommand())) {
echo " [<options>]";
}
if ($hasArgs = $this->hasArgs($args->getCommand())) {
echo $hasArgs === 2 ? " <args>" : " [<args>]";
}
echo PHP_EOL.PHP_EOL;
}
} | [
"protected",
"function",
"writeUsage",
"(",
"Args",
"$",
"args",
")",
"{",
"if",
"(",
"$",
"filename",
"=",
"$",
"args",
"->",
"getMeta",
"(",
"'filename'",
")",
")",
"{",
"$",
"schema",
"=",
"$",
"this",
"->",
"getSchema",
"(",
"$",
"args",
"->",
"getCommand",
"(",
")",
")",
";",
"unset",
"(",
"$",
"schema",
"[",
"Cli",
"::",
"META",
"]",
")",
";",
"echo",
"static",
"::",
"bold",
"(",
"\"usage: \"",
")",
".",
"$",
"filename",
";",
"if",
"(",
"$",
"this",
"->",
"hasCommand",
"(",
")",
")",
"{",
"if",
"(",
"$",
"args",
"->",
"getCommand",
"(",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"commandSchemas",
"[",
"$",
"args",
"->",
"getCommand",
"(",
")",
"]",
")",
")",
"{",
"echo",
"' '",
".",
"$",
"args",
"->",
"getCommand",
"(",
")",
";",
"}",
"else",
"{",
"echo",
"' <command>'",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"hasOptions",
"(",
"$",
"args",
"->",
"getCommand",
"(",
")",
")",
")",
"{",
"echo",
"\" [<options>]\"",
";",
"}",
"if",
"(",
"$",
"hasArgs",
"=",
"$",
"this",
"->",
"hasArgs",
"(",
"$",
"args",
"->",
"getCommand",
"(",
")",
")",
")",
"{",
"echo",
"$",
"hasArgs",
"===",
"2",
"?",
"\" <args>\"",
":",
"\" [<args>]\"",
";",
"}",
"echo",
"PHP_EOL",
".",
"PHP_EOL",
";",
"}",
"}"
]
| Writes the basic usage information of the command.
@param Args $args The parsed args returned from {@link Cli::parseRaw()}. | [
"Writes",
"the",
"basic",
"usage",
"information",
"of",
"the",
"command",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Cli.php#L1124-L1150 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginDebug | public function beginDebug(string $message, array $context = []) {
return $this->begin(LogLevel::DEBUG, $message, $context);
} | php | public function beginDebug(string $message, array $context = []) {
return $this->begin(LogLevel::DEBUG, $message, $context);
} | [
"public",
"function",
"beginDebug",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"DEBUG",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output a debug message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"a",
"debug",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L72-L74 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.compareLevel | private function compareLevel(string $a, string $b): int {
$i = array_search($a, static::$levels);
if ($i === false) {
throw new InvalidArgumentException("Log level is invalid: $a", 500);
}
return $i <=> array_search($b, static::$levels);
} | php | private function compareLevel(string $a, string $b): int {
$i = array_search($a, static::$levels);
if ($i === false) {
throw new InvalidArgumentException("Log level is invalid: $a", 500);
}
return $i <=> array_search($b, static::$levels);
} | [
"private",
"function",
"compareLevel",
"(",
"string",
"$",
"a",
",",
"string",
"$",
"b",
")",
":",
"int",
"{",
"$",
"i",
"=",
"array_search",
"(",
"$",
"a",
",",
"static",
"::",
"$",
"levels",
")",
";",
"if",
"(",
"$",
"i",
"===",
"false",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Log level is invalid: $a\"",
",",
"500",
")",
";",
"}",
"return",
"$",
"i",
"<=>",
"array_search",
"(",
"$",
"b",
",",
"static",
"::",
"$",
"levels",
")",
";",
"}"
]
| Compare two log levels.
@param string $a The first log level to compare.
@param string $b The second log level to compare.
@return int Returns -1, 0, or 1. | [
"Compare",
"two",
"log",
"levels",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L105-L112 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.outputTaskStack | private function outputTaskStack() {
foreach ($this->taskStack as $indent => &$task) {
list($taskLevel, $taskMessage, $taskContext, $taskOutput) = $task;
if (!$taskOutput) {
$this->logInternal($taskLevel, $taskMessage, [self::FIELD_INDENT => $indent] + $taskContext);
$task[3] = true; // mark task as outputted
}
}
} | php | private function outputTaskStack() {
foreach ($this->taskStack as $indent => &$task) {
list($taskLevel, $taskMessage, $taskContext, $taskOutput) = $task;
if (!$taskOutput) {
$this->logInternal($taskLevel, $taskMessage, [self::FIELD_INDENT => $indent] + $taskContext);
$task[3] = true; // mark task as outputted
}
}
} | [
"private",
"function",
"outputTaskStack",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"taskStack",
"as",
"$",
"indent",
"=>",
"&",
"$",
"task",
")",
"{",
"list",
"(",
"$",
"taskLevel",
",",
"$",
"taskMessage",
",",
"$",
"taskContext",
",",
"$",
"taskOutput",
")",
"=",
"$",
"task",
";",
"if",
"(",
"!",
"$",
"taskOutput",
")",
"{",
"$",
"this",
"->",
"logInternal",
"(",
"$",
"taskLevel",
",",
"$",
"taskMessage",
",",
"[",
"self",
"::",
"FIELD_INDENT",
"=>",
"$",
"indent",
"]",
"+",
"$",
"taskContext",
")",
";",
"$",
"task",
"[",
"3",
"]",
"=",
"true",
";",
"// mark task as outputted",
"}",
"}",
"}"
]
| Output the task stack. | [
"Output",
"the",
"task",
"stack",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L159-L168 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.logInternal | private function logInternal(string $level, string $message, array $context = []) {
$context = $context + [self::FIELD_INDENT => $this->currentIndent(), self::FIELD_TIME => microtime(true)];
$this->logger->log($level, $message, $context);
} | php | private function logInternal(string $level, string $message, array $context = []) {
$context = $context + [self::FIELD_INDENT => $this->currentIndent(), self::FIELD_TIME => microtime(true)];
$this->logger->log($level, $message, $context);
} | [
"private",
"function",
"logInternal",
"(",
"string",
"$",
"level",
",",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"context",
"=",
"$",
"context",
"+",
"[",
"self",
"::",
"FIELD_INDENT",
"=>",
"$",
"this",
"->",
"currentIndent",
"(",
")",
",",
"self",
"::",
"FIELD_TIME",
"=>",
"microtime",
"(",
"true",
")",
"]",
";",
"$",
"this",
"->",
"logger",
"->",
"log",
"(",
"$",
"level",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Internal log implementation with less error checking.
@param string $level The log level.
@param string $message The log message.
@param array $context The log context. | [
"Internal",
"log",
"implementation",
"with",
"less",
"error",
"checking",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L177-L180 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginInfo | public function beginInfo(string $message, array $context = []) {
return $this->begin(LogLevel::INFO, $message, $context);
} | php | public function beginInfo(string $message, array $context = []) {
return $this->begin(LogLevel::INFO, $message, $context);
} | [
"public",
"function",
"beginInfo",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"INFO",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output an info message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"an",
"info",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L198-L200 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginNotice | public function beginNotice(string $message, array $context = []) {
return $this->begin(LogLevel::NOTICE, $message, $context);
} | php | public function beginNotice(string $message, array $context = []) {
return $this->begin(LogLevel::NOTICE, $message, $context);
} | [
"public",
"function",
"beginNotice",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"NOTICE",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output a notice message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"a",
"notice",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L209-L211 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginWarning | public function beginWarning(string $message, array $context = []) {
return $this->begin(LogLevel::WARNING, $message, $context);
} | php | public function beginWarning(string $message, array $context = []) {
return $this->begin(LogLevel::WARNING, $message, $context);
} | [
"public",
"function",
"beginWarning",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"WARNING",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output a warning message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"a",
"warning",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L220-L222 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginError | public function beginError(string $message, array $context = []) {
return $this->begin(LogLevel::ERROR, $message, $context);
} | php | public function beginError(string $message, array $context = []) {
return $this->begin(LogLevel::ERROR, $message, $context);
} | [
"public",
"function",
"beginError",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"ERROR",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output an error message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"an",
"error",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L231-L233 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginCritical | public function beginCritical(string $message, array $context = []) {
return $this->begin(LogLevel::CRITICAL, $message, $context);
} | php | public function beginCritical(string $message, array $context = []) {
return $this->begin(LogLevel::CRITICAL, $message, $context);
} | [
"public",
"function",
"beginCritical",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"CRITICAL",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output a critical message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"a",
"critical",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L242-L244 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginAlert | public function beginAlert(string $message, array $context = []) {
return $this->begin(LogLevel::ALERT, $message, $context);
} | php | public function beginAlert(string $message, array $context = []) {
return $this->begin(LogLevel::ALERT, $message, $context);
} | [
"public",
"function",
"beginAlert",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"ALERT",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output an alert message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"an",
"alert",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L253-L255 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.beginEmergency | public function beginEmergency(string $message, array $context = []) {
return $this->begin(LogLevel::EMERGENCY, $message, $context);
} | php | public function beginEmergency(string $message, array $context = []) {
return $this->begin(LogLevel::EMERGENCY, $message, $context);
} | [
"public",
"function",
"beginEmergency",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"begin",
"(",
"LogLevel",
"::",
"EMERGENCY",
",",
"$",
"message",
",",
"$",
"context",
")",
";",
"}"
]
| Output an emergency message that designates the beginning of a task.
@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this | [
"Output",
"an",
"emergency",
"message",
"that",
"designates",
"the",
"beginning",
"of",
"a",
"task",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L264-L266 | train |
vanilla/garden-cli | src/TaskLogger.php | TaskLogger.endError | public function endError(string $message, array $context = []) {
return $this->end($message, [self::FIELD_LEVEL => LogLevel::ERROR] + $context);
} | php | public function endError(string $message, array $context = []) {
return $this->end($message, [self::FIELD_LEVEL => LogLevel::ERROR] + $context);
} | [
"public",
"function",
"endError",
"(",
"string",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"end",
"(",
"$",
"message",
",",
"[",
"self",
"::",
"FIELD_LEVEL",
"=>",
"LogLevel",
"::",
"ERROR",
"]",
"+",
"$",
"context",
")",
";",
"}"
]
| Output a message that represents a task being completed in an error.
When formatting is turned on, error messages are output in red.
@param string $message The message to output.
@param array $context The log context.
@return $this | [
"Output",
"a",
"message",
"that",
"represents",
"a",
"task",
"being",
"completed",
"in",
"an",
"error",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/TaskLogger.php#L335-L337 | train |
vanilla/garden-cli | src/Args.php | Args.addArg | public function addArg($value, $index = null) {
if ($index !== null) {
$this->args[$index] = $value;
} else {
$this->args[] = $value;
}
return $this;
} | php | public function addArg($value, $index = null) {
if ($index !== null) {
$this->args[$index] = $value;
} else {
$this->args[] = $value;
}
return $this;
} | [
"public",
"function",
"addArg",
"(",
"$",
"value",
",",
"$",
"index",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"index",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"args",
"[",
"$",
"index",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"args",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Add an argument to the args array.
@param string $value The argument to add.
@param string|null $index The index to add the arg at.
@return $this | [
"Add",
"an",
"argument",
"to",
"the",
"args",
"array",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Args.php#L40-L47 | train |
vanilla/garden-cli | src/Args.php | Args.getArg | public function getArg($index, $default = null) {
if (array_key_exists($index, $this->args)) {
return $this->args[$index];
} elseif (is_int($index)) {
$values = array_values($this->args);
if (array_key_exists($index, $values)) {
return $values[$index];
}
}
return $default;
} | php | public function getArg($index, $default = null) {
if (array_key_exists($index, $this->args)) {
return $this->args[$index];
} elseif (is_int($index)) {
$values = array_values($this->args);
if (array_key_exists($index, $values)) {
return $values[$index];
}
}
return $default;
} | [
"public",
"function",
"getArg",
"(",
"$",
"index",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"index",
",",
"$",
"this",
"->",
"args",
")",
")",
"{",
"return",
"$",
"this",
"->",
"args",
"[",
"$",
"index",
"]",
";",
"}",
"elseif",
"(",
"is_int",
"(",
"$",
"index",
")",
")",
"{",
"$",
"values",
"=",
"array_values",
"(",
"$",
"this",
"->",
"args",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"index",
",",
"$",
"values",
")",
")",
"{",
"return",
"$",
"values",
"[",
"$",
"index",
"]",
";",
"}",
"}",
"return",
"$",
"default",
";",
"}"
]
| Get an argument at a given index.
Arguments can be accessed by name or index.
@param string|int $index
@param mixed $default The default value to return if the argument is not found.
@return mixed Returns the argument at {@link $index} or {@link $default}. | [
"Get",
"an",
"argument",
"at",
"a",
"given",
"index",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/Args.php#L58-L68 | train |
vanilla/garden-cli | src/StreamLogger.php | StreamLogger.setTimeFormat | public function setTimeFormat($format) {
if (is_string($format)) {
$this->timeFormatter = function ($t) use ($format) {
return strftime($format, $t);
};
} else {
$this->timeFormatter = $format;
}
return $this;
} | php | public function setTimeFormat($format) {
if (is_string($format)) {
$this->timeFormatter = function ($t) use ($format) {
return strftime($format, $t);
};
} else {
$this->timeFormatter = $format;
}
return $this;
} | [
"public",
"function",
"setTimeFormat",
"(",
"$",
"format",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"format",
")",
")",
"{",
"$",
"this",
"->",
"timeFormatter",
"=",
"function",
"(",
"$",
"t",
")",
"use",
"(",
"$",
"format",
")",
"{",
"return",
"strftime",
"(",
"$",
"format",
",",
"$",
"t",
")",
";",
"}",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"timeFormatter",
"=",
"$",
"format",
";",
"}",
"return",
"$",
"this",
";",
"}"
]
| Set the time formatter.
This method takes either a format string for **strftime()** or a callable that must format a timestamp.
@param string|callable $format The new format.
@return $this
@see strftime() | [
"Set",
"the",
"time",
"formatter",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/StreamLogger.php#L116-L126 | train |
vanilla/garden-cli | src/StreamLogger.php | StreamLogger.replaceContext | private function replaceContext(string $format, array $context): string {
$msg = preg_replace_callback('`({[^\s{}]+})`', function ($m) use ($context) {
$field = trim($m[1], '{}');
if (array_key_exists($field, $context)) {
return $context[$field];
} else {
return $m[1];
}
}, $format);
return $msg;
} | php | private function replaceContext(string $format, array $context): string {
$msg = preg_replace_callback('`({[^\s{}]+})`', function ($m) use ($context) {
$field = trim($m[1], '{}');
if (array_key_exists($field, $context)) {
return $context[$field];
} else {
return $m[1];
}
}, $format);
return $msg;
} | [
"private",
"function",
"replaceContext",
"(",
"string",
"$",
"format",
",",
"array",
"$",
"context",
")",
":",
"string",
"{",
"$",
"msg",
"=",
"preg_replace_callback",
"(",
"'`({[^\\s{}]+})`'",
",",
"function",
"(",
"$",
"m",
")",
"use",
"(",
"$",
"context",
")",
"{",
"$",
"field",
"=",
"trim",
"(",
"$",
"m",
"[",
"1",
"]",
",",
"'{}'",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"field",
",",
"$",
"context",
")",
")",
"{",
"return",
"$",
"context",
"[",
"$",
"field",
"]",
";",
"}",
"else",
"{",
"return",
"$",
"m",
"[",
"1",
"]",
";",
"}",
"}",
",",
"$",
"format",
")",
";",
"return",
"$",
"msg",
";",
"}"
]
| Replace a message format with context information.
The message format contains fields wrapped in curly braces.
@param string $format The message format to replace.
@param array $context The context data.
@return string Returns the formatted message. | [
"Replace",
"a",
"message",
"format",
"with",
"context",
"information",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/StreamLogger.php#L199-L209 | train |
vanilla/garden-cli | src/StreamLogger.php | StreamLogger.setEol | public function setEol(string $eol) {
if (strpos($eol, "\n") === false) {
throw new \InvalidArgumentException('The EOL must include the "\n" character."', 500);
}
$this->eol = $eol;
return $this;
} | php | public function setEol(string $eol) {
if (strpos($eol, "\n") === false) {
throw new \InvalidArgumentException('The EOL must include the "\n" character."', 500);
}
$this->eol = $eol;
return $this;
} | [
"public",
"function",
"setEol",
"(",
"string",
"$",
"eol",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"eol",
",",
"\"\\n\"",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The EOL must include the \"\\n\" character.\"'",
",",
"500",
")",
";",
"}",
"$",
"this",
"->",
"eol",
"=",
"$",
"eol",
";",
"return",
"$",
"this",
";",
"}"
]
| Set the end of line string.
@param string $eol The end of line string to use.
@return $this | [
"Set",
"the",
"end",
"of",
"line",
"string",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/StreamLogger.php#L334-L341 | train |
thephpleague/flysystem-azure | src/AzureAdapter.php | AzureAdapter.normalize | protected function normalize($path, $timestamp, $content = null)
{
$data = [
'path' => $path,
'timestamp' => (int) $timestamp,
'dirname' => Util::dirname($path),
'type' => 'file',
];
if (is_string($content)) {
$data['contents'] = $content;
}
return $data;
} | php | protected function normalize($path, $timestamp, $content = null)
{
$data = [
'path' => $path,
'timestamp' => (int) $timestamp,
'dirname' => Util::dirname($path),
'type' => 'file',
];
if (is_string($content)) {
$data['contents'] = $content;
}
return $data;
} | [
"protected",
"function",
"normalize",
"(",
"$",
"path",
",",
"$",
"timestamp",
",",
"$",
"content",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"[",
"'path'",
"=>",
"$",
"path",
",",
"'timestamp'",
"=>",
"(",
"int",
")",
"$",
"timestamp",
",",
"'dirname'",
"=>",
"Util",
"::",
"dirname",
"(",
"$",
"path",
")",
",",
"'type'",
"=>",
"'file'",
",",
"]",
";",
"if",
"(",
"is_string",
"(",
"$",
"content",
")",
")",
"{",
"$",
"data",
"[",
"'contents'",
"]",
"=",
"$",
"content",
";",
"}",
"return",
"$",
"data",
";",
"}"
]
| Builds the normalized output array.
@param string $path
@param int $timestamp
@param mixed $content
@return array | [
"Builds",
"the",
"normalized",
"output",
"array",
"."
]
| b61bdb369ad6368e38637a0f239ea1df5783d83b | https://github.com/thephpleague/flysystem-azure/blob/b61bdb369ad6368e38637a0f239ea1df5783d83b/src/AzureAdapter.php#L286-L300 | train |
thephpleague/flysystem-azure | src/AzureAdapter.php | AzureAdapter.normalizeBlobProperties | protected function normalizeBlobProperties($path, BlobProperties $properties)
{
if (substr($path, -1) === '/') {
return ['type' => 'dir', 'path' => $this->removePathPrefix(rtrim($path, '/'))];
}
$path = $this->removePathPrefix($path);
return [
'path' => $path,
'timestamp' => (int) $properties->getLastModified()->format('U'),
'dirname' => Util::dirname($path),
'mimetype' => $properties->getContentType(),
'size' => $properties->getContentLength(),
'type' => 'file',
];
} | php | protected function normalizeBlobProperties($path, BlobProperties $properties)
{
if (substr($path, -1) === '/') {
return ['type' => 'dir', 'path' => $this->removePathPrefix(rtrim($path, '/'))];
}
$path = $this->removePathPrefix($path);
return [
'path' => $path,
'timestamp' => (int) $properties->getLastModified()->format('U'),
'dirname' => Util::dirname($path),
'mimetype' => $properties->getContentType(),
'size' => $properties->getContentLength(),
'type' => 'file',
];
} | [
"protected",
"function",
"normalizeBlobProperties",
"(",
"$",
"path",
",",
"BlobProperties",
"$",
"properties",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"path",
",",
"-",
"1",
")",
"===",
"'/'",
")",
"{",
"return",
"[",
"'type'",
"=>",
"'dir'",
",",
"'path'",
"=>",
"$",
"this",
"->",
"removePathPrefix",
"(",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
")",
")",
"]",
";",
"}",
"$",
"path",
"=",
"$",
"this",
"->",
"removePathPrefix",
"(",
"$",
"path",
")",
";",
"return",
"[",
"'path'",
"=>",
"$",
"path",
",",
"'timestamp'",
"=>",
"(",
"int",
")",
"$",
"properties",
"->",
"getLastModified",
"(",
")",
"->",
"format",
"(",
"'U'",
")",
",",
"'dirname'",
"=>",
"Util",
"::",
"dirname",
"(",
"$",
"path",
")",
",",
"'mimetype'",
"=>",
"$",
"properties",
"->",
"getContentType",
"(",
")",
",",
"'size'",
"=>",
"$",
"properties",
"->",
"getContentLength",
"(",
")",
",",
"'type'",
"=>",
"'file'",
",",
"]",
";",
"}"
]
| Builds the normalized output array from a Blob object.
@param string $path
@param BlobProperties $properties
@return array | [
"Builds",
"the",
"normalized",
"output",
"array",
"from",
"a",
"Blob",
"object",
"."
]
| b61bdb369ad6368e38637a0f239ea1df5783d83b | https://github.com/thephpleague/flysystem-azure/blob/b61bdb369ad6368e38637a0f239ea1df5783d83b/src/AzureAdapter.php#L310-L326 | train |
thephpleague/flysystem-azure | src/AzureAdapter.php | AzureAdapter.getOptionsFromConfig | protected function getOptionsFromConfig(Config $config)
{
$options = new CreateBlobOptions();
foreach (static::$metaOptions as $option) {
if ( ! $config->has($option)) {
continue;
}
call_user_func([$options, "set$option"], $config->get($option));
}
if ($mimetype = $config->get('mimetype')) {
$options->setContentType($mimetype);
}
return $options;
} | php | protected function getOptionsFromConfig(Config $config)
{
$options = new CreateBlobOptions();
foreach (static::$metaOptions as $option) {
if ( ! $config->has($option)) {
continue;
}
call_user_func([$options, "set$option"], $config->get($option));
}
if ($mimetype = $config->get('mimetype')) {
$options->setContentType($mimetype);
}
return $options;
} | [
"protected",
"function",
"getOptionsFromConfig",
"(",
"Config",
"$",
"config",
")",
"{",
"$",
"options",
"=",
"new",
"CreateBlobOptions",
"(",
")",
";",
"foreach",
"(",
"static",
"::",
"$",
"metaOptions",
"as",
"$",
"option",
")",
"{",
"if",
"(",
"!",
"$",
"config",
"->",
"has",
"(",
"$",
"option",
")",
")",
"{",
"continue",
";",
"}",
"call_user_func",
"(",
"[",
"$",
"options",
",",
"\"set$option\"",
"]",
",",
"$",
"config",
"->",
"get",
"(",
"$",
"option",
")",
")",
";",
"}",
"if",
"(",
"$",
"mimetype",
"=",
"$",
"config",
"->",
"get",
"(",
"'mimetype'",
")",
")",
"{",
"$",
"options",
"->",
"setContentType",
"(",
"$",
"mimetype",
")",
";",
"}",
"return",
"$",
"options",
";",
"}"
]
| Retrieve options from a Config instance.
@param Config $config
@return CreateBlobOptions | [
"Retrieve",
"options",
"from",
"a",
"Config",
"instance",
"."
]
| b61bdb369ad6368e38637a0f239ea1df5783d83b | https://github.com/thephpleague/flysystem-azure/blob/b61bdb369ad6368e38637a0f239ea1df5783d83b/src/AzureAdapter.php#L383-L400 | train |
vanilla/garden-cli | src/LogFormatter.php | LogFormatter.endSuccess | public function endSuccess($str, $force = false) {
return $this->end($this->formatString($str, ["\033[1;32m", "\033[0m"]), $force);
} | php | public function endSuccess($str, $force = false) {
return $this->end($this->formatString($str, ["\033[1;32m", "\033[0m"]), $force);
} | [
"public",
"function",
"endSuccess",
"(",
"$",
"str",
",",
"$",
"force",
"=",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"end",
"(",
"$",
"this",
"->",
"formatString",
"(",
"$",
"str",
",",
"[",
"\"\\033[1;32m\"",
",",
"\"\\033[0m\"",
"]",
")",
",",
"$",
"force",
")",
";",
"}"
]
| Output a message that represents a task being completed in success.
When formatting is turned on, success messages are output in green.
@param string $str The message to output.
@param bool $force Whether or not to force a message past the max level to be output.
@return $this | [
"Output",
"a",
"message",
"that",
"represents",
"a",
"task",
"being",
"completed",
"in",
"success",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/LogFormatter.php#L193-L195 | train |
vanilla/garden-cli | src/LogFormatter.php | LogFormatter.messageStr | protected function messageStr($str, $eol = true) {
return $this->fullMessageStr(time(), $str, null, $eol);
} | php | protected function messageStr($str, $eol = true) {
return $this->fullMessageStr(time(), $str, null, $eol);
} | [
"protected",
"function",
"messageStr",
"(",
"$",
"str",
",",
"$",
"eol",
"=",
"true",
")",
"{",
"return",
"$",
"this",
"->",
"fullMessageStr",
"(",
"time",
"(",
")",
",",
"$",
"str",
",",
"null",
",",
"$",
"eol",
")",
";",
"}"
]
| Create a message string.
@param string $str The message to output.
@param bool $eol Whether or not to add an EOL.
@return string Returns the message. | [
"Create",
"a",
"message",
"string",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/LogFormatter.php#L358-L360 | train |
vanilla/garden-cli | src/LogFormatter.php | LogFormatter.write | public function write($str) {
if (feof($this->outputHandle)) {
trigger_error('Called LogFormatter::write() but file handle was closed.', E_USER_WARNING);
return;
}
fwrite($this->outputHandle, $str);
} | php | public function write($str) {
if (feof($this->outputHandle)) {
trigger_error('Called LogFormatter::write() but file handle was closed.', E_USER_WARNING);
return;
}
fwrite($this->outputHandle, $str);
} | [
"public",
"function",
"write",
"(",
"$",
"str",
")",
"{",
"if",
"(",
"feof",
"(",
"$",
"this",
"->",
"outputHandle",
")",
")",
"{",
"trigger_error",
"(",
"'Called LogFormatter::write() but file handle was closed.'",
",",
"E_USER_WARNING",
")",
";",
"return",
";",
"}",
"fwrite",
"(",
"$",
"this",
"->",
"outputHandle",
",",
"$",
"str",
")",
";",
"}"
]
| Write a string to the CLI.
This method is intended to centralize the echoing of output in case the class is subclassed and the behaviour
needs to change.
@param string $str The string to write. | [
"Write",
"a",
"string",
"to",
"the",
"CLI",
"."
]
| d9f57b2a96d34898bdefead355c644ef52ccb065 | https://github.com/vanilla/garden-cli/blob/d9f57b2a96d34898bdefead355c644ef52ccb065/src/LogFormatter.php#L483-L489 | train |
rinvex/laravel-forms | src/Models/FormResponse.php | FormResponse.scopeOfUser | public function scopeOfUser(Builder $builder, Model $user): Builder
{
return $builder->where('user_type', $user->getMorphClass())->where('user_id', $user->getKey());
} | php | public function scopeOfUser(Builder $builder, Model $user): Builder
{
return $builder->where('user_type', $user->getMorphClass())->where('user_id', $user->getKey());
} | [
"public",
"function",
"scopeOfUser",
"(",
"Builder",
"$",
"builder",
",",
"Model",
"$",
"user",
")",
":",
"Builder",
"{",
"return",
"$",
"builder",
"->",
"where",
"(",
"'user_type'",
",",
"$",
"user",
"->",
"getMorphClass",
"(",
")",
")",
"->",
"where",
"(",
"'user_id'",
",",
"$",
"user",
"->",
"getKey",
"(",
")",
")",
";",
"}"
]
| Get form responses of the given user.
@param \Illuminate\Database\Eloquent\Builder $builder
@param \Illuminate\Database\Eloquent\Model $user
@return \Illuminate\Database\Eloquent\Builder | [
"Get",
"form",
"responses",
"of",
"the",
"given",
"user",
"."
]
| 964bf5a1ef7b49c97093771f7762a08571cb5e63 | https://github.com/rinvex/laravel-forms/blob/964bf5a1ef7b49c97093771f7762a08571cb5e63/src/Models/FormResponse.php#L124-L127 | train |
stechstudio/backoff | src/Backoff.php | Backoff.buildStrategy | protected function buildStrategy($strategy)
{
if (is_string($strategy) && array_key_exists($strategy, $this->strategies)) {
return new $this->strategies[$strategy];
}
if (is_callable($strategy)) {
return $strategy;
}
if (is_int($strategy)) {
return new ConstantStrategy($strategy);
}
throw new InvalidArgumentException("Invalid strategy: " . $strategy);
} | php | protected function buildStrategy($strategy)
{
if (is_string($strategy) && array_key_exists($strategy, $this->strategies)) {
return new $this->strategies[$strategy];
}
if (is_callable($strategy)) {
return $strategy;
}
if (is_int($strategy)) {
return new ConstantStrategy($strategy);
}
throw new InvalidArgumentException("Invalid strategy: " . $strategy);
} | [
"protected",
"function",
"buildStrategy",
"(",
"$",
"strategy",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"strategy",
")",
"&&",
"array_key_exists",
"(",
"$",
"strategy",
",",
"$",
"this",
"->",
"strategies",
")",
")",
"{",
"return",
"new",
"$",
"this",
"->",
"strategies",
"[",
"$",
"strategy",
"]",
";",
"}",
"if",
"(",
"is_callable",
"(",
"$",
"strategy",
")",
")",
"{",
"return",
"$",
"strategy",
";",
"}",
"if",
"(",
"is_int",
"(",
"$",
"strategy",
")",
")",
"{",
"return",
"new",
"ConstantStrategy",
"(",
"$",
"strategy",
")",
";",
"}",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid strategy: \"",
".",
"$",
"strategy",
")",
";",
"}"
]
| Builds a callable strategy.
@param mixed $strategy Can be a string that matches a key in $strategies, an instance of AbstractStrategy
(or any other instance that has an __invoke method), a callback function, or
an integer (which we interpret to mean you want a ConstantStrategy)
@return callable | [
"Builds",
"a",
"callable",
"strategy",
"."
]
| 88b9a4a5da1cc5485e6fb0c5d35ee0d4149c3361 | https://github.com/stechstudio/backoff/blob/88b9a4a5da1cc5485e6fb0c5d35ee0d4149c3361/src/Backoff.php#L206-L221 | train |
stechstudio/backoff | src/Backoff.php | Backoff.getDefaultDecider | protected function getDefaultDecider()
{
return function ($retry, $maxAttempts, $result = null, $exception = null) {
if($retry >= $maxAttempts && ! is_null($exception)) {
throw $exception;
}
return $retry < $maxAttempts && !is_null($exception);
};
} | php | protected function getDefaultDecider()
{
return function ($retry, $maxAttempts, $result = null, $exception = null) {
if($retry >= $maxAttempts && ! is_null($exception)) {
throw $exception;
}
return $retry < $maxAttempts && !is_null($exception);
};
} | [
"protected",
"function",
"getDefaultDecider",
"(",
")",
"{",
"return",
"function",
"(",
"$",
"retry",
",",
"$",
"maxAttempts",
",",
"$",
"result",
"=",
"null",
",",
"$",
"exception",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"retry",
">=",
"$",
"maxAttempts",
"&&",
"!",
"is_null",
"(",
"$",
"exception",
")",
")",
"{",
"throw",
"$",
"exception",
";",
"}",
"return",
"$",
"retry",
"<",
"$",
"maxAttempts",
"&&",
"!",
"is_null",
"(",
"$",
"exception",
")",
";",
"}",
";",
"}"
]
| Gets a default decider that simply check exceptions and maxattempts
@return \Closure | [
"Gets",
"a",
"default",
"decider",
"that",
"simply",
"check",
"exceptions",
"and",
"maxattempts"
]
| 88b9a4a5da1cc5485e6fb0c5d35ee0d4149c3361 | https://github.com/stechstudio/backoff/blob/88b9a4a5da1cc5485e6fb0c5d35ee0d4149c3361/src/Backoff.php#L282-L291 | train |
frankkessler/guzzle-oauth2-middleware | src/GrantType/JwtBearer.php | JwtBearer.computeJwt | protected function computeJwt()
{
$payload = [
'iss' => $this->getConfig('client_id'),
'aud' => rtrim($this->getConfig('base_uri'), '/'),
'exp' => time() + 60 * 60,
'iat' => time(),
'sub' => '',
];
if (isset($this->config['jwt_payload']) && is_array($this->config['jwt_payload'])) {
$payload = array_replace($payload, $this->config['jwt_payload']);
}
$signer = $this->signerFactory($this->config['jwt_algorithm']);
$privateKey = new Key(file_get_contents($this->config['jwt_private_key']), $this->config['jwt_private_key_passphrase']);
$builder = $this->tokenBuilderFactory($payload);
$token = $builder->sign($signer, $privateKey)
->getToken();
return (string) $token;
} | php | protected function computeJwt()
{
$payload = [
'iss' => $this->getConfig('client_id'),
'aud' => rtrim($this->getConfig('base_uri'), '/'),
'exp' => time() + 60 * 60,
'iat' => time(),
'sub' => '',
];
if (isset($this->config['jwt_payload']) && is_array($this->config['jwt_payload'])) {
$payload = array_replace($payload, $this->config['jwt_payload']);
}
$signer = $this->signerFactory($this->config['jwt_algorithm']);
$privateKey = new Key(file_get_contents($this->config['jwt_private_key']), $this->config['jwt_private_key_passphrase']);
$builder = $this->tokenBuilderFactory($payload);
$token = $builder->sign($signer, $privateKey)
->getToken();
return (string) $token;
} | [
"protected",
"function",
"computeJwt",
"(",
")",
"{",
"$",
"payload",
"=",
"[",
"'iss'",
"=>",
"$",
"this",
"->",
"getConfig",
"(",
"'client_id'",
")",
",",
"'aud'",
"=>",
"rtrim",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'base_uri'",
")",
",",
"'/'",
")",
",",
"'exp'",
"=>",
"time",
"(",
")",
"+",
"60",
"*",
"60",
",",
"'iat'",
"=>",
"time",
"(",
")",
",",
"'sub'",
"=>",
"''",
",",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"config",
"[",
"'jwt_payload'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"this",
"->",
"config",
"[",
"'jwt_payload'",
"]",
")",
")",
"{",
"$",
"payload",
"=",
"array_replace",
"(",
"$",
"payload",
",",
"$",
"this",
"->",
"config",
"[",
"'jwt_payload'",
"]",
")",
";",
"}",
"$",
"signer",
"=",
"$",
"this",
"->",
"signerFactory",
"(",
"$",
"this",
"->",
"config",
"[",
"'jwt_algorithm'",
"]",
")",
";",
"$",
"privateKey",
"=",
"new",
"Key",
"(",
"file_get_contents",
"(",
"$",
"this",
"->",
"config",
"[",
"'jwt_private_key'",
"]",
")",
",",
"$",
"this",
"->",
"config",
"[",
"'jwt_private_key_passphrase'",
"]",
")",
";",
"$",
"builder",
"=",
"$",
"this",
"->",
"tokenBuilderFactory",
"(",
"$",
"payload",
")",
";",
"$",
"token",
"=",
"$",
"builder",
"->",
"sign",
"(",
"$",
"signer",
",",
"$",
"privateKey",
")",
"->",
"getToken",
"(",
")",
";",
"return",
"(",
"string",
")",
"$",
"token",
";",
"}"
]
| Compute JWT, signing with provided private key. | [
"Compute",
"JWT",
"signing",
"with",
"provided",
"private",
"key",
"."
]
| 00c0dd4093887f1921faa06cbbf0b5919ad5ad03 | https://github.com/frankkessler/guzzle-oauth2-middleware/blob/00c0dd4093887f1921faa06cbbf0b5919ad5ad03/src/GrantType/JwtBearer.php#L49-L73 | train |
frankkessler/guzzle-oauth2-middleware | src/Oauth2Client.php | Oauth2Client.returnHandlers | protected function returnHandlers()
{
// Create a handler stack that has all of the default middlewares attached
$handler = HandlerStack::create();
//Add the Authorization header to requests.
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
if ($this->getConfig('auth') == 'oauth2') {
$token = $this->getAccessToken();
if ($token !== null) {
$request = $request->withHeader('Authorization', 'Bearer '.$token->getToken());
return $request;
}
}
return $request;
}), 'add_oauth_header');
$handler->before('add_oauth_header', $this->retry_modify_request(function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) {
if ($retries > 0) {
return false;
}
if ($response instanceof ResponseInterface) {
if (in_array($response->getStatusCode(), [400, 401])) {
return true;
}
}
return false;
},
function (RequestInterface $request, ResponseInterface $response) {
if ($response instanceof ResponseInterface) {
if (in_array($response->getStatusCode(), [400, 401])) {
$token = $this->acquireAccessToken();
$this->setAccessToken($token, 'Bearer');
$modify['set_headers']['Authorization'] = 'Bearer '.$token->getToken();
return Psr7\modify_request($request, $modify);
}
}
return $request;
}
));
return $handler;
} | php | protected function returnHandlers()
{
// Create a handler stack that has all of the default middlewares attached
$handler = HandlerStack::create();
//Add the Authorization header to requests.
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
if ($this->getConfig('auth') == 'oauth2') {
$token = $this->getAccessToken();
if ($token !== null) {
$request = $request->withHeader('Authorization', 'Bearer '.$token->getToken());
return $request;
}
}
return $request;
}), 'add_oauth_header');
$handler->before('add_oauth_header', $this->retry_modify_request(function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) {
if ($retries > 0) {
return false;
}
if ($response instanceof ResponseInterface) {
if (in_array($response->getStatusCode(), [400, 401])) {
return true;
}
}
return false;
},
function (RequestInterface $request, ResponseInterface $response) {
if ($response instanceof ResponseInterface) {
if (in_array($response->getStatusCode(), [400, 401])) {
$token = $this->acquireAccessToken();
$this->setAccessToken($token, 'Bearer');
$modify['set_headers']['Authorization'] = 'Bearer '.$token->getToken();
return Psr7\modify_request($request, $modify);
}
}
return $request;
}
));
return $handler;
} | [
"protected",
"function",
"returnHandlers",
"(",
")",
"{",
"// Create a handler stack that has all of the default middlewares attached",
"$",
"handler",
"=",
"HandlerStack",
"::",
"create",
"(",
")",
";",
"//Add the Authorization header to requests.",
"$",
"handler",
"->",
"push",
"(",
"Middleware",
"::",
"mapRequest",
"(",
"function",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getConfig",
"(",
"'auth'",
")",
"==",
"'oauth2'",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"if",
"(",
"$",
"token",
"!==",
"null",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'Authorization'",
",",
"'Bearer '",
".",
"$",
"token",
"->",
"getToken",
"(",
")",
")",
";",
"return",
"$",
"request",
";",
"}",
"}",
"return",
"$",
"request",
";",
"}",
")",
",",
"'add_oauth_header'",
")",
";",
"$",
"handler",
"->",
"before",
"(",
"'add_oauth_header'",
",",
"$",
"this",
"->",
"retry_modify_request",
"(",
"function",
"(",
"$",
"retries",
",",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
"=",
"null",
",",
"$",
"error",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"retries",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"response",
"instanceof",
"ResponseInterface",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
",",
"[",
"400",
",",
"401",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
",",
"function",
"(",
"RequestInterface",
"$",
"request",
",",
"ResponseInterface",
"$",
"response",
")",
"{",
"if",
"(",
"$",
"response",
"instanceof",
"ResponseInterface",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
",",
"[",
"400",
",",
"401",
"]",
")",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"acquireAccessToken",
"(",
")",
";",
"$",
"this",
"->",
"setAccessToken",
"(",
"$",
"token",
",",
"'Bearer'",
")",
";",
"$",
"modify",
"[",
"'set_headers'",
"]",
"[",
"'Authorization'",
"]",
"=",
"'Bearer '",
".",
"$",
"token",
"->",
"getToken",
"(",
")",
";",
"return",
"Psr7",
"\\",
"modify_request",
"(",
"$",
"request",
",",
"$",
"modify",
")",
";",
"}",
"}",
"return",
"$",
"request",
";",
"}",
")",
")",
";",
"return",
"$",
"handler",
";",
"}"
]
| Set the middleware handlers for all requests using Oauth2.
@return HandlerStack|null | [
"Set",
"the",
"middleware",
"handlers",
"for",
"all",
"requests",
"using",
"Oauth2",
"."
]
| 00c0dd4093887f1921faa06cbbf0b5919ad5ad03 | https://github.com/frankkessler/guzzle-oauth2-middleware/blob/00c0dd4093887f1921faa06cbbf0b5919ad5ad03/src/Oauth2Client.php#L49-L98 | train |
frankkessler/guzzle-oauth2-middleware | src/Oauth2Client.php | Oauth2Client.retry_modify_request | public function retry_modify_request(callable $decider, callable $requestModifier, callable $delay = null)
{
return function (callable $handler) use ($decider, $requestModifier, $delay) {
return new RetryModifyRequestMiddleware($decider, $requestModifier, $handler, $delay);
};
} | php | public function retry_modify_request(callable $decider, callable $requestModifier, callable $delay = null)
{
return function (callable $handler) use ($decider, $requestModifier, $delay) {
return new RetryModifyRequestMiddleware($decider, $requestModifier, $handler, $delay);
};
} | [
"public",
"function",
"retry_modify_request",
"(",
"callable",
"$",
"decider",
",",
"callable",
"$",
"requestModifier",
",",
"callable",
"$",
"delay",
"=",
"null",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"decider",
",",
"$",
"requestModifier",
",",
"$",
"delay",
")",
"{",
"return",
"new",
"RetryModifyRequestMiddleware",
"(",
"$",
"decider",
",",
"$",
"requestModifier",
",",
"$",
"handler",
",",
"$",
"delay",
")",
";",
"}",
";",
"}"
]
| Retry Call after updating access token. | [
"Retry",
"Call",
"after",
"updating",
"access",
"token",
"."
]
| 00c0dd4093887f1921faa06cbbf0b5919ad5ad03 | https://github.com/frankkessler/guzzle-oauth2-middleware/blob/00c0dd4093887f1921faa06cbbf0b5919ad5ad03/src/Oauth2Client.php#L103-L108 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.