repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
scotteh/php-goose | src/Traits/DocumentMutatorTrait.php | DocumentMutatorTrait.document | protected function document(Document $document = null): ?Document {
if ($document === null) {
return $this->document;
}
$this->document = $document;
return $this->document;
} | php | protected function document(Document $document = null): ?Document {
if ($document === null) {
return $this->document;
}
$this->document = $document;
return $this->document;
} | [
"protected",
"function",
"document",
"(",
"Document",
"$",
"document",
"=",
"null",
")",
":",
"?",
"Document",
"{",
"if",
"(",
"$",
"document",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"document",
";",
"}",
"$",
"this",
"->",
"document",
... | @param Document $document
@return Document|null | [
"@param",
"Document",
"$document"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Traits/DocumentMutatorTrait.php#L22-L30 |
scotteh/php-goose | src/Crawler.php | Crawler.crawl | public function crawl(string $url, string $rawHTML = null): ?Article {
$article = new Article();
$parseCandidate = Helper::getCleanedUrl($url);
$xmlInternalErrors = libxml_use_internal_errors(true);
if (empty($rawHTML)) {
$guzzle = new \GuzzleHttp\Client();
$response = $guzzle->get($parseCandidate->url, $this->config()->get('browser'));
$article->setRawResponse($response);
$rawHTML = $response->getBody()->getContents();
}
// Generate document
$doc = $this->getDocument($rawHTML);
// Set core mutators
$article->setFinalUrl($parseCandidate->url);
$article->setDomain($parseCandidate->parts->host);
$article->setLinkhash($parseCandidate->linkhash);
$article->setRawHtml($rawHTML);
$article->setDoc($doc);
$article->setRawDoc(clone $doc);
// Pre-extraction document cleaning
$this->modules('cleaners', $article);
// Extract content
$this->modules('extractors', $article);
// Post-extraction content formatting
$this->modules('formatters', $article);
libxml_use_internal_errors($xmlInternalErrors);
return $article;
} | php | public function crawl(string $url, string $rawHTML = null): ?Article {
$article = new Article();
$parseCandidate = Helper::getCleanedUrl($url);
$xmlInternalErrors = libxml_use_internal_errors(true);
if (empty($rawHTML)) {
$guzzle = new \GuzzleHttp\Client();
$response = $guzzle->get($parseCandidate->url, $this->config()->get('browser'));
$article->setRawResponse($response);
$rawHTML = $response->getBody()->getContents();
}
// Generate document
$doc = $this->getDocument($rawHTML);
// Set core mutators
$article->setFinalUrl($parseCandidate->url);
$article->setDomain($parseCandidate->parts->host);
$article->setLinkhash($parseCandidate->linkhash);
$article->setRawHtml($rawHTML);
$article->setDoc($doc);
$article->setRawDoc(clone $doc);
// Pre-extraction document cleaning
$this->modules('cleaners', $article);
// Extract content
$this->modules('extractors', $article);
// Post-extraction content formatting
$this->modules('formatters', $article);
libxml_use_internal_errors($xmlInternalErrors);
return $article;
} | [
"public",
"function",
"crawl",
"(",
"string",
"$",
"url",
",",
"string",
"$",
"rawHTML",
"=",
"null",
")",
":",
"?",
"Article",
"{",
"$",
"article",
"=",
"new",
"Article",
"(",
")",
";",
"$",
"parseCandidate",
"=",
"Helper",
"::",
"getCleanedUrl",
"(",... | @param string $url
@param string|null $rawHTML
@return Article | [
"@param",
"string",
"$url",
"@param",
"string|null",
"$rawHTML"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Crawler.php#L38-L75 |
scotteh/php-goose | src/Crawler.php | Crawler.getDocument | private function getDocument(string $rawHTML): Document {
$doc = new Document();
$doc->html($rawHTML);
return $doc;
} | php | private function getDocument(string $rawHTML): Document {
$doc = new Document();
$doc->html($rawHTML);
return $doc;
} | [
"private",
"function",
"getDocument",
"(",
"string",
"$",
"rawHTML",
")",
":",
"Document",
"{",
"$",
"doc",
"=",
"new",
"Document",
"(",
")",
";",
"$",
"doc",
"->",
"html",
"(",
"$",
"rawHTML",
")",
";",
"return",
"$",
"doc",
";",
"}"
] | @param string $rawHTML
@return Document | [
"@param",
"string",
"$rawHTML"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Crawler.php#L82-L87 |
scotteh/php-goose | src/Crawler.php | Crawler.modules | public function modules(string $category, Article $article): self {
$modules = $this->config->getModules($category);
foreach ($modules as $module) {
$obj = new $module($this->config());
$obj->run($article);
}
return $this;
} | php | public function modules(string $category, Article $article): self {
$modules = $this->config->getModules($category);
foreach ($modules as $module) {
$obj = new $module($this->config());
$obj->run($article);
}
return $this;
} | [
"public",
"function",
"modules",
"(",
"string",
"$",
"category",
",",
"Article",
"$",
"article",
")",
":",
"self",
"{",
"$",
"modules",
"=",
"$",
"this",
"->",
"config",
"->",
"getModules",
"(",
"$",
"category",
")",
";",
"foreach",
"(",
"$",
"modules"... | @param string $category
@param Article $article
@return self | [
"@param",
"string",
"$category",
"@param",
"Article",
"$article"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Crawler.php#L95-L104 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getOpenGraph | private function getOpenGraph(): array {
$results = array();
$nodes = $this->article()->getDoc()->find('meta[property^="og:"]');
foreach ($nodes as $node) {
$property = explode(':', $node->attr('property'));
array_shift($property);
$results[implode(':', $property)] = $node->attr('content');
}
// Additionally retrieve type values based on provided og:type (http://ogp.me/#types)
if (isset($results['type'])) {
$nodes = $this->article()->getDoc()->find('meta[property^="' . $results['type'] .':"]');
foreach ($nodes as $node) {
$property = explode(':', $node->attr('property'));
array_shift($property);
$results[implode(':', $property)] = $node->attr('content');
}
}
return $results;
} | php | private function getOpenGraph(): array {
$results = array();
$nodes = $this->article()->getDoc()->find('meta[property^="og:"]');
foreach ($nodes as $node) {
$property = explode(':', $node->attr('property'));
array_shift($property);
$results[implode(':', $property)] = $node->attr('content');
}
// Additionally retrieve type values based on provided og:type (http://ogp.me/#types)
if (isset($results['type'])) {
$nodes = $this->article()->getDoc()->find('meta[property^="' . $results['type'] .':"]');
foreach ($nodes as $node) {
$property = explode(':', $node->attr('property'));
array_shift($property);
$results[implode(':', $property)] = $node->attr('content');
}
}
return $results;
} | [
"private",
"function",
"getOpenGraph",
"(",
")",
":",
"array",
"{",
"$",
"results",
"=",
"array",
"(",
")",
";",
"$",
"nodes",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getDoc",
"(",
")",
"->",
"find",
"(",
"'meta[property^=\"og:\"]'",
")",
... | Retrieve all OpenGraph meta data
Ported from python-goose https://github.com/grangier/python-goose/ by Xavier Grangier
@return string[] | [
"Retrieve",
"all",
"OpenGraph",
"meta",
"data"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L48-L71 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.cleanTitle | private function cleanTitle(string $title): string {
$openGraph = $this->article()->getOpenGraph();
// Check if we have the site name in OpenGraph data and it does not match the title
if (isset($openGraph['site_name']) && $openGraph['site_name'] != $title) {
$title = str_replace($openGraph['site_name'], '', $title);
}
// Try to remove the domain from URL
if ($this->article()->getDomain()) {
$title = str_ireplace($this->article()->getDomain(), '', $title);
}
// Split the title in words
// TechCrunch | my wonderfull article
// my wonderfull article | TechCrunch
$titleWords = preg_split('@[\s]+@', trim($title));
// Check for an empty title
if (empty($titleWords)) {
return '';
}
// Check if last letter is in self::$SPLITTER_CHARS
// if so remove it
if (in_array($titleWords[count($titleWords) - 1], self::$SPLITTER_CHARS)) {
array_pop($titleWords);
}
// Check if first letter is in self::$SPLITTER_CHARS
// if so remove it
if (isset($titleWords[0]) && in_array($titleWords[0], self::$SPLITTER_CHARS)) {
array_shift($titleWords);
}
// Rebuild the title
$title = trim(implode(' ', $titleWords));
return $title;
} | php | private function cleanTitle(string $title): string {
$openGraph = $this->article()->getOpenGraph();
// Check if we have the site name in OpenGraph data and it does not match the title
if (isset($openGraph['site_name']) && $openGraph['site_name'] != $title) {
$title = str_replace($openGraph['site_name'], '', $title);
}
// Try to remove the domain from URL
if ($this->article()->getDomain()) {
$title = str_ireplace($this->article()->getDomain(), '', $title);
}
// Split the title in words
// TechCrunch | my wonderfull article
// my wonderfull article | TechCrunch
$titleWords = preg_split('@[\s]+@', trim($title));
// Check for an empty title
if (empty($titleWords)) {
return '';
}
// Check if last letter is in self::$SPLITTER_CHARS
// if so remove it
if (in_array($titleWords[count($titleWords) - 1], self::$SPLITTER_CHARS)) {
array_pop($titleWords);
}
// Check if first letter is in self::$SPLITTER_CHARS
// if so remove it
if (isset($titleWords[0]) && in_array($titleWords[0], self::$SPLITTER_CHARS)) {
array_shift($titleWords);
}
// Rebuild the title
$title = trim(implode(' ', $titleWords));
return $title;
} | [
"private",
"function",
"cleanTitle",
"(",
"string",
"$",
"title",
")",
":",
"string",
"{",
"$",
"openGraph",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getOpenGraph",
"(",
")",
";",
"// Check if we have the site name in OpenGraph data and it does not match ... | Clean title text
Ported from python-goose https://github.com/grangier/python-goose/ by Xavier Grangier
@param string $title
@return string | [
"Clean",
"title",
"text"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L82-L121 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getTitle | private function getTitle(): string {
$openGraph = $this->article()->getOpenGraph();
// Rely on OpenGraph in case we have the data
if (isset($openGraph['title'])) {
return $this->cleanTitle($openGraph['title']);
}
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'meta', 'name', 'headline');
if ($nodes->count()) {
return $this->cleanTitle($nodes->first()->attr('content'));
}
$nodes = $this->article()->getDoc()->find('html > head > title');
if ($nodes->count()) {
return $this->cleanTitle(Helper::textNormalise($nodes->first()->text()));
}
return '';
} | php | private function getTitle(): string {
$openGraph = $this->article()->getOpenGraph();
// Rely on OpenGraph in case we have the data
if (isset($openGraph['title'])) {
return $this->cleanTitle($openGraph['title']);
}
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'meta', 'name', 'headline');
if ($nodes->count()) {
return $this->cleanTitle($nodes->first()->attr('content'));
}
$nodes = $this->article()->getDoc()->find('html > head > title');
if ($nodes->count()) {
return $this->cleanTitle(Helper::textNormalise($nodes->first()->text()));
}
return '';
} | [
"private",
"function",
"getTitle",
"(",
")",
":",
"string",
"{",
"$",
"openGraph",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getOpenGraph",
"(",
")",
";",
"// Rely on OpenGraph in case we have the data",
"if",
"(",
"isset",
"(",
"$",
"openGraph",
"... | Get article title
Ported from python-goose https://github.com/grangier/python-goose/ by Xavier Grangier
@return string | [
"Get",
"article",
"title"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L130-L149 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getNodesByLowercasePropertyValue | private function getNodesByLowercasePropertyValue(Document $doc, string $tag, string $property, string $value): NodeList {
return $doc->findXPath("descendant::".$tag."[translate(@".$property.", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='".$value."']");
} | php | private function getNodesByLowercasePropertyValue(Document $doc, string $tag, string $property, string $value): NodeList {
return $doc->findXPath("descendant::".$tag."[translate(@".$property.", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='".$value."']");
} | [
"private",
"function",
"getNodesByLowercasePropertyValue",
"(",
"Document",
"$",
"doc",
",",
"string",
"$",
"tag",
",",
"string",
"$",
"property",
",",
"string",
"$",
"value",
")",
":",
"NodeList",
"{",
"return",
"$",
"doc",
"->",
"findXPath",
"(",
"\"descen... | @param Document $doc
@param string $tag
@param string $property
@param string $value
@return NodeList | [
"@param",
"Document",
"$doc",
"@param",
"string",
"$tag",
"@param",
"string",
"$property",
"@param",
"string",
"$value"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L159-L161 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getMetaContent | private function getMetaContent(Document $doc, string $property, string $value, string $attr = 'content'): string {
$nodes = $this->getNodesByLowercasePropertyValue($doc, 'meta', $property, $value);
if (!$nodes->count()) {
return '';
}
$content = $nodes->first()->attr($attr);
if (!is_string($content)) {
return '';
}
return trim($content);
} | php | private function getMetaContent(Document $doc, string $property, string $value, string $attr = 'content'): string {
$nodes = $this->getNodesByLowercasePropertyValue($doc, 'meta', $property, $value);
if (!$nodes->count()) {
return '';
}
$content = $nodes->first()->attr($attr);
if (!is_string($content)) {
return '';
}
return trim($content);
} | [
"private",
"function",
"getMetaContent",
"(",
"Document",
"$",
"doc",
",",
"string",
"$",
"property",
",",
"string",
"$",
"value",
",",
"string",
"$",
"attr",
"=",
"'content'",
")",
":",
"string",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"getNodesByLow... | @param Document $doc
@param string $property
@param string $value
@param string $attr
@return string | [
"@param",
"Document",
"$doc",
"@param",
"string",
"$property",
"@param",
"string",
"$value",
"@param",
"string",
"$attr"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L171-L185 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getMetaLanguage | private function getMetaLanguage(): string {
$lang = '';
$el = $this->article()->getDoc()->find('html[lang]');
if ($el->count()) {
$lang = $el->first()->attr('lang');
}
if (empty($lang)) {
$selectors = [
'html > head > meta[http-equiv=content-language]',
'html > head > meta[name=lang]',
];
foreach ($selectors as $selector) {
$el = $this->article()->getDoc()->find($selector);
if ($el->count()) {
$lang = $el->first()->attr('content');
break;
}
}
}
if (preg_match('@^[A-Za-z]{2}$@', $lang)) {
return strtolower($lang);
}
return '';
} | php | private function getMetaLanguage(): string {
$lang = '';
$el = $this->article()->getDoc()->find('html[lang]');
if ($el->count()) {
$lang = $el->first()->attr('lang');
}
if (empty($lang)) {
$selectors = [
'html > head > meta[http-equiv=content-language]',
'html > head > meta[name=lang]',
];
foreach ($selectors as $selector) {
$el = $this->article()->getDoc()->find($selector);
if ($el->count()) {
$lang = $el->first()->attr('content');
break;
}
}
}
if (preg_match('@^[A-Za-z]{2}$@', $lang)) {
return strtolower($lang);
}
return '';
} | [
"private",
"function",
"getMetaLanguage",
"(",
")",
":",
"string",
"{",
"$",
"lang",
"=",
"''",
";",
"$",
"el",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getDoc",
"(",
")",
"->",
"find",
"(",
"'html[lang]'",
")",
";",
"if",
"(",
"$",
"e... | If the article has meta language set in the source, use that
@return string | [
"If",
"the",
"article",
"has",
"meta",
"language",
"set",
"in",
"the",
"source",
"use",
"that"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L192-L222 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getMetaDescription | private function getMetaDescription(): string {
$desc = $this->getMetaContent($this->article()->getDoc(), 'name', 'description');
if (empty($desc)) {
$desc = $this->getMetaContent($this->article()->getDoc(), 'property', 'og:description');
}
if (empty($desc)) {
$desc = $this->getMetaContent($this->article()->getDoc(), 'name', 'twitter:description');
}
return trim($desc);
} | php | private function getMetaDescription(): string {
$desc = $this->getMetaContent($this->article()->getDoc(), 'name', 'description');
if (empty($desc)) {
$desc = $this->getMetaContent($this->article()->getDoc(), 'property', 'og:description');
}
if (empty($desc)) {
$desc = $this->getMetaContent($this->article()->getDoc(), 'name', 'twitter:description');
}
return trim($desc);
} | [
"private",
"function",
"getMetaDescription",
"(",
")",
":",
"string",
"{",
"$",
"desc",
"=",
"$",
"this",
"->",
"getMetaContent",
"(",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getDoc",
"(",
")",
",",
"'name'",
",",
"'description'",
")",
";",
"if"... | If the article has meta description set in the source, use that
@return string | [
"If",
"the",
"article",
"has",
"meta",
"description",
"set",
"in",
"the",
"source",
"use",
"that"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L229-L241 |
scotteh/php-goose | src/Modules/Extractors/MetaExtractor.php | MetaExtractor.getCanonicalLink | private function getCanonicalLink(): ?string {
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'link', 'rel', 'canonical');
if ($nodes->count()) {
return trim($nodes->first()->attr('href'));
}
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'meta', 'property', 'og:url');
if ($nodes->count()) {
return trim($nodes->first()->attr('content'));
}
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'meta', 'name', 'twitter:url');
if ($nodes->count()) {
return trim($nodes->first()->attr('content'));
}
return $this->article()->getFinalUrl();
} | php | private function getCanonicalLink(): ?string {
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'link', 'rel', 'canonical');
if ($nodes->count()) {
return trim($nodes->first()->attr('href'));
}
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'meta', 'property', 'og:url');
if ($nodes->count()) {
return trim($nodes->first()->attr('content'));
}
$nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'meta', 'name', 'twitter:url');
if ($nodes->count()) {
return trim($nodes->first()->attr('content'));
}
return $this->article()->getFinalUrl();
} | [
"private",
"function",
"getCanonicalLink",
"(",
")",
":",
"?",
"string",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"getNodesByLowercasePropertyValue",
"(",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getDoc",
"(",
")",
",",
"'link'",
",",
"'rel'",
",... | If the article has meta canonical link set in the url
@return string|null | [
"If",
"the",
"article",
"has",
"meta",
"canonical",
"link",
"set",
"in",
"the",
"url"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/MetaExtractor.php#L257-L277 |
middlewares/fast-route | src/FastRoute.php | FastRoute.process | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$route = $this->router->dispatch($request->getMethod(), rawurldecode($request->getUri()->getPath()));
if ($route[0] === Dispatcher::NOT_FOUND) {
return $this->createResponse(404);
}
if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) {
return $this->createResponse(405)->withHeader('Allow', implode(', ', $route[1]));
}
foreach ($route[2] as $name => $value) {
$request = $request->withAttribute($name, $value);
}
$request = $this->setHandler($request, $route[1]);
return $handler->handle($request);
} | php | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$route = $this->router->dispatch($request->getMethod(), rawurldecode($request->getUri()->getPath()));
if ($route[0] === Dispatcher::NOT_FOUND) {
return $this->createResponse(404);
}
if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) {
return $this->createResponse(405)->withHeader('Allow', implode(', ', $route[1]));
}
foreach ($route[2] as $name => $value) {
$request = $request->withAttribute($name, $value);
}
$request = $this->setHandler($request, $route[1]);
return $handler->handle($request);
} | [
"public",
"function",
"process",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"RequestHandlerInterface",
"$",
"handler",
")",
":",
"ResponseInterface",
"{",
"$",
"route",
"=",
"$",
"this",
"->",
"router",
"->",
"dispatch",
"(",
"$",
"request",
"->",
"ge... | Process a server request and return a response. | [
"Process",
"a",
"server",
"request",
"and",
"return",
"a",
"response",
"."
] | train | https://github.com/middlewares/fast-route/blob/5f47b9fe253c08f3bf79dc4a245f51468d8df2f8/src/FastRoute.php#L51-L70 |
middlewares/fast-route | src/FastRoute.php | FastRoute.setHandler | protected function setHandler(ServerRequestInterface $request, $handler): ServerRequestInterface
{
return $request->withAttribute($this->attribute, $handler);
} | php | protected function setHandler(ServerRequestInterface $request, $handler): ServerRequestInterface
{
return $request->withAttribute($this->attribute, $handler);
} | [
"protected",
"function",
"setHandler",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"$",
"handler",
")",
":",
"ServerRequestInterface",
"{",
"return",
"$",
"request",
"->",
"withAttribute",
"(",
"$",
"this",
"->",
"attribute",
",",
"$",
"handler",
")",
... | Set the handler reference on the request.
@param mixed $handler | [
"Set",
"the",
"handler",
"reference",
"on",
"the",
"request",
"."
] | train | https://github.com/middlewares/fast-route/blob/5f47b9fe253c08f3bf79dc4a245f51468d8df2f8/src/FastRoute.php#L77-L80 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.create | public function create($bare = null)
{
mkdir($this->getPath());
$command = 'init';
if ($bare) {
$command .= ' --bare';
}
$this->getClient()->run($this, $command);
return $this;
} | php | public function create($bare = null)
{
mkdir($this->getPath());
$command = 'init';
if ($bare) {
$command .= ' --bare';
}
$this->getClient()->run($this, $command);
return $this;
} | [
"public",
"function",
"create",
"(",
"$",
"bare",
"=",
"null",
")",
"{",
"mkdir",
"(",
"$",
"this",
"->",
"getPath",
"(",
")",
")",
";",
"$",
"command",
"=",
"'init'",
";",
"if",
"(",
"$",
"bare",
")",
"{",
"$",
"command",
".=",
"' --bare'",
";",... | Create a new git repository. | [
"Create",
"a",
"new",
"git",
"repository",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L53-L65 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getConfig | public function getConfig($key)
{
$key = $this->getClient()->run($this, 'config ' . $key);
return trim($key);
} | php | public function getConfig($key)
{
$key = $this->getClient()->run($this, 'config ' . $key);
return trim($key);
} | [
"public",
"function",
"getConfig",
"(",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"run",
"(",
"$",
"this",
",",
"'config '",
".",
"$",
"key",
")",
";",
"return",
"trim",
"(",
"$",
"key",
")",
";",
"}... | Get a git configuration variable.
@param string $key Configuration key | [
"Get",
"a",
"git",
"configuration",
"variable",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L72-L77 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.addStatistics | public function addStatistics($statistics)
{
if (!is_array($statistics)) {
$statistics = array($statistics);
}
foreach ($statistics as $statistic) {
$reflect = new \ReflectionClass($statistic);
$this->statistics[strtolower($reflect->getShortName())] = $statistic;
}
} | php | public function addStatistics($statistics)
{
if (!is_array($statistics)) {
$statistics = array($statistics);
}
foreach ($statistics as $statistic) {
$reflect = new \ReflectionClass($statistic);
$this->statistics[strtolower($reflect->getShortName())] = $statistic;
}
} | [
"public",
"function",
"addStatistics",
"(",
"$",
"statistics",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"statistics",
")",
")",
"{",
"$",
"statistics",
"=",
"array",
"(",
"$",
"statistics",
")",
";",
"}",
"foreach",
"(",
"$",
"statistics",
"as",... | Add statistic aggregator.
@param StatisticsInterface|array $statistics | [
"Add",
"statistic",
"aggregator",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L97-L107 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getStatistics | public function getStatistics()
{
if (false === $this->getCommitsHaveBeenParsed()) {
$this->getCommits();
}
foreach ($this->statistics as $statistic) {
$statistic->sortCommits();
}
return $this->statistics;
} | php | public function getStatistics()
{
if (false === $this->getCommitsHaveBeenParsed()) {
$this->getCommits();
}
foreach ($this->statistics as $statistic) {
$statistic->sortCommits();
}
return $this->statistics;
} | [
"public",
"function",
"getStatistics",
"(",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"this",
"->",
"getCommitsHaveBeenParsed",
"(",
")",
")",
"{",
"$",
"this",
"->",
"getCommits",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"statistics",
"a... | Get statistic aggregators.
@return array | [
"Get",
"statistic",
"aggregators",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L114-L125 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.add | public function add($files = '.')
{
if (is_array($files)) {
$files = implode(' ', array_map('escapeshellarg', $files));
} else {
$files = escapeshellarg($files);
}
$this->getClient()->run($this, "add $files");
return $this;
} | php | public function add($files = '.')
{
if (is_array($files)) {
$files = implode(' ', array_map('escapeshellarg', $files));
} else {
$files = escapeshellarg($files);
}
$this->getClient()->run($this, "add $files");
return $this;
} | [
"public",
"function",
"add",
"(",
"$",
"files",
"=",
"'.'",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"files",
")",
")",
"{",
"$",
"files",
"=",
"implode",
"(",
"' '",
",",
"array_map",
"(",
"'escapeshellarg'",
",",
"$",
"files",
")",
")",
";",
... | Add untracked files.
@param mixed $files Files to be added to the repository | [
"Add",
"untracked",
"files",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L132-L143 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.push | public function push($repository = null, $refspec = null)
{
$command = 'push';
if ($repository) {
$command .= " $repository";
}
if ($refspec) {
$command .= " $refspec";
}
$this->getClient()->run($this, $command);
return $this;
} | php | public function push($repository = null, $refspec = null)
{
$command = 'push';
if ($repository) {
$command .= " $repository";
}
if ($refspec) {
$command .= " $refspec";
}
$this->getClient()->run($this, $command);
return $this;
} | [
"public",
"function",
"push",
"(",
"$",
"repository",
"=",
"null",
",",
"$",
"refspec",
"=",
"null",
")",
"{",
"$",
"command",
"=",
"'push'",
";",
"if",
"(",
"$",
"repository",
")",
"{",
"$",
"command",
".=",
"\" $repository\"",
";",
"}",
"if",
"(",
... | Update remote references.
@param string $repository Repository to be pushed
@param string $refspec Refspec for the push | [
"Update",
"remote",
"references",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L195-L210 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getName | public function getName()
{
$name = rtrim($this->path, '/');
if (strstr($name, DIRECTORY_SEPARATOR)) {
$name = substr($name, strrpos($name, DIRECTORY_SEPARATOR) + 1);
}
return trim($name);
} | php | public function getName()
{
$name = rtrim($this->path, '/');
if (strstr($name, DIRECTORY_SEPARATOR)) {
$name = substr($name, strrpos($name, DIRECTORY_SEPARATOR) + 1);
}
return trim($name);
} | [
"public",
"function",
"getName",
"(",
")",
"{",
"$",
"name",
"=",
"rtrim",
"(",
"$",
"this",
"->",
"path",
",",
"'/'",
")",
";",
"if",
"(",
"strstr",
"(",
"$",
"name",
",",
"DIRECTORY_SEPARATOR",
")",
")",
"{",
"$",
"name",
"=",
"substr",
"(",
"$... | Get name of repository (top level directory).
@return string | [
"Get",
"name",
"of",
"repository",
"(",
"top",
"level",
"directory",
")",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L217-L226 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getBranches | public function getBranches()
{
static $cache = array();
if (array_key_exists($this->path, $cache)) {
return $cache[$this->path];
}
$branches = $this->getClient()->run($this, 'branch');
$branches = explode("\n", $branches);
$branches = array_filter(preg_replace('/[\*\s]/', '', $branches));
if (empty($branches)) {
return $cache[$this->path] = $branches;
}
// Since we've stripped whitespace, the result "* (detached from "
// and "* (no branch)" that is displayed in detached HEAD state
// becomes "(detachedfrom" and "(nobranch)" respectively.
if ((0 === strpos($branches[0], '(detachedfrom')) || ('(nobranch)' === $branches[0])) {
$branches = array_slice($branches, 1);
}
return $cache[$this->path] = $branches;
} | php | public function getBranches()
{
static $cache = array();
if (array_key_exists($this->path, $cache)) {
return $cache[$this->path];
}
$branches = $this->getClient()->run($this, 'branch');
$branches = explode("\n", $branches);
$branches = array_filter(preg_replace('/[\*\s]/', '', $branches));
if (empty($branches)) {
return $cache[$this->path] = $branches;
}
// Since we've stripped whitespace, the result "* (detached from "
// and "* (no branch)" that is displayed in detached HEAD state
// becomes "(detachedfrom" and "(nobranch)" respectively.
if ((0 === strpos($branches[0], '(detachedfrom')) || ('(nobranch)' === $branches[0])) {
$branches = array_slice($branches, 1);
}
return $cache[$this->path] = $branches;
} | [
"public",
"function",
"getBranches",
"(",
")",
"{",
"static",
"$",
"cache",
"=",
"array",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"this",
"->",
"path",
",",
"$",
"cache",
")",
")",
"{",
"return",
"$",
"cache",
"[",
"$",
"this",
"->"... | Show a list of the repository branches.
@return array List of branches | [
"Show",
"a",
"list",
"of",
"the",
"repository",
"branches",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L233-L257 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getCurrentBranch | public function getCurrentBranch()
{
$branches = $this->getClient()->run($this, 'branch');
$branches = explode("\n", $branches);
foreach ($branches as $branch) {
if ('*' === $branch[0]) {
if (preg_match('/(detached|no branch)/', $branch)) {
return null;
}
return substr($branch, 2);
}
}
} | php | public function getCurrentBranch()
{
$branches = $this->getClient()->run($this, 'branch');
$branches = explode("\n", $branches);
foreach ($branches as $branch) {
if ('*' === $branch[0]) {
if (preg_match('/(detached|no branch)/', $branch)) {
return null;
}
return substr($branch, 2);
}
}
} | [
"public",
"function",
"getCurrentBranch",
"(",
")",
"{",
"$",
"branches",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"run",
"(",
"$",
"this",
",",
"'branch'",
")",
";",
"$",
"branches",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"branches",
... | Return the current repository branch.
@return mixed current repository branch as a string, or NULL if in
detached HEAD state | [
"Return",
"the",
"current",
"repository",
"branch",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L265-L279 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.hasBranch | public function hasBranch($branch)
{
$branches = $this->getBranches();
$status = in_array($branch, $branches);
return $status;
} | php | public function hasBranch($branch)
{
$branches = $this->getBranches();
$status = in_array($branch, $branches);
return $status;
} | [
"public",
"function",
"hasBranch",
"(",
"$",
"branch",
")",
"{",
"$",
"branches",
"=",
"$",
"this",
"->",
"getBranches",
"(",
")",
";",
"$",
"status",
"=",
"in_array",
"(",
"$",
"branch",
",",
"$",
"branches",
")",
";",
"return",
"$",
"status",
";",
... | Check if a specified branch exists.
@param string $branch Branch to be checked
@return bool True if the branch exists | [
"Check",
"if",
"a",
"specified",
"branch",
"exists",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L288-L294 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.createTag | public function createTag($tag, $message = null)
{
$command = 'tag';
if ($message) {
$command .= " -a -m '$message'";
}
$command .= " $tag";
$this->getClient()->run($this, $command);
} | php | public function createTag($tag, $message = null)
{
$command = 'tag';
if ($message) {
$command .= " -a -m '$message'";
}
$command .= " $tag";
$this->getClient()->run($this, $command);
} | [
"public",
"function",
"createTag",
"(",
"$",
"tag",
",",
"$",
"message",
"=",
"null",
")",
"{",
"$",
"command",
"=",
"'tag'",
";",
"if",
"(",
"$",
"message",
")",
"{",
"$",
"command",
".=",
"\" -a -m '$message'\"",
";",
"}",
"$",
"command",
".=",
"\"... | Create a new repository tag.
@param string $tag Tag name | [
"Create",
"a",
"new",
"repository",
"tag",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L311-L322 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getTags | public function getTags()
{
static $cache = array();
if (array_key_exists($this->path, $cache)) {
return $cache[$this->path];
}
$tags = $this->getClient()->run($this, 'tag');
$tags = explode("\n", $tags);
array_pop($tags);
if (empty($tags[0])) {
return $cache[$this->path] = null;
}
return $cache[$this->path] = $tags;
} | php | public function getTags()
{
static $cache = array();
if (array_key_exists($this->path, $cache)) {
return $cache[$this->path];
}
$tags = $this->getClient()->run($this, 'tag');
$tags = explode("\n", $tags);
array_pop($tags);
if (empty($tags[0])) {
return $cache[$this->path] = null;
}
return $cache[$this->path] = $tags;
} | [
"public",
"function",
"getTags",
"(",
")",
"{",
"static",
"$",
"cache",
"=",
"array",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"this",
"->",
"path",
",",
"$",
"cache",
")",
")",
"{",
"return",
"$",
"cache",
"[",
"$",
"this",
"->",
... | Show a list of the repository tags.
@return array List of tags | [
"Show",
"a",
"list",
"of",
"the",
"repository",
"tags",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L329-L346 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getTotalCommits | public function getTotalCommits($file = null)
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = "rev-list --count --all $file";
} else {
$command = "rev-list --all $file | wc -l";
}
$commits = $this->getClient()->run($this, $command);
return trim($commits);
} | php | public function getTotalCommits($file = null)
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$command = "rev-list --count --all $file";
} else {
$command = "rev-list --all $file | wc -l";
}
$commits = $this->getClient()->run($this, $command);
return trim($commits);
} | [
"public",
"function",
"getTotalCommits",
"(",
"$",
"file",
"=",
"null",
")",
"{",
"if",
"(",
"defined",
"(",
"'PHP_WINDOWS_VERSION_BUILD'",
")",
")",
"{",
"$",
"command",
"=",
"\"rev-list --count --all $file\"",
";",
"}",
"else",
"{",
"$",
"command",
"=",
"\... | Show the amount of commits on the repository.
@return int Total number of commits | [
"Show",
"the",
"amount",
"of",
"commits",
"on",
"the",
"repository",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L353-L364 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getCommits | public function getCommits($file = null)
{
$command = 'log --pretty=format:"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</commiter><commiter_email>%ce</commiter_email><commiter_date>%ct</commiter_date><message><![CDATA[%s]]></message></item>"';
if ($file) {
$command .= " $file";
}
$logs = $this->getPrettyFormat($command);
foreach ($logs as $log) {
$commit = new Commit();
$commit->importData($log);
$commits[] = $commit;
foreach ($this->statistics as $statistic) {
$statistic->addCommit($commit);
}
}
$this->setCommitsHaveBeenParsed(true);
return $commits;
} | php | public function getCommits($file = null)
{
$command = 'log --pretty=format:"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</commiter><commiter_email>%ce</commiter_email><commiter_date>%ct</commiter_date><message><![CDATA[%s]]></message></item>"';
if ($file) {
$command .= " $file";
}
$logs = $this->getPrettyFormat($command);
foreach ($logs as $log) {
$commit = new Commit();
$commit->importData($log);
$commits[] = $commit;
foreach ($this->statistics as $statistic) {
$statistic->addCommit($commit);
}
}
$this->setCommitsHaveBeenParsed(true);
return $commits;
} | [
"public",
"function",
"getCommits",
"(",
"$",
"file",
"=",
"null",
")",
"{",
"$",
"command",
"=",
"'log --pretty=format:\"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</c... | Show the repository commit log.
@return array Commit log | [
"Show",
"the",
"repository",
"commit",
"log",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L371-L394 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getCommit | public function getCommit($commitHash)
{
if (version_compare($this->getClient()->getVersion(), '1.8.4', '>=')) {
$logs = $this->getClient()->run($this, "show --ignore-blank-lines -w -b --pretty=format:\"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</commiter><commiter_email>%ce</commiter_email><commiter_date>%ct</commiter_date><message><![CDATA[%s]]></message><body><![CDATA[%b]]></body></item>\" $commitHash");
} else {
$logs = $this->getClient()->run($this, "show --pretty=format:\"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</commiter><commiter_email>%ce</commiter_email><commiter_date>%ct</commiter_date><message><![CDATA[%s]]></message><body><![CDATA[%b]]></body></item>\" $commitHash");
}
$xmlEnd = strpos($logs, '</item>') + 7;
$commitInfo = substr($logs, 0, $xmlEnd);
$commitData = substr($logs, $xmlEnd);
$logs = explode("\n", $commitData);
array_shift($logs);
// Read commit metadata
$format = new PrettyFormat();
$data = $format->parse($commitInfo);
$commit = new Commit();
$commit->importData($data[0]);
if (empty($logs[1])) {
$logs = explode("\n", $this->getClient()->run($this, 'diff ' . $commitHash . '~1..' . $commitHash));
}
$commit->setDiffs($this->readDiffLogs($logs));
return $commit;
} | php | public function getCommit($commitHash)
{
if (version_compare($this->getClient()->getVersion(), '1.8.4', '>=')) {
$logs = $this->getClient()->run($this, "show --ignore-blank-lines -w -b --pretty=format:\"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</commiter><commiter_email>%ce</commiter_email><commiter_date>%ct</commiter_date><message><![CDATA[%s]]></message><body><![CDATA[%b]]></body></item>\" $commitHash");
} else {
$logs = $this->getClient()->run($this, "show --pretty=format:\"<item><hash>%H</hash><short_hash>%h</short_hash><tree>%T</tree><parents>%P</parents><author>%an</author><author_email>%ae</author_email><date>%at</date><commiter>%cn</commiter><commiter_email>%ce</commiter_email><commiter_date>%ct</commiter_date><message><![CDATA[%s]]></message><body><![CDATA[%b]]></body></item>\" $commitHash");
}
$xmlEnd = strpos($logs, '</item>') + 7;
$commitInfo = substr($logs, 0, $xmlEnd);
$commitData = substr($logs, $xmlEnd);
$logs = explode("\n", $commitData);
array_shift($logs);
// Read commit metadata
$format = new PrettyFormat();
$data = $format->parse($commitInfo);
$commit = new Commit();
$commit->importData($data[0]);
if (empty($logs[1])) {
$logs = explode("\n", $this->getClient()->run($this, 'diff ' . $commitHash . '~1..' . $commitHash));
}
$commit->setDiffs($this->readDiffLogs($logs));
return $commit;
} | [
"public",
"function",
"getCommit",
"(",
"$",
"commitHash",
")",
"{",
"if",
"(",
"version_compare",
"(",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"getVersion",
"(",
")",
",",
"'1.8.4'",
",",
"'>='",
")",
")",
"{",
"$",
"logs",
"=",
"$",
"this",... | Show the data from a specific commit.
@param string $commitHash Hash of the specific commit to read data
@return array Commit data | [
"Show",
"the",
"data",
"from",
"a",
"specific",
"commit",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L403-L429 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.readDiffLogs | public function readDiffLogs(array $logs)
{
$diffs = array();
$lineNumOld = 0;
$lineNumNew = 0;
foreach ($logs as $log) {
if ('diff' === substr($log, 0, 4)) {
if (isset($diff)) {
$diffs[] = $diff;
}
$diff = new Diff();
if (preg_match('/^diff --[\S]+ a\/?(.+) b\/?/', $log, $name)) {
$diff->setFile($name[1]);
}
continue;
}
if ('index' === substr($log, 0, 5)) {
$diff->setIndex($log);
continue;
}
if ('---' === substr($log, 0, 3)) {
$diff->setOld($log);
continue;
}
if ('+++' === substr($log, 0, 3)) {
$diff->setNew($log);
continue;
}
// Handle binary files properly.
if ('Binary' === substr($log, 0, 6)) {
$m = array();
if (preg_match('/Binary files (.+) and (.+) differ/', $log, $m)) {
$diff->setOld($m[1]);
$diff->setNew(" {$m[2]}");
}
}
if (!empty($log)) {
switch ($log[0]) {
case '@':
// Set the line numbers
preg_match('/@@ -([0-9]+)/', $log, $matches);
$lineNumOld = $matches[1] - 1;
$lineNumNew = $matches[1] - 1;
break;
case '-':
$lineNumOld++;
break;
case '+':
$lineNumNew++;
break;
default:
$lineNumOld++;
$lineNumNew++;
}
} else {
$lineNumOld++;
$lineNumNew++;
}
if ($diff) {
$diff->addLine($log, $lineNumOld, $lineNumNew);
}
}
if (isset($diff)) {
$diffs[] = $diff;
}
return $diffs;
} | php | public function readDiffLogs(array $logs)
{
$diffs = array();
$lineNumOld = 0;
$lineNumNew = 0;
foreach ($logs as $log) {
if ('diff' === substr($log, 0, 4)) {
if (isset($diff)) {
$diffs[] = $diff;
}
$diff = new Diff();
if (preg_match('/^diff --[\S]+ a\/?(.+) b\/?/', $log, $name)) {
$diff->setFile($name[1]);
}
continue;
}
if ('index' === substr($log, 0, 5)) {
$diff->setIndex($log);
continue;
}
if ('---' === substr($log, 0, 3)) {
$diff->setOld($log);
continue;
}
if ('+++' === substr($log, 0, 3)) {
$diff->setNew($log);
continue;
}
// Handle binary files properly.
if ('Binary' === substr($log, 0, 6)) {
$m = array();
if (preg_match('/Binary files (.+) and (.+) differ/', $log, $m)) {
$diff->setOld($m[1]);
$diff->setNew(" {$m[2]}");
}
}
if (!empty($log)) {
switch ($log[0]) {
case '@':
// Set the line numbers
preg_match('/@@ -([0-9]+)/', $log, $matches);
$lineNumOld = $matches[1] - 1;
$lineNumNew = $matches[1] - 1;
break;
case '-':
$lineNumOld++;
break;
case '+':
$lineNumNew++;
break;
default:
$lineNumOld++;
$lineNumNew++;
}
} else {
$lineNumOld++;
$lineNumNew++;
}
if ($diff) {
$diff->addLine($log, $lineNumOld, $lineNumNew);
}
}
if (isset($diff)) {
$diffs[] = $diff;
}
return $diffs;
} | [
"public",
"function",
"readDiffLogs",
"(",
"array",
"$",
"logs",
")",
"{",
"$",
"diffs",
"=",
"array",
"(",
")",
";",
"$",
"lineNumOld",
"=",
"0",
";",
"$",
"lineNumNew",
"=",
"0",
";",
"foreach",
"(",
"$",
"logs",
"as",
"$",
"log",
")",
"{",
"if... | Read diff logs and generate a collection of diffs.
@param array $logs Array of log rows
@return array Array of diffs | [
"Read",
"diff",
"logs",
"and",
"generate",
"a",
"collection",
"of",
"diffs",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L438-L513 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getHead | public function getHead($default = null)
{
$file = '';
if (file_exists($this->getPath() . '/.git/HEAD')) {
$file = file_get_contents($this->getPath() . '/.git/HEAD');
} elseif (file_exists($this->getPath() . '/HEAD')) {
$file = file_get_contents($this->getPath() . '/HEAD');
}
// Find first existing branch
foreach (explode("\n", $file) as $line) {
$m = array();
if (preg_match('#ref:\srefs/heads/(.+)#', $line, $m)) {
if ($this->hasBranch($m[1])) {
return $m[1];
}
}
}
// If we were given a default branch and it exists, return that.
if (null !== $default && $this->hasBranch($default)) {
return $default;
}
// Otherwise, return the first existing branch.
$branches = $this->getBranches();
if (!empty($branches)) {
return current($branches);
}
// No branches exist - null is the best we can do in this case.
return null;
} | php | public function getHead($default = null)
{
$file = '';
if (file_exists($this->getPath() . '/.git/HEAD')) {
$file = file_get_contents($this->getPath() . '/.git/HEAD');
} elseif (file_exists($this->getPath() . '/HEAD')) {
$file = file_get_contents($this->getPath() . '/HEAD');
}
// Find first existing branch
foreach (explode("\n", $file) as $line) {
$m = array();
if (preg_match('#ref:\srefs/heads/(.+)#', $line, $m)) {
if ($this->hasBranch($m[1])) {
return $m[1];
}
}
}
// If we were given a default branch and it exists, return that.
if (null !== $default && $this->hasBranch($default)) {
return $default;
}
// Otherwise, return the first existing branch.
$branches = $this->getBranches();
if (!empty($branches)) {
return current($branches);
}
// No branches exist - null is the best we can do in this case.
return null;
} | [
"public",
"function",
"getHead",
"(",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"''",
";",
"if",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"getPath",
"(",
")",
".",
"'/.git/HEAD'",
")",
")",
"{",
"$",
"file",
"=",
"file_get_contents"... | Get the current HEAD.
@param $default Optional branch to default to if in detached HEAD state.
If not passed, just grabs the first branch listed.
@return string the name of the HEAD branch, or a backup option if
in detached HEAD state | [
"Get",
"the",
"current",
"HEAD",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L524-L556 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getBranchTree | public function getBranchTree($branch)
{
$hash = $this->getClient()->run($this, "log --pretty=\"%T\" --max-count=1 $branch");
$hash = trim($hash, "\r\n ");
return $hash ?: false;
} | php | public function getBranchTree($branch)
{
$hash = $this->getClient()->run($this, "log --pretty=\"%T\" --max-count=1 $branch");
$hash = trim($hash, "\r\n ");
return $hash ?: false;
} | [
"public",
"function",
"getBranchTree",
"(",
"$",
"branch",
")",
"{",
"$",
"hash",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"run",
"(",
"$",
"this",
",",
"\"log --pretty=\\\"%T\\\" --max-count=1 $branch\"",
")",
";",
"$",
"hash",
"=",
"trim",
"(... | Extract the tree hash for a given branch or tree reference.
@param string $branch
@return string | [
"Extract",
"the",
"tree",
"hash",
"for",
"a",
"given",
"branch",
"or",
"tree",
"reference",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L565-L571 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getBlame | public function getBlame($file)
{
$blame = array();
$logs = $this->getClient()->run($this, "blame -s $file");
$logs = explode("\n", $logs);
$i = 0;
$previousCommit = '';
foreach ($logs as $log) {
if ('' == $log) {
continue;
}
preg_match_all("/([a-zA-Z0-9^]{8})\s+.*?([0-9]+)\)(.+)/", $log, $match);
$currentCommit = $match[1][0];
if ($currentCommit != $previousCommit) {
$i++;
$blame[$i] = array('line' => '', 'commit' => $currentCommit);
}
$blame[$i]['line'] .= PHP_EOL . $match[3][0];
$previousCommit = $currentCommit;
}
return $blame;
} | php | public function getBlame($file)
{
$blame = array();
$logs = $this->getClient()->run($this, "blame -s $file");
$logs = explode("\n", $logs);
$i = 0;
$previousCommit = '';
foreach ($logs as $log) {
if ('' == $log) {
continue;
}
preg_match_all("/([a-zA-Z0-9^]{8})\s+.*?([0-9]+)\)(.+)/", $log, $match);
$currentCommit = $match[1][0];
if ($currentCommit != $previousCommit) {
$i++;
$blame[$i] = array('line' => '', 'commit' => $currentCommit);
}
$blame[$i]['line'] .= PHP_EOL . $match[3][0];
$previousCommit = $currentCommit;
}
return $blame;
} | [
"public",
"function",
"getBlame",
"(",
"$",
"file",
")",
"{",
"$",
"blame",
"=",
"array",
"(",
")",
";",
"$",
"logs",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"run",
"(",
"$",
"this",
",",
"\"blame -s $file\"",
")",
";",
"$",
"logs",
... | Blames the provided file and parses the output.
@param string $file File that will be blamed
@return array Commits hashes containing the lines | [
"Blames",
"the",
"provided",
"file",
"and",
"parses",
"the",
"output",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L607-L633 |
klaussilveira/gitter | lib/Gitter/Repository.php | Repository.getPrettyFormat | public function getPrettyFormat($command)
{
$output = $this->getClient()->run($this, $command);
$format = new PrettyFormat();
return $format->parse($output);
} | php | public function getPrettyFormat($command)
{
$output = $this->getClient()->run($this, $command);
$format = new PrettyFormat();
return $format->parse($output);
} | [
"public",
"function",
"getPrettyFormat",
"(",
"$",
"command",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"run",
"(",
"$",
"this",
",",
"$",
"command",
")",
";",
"$",
"format",
"=",
"new",
"PrettyFormat",
"(",
")",
... | Get and parse the output of a git command with a XML-based pretty format.
@param string $command Command to be run by git
@return array Parsed command output | [
"Get",
"and",
"parse",
"the",
"output",
"of",
"a",
"git",
"command",
"with",
"a",
"XML",
"-",
"based",
"pretty",
"format",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Repository.php#L684-L690 |
klaussilveira/gitter | lib/Gitter/Client.php | Client.createRepository | public function createRepository($path, $bare = null)
{
if (file_exists($path . '/.git/HEAD') && !file_exists($path . '/HEAD')) {
throw new \RuntimeException('A GIT repository already exists at ' . $path);
}
$repository = new Repository($path, $this);
return $repository->create($bare);
} | php | public function createRepository($path, $bare = null)
{
if (file_exists($path . '/.git/HEAD') && !file_exists($path . '/HEAD')) {
throw new \RuntimeException('A GIT repository already exists at ' . $path);
}
$repository = new Repository($path, $this);
return $repository->create($bare);
} | [
"public",
"function",
"createRepository",
"(",
"$",
"path",
",",
"$",
"bare",
"=",
"null",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"path",
".",
"'/.git/HEAD'",
")",
"&&",
"!",
"file_exists",
"(",
"$",
"path",
".",
"'/HEAD'",
")",
")",
"{",
"thr... | Creates a new repository on the specified path.
@param string $path Path where the new repository will be created
@return Repository Instance of Repository | [
"Creates",
"a",
"new",
"repository",
"on",
"the",
"specified",
"path",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Client.php#L38-L47 |
klaussilveira/gitter | lib/Gitter/Client.php | Client.getRepository | public function getRepository($path)
{
if (!file_exists($path) || !file_exists($path . '/.git/HEAD') && !file_exists($path . '/HEAD')) {
throw new \RuntimeException('There is no GIT repository at ' . $path);
}
return new Repository($path, $this);
} | php | public function getRepository($path)
{
if (!file_exists($path) || !file_exists($path . '/.git/HEAD') && !file_exists($path . '/HEAD')) {
throw new \RuntimeException('There is no GIT repository at ' . $path);
}
return new Repository($path, $this);
} | [
"public",
"function",
"getRepository",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
"||",
"!",
"file_exists",
"(",
"$",
"path",
".",
"'/.git/HEAD'",
")",
"&&",
"!",
"file_exists",
"(",
"$",
"path",
".",
"'/HEAD'",
... | Opens a repository at the specified path.
@param string $path Path where the repository is located
@return Repository Instance of Repository | [
"Opens",
"a",
"repository",
"at",
"the",
"specified",
"path",
"."
] | train | https://github.com/klaussilveira/gitter/blob/649f8423323c844bf7e516dec2e39711206b2a02/lib/Gitter/Client.php#L56-L63 |
JellyBool/flysystem-upyun | src/UpyunServiceProvider.php | UpyunServiceProvider.boot | public function boot()
{
Storage::extend('upyun', function ($app, $config) {
$adapter = new UpyunAdapter(
$config['bucket'], $config['operator'],
$config['password'],$config['domain'],$config['protocol']
);
$filesystem = new Filesystem($adapter);
$filesystem->addPlugin(new ImagePreviewUrl());
return $filesystem;
});
} | php | public function boot()
{
Storage::extend('upyun', function ($app, $config) {
$adapter = new UpyunAdapter(
$config['bucket'], $config['operator'],
$config['password'],$config['domain'],$config['protocol']
);
$filesystem = new Filesystem($adapter);
$filesystem->addPlugin(new ImagePreviewUrl());
return $filesystem;
});
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"Storage",
"::",
"extend",
"(",
"'upyun'",
",",
"function",
"(",
"$",
"app",
",",
"$",
"config",
")",
"{",
"$",
"adapter",
"=",
"new",
"UpyunAdapter",
"(",
"$",
"config",
"[",
"'bucket'",
"]",
",",
"$",
... | Bootstrap the application services.
@return void | [
"Bootstrap",
"the",
"application",
"services",
"."
] | train | https://github.com/JellyBool/flysystem-upyun/blob/5a60ef34cd42b1cebfad7fdb39b7bc5ccc550fff/src/UpyunServiceProvider.php#L17-L31 |
JellyBool/flysystem-upyun | src/UpyunAdapter.php | UpyunAdapter.normalizeFileInfo | protected function normalizeFileInfo(array $stats, string $directory)
{
$filePath = ltrim($directory . '/' . $stats['name'], '/');
return [
'type' => $this->getType($filePath)['type'],
'path' => $filePath,
'timestamp' => $stats['time'],
'size' => $stats['size'],
];
} | php | protected function normalizeFileInfo(array $stats, string $directory)
{
$filePath = ltrim($directory . '/' . $stats['name'], '/');
return [
'type' => $this->getType($filePath)['type'],
'path' => $filePath,
'timestamp' => $stats['time'],
'size' => $stats['size'],
];
} | [
"protected",
"function",
"normalizeFileInfo",
"(",
"array",
"$",
"stats",
",",
"string",
"$",
"directory",
")",
"{",
"$",
"filePath",
"=",
"ltrim",
"(",
"$",
"directory",
".",
"'/'",
".",
"$",
"stats",
"[",
"'name'",
"]",
",",
"'/'",
")",
";",
"return"... | Normalize the file info.
@param array $stats
@param string $directory
@return array | [
"Normalize",
"the",
"file",
"info",
"."
] | train | https://github.com/JellyBool/flysystem-upyun/blob/5a60ef34cd42b1cebfad7fdb39b7bc5ccc550fff/src/UpyunAdapter.php#L274-L284 |
skeeks-semenov/yii2-assets-auto-compress | src/AssetsAutoCompressComponent.php | AssetsAutoCompressComponent.fileGetContents | public function fileGetContents($file)
{
$client = new Client();
$response = $client->createRequest()
->setMethod('get')
->setUrl($file)
->addHeaders(['user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'])
->setOptions([
'timeout' => $this->readFileTimeout, // set timeout to 1 seconds for the case server is not responding
])
->send();
if ($response->isOk) {
return $response->content;
}
throw new \Exception("File get contents '{$file}' error: ".$response->content);
} | php | public function fileGetContents($file)
{
$client = new Client();
$response = $client->createRequest()
->setMethod('get')
->setUrl($file)
->addHeaders(['user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'])
->setOptions([
'timeout' => $this->readFileTimeout, // set timeout to 1 seconds for the case server is not responding
])
->send();
if ($response->isOk) {
return $response->content;
}
throw new \Exception("File get contents '{$file}' error: ".$response->content);
} | [
"public",
"function",
"fileGetContents",
"(",
"$",
"file",
")",
"{",
"$",
"client",
"=",
"new",
"Client",
"(",
")",
";",
"$",
"response",
"=",
"$",
"client",
"->",
"createRequest",
"(",
")",
"->",
"setMethod",
"(",
"'get'",
")",
"->",
"setUrl",
"(",
... | Read file contents
@param $file
@return string | [
"Read",
"file",
"contents"
] | train | https://github.com/skeeks-semenov/yii2-assets-auto-compress/blob/73e17eebe59039a60575c4e259b3bfba4a0b1921/src/AssetsAutoCompressComponent.php#L446-L463 |
tomzx/php-semver-checker | src/PHPSemVerChecker/Analyzer/Analyzer.php | Analyzer.analyze | public function analyze(Registry $registryBefore, Registry $registryAfter)
{
$finalReport = new Report();
$analyzers = [
new FunctionAnalyzer(),
new ClassAnalyzer(),
new InterfaceAnalyzer(),
new TraitAnalyzer(),
];
foreach ($analyzers as $analyzer) {
$report = $analyzer->analyze($registryBefore, $registryAfter);
$finalReport->merge($report);
}
return $finalReport;
} | php | public function analyze(Registry $registryBefore, Registry $registryAfter)
{
$finalReport = new Report();
$analyzers = [
new FunctionAnalyzer(),
new ClassAnalyzer(),
new InterfaceAnalyzer(),
new TraitAnalyzer(),
];
foreach ($analyzers as $analyzer) {
$report = $analyzer->analyze($registryBefore, $registryAfter);
$finalReport->merge($report);
}
return $finalReport;
} | [
"public",
"function",
"analyze",
"(",
"Registry",
"$",
"registryBefore",
",",
"Registry",
"$",
"registryAfter",
")",
"{",
"$",
"finalReport",
"=",
"new",
"Report",
"(",
")",
";",
"$",
"analyzers",
"=",
"[",
"new",
"FunctionAnalyzer",
"(",
")",
",",
"new",
... | Compare with a destination registry (what the new source code is like).
@param \PHPSemVerChecker\Registry\Registry $registryBefore
@param \PHPSemVerChecker\Registry\Registry $registryAfter
@return \PHPSemVerChecker\Report\Report | [
"Compare",
"with",
"a",
"destination",
"registry",
"(",
"what",
"the",
"new",
"source",
"code",
"is",
"like",
")",
"."
] | train | https://github.com/tomzx/php-semver-checker/blob/4a545c5a1aaa48df605bbbe4d091257daa31618e/src/PHPSemVerChecker/Analyzer/Analyzer.php#L17-L34 |
tomzx/php-semver-checker | src/PHPSemVerChecker/Scanner/ProgressScanner.php | ProgressScanner.runJob | public function runJob($jobName)
{
$progress = $this->getProgressBar();
$progress->setMessage('Scanning ' . $jobName);
$scanner = $this->scanners[$jobName];
foreach ($this->fileLists[$jobName] as $filePath) {
$scanner->scan($filePath);
$progress->advance();
}
if ($progress->getProgress() === $progress->getMaxSteps()) {
$progress->clear();
}
} | php | public function runJob($jobName)
{
$progress = $this->getProgressBar();
$progress->setMessage('Scanning ' . $jobName);
$scanner = $this->scanners[$jobName];
foreach ($this->fileLists[$jobName] as $filePath) {
$scanner->scan($filePath);
$progress->advance();
}
if ($progress->getProgress() === $progress->getMaxSteps()) {
$progress->clear();
}
} | [
"public",
"function",
"runJob",
"(",
"$",
"jobName",
")",
"{",
"$",
"progress",
"=",
"$",
"this",
"->",
"getProgressBar",
"(",
")",
";",
"$",
"progress",
"->",
"setMessage",
"(",
"'Scanning '",
".",
"$",
"jobName",
")",
";",
"$",
"scanner",
"=",
"$",
... | Run a single job.
@param string $jobName | [
"Run",
"a",
"single",
"job",
"."
] | train | https://github.com/tomzx/php-semver-checker/blob/4a545c5a1aaa48df605bbbe4d091257daa31618e/src/PHPSemVerChecker/Scanner/ProgressScanner.php#L64-L76 |
tomzx/php-semver-checker | src/PHPSemVerChecker/Configuration/Configuration.php | Configuration.merge | public function merge($data)
{
foreach ($data as $key => $value) {
$this->set($key, $value);
}
} | php | public function merge($data)
{
foreach ($data as $key => $value) {
$this->set($key, $value);
}
} | [
"public",
"function",
"merge",
"(",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}",
"}"
] | Merge this configuration with an associative array.
Note that dot notation is used for keys.
@param array $data | [
"Merge",
"this",
"configuration",
"with",
"an",
"associative",
"array",
"."
] | train | https://github.com/tomzx/php-semver-checker/blob/4a545c5a1aaa48df605bbbe4d091257daa31618e/src/PHPSemVerChecker/Configuration/Configuration.php#L96-L101 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.makeCachedType | private static function makeCachedType($key) {
if (!isset(self::$typeCache[$key])) {
self::$typeCache[$key] = new Type($key);
}
return self::$typeCache[$key];
} | php | private static function makeCachedType($key) {
if (!isset(self::$typeCache[$key])) {
self::$typeCache[$key] = new Type($key);
}
return self::$typeCache[$key];
} | [
"private",
"static",
"function",
"makeCachedType",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"typeCache",
"[",
"$",
"key",
"]",
")",
")",
"{",
"self",
"::",
"$",
"typeCache",
"[",
"$",
"key",
"]",
"=",
"new",
"Ty... | @param int $key
@return Type | [
"@param",
"int",
"$key"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L105-L110 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.getPrimitives | public static function getPrimitives() {
return [
Type::TYPE_NULL => 'null',
Type::TYPE_BOOLEAN => 'bool',
Type::TYPE_LONG => 'int',
Type::TYPE_DOUBLE => 'float',
Type::TYPE_STRING => 'string',
Type::TYPE_OBJECT => 'object',
Type::TYPE_ARRAY => 'array',
Type::TYPE_CALLABLE => 'callable',
];
} | php | public static function getPrimitives() {
return [
Type::TYPE_NULL => 'null',
Type::TYPE_BOOLEAN => 'bool',
Type::TYPE_LONG => 'int',
Type::TYPE_DOUBLE => 'float',
Type::TYPE_STRING => 'string',
Type::TYPE_OBJECT => 'object',
Type::TYPE_ARRAY => 'array',
Type::TYPE_CALLABLE => 'callable',
];
} | [
"public",
"static",
"function",
"getPrimitives",
"(",
")",
"{",
"return",
"[",
"Type",
"::",
"TYPE_NULL",
"=>",
"'null'",
",",
"Type",
"::",
"TYPE_BOOLEAN",
"=>",
"'bool'",
",",
"Type",
"::",
"TYPE_LONG",
"=>",
"'int'",
",",
"Type",
"::",
"TYPE_DOUBLE",
"=... | Get the primitives
@return string[] | [
"Get",
"the",
"primitives"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L158-L169 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.extractTypeFromComment | public static function extractTypeFromComment($kind, $comment, $name = '') {
$match = [];
switch ($kind) {
case 'var':
if (preg_match('(@var\s+(\S+))', $comment, $match)) {
$return = Type::fromDecl($match[1]);
return $return;
}
break;
case 'return':
if (preg_match('(@return\s+(\S+))', $comment, $match)) {
$return = Type::fromDecl($match[1]);
return $return;
}
break;
case 'param':
if (preg_match("(@param\\s+(\\S+)\\s+\\\${$name})i", $comment, $match)) {
$param = Type::fromDecl($match[1]);
return $param;
}
break;
}
return self::mixed();
} | php | public static function extractTypeFromComment($kind, $comment, $name = '') {
$match = [];
switch ($kind) {
case 'var':
if (preg_match('(@var\s+(\S+))', $comment, $match)) {
$return = Type::fromDecl($match[1]);
return $return;
}
break;
case 'return':
if (preg_match('(@return\s+(\S+))', $comment, $match)) {
$return = Type::fromDecl($match[1]);
return $return;
}
break;
case 'param':
if (preg_match("(@param\\s+(\\S+)\\s+\\\${$name})i", $comment, $match)) {
$param = Type::fromDecl($match[1]);
return $param;
}
break;
}
return self::mixed();
} | [
"public",
"static",
"function",
"extractTypeFromComment",
"(",
"$",
"kind",
",",
"$",
"comment",
",",
"$",
"name",
"=",
"''",
")",
"{",
"$",
"match",
"=",
"[",
"]",
";",
"switch",
"(",
"$",
"kind",
")",
"{",
"case",
"'var'",
":",
"if",
"(",
"preg_m... | @param string $kind
@param string $comment
@param string $name The name of the parameter
@return Type The type | [
"@param",
"string",
"$kind",
"@param",
"string",
"$comment",
"@param",
"string",
"$name",
"The",
"name",
"of",
"the",
"parameter"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L238-L261 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.fromDecl | public static function fromDecl($decl) {
if ($decl instanceof Type) {
return $decl;
} elseif (!is_string($decl)) {
throw new \LogicException("Should never happen");
} elseif (empty($decl)) {
throw new \RuntimeException("Empty declaration found");
}
if ($decl[0] === '\\') {
$decl = substr($decl, 1);
} elseif ($decl[0] === '?') {
$decl = substr($decl, 1);
$type = Type::fromDecl($decl);
return (new Type(Type::TYPE_UNION, [
$type,
new Type(Type::TYPE_NULL)
]))->simplify();
}
switch (strtolower($decl)) {
case 'boolean':
case 'bool':
case 'false':
case 'true':
return new Type(Type::TYPE_BOOLEAN);
case 'integer':
case 'int':
return new Type(Type::TYPE_LONG);
case 'double':
case 'real':
case 'float':
return new Type(Type::TYPE_DOUBLE);
case 'string':
return new Type(Type::TYPE_STRING);
case 'array':
return new Type(Type::TYPE_ARRAY);
case 'callable':
return new Type(Type::TYPE_CALLABLE);
case 'null':
case 'void':
return new Type(Type::TYPE_NULL);
case 'numeric':
return Type::fromDecl('int|float');
}
// TODO: parse | and & and ()
if (strpos($decl, '|') !== false || strpos($decl, '&') !== false || strpos($decl, '(') !== false) {
return self::parseCompexDecl($decl)->simplify();
}
if (substr($decl, -2) === '[]') {
$type = Type::fromDecl(substr($decl, 0, -2));
return new Type(Type::TYPE_ARRAY, [$type]);
}
$regex = '(^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\\\\)*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$)';
if (!preg_match($regex, $decl)) {
throw new \RuntimeException("Unknown type declaration found: $decl");
}
return new Type(Type::TYPE_OBJECT, [], $decl);
} | php | public static function fromDecl($decl) {
if ($decl instanceof Type) {
return $decl;
} elseif (!is_string($decl)) {
throw new \LogicException("Should never happen");
} elseif (empty($decl)) {
throw new \RuntimeException("Empty declaration found");
}
if ($decl[0] === '\\') {
$decl = substr($decl, 1);
} elseif ($decl[0] === '?') {
$decl = substr($decl, 1);
$type = Type::fromDecl($decl);
return (new Type(Type::TYPE_UNION, [
$type,
new Type(Type::TYPE_NULL)
]))->simplify();
}
switch (strtolower($decl)) {
case 'boolean':
case 'bool':
case 'false':
case 'true':
return new Type(Type::TYPE_BOOLEAN);
case 'integer':
case 'int':
return new Type(Type::TYPE_LONG);
case 'double':
case 'real':
case 'float':
return new Type(Type::TYPE_DOUBLE);
case 'string':
return new Type(Type::TYPE_STRING);
case 'array':
return new Type(Type::TYPE_ARRAY);
case 'callable':
return new Type(Type::TYPE_CALLABLE);
case 'null':
case 'void':
return new Type(Type::TYPE_NULL);
case 'numeric':
return Type::fromDecl('int|float');
}
// TODO: parse | and & and ()
if (strpos($decl, '|') !== false || strpos($decl, '&') !== false || strpos($decl, '(') !== false) {
return self::parseCompexDecl($decl)->simplify();
}
if (substr($decl, -2) === '[]') {
$type = Type::fromDecl(substr($decl, 0, -2));
return new Type(Type::TYPE_ARRAY, [$type]);
}
$regex = '(^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\\\\)*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$)';
if (!preg_match($regex, $decl)) {
throw new \RuntimeException("Unknown type declaration found: $decl");
}
return new Type(Type::TYPE_OBJECT, [], $decl);
} | [
"public",
"static",
"function",
"fromDecl",
"(",
"$",
"decl",
")",
"{",
"if",
"(",
"$",
"decl",
"instanceof",
"Type",
")",
"{",
"return",
"$",
"decl",
";",
"}",
"elseif",
"(",
"!",
"is_string",
"(",
"$",
"decl",
")",
")",
"{",
"throw",
"new",
"\\",... | @param string $decl
@return Type The type | [
"@param",
"string",
"$decl"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L288-L344 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.parseCompexDecl | private static function parseCompexDecl($decl) {
$left = null;
$right = null;
$combinator = '';
if (substr($decl, 0, 1) === '(') {
$regex = '(^(\(((?>[^()]+)|(?1))*\)))';
$match = [];
if (preg_match($regex, $decl, $match)) {
$sub = (string) $match[0];
$left = self::fromDecl(substr($sub, 1, -1));
if ($sub === $decl) {
return $left;
}
$decl = substr($decl, strlen($sub));
} else {
throw new \RuntimeException("Unmatched braces?");
}
if (!in_array(substr($decl, 0, 1), ['|', '&'])) {
throw new \RuntimeException("Unknown position of combinator: $decl");
}
$right = self::fromDecl(substr($decl, 1));
$combinator = substr($decl, 0, 1);
} else {
$orPos = strpos($decl, '|');
$andPos = strpos($decl, '&');
$pos = 0;
if ($orPos === false && $andPos !== false) {
$pos = $andPos;
} elseif ($orPos !== false && $andPos === false) {
$pos = $orPos;
} elseif ($orPos !== false && $andPos !== false) {
$pos = min($orPos, $andPos);
} else {
throw new \RuntimeException("No combinator found: $decl");
}
if ($pos === 0) {
throw new \RuntimeException("Unknown position of combinator: $decl");
}
$left = self::fromDecl(substr($decl, 0, $pos));
$right = self::fromDecl(substr($decl, $pos + 1));
$combinator = substr($decl, $pos, 1);
}
if ($combinator === '|') {
return new Type(Type::TYPE_UNION, [$left, $right]);
} elseif ($combinator === '&') {
return new Type(Type::TYPE_INTERSECTION, [$left, $right]);
}
throw new \RuntimeException("Unknown combinator $combinator");
} | php | private static function parseCompexDecl($decl) {
$left = null;
$right = null;
$combinator = '';
if (substr($decl, 0, 1) === '(') {
$regex = '(^(\(((?>[^()]+)|(?1))*\)))';
$match = [];
if (preg_match($regex, $decl, $match)) {
$sub = (string) $match[0];
$left = self::fromDecl(substr($sub, 1, -1));
if ($sub === $decl) {
return $left;
}
$decl = substr($decl, strlen($sub));
} else {
throw new \RuntimeException("Unmatched braces?");
}
if (!in_array(substr($decl, 0, 1), ['|', '&'])) {
throw new \RuntimeException("Unknown position of combinator: $decl");
}
$right = self::fromDecl(substr($decl, 1));
$combinator = substr($decl, 0, 1);
} else {
$orPos = strpos($decl, '|');
$andPos = strpos($decl, '&');
$pos = 0;
if ($orPos === false && $andPos !== false) {
$pos = $andPos;
} elseif ($orPos !== false && $andPos === false) {
$pos = $orPos;
} elseif ($orPos !== false && $andPos !== false) {
$pos = min($orPos, $andPos);
} else {
throw new \RuntimeException("No combinator found: $decl");
}
if ($pos === 0) {
throw new \RuntimeException("Unknown position of combinator: $decl");
}
$left = self::fromDecl(substr($decl, 0, $pos));
$right = self::fromDecl(substr($decl, $pos + 1));
$combinator = substr($decl, $pos, 1);
}
if ($combinator === '|') {
return new Type(Type::TYPE_UNION, [$left, $right]);
} elseif ($combinator === '&') {
return new Type(Type::TYPE_INTERSECTION, [$left, $right]);
}
throw new \RuntimeException("Unknown combinator $combinator");
} | [
"private",
"static",
"function",
"parseCompexDecl",
"(",
"$",
"decl",
")",
"{",
"$",
"left",
"=",
"null",
";",
"$",
"right",
"=",
"null",
";",
"$",
"combinator",
"=",
"''",
";",
"if",
"(",
"substr",
"(",
"$",
"decl",
",",
"0",
",",
"1",
")",
"===... | @param string $decl
@return Type | [
"@param",
"string",
"$decl"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L351-L399 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.fromValue | public static function fromValue($value) {
if (is_int($value)) {
return new Type(Type::TYPE_LONG);
} elseif (is_bool($value)) {
return new Type(Type::TYPE_BOOLEAN);
} elseif (is_double($value)) {
return new Type(Type::TYPE_DOUBLE);
} elseif (is_string($value)) {
return new Type(Type::TYPE_STRING);
}
throw new \RuntimeException("Unknown value type found: " . gettype($value));
} | php | public static function fromValue($value) {
if (is_int($value)) {
return new Type(Type::TYPE_LONG);
} elseif (is_bool($value)) {
return new Type(Type::TYPE_BOOLEAN);
} elseif (is_double($value)) {
return new Type(Type::TYPE_DOUBLE);
} elseif (is_string($value)) {
return new Type(Type::TYPE_STRING);
}
throw new \RuntimeException("Unknown value type found: " . gettype($value));
} | [
"public",
"static",
"function",
"fromValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"value",
")",
")",
"{",
"return",
"new",
"Type",
"(",
"Type",
"::",
"TYPE_LONG",
")",
";",
"}",
"elseif",
"(",
"is_bool",
"(",
"$",
"value",
")... | @param mixed $value
@return Type The type | [
"@param",
"mixed",
"$value"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L406-L417 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.equals | public function equals(Type $type) {
if ($type === $this) {
return true;
}
if ($type->type !== $this->type) {
return false;
}
if ($type->type === Type::TYPE_OBJECT) {
return strtolower($type->userType) === strtolower($this->userType);
}
// TODO: handle sub types
if (isset(self::$hasSubtypes[$this->type]) && isset(self::$hasSubtypes[$type->type])) {
if (count($this->subTypes) !== count($type->subTypes)) {
return false;
}
// compare
$other = $type->subTypes;
foreach ($this->subTypes as $st1) {
foreach ($other as $key => $st2) {
if ($st1->equals($st2)) {
unset($other[$key]);
continue 2;
}
// We have a subtype that's not equal
return false;
}
}
return empty($other);
}
return true;
} | php | public function equals(Type $type) {
if ($type === $this) {
return true;
}
if ($type->type !== $this->type) {
return false;
}
if ($type->type === Type::TYPE_OBJECT) {
return strtolower($type->userType) === strtolower($this->userType);
}
// TODO: handle sub types
if (isset(self::$hasSubtypes[$this->type]) && isset(self::$hasSubtypes[$type->type])) {
if (count($this->subTypes) !== count($type->subTypes)) {
return false;
}
// compare
$other = $type->subTypes;
foreach ($this->subTypes as $st1) {
foreach ($other as $key => $st2) {
if ($st1->equals($st2)) {
unset($other[$key]);
continue 2;
}
// We have a subtype that's not equal
return false;
}
}
return empty($other);
}
return true;
} | [
"public",
"function",
"equals",
"(",
"Type",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"$",
"this",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"type",
"->",
"type",
"!==",
"$",
"this",
"->",
"type",
")",
"{",
"return",
"f... | @param Type $type
@return bool The status | [
"@param",
"Type",
"$type"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L424-L454 |
ircmaxell/php-types | lib/PHPTypes/Type.php | Type.removeType | public function removeType(Type $type) {
if (!isset(self::$hasSubtypes[$this->type])) {
if ($this->equals($type)) {
// left with an unknown type
return Type::null();
}
return $this;
}
$new = [];
foreach ($this->subTypes as $key => $st) {
if (!$st->equals($type)) {
$new[] = $st;
}
}
if (empty($new)) {
throw new \LogicException('Unknown type encountered');
} elseif (count($new) === 1) {
return $new[0];
}
return new Type($this->type, $new);
} | php | public function removeType(Type $type) {
if (!isset(self::$hasSubtypes[$this->type])) {
if ($this->equals($type)) {
// left with an unknown type
return Type::null();
}
return $this;
}
$new = [];
foreach ($this->subTypes as $key => $st) {
if (!$st->equals($type)) {
$new[] = $st;
}
}
if (empty($new)) {
throw new \LogicException('Unknown type encountered');
} elseif (count($new) === 1) {
return $new[0];
}
return new Type($this->type, $new);
} | [
"public",
"function",
"removeType",
"(",
"Type",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"hasSubtypes",
"[",
"$",
"this",
"->",
"type",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"equals",
"(",
"$",
"type",
... | @param Type $toRemove
@return Type the removed type | [
"@param",
"Type",
"$toRemove"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/Type.php#L461-L481 |
ircmaxell/php-types | lib/PHPTypes/InternalArgInfo.php | InternalArgInfo.parseInfo | protected function parseInfo(array $info) {
$return = array_shift($info);
$params = [];
foreach ($info as $name => $param) {
$params[] = ["name" => $name, "type" => $param];
}
return [
'return' => $return,
'params' => $params,
];
} | php | protected function parseInfo(array $info) {
$return = array_shift($info);
$params = [];
foreach ($info as $name => $param) {
$params[] = ["name" => $name, "type" => $param];
}
return [
'return' => $return,
'params' => $params,
];
} | [
"protected",
"function",
"parseInfo",
"(",
"array",
"$",
"info",
")",
"{",
"$",
"return",
"=",
"array_shift",
"(",
"$",
"info",
")",
";",
"$",
"params",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"info",
"as",
"$",
"name",
"=>",
"$",
"param",
")",
... | @var array
@return array | [
"@var",
"array"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/InternalArgInfo.php#L8538-L8548 |
ircmaxell/php-types | lib/PHPTypes/TypeReconstructor.php | TypeReconstructor.computeMergedType | protected function computeMergedType(array $types) {
if (count($types) === 1) {
return $types[0];
}
$same = null;
foreach ($types as $key => $type) {
if (!$type instanceof Type) {
var_dump($types);
throw new \RuntimeException("Invalid type found");
}
if (is_null($same)) {
$same = $type;
} elseif ($same && !$same->equals($type)) {
$same = false;
}
if ($type->type === Type::TYPE_UNKNOWN) {
return false;
}
}
if ($same) {
return $same;
}
return (new Type(Type::TYPE_UNION, $types))->simplify();
} | php | protected function computeMergedType(array $types) {
if (count($types) === 1) {
return $types[0];
}
$same = null;
foreach ($types as $key => $type) {
if (!$type instanceof Type) {
var_dump($types);
throw new \RuntimeException("Invalid type found");
}
if (is_null($same)) {
$same = $type;
} elseif ($same && !$same->equals($type)) {
$same = false;
}
if ($type->type === Type::TYPE_UNKNOWN) {
return false;
}
}
if ($same) {
return $same;
}
return (new Type(Type::TYPE_UNION, $types))->simplify();
} | [
"protected",
"function",
"computeMergedType",
"(",
"array",
"$",
"types",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"types",
")",
"===",
"1",
")",
"{",
"return",
"$",
"types",
"[",
"0",
"]",
";",
"}",
"$",
"same",
"=",
"null",
";",
"foreach",
"(",
... | @param Type[] $types
@return Type | [
"@param",
"Type",
"[]",
"$types"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/TypeReconstructor.php#L72-L95 |
ircmaxell/php-types | lib/PHPTypes/TypeReconstructor.php | TypeReconstructor.resolveProperty | private function resolveProperty(Type $objType, $propName) {
if ($objType->type === Type::TYPE_OBJECT) {
$types = [];
$ut = strtolower($objType->userType);
if (!isset($this->state->classResolves[$ut])) {
// unknown type
return false;
}
foreach ($this->state->classResolves[$ut] as $class) {
// Lookup property on class
$property = $this->findProperty($class, $propName);
if ($property) {
if ($property->type) {
$types[] = $property->type;
} else {
echo "Property found to be untyped: $propName\n";
// untyped property
return false;
}
}
}
if ($types) {
return $types;
}
}
return false;
} | php | private function resolveProperty(Type $objType, $propName) {
if ($objType->type === Type::TYPE_OBJECT) {
$types = [];
$ut = strtolower($objType->userType);
if (!isset($this->state->classResolves[$ut])) {
// unknown type
return false;
}
foreach ($this->state->classResolves[$ut] as $class) {
// Lookup property on class
$property = $this->findProperty($class, $propName);
if ($property) {
if ($property->type) {
$types[] = $property->type;
} else {
echo "Property found to be untyped: $propName\n";
// untyped property
return false;
}
}
}
if ($types) {
return $types;
}
}
return false;
} | [
"private",
"function",
"resolveProperty",
"(",
"Type",
"$",
"objType",
",",
"$",
"propName",
")",
"{",
"if",
"(",
"$",
"objType",
"->",
"type",
"===",
"Type",
"::",
"TYPE_OBJECT",
")",
"{",
"$",
"types",
"=",
"[",
"]",
";",
"$",
"ut",
"=",
"strtolowe... | @param Type $objType
@param string $propName
@return Type[]|false | [
"@param",
"Type",
"$objType",
"@param",
"string",
"$propName"
] | train | https://github.com/ircmaxell/php-types/blob/4a1d4375e186759c5008d9fc762f490d0788f35b/lib/PHPTypes/TypeReconstructor.php#L545-L571 |
liip/RMT | src/Liip/RMT/Output/Output.php | Output.askQuestion | public function askQuestion(InteractiveQuestion $question, $position = null, InputInterface $input = null)
{
$text = ($position !== null ? $position .') ' : null) . $question->getFormatedText();
if ($this->dialogHelper instanceof QuestionHelper) {
if (!$input) {
throw new \InvalidArgumentException('With symfony 3, the input stream may not be null');
}
$q = new Question($text, $question->getDefault());
$q->setValidator($question->getValidator());
if ($question->isHiddenAnswer()) {
$q->setHidden(true);
}
return $this->dialogHelper->ask($input, $this, $q);
}
if ($this->dialogHelper instanceof DialogHelper) {
if ($question->isHiddenAnswer()) {
return $this->dialogHelper->askHiddenResponseAndValidate($this, $text, $question->getValidator(), false);
}
return $this->dialogHelper->askAndValidate($this, $text, $question->getValidator(), false, $question->getDefault());
}
throw new \RuntimeException("Invalid dialogHelper");
} | php | public function askQuestion(InteractiveQuestion $question, $position = null, InputInterface $input = null)
{
$text = ($position !== null ? $position .') ' : null) . $question->getFormatedText();
if ($this->dialogHelper instanceof QuestionHelper) {
if (!$input) {
throw new \InvalidArgumentException('With symfony 3, the input stream may not be null');
}
$q = new Question($text, $question->getDefault());
$q->setValidator($question->getValidator());
if ($question->isHiddenAnswer()) {
$q->setHidden(true);
}
return $this->dialogHelper->ask($input, $this, $q);
}
if ($this->dialogHelper instanceof DialogHelper) {
if ($question->isHiddenAnswer()) {
return $this->dialogHelper->askHiddenResponseAndValidate($this, $text, $question->getValidator(), false);
}
return $this->dialogHelper->askAndValidate($this, $text, $question->getValidator(), false, $question->getDefault());
}
throw new \RuntimeException("Invalid dialogHelper");
} | [
"public",
"function",
"askQuestion",
"(",
"InteractiveQuestion",
"$",
"question",
",",
"$",
"position",
"=",
"null",
",",
"InputInterface",
"$",
"input",
"=",
"null",
")",
"{",
"$",
"text",
"=",
"(",
"$",
"position",
"!==",
"null",
"?",
"$",
"position",
... | QuestionHelper does about the same as we do here. | [
"QuestionHelper",
"does",
"about",
"the",
"same",
"as",
"we",
"do",
"here",
"."
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Output/Output.php#L118-L145 |
liip/RMT | src/Liip/RMT/Output/Output.php | Output.askConfirmation | public function askConfirmation($text, InputInterface $input = null)
{
if ($this->dialogHelper instanceof QuestionHelper) {
if (!$input) {
throw new \InvalidArgumentException('With symfony 3, the input stream may not be null');
}
return $this->dialogHelper->ask($input, $this, new ConfirmationQuestion($text));
}
if ($this->dialogHelper instanceof DialogHelper) {
return $this->dialogHelper->askConfirmation($this, $text);
}
throw new \RuntimeException("Invalid dialogHelper");
} | php | public function askConfirmation($text, InputInterface $input = null)
{
if ($this->dialogHelper instanceof QuestionHelper) {
if (!$input) {
throw new \InvalidArgumentException('With symfony 3, the input stream may not be null');
}
return $this->dialogHelper->ask($input, $this, new ConfirmationQuestion($text));
}
if ($this->dialogHelper instanceof DialogHelper) {
return $this->dialogHelper->askConfirmation($this, $text);
}
throw new \RuntimeException("Invalid dialogHelper");
} | [
"public",
"function",
"askConfirmation",
"(",
"$",
"text",
",",
"InputInterface",
"$",
"input",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"dialogHelper",
"instanceof",
"QuestionHelper",
")",
"{",
"if",
"(",
"!",
"$",
"input",
")",
"{",
"throw"... | when we drop symfony 2.3 support, we should switch to the QuestionHelper (since 2.5) and drop this method as it adds no value | [
"when",
"we",
"drop",
"symfony",
"2",
".",
"3",
"support",
"we",
"should",
"switch",
"to",
"the",
"QuestionHelper",
"(",
"since",
"2",
".",
"5",
")",
"and",
"drop",
"this",
"method",
"as",
"it",
"adds",
"no",
"value"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Output/Output.php#L148-L163 |
liip/RMT | src/Liip/RMT/Information/InformationCollector.php | InformationCollector.getCommandOptions | public function getCommandOptions()
{
$consoleOptions = array();
foreach ($this->requests as $name => $request) {
if ($request->isAvailableAsCommandOption()) {
$consoleOptions[$name] = $request->convertToCommandOption();
}
}
return $consoleOptions;
} | php | public function getCommandOptions()
{
$consoleOptions = array();
foreach ($this->requests as $name => $request) {
if ($request->isAvailableAsCommandOption()) {
$consoleOptions[$name] = $request->convertToCommandOption();
}
}
return $consoleOptions;
} | [
"public",
"function",
"getCommandOptions",
"(",
")",
"{",
"$",
"consoleOptions",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"requests",
"as",
"$",
"name",
"=>",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"isAvailabl... | Return a set of command request, converted from the Base Request
@return InputOption[] | [
"Return",
"a",
"set",
"of",
"command",
"request",
"converted",
"from",
"the",
"Base",
"Request"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Information/InformationCollector.php#L106-L116 |
liip/RMT | src/Liip/RMT/Version/Persister/TagValidator.php | TagValidator.isValid | public function isValid($tag)
{
if (strlen($this->tagPrefix) > 0 && strpos($tag, $this->tagPrefix) !== 0) {
return false;
}
return preg_match('/^' . $this->regex . '$/', substr($tag, strlen($this->tagPrefix))) == 1;
} | php | public function isValid($tag)
{
if (strlen($this->tagPrefix) > 0 && strpos($tag, $this->tagPrefix) !== 0) {
return false;
}
return preg_match('/^' . $this->regex . '$/', substr($tag, strlen($this->tagPrefix))) == 1;
} | [
"public",
"function",
"isValid",
"(",
"$",
"tag",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"this",
"->",
"tagPrefix",
")",
">",
"0",
"&&",
"strpos",
"(",
"$",
"tag",
",",
"$",
"this",
"->",
"tagPrefix",
")",
"!==",
"0",
")",
"{",
"return",
"false... | Check if a tag is valid
@param string $tag
@return bool | [
"Check",
"if",
"a",
"tag",
"is",
"valid"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Version/Persister/TagValidator.php#L29-L36 |
liip/RMT | src/Liip/RMT/Version/Persister/TagValidator.php | TagValidator.filtrateList | public function filtrateList($tags)
{
$validTags = array();
foreach ($tags as $tag) {
if ($this->isValid($tag)) {
$validTags[] = $tag;
}
}
return $validTags;
} | php | public function filtrateList($tags)
{
$validTags = array();
foreach ($tags as $tag) {
if ($this->isValid($tag)) {
$validTags[] = $tag;
}
}
return $validTags;
} | [
"public",
"function",
"filtrateList",
"(",
"$",
"tags",
")",
"{",
"$",
"validTags",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"tag",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isValid",
"(",
"$",
"tag",
")",
")",
"{",
"... | Remove all invalid tags from a list
@param array $tags
@return array | [
"Remove",
"all",
"invalid",
"tags",
"from",
"a",
"list"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Version/Persister/TagValidator.php#L45-L55 |
liip/RMT | src/Liip/RMT/Command/ReleaseCommand.php | ReleaseCommand.configure | protected function configure()
{
$this->setName('release');
$this->setDescription('Release a new version of the project');
$this->setHelp('The <comment>release</comment> interactive task must be used to create a new version of a project');
$this->loadContext();
$this->loadInformationCollector();
// Register the command option
foreach (Context::get('information-collector')->getCommandOptions() as $option) {
$this->getDefinition()->addOption($option);
}
} | php | protected function configure()
{
$this->setName('release');
$this->setDescription('Release a new version of the project');
$this->setHelp('The <comment>release</comment> interactive task must be used to create a new version of a project');
$this->loadContext();
$this->loadInformationCollector();
// Register the command option
foreach (Context::get('information-collector')->getCommandOptions() as $option) {
$this->getDefinition()->addOption($option);
}
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'release'",
")",
";",
"$",
"this",
"->",
"setDescription",
"(",
"'Release a new version of the project'",
")",
";",
"$",
"this",
"->",
"setHelp",
"(",
"'The <comment>release... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/ReleaseCommand.php#L28-L41 |
liip/RMT | src/Liip/RMT/Command/ReleaseCommand.php | ReleaseCommand.initialize | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
Context::get('information-collector')->handleCommandInput($input);
$this->getOutput()->writeBigTitle('Welcome to Release Management Tool');
$this->executeActionListIfExist('prerequisites');
} | php | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
Context::get('information-collector')->handleCommandInput($input);
$this->getOutput()->writeBigTitle('Welcome to Release Management Tool');
$this->executeActionListIfExist('prerequisites');
} | [
"protected",
"function",
"initialize",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"parent",
"::",
"initialize",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"Context",
"::",
"get",
"(",
"'information-collector'",
... | Always executed
{@inheritdoc} | [
"Always",
"executed"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/ReleaseCommand.php#L80-L89 |
liip/RMT | src/Liip/RMT/Command/ReleaseCommand.php | ReleaseCommand.interact | protected function interact(InputInterface $input, OutputInterface $output)
{
parent::interact($input, $output);
// Fill up questions
if (Context::get('information-collector')->hasMissingInformation()) {
$questions = Context::get('information-collector')->getInteractiveQuestions();
$this->getOutput()->writeSmallTitle('Information collect ('.count($questions).' questions)');
$this->getOutput()->indent();
$count = 1;
foreach ($questions as $name => $question) {
$answer = $this->getOutput()->askQuestion($question, $count++, $this->input);
Context::get('information-collector')->setValueFor($name, $answer);
$this->getOutput()->writeEmptyLine();
}
$this->getOutput()->unIndent();
}
} | php | protected function interact(InputInterface $input, OutputInterface $output)
{
parent::interact($input, $output);
// Fill up questions
if (Context::get('information-collector')->hasMissingInformation()) {
$questions = Context::get('information-collector')->getInteractiveQuestions();
$this->getOutput()->writeSmallTitle('Information collect ('.count($questions).' questions)');
$this->getOutput()->indent();
$count = 1;
foreach ($questions as $name => $question) {
$answer = $this->getOutput()->askQuestion($question, $count++, $this->input);
Context::get('information-collector')->setValueFor($name, $answer);
$this->getOutput()->writeEmptyLine();
}
$this->getOutput()->unIndent();
}
} | [
"protected",
"function",
"interact",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"parent",
"::",
"interact",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"// Fill up questions",
"if",
"(",
"Context",
"::",
"get",... | Executed only when we are in interactive mode
{@inheritdoc} | [
"Executed",
"only",
"when",
"we",
"are",
"in",
"interactive",
"mode"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/ReleaseCommand.php#L96-L113 |
liip/RMT | src/Liip/RMT/Command/ReleaseCommand.php | ReleaseCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
// Get the current version or generate a new one if the user has confirm that this is required
try {
$currentVersion = Context::get('version-persister')->getCurrentVersion();
} catch (\Liip\RMT\Exception\NoReleaseFoundException $e) {
if (Context::get('information-collector')->getValueFor('confirm-first') == false) {
throw $e;
}
$currentVersion = Context::get('version-generator')->getInitialVersion();
}
Context::getInstance()->setParameter('current-version', $currentVersion);
// Generate and save the new version number
$newVersion = Context::get('version-generator')->generateNextVersion(
Context::getParam('current-version')
);
Context::getInstance()->setParameter('new-version', $newVersion);
$this->executeActionListIfExist('pre-release-actions');
$this->getOutput()->writeSmallTitle('Release process');
$this->getOutput()->indent();
$this->getOutput()->writeln("A new version named [<yellow>$newVersion</yellow>] is going to be released");
Context::get('version-persister')->save($newVersion);
$this->getOutput()->writeln('Release: <green>Success</green>');
$this->getOutput()->unIndent();
$this->executeActionListIfExist('post-release-actions');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
// Get the current version or generate a new one if the user has confirm that this is required
try {
$currentVersion = Context::get('version-persister')->getCurrentVersion();
} catch (\Liip\RMT\Exception\NoReleaseFoundException $e) {
if (Context::get('information-collector')->getValueFor('confirm-first') == false) {
throw $e;
}
$currentVersion = Context::get('version-generator')->getInitialVersion();
}
Context::getInstance()->setParameter('current-version', $currentVersion);
// Generate and save the new version number
$newVersion = Context::get('version-generator')->generateNextVersion(
Context::getParam('current-version')
);
Context::getInstance()->setParameter('new-version', $newVersion);
$this->executeActionListIfExist('pre-release-actions');
$this->getOutput()->writeSmallTitle('Release process');
$this->getOutput()->indent();
$this->getOutput()->writeln("A new version named [<yellow>$newVersion</yellow>] is going to be released");
Context::get('version-persister')->save($newVersion);
$this->getOutput()->writeln('Release: <green>Success</green>');
$this->getOutput()->unIndent();
$this->executeActionListIfExist('post-release-actions');
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"// Get the current version or generate a new one if the user has confirm that this is required",
"try",
"{",
"$",
"currentVersion",
"=",
"Context",
"::",... | Always executed, but first initialize and interact have already been called
{@inheritdoc} | [
"Always",
"executed",
"but",
"first",
"initialize",
"and",
"interact",
"have",
"already",
"been",
"called"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/ReleaseCommand.php#L120-L151 |
liip/RMT | src/Liip/RMT/Config/Handler.php | Handler.normalize | protected function normalize($config)
{
// Validate the config entry
$this->validateRootElements($config);
// For single value elements, normalize all class name and options, remove null entry
foreach (array('vcs', 'version-generator', 'version-persister') as $configKey) {
$value = $config[$configKey];
if ($value == null) {
unset($config[$configKey]);
continue;
}
$config[$configKey] = $this->getClassAndOptions($value, $configKey);
}
// Same process but for list value elements
foreach (array('prerequisites', 'pre-release-actions', 'post-release-actions') as $configKey) {
foreach ($config[$configKey] as $key => $item) {
// Accept the element to be define by key or by value
if (!is_numeric($key)) {
if ($item == null) {
$item = array();
}
$item['name'] = $key;
}
$config[$configKey][$key] = $this->getClassAndOptions($item, $configKey.'_'.$key);
}
}
return $config;
} | php | protected function normalize($config)
{
// Validate the config entry
$this->validateRootElements($config);
// For single value elements, normalize all class name and options, remove null entry
foreach (array('vcs', 'version-generator', 'version-persister') as $configKey) {
$value = $config[$configKey];
if ($value == null) {
unset($config[$configKey]);
continue;
}
$config[$configKey] = $this->getClassAndOptions($value, $configKey);
}
// Same process but for list value elements
foreach (array('prerequisites', 'pre-release-actions', 'post-release-actions') as $configKey) {
foreach ($config[$configKey] as $key => $item) {
// Accept the element to be define by key or by value
if (!is_numeric($key)) {
if ($item == null) {
$item = array();
}
$item['name'] = $key;
}
$config[$configKey][$key] = $this->getClassAndOptions($item, $configKey.'_'.$key);
}
}
return $config;
} | [
"protected",
"function",
"normalize",
"(",
"$",
"config",
")",
"{",
"// Validate the config entry",
"$",
"this",
"->",
"validateRootElements",
"(",
"$",
"config",
")",
";",
"// For single value elements, normalize all class name and options, remove null entry",
"foreach",
"("... | Normalize all config entry to be a normalize class entry: array("class"=>XXX, "options"=>YYY) | [
"Normalize",
"all",
"config",
"entry",
"to",
"be",
"a",
"normalize",
"class",
"entry",
":",
"array",
"(",
"class",
"=",
">",
"XXX",
"options",
"=",
">",
"YYY",
")"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Config/Handler.php#L82-L114 |
liip/RMT | src/Liip/RMT/Config/Handler.php | Handler.getClassAndOptions | protected function getClassAndOptions($rawConfig, $sectionName)
{
if (is_string($rawConfig)) {
$class = $this->findClass($rawConfig, $sectionName);
$options = array();
} elseif (is_array($rawConfig)) {
// Handling Yml corner case (see https://github.com/liip/RMT/issues/54)
if (count($rawConfig) == 1 && key($rawConfig) !== 'name') {
$name = key($rawConfig);
$rawConfig = is_array(reset($rawConfig)) ? reset($rawConfig) : array();
$rawConfig['name'] = $name;
}
if (!isset($rawConfig['name'])) {
throw new Exception("Missing information for [$sectionName], you must provide a [name] value");
}
$class = $this->findClass($rawConfig['name'], $sectionName);
unset($rawConfig['name']);
$options = $rawConfig;
} else {
throw new Exception("Invalid configuration for [$sectionName] should be a object name or an array with name and options");
}
return array('class' => $class, 'options' => $options);
} | php | protected function getClassAndOptions($rawConfig, $sectionName)
{
if (is_string($rawConfig)) {
$class = $this->findClass($rawConfig, $sectionName);
$options = array();
} elseif (is_array($rawConfig)) {
// Handling Yml corner case (see https://github.com/liip/RMT/issues/54)
if (count($rawConfig) == 1 && key($rawConfig) !== 'name') {
$name = key($rawConfig);
$rawConfig = is_array(reset($rawConfig)) ? reset($rawConfig) : array();
$rawConfig['name'] = $name;
}
if (!isset($rawConfig['name'])) {
throw new Exception("Missing information for [$sectionName], you must provide a [name] value");
}
$class = $this->findClass($rawConfig['name'], $sectionName);
unset($rawConfig['name']);
$options = $rawConfig;
} else {
throw new Exception("Invalid configuration for [$sectionName] should be a object name or an array with name and options");
}
return array('class' => $class, 'options' => $options);
} | [
"protected",
"function",
"getClassAndOptions",
"(",
"$",
"rawConfig",
",",
"$",
"sectionName",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"rawConfig",
")",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"findClass",
"(",
"$",
"rawConfig",
",",
"$",
"... | Sub part of the normalize() | [
"Sub",
"part",
"of",
"the",
"normalize",
"()"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Config/Handler.php#L137-L164 |
liip/RMT | src/Liip/RMT/Config/Handler.php | Handler.findClass | protected function findClass($name, $sectionName)
{
$file = $this->projectRoot.DIRECTORY_SEPARATOR.$name;
if (strpos($file, '.php') > 0) {
if (file_exists($file)) {
require_once $file;
$parts = explode(DIRECTORY_SEPARATOR, $file);
$lastPart = array_pop($parts);
return str_replace('.php', '', $lastPart);
} else {
throw new \Liip\RMT\Exception("Impossible to open [$file] please review your config");
}
}
return $this->findInternalClass($name, $sectionName);
} | php | protected function findClass($name, $sectionName)
{
$file = $this->projectRoot.DIRECTORY_SEPARATOR.$name;
if (strpos($file, '.php') > 0) {
if (file_exists($file)) {
require_once $file;
$parts = explode(DIRECTORY_SEPARATOR, $file);
$lastPart = array_pop($parts);
return str_replace('.php', '', $lastPart);
} else {
throw new \Liip\RMT\Exception("Impossible to open [$file] please review your config");
}
}
return $this->findInternalClass($name, $sectionName);
} | [
"protected",
"function",
"findClass",
"(",
"$",
"name",
",",
"$",
"sectionName",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"projectRoot",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"name",
";",
"if",
"(",
"strpos",
"(",
"$",
"file",
",",
"'.php'",
")",... | Sub part of the normalize() | [
"Sub",
"part",
"of",
"the",
"normalize",
"()"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Config/Handler.php#L169-L185 |
liip/RMT | src/Liip/RMT/Config/Handler.php | Handler.findInternalClass | protected function findInternalClass($name, $sectionName)
{
// Remove list id like xxx_3
$classType = $sectionName;
if (strpos($classType, '_') !== false) {
$classType = substr($classType, 0, strpos($classType, '_'));
}
// Guess the namespace
$namespacesByType = array(
'vcs' => 'Liip\RMT\VCS',
'prerequisites' => 'Liip\RMT\Prerequisite',
'pre-release-actions' => 'Liip\RMT\Action',
'post-release-actions' => 'Liip\RMT\Action',
'version-generator' => 'Liip\RMT\Version\Generator',
'version-persister' => 'Liip\RMT\Version\Persister',
);
$nameSpace = $namespacesByType[$classType];
// Guess the class name
// Convert from xxx-yyy-zzz to XxxYyyZzz and append suffix
$suffixByType = array(
'vcs' => '',
'prerequisites' => '',
'pre-release-actions' => 'Action',
'post-release-actions' => 'Action',
'version-generator' => 'Generator',
'version-persister' => 'Persister',
);
$nameSpace = $namespacesByType[$classType];
$className = str_replace(' ', '', ucwords(str_replace('-', ' ', $name))).$suffixByType[$classType];
return $nameSpace.'\\'.$className;
} | php | protected function findInternalClass($name, $sectionName)
{
// Remove list id like xxx_3
$classType = $sectionName;
if (strpos($classType, '_') !== false) {
$classType = substr($classType, 0, strpos($classType, '_'));
}
// Guess the namespace
$namespacesByType = array(
'vcs' => 'Liip\RMT\VCS',
'prerequisites' => 'Liip\RMT\Prerequisite',
'pre-release-actions' => 'Liip\RMT\Action',
'post-release-actions' => 'Liip\RMT\Action',
'version-generator' => 'Liip\RMT\Version\Generator',
'version-persister' => 'Liip\RMT\Version\Persister',
);
$nameSpace = $namespacesByType[$classType];
// Guess the class name
// Convert from xxx-yyy-zzz to XxxYyyZzz and append suffix
$suffixByType = array(
'vcs' => '',
'prerequisites' => '',
'pre-release-actions' => 'Action',
'post-release-actions' => 'Action',
'version-generator' => 'Generator',
'version-persister' => 'Persister',
);
$nameSpace = $namespacesByType[$classType];
$className = str_replace(' ', '', ucwords(str_replace('-', ' ', $name))).$suffixByType[$classType];
return $nameSpace.'\\'.$className;
} | [
"protected",
"function",
"findInternalClass",
"(",
"$",
"name",
",",
"$",
"sectionName",
")",
"{",
"// Remove list id like xxx_3",
"$",
"classType",
"=",
"$",
"sectionName",
";",
"if",
"(",
"strpos",
"(",
"$",
"classType",
",",
"'_'",
")",
"!==",
"false",
")... | Sub part of the normalize() | [
"Sub",
"part",
"of",
"the",
"normalize",
"()"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Config/Handler.php#L190-L223 |
liip/RMT | src/Liip/RMT/Action/VcsPublishAction.php | VcsPublishAction.getRemote | protected function getRemote()
{
if ($this->options['ask-remote-name']) {
return Context::get('information-collector')->getValueFor('remote');
}
if ($this->options['remote-name'] !== null) {
return $this->options['remote-name'];
}
return;
} | php | protected function getRemote()
{
if ($this->options['ask-remote-name']) {
return Context::get('information-collector')->getValueFor('remote');
}
if ($this->options['remote-name'] !== null) {
return $this->options['remote-name'];
}
return;
} | [
"protected",
"function",
"getRemote",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"options",
"[",
"'ask-remote-name'",
"]",
")",
"{",
"return",
"Context",
"::",
"get",
"(",
"'information-collector'",
")",
"->",
"getValueFor",
"(",
"'remote'",
")",
";",
"}... | Return the remote name where to publish or null if not defined
@return string|null | [
"Return",
"the",
"remote",
"name",
"where",
"to",
"publish",
"or",
"null",
"if",
"not",
"defined"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/VcsPublishAction.php#L89-L99 |
liip/RMT | src/Liip/RMT/Action/BuildPharPackageAction.php | BuildPharPackageAction.create | protected function create()
{
$this->setReleaseVersion();
$output = $this->getDestination() . '/' . $this->getFilename();
$phar = new Phar($output, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME);
$phar->buildFromDirectory(Context::getParam('project-root'), $this->options['excluded-paths']);
$phar->setMetadata(array_merge(array('version' => $this->releaseVersion), $this->options['metadata']));
$phar->setDefaultStub($this->options['default-stub-cli'], $this->options['default-stub-web']);
return $output;
} | php | protected function create()
{
$this->setReleaseVersion();
$output = $this->getDestination() . '/' . $this->getFilename();
$phar = new Phar($output, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME);
$phar->buildFromDirectory(Context::getParam('project-root'), $this->options['excluded-paths']);
$phar->setMetadata(array_merge(array('version' => $this->releaseVersion), $this->options['metadata']));
$phar->setDefaultStub($this->options['default-stub-cli'], $this->options['default-stub-web']);
return $output;
} | [
"protected",
"function",
"create",
"(",
")",
"{",
"$",
"this",
"->",
"setReleaseVersion",
"(",
")",
";",
"$",
"output",
"=",
"$",
"this",
"->",
"getDestination",
"(",
")",
".",
"'/'",
".",
"$",
"this",
"->",
"getFilename",
"(",
")",
";",
"$",
"phar",... | Handles the creation of the package. | [
"Handles",
"the",
"creation",
"of",
"the",
"package",
"."
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/BuildPharPackageAction.php#L49-L61 |
liip/RMT | src/Liip/RMT/Action/BuildPharPackageAction.php | BuildPharPackageAction.getDestination | protected function getDestination()
{
$destination = $this->options['destination'];
if ($this->isRelativePath($destination)) {
return Context::getParam('project-root') . '/' . $destination;
}
return $destination;
} | php | protected function getDestination()
{
$destination = $this->options['destination'];
if ($this->isRelativePath($destination)) {
return Context::getParam('project-root') . '/' . $destination;
}
return $destination;
} | [
"protected",
"function",
"getDestination",
"(",
")",
"{",
"$",
"destination",
"=",
"$",
"this",
"->",
"options",
"[",
"'destination'",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"isRelativePath",
"(",
"$",
"destination",
")",
")",
"{",
"return",
"Context",
... | Get the destination directory to build the package into.
@return string The destination | [
"Get",
"the",
"destination",
"directory",
"to",
"build",
"the",
"package",
"into",
"."
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/BuildPharPackageAction.php#L90-L99 |
liip/RMT | src/Liip/RMT/Action/BuildPharPackageAction.php | BuildPharPackageAction.setReleaseVersion | protected function setReleaseVersion()
{
try {
$currentVersion = Context::get('version-persister')->getCurrentVersion();
} catch (\Exception $e) {
$currentVersion = Context::get('version-generator')->getInitialVersion();
}
$this->releaseVersion = Context::get('version-generator')->generateNextVersion($currentVersion);
} | php | protected function setReleaseVersion()
{
try {
$currentVersion = Context::get('version-persister')->getCurrentVersion();
} catch (\Exception $e) {
$currentVersion = Context::get('version-generator')->getInitialVersion();
}
$this->releaseVersion = Context::get('version-generator')->generateNextVersion($currentVersion);
} | [
"protected",
"function",
"setReleaseVersion",
"(",
")",
"{",
"try",
"{",
"$",
"currentVersion",
"=",
"Context",
"::",
"get",
"(",
"'version-persister'",
")",
"->",
"getCurrentVersion",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{"... | Determine and set the next release version. | [
"Determine",
"and",
"set",
"the",
"next",
"release",
"version",
"."
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/BuildPharPackageAction.php#L104-L113 |
liip/RMT | src/Liip/RMT/Action/FilesUpdateAction.php | FilesUpdateAction.updateFile | protected function updateFile($filename, $pattern = null)
{
$current = Context::getParam('current-version');
$next = Context::getParam('new-version');
$content = file_get_contents($filename);
if (false === strpos($content, $current)) {
throw new Exception("The version file $filename does not contain the current version $current");
}
if ($pattern) {
$current = str_replace('%version%', $current, $pattern);
$next = str_replace('%version%', $next, $pattern);
}
$content = str_replace($current, $next, $content);
if (false === strpos($content, (string)$next)) {
throw new Exception("The version file $filename could not be updated with version $next");
}
file_put_contents($filename, $content);
} | php | protected function updateFile($filename, $pattern = null)
{
$current = Context::getParam('current-version');
$next = Context::getParam('new-version');
$content = file_get_contents($filename);
if (false === strpos($content, $current)) {
throw new Exception("The version file $filename does not contain the current version $current");
}
if ($pattern) {
$current = str_replace('%version%', $current, $pattern);
$next = str_replace('%version%', $next, $pattern);
}
$content = str_replace($current, $next, $content);
if (false === strpos($content, (string)$next)) {
throw new Exception("The version file $filename could not be updated with version $next");
}
file_put_contents($filename, $content);
} | [
"protected",
"function",
"updateFile",
"(",
"$",
"filename",
",",
"$",
"pattern",
"=",
"null",
")",
"{",
"$",
"current",
"=",
"Context",
"::",
"getParam",
"(",
"'current-version'",
")",
";",
"$",
"next",
"=",
"Context",
"::",
"getParam",
"(",
"'new-version... | will update a given filename with the current version
@param string $filename
@param null $pattern
@throws Exception | [
"will",
"update",
"a",
"given",
"filename",
"with",
"the",
"current",
"version"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/FilesUpdateAction.php#L56-L76 |
liip/RMT | src/Liip/RMT/Changelog/Formatter/MarkdownChangelogFormatter.php | MarkdownChangelogFormatter.formatExtraLines | protected function formatExtraLines($lines)
{
foreach ($lines as $pos => $line) {
$lines[$pos] = ' * '.$line;
}
return $lines;
} | php | protected function formatExtraLines($lines)
{
foreach ($lines as $pos => $line) {
$lines[$pos] = ' * '.$line;
}
return $lines;
} | [
"protected",
"function",
"formatExtraLines",
"(",
"$",
"lines",
")",
"{",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"pos",
"=>",
"$",
"line",
")",
"{",
"$",
"lines",
"[",
"$",
"pos",
"]",
"=",
"' * '",
".",
"$",
"line",
";",
"}",
"return",
"$",... | format extra lines (such as commit details)
@param array $lines
@return array | [
"format",
"extra",
"lines",
"(",
"such",
"as",
"commit",
"details",
")"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Changelog/Formatter/MarkdownChangelogFormatter.php#L135-L141 |
liip/RMT | src/Liip/RMT/Application.php | Application.run | public function run(InputInterface $input = null, OutputInterface $output = null)
{
return parent::run($input, new \Liip\RMT\Output\Output());
} | php | public function run(InputInterface $input = null, OutputInterface $output = null)
{
return parent::run($input, new \Liip\RMT\Output\Output());
} | [
"public",
"function",
"run",
"(",
"InputInterface",
"$",
"input",
"=",
"null",
",",
"OutputInterface",
"$",
"output",
"=",
"null",
")",
"{",
"return",
"parent",
"::",
"run",
"(",
"$",
"input",
",",
"new",
"\\",
"Liip",
"\\",
"RMT",
"\\",
"Output",
"\\"... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Application.php#L68-L71 |
liip/RMT | src/Liip/RMT/Application.php | Application.asText | public function asText($namespace = null, $raw = false)
{
$messages = array();
// Title
$title = 'RMT '.$this->getLongVersion();
$messages[] = '';
$messages[] = $title;
$messages[] = str_pad('', 41, '-'); // strlen is not working here...
$messages[] = '';
// Usage
$messages[] = '<comment>Usage:</comment>';
$messages[] = ' RMT command [arguments] [options]';
$messages[] = '';
// Commands
$messages[] = '<comment>Available commands:</comment>';
$commands = $this->all();
$width = 0;
foreach ($commands as $command) {
$width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
}
$width += 2;
foreach ($commands as $name => $command) {
if (in_array($name, array('list', 'help'))) {
continue;
}
$messages[] = sprintf(" <info>%-${width}s</info> %s", $name, $command->getDescription());
}
$messages[] = '';
// Options
$messages[] = '<comment>Common options:</comment>';
foreach ($this->getDefinition()->getOptions() as $option) {
if (in_array($option->getName(), array('help', 'ansi', 'no-ansi', 'no-interaction', 'version'))) {
continue;
}
$messages[] = sprintf(
' %-29s %s %s',
'<info>--'.$option->getName().'</info>',
$option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
$option->getDescription()
);
}
$messages[] = '';
// Help
$messages[] = '<comment>Help:</comment>';
$messages[] = ' To get more information about a given command, you can use the help option:';
$messages[] = sprintf(' %-26s %s %s', '<info>--help</info>', '<info>-h</info>', 'Provide help for the given command');
$messages[] = '';
return implode(PHP_EOL, $messages);
} | php | public function asText($namespace = null, $raw = false)
{
$messages = array();
// Title
$title = 'RMT '.$this->getLongVersion();
$messages[] = '';
$messages[] = $title;
$messages[] = str_pad('', 41, '-'); // strlen is not working here...
$messages[] = '';
// Usage
$messages[] = '<comment>Usage:</comment>';
$messages[] = ' RMT command [arguments] [options]';
$messages[] = '';
// Commands
$messages[] = '<comment>Available commands:</comment>';
$commands = $this->all();
$width = 0;
foreach ($commands as $command) {
$width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
}
$width += 2;
foreach ($commands as $name => $command) {
if (in_array($name, array('list', 'help'))) {
continue;
}
$messages[] = sprintf(" <info>%-${width}s</info> %s", $name, $command->getDescription());
}
$messages[] = '';
// Options
$messages[] = '<comment>Common options:</comment>';
foreach ($this->getDefinition()->getOptions() as $option) {
if (in_array($option->getName(), array('help', 'ansi', 'no-ansi', 'no-interaction', 'version'))) {
continue;
}
$messages[] = sprintf(
' %-29s %s %s',
'<info>--'.$option->getName().'</info>',
$option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
$option->getDescription()
);
}
$messages[] = '';
// Help
$messages[] = '<comment>Help:</comment>';
$messages[] = ' To get more information about a given command, you can use the help option:';
$messages[] = sprintf(' %-26s %s %s', '<info>--help</info>', '<info>-h</info>', 'Provide help for the given command');
$messages[] = '';
return implode(PHP_EOL, $messages);
} | [
"public",
"function",
"asText",
"(",
"$",
"namespace",
"=",
"null",
",",
"$",
"raw",
"=",
"false",
")",
"{",
"$",
"messages",
"=",
"array",
"(",
")",
";",
"// Title",
"$",
"title",
"=",
"'RMT '",
".",
"$",
"this",
"->",
"getLongVersion",
"(",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Application.php#L126-L180 |
liip/RMT | src/Liip/RMT/Version/Persister/VcsTagPersister.php | VcsTagPersister.getCurrentVersion | public function getCurrentVersion()
{
$tags = $this->getValidVersionTags($this->versionRegex);
if (count($tags) === 0) {
throw new \Liip\RMT\Exception\NoReleaseFoundException('No VCS tag matching the regex [' . $this->getTagPrefix() . $this->versionRegex . ']');
}
// Extract versions from tags and sort them
$versions = $this->getVersionFromTags($tags);
usort($versions, array(Context::get('version-generator'), 'compareTwoVersions'));
return array_pop($versions);
} | php | public function getCurrentVersion()
{
$tags = $this->getValidVersionTags($this->versionRegex);
if (count($tags) === 0) {
throw new \Liip\RMT\Exception\NoReleaseFoundException('No VCS tag matching the regex [' . $this->getTagPrefix() . $this->versionRegex . ']');
}
// Extract versions from tags and sort them
$versions = $this->getVersionFromTags($tags);
usort($versions, array(Context::get('version-generator'), 'compareTwoVersions'));
return array_pop($versions);
} | [
"public",
"function",
"getCurrentVersion",
"(",
")",
"{",
"$",
"tags",
"=",
"$",
"this",
"->",
"getValidVersionTags",
"(",
"$",
"this",
"->",
"versionRegex",
")",
";",
"if",
"(",
"count",
"(",
"$",
"tags",
")",
"===",
"0",
")",
"{",
"throw",
"new",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Version/Persister/VcsTagPersister.php#L35-L47 |
liip/RMT | src/Liip/RMT/Version/Persister/VcsTagPersister.php | VcsTagPersister.getValidVersionTags | public function getValidVersionTags($versionRegex)
{
$validator = new TagValidator($versionRegex, $this->getTagPrefix());
return $validator->filtrateList($this->vcs->getTags());
} | php | public function getValidVersionTags($versionRegex)
{
$validator = new TagValidator($versionRegex, $this->getTagPrefix());
return $validator->filtrateList($this->vcs->getTags());
} | [
"public",
"function",
"getValidVersionTags",
"(",
"$",
"versionRegex",
")",
"{",
"$",
"validator",
"=",
"new",
"TagValidator",
"(",
"$",
"versionRegex",
",",
"$",
"this",
"->",
"getTagPrefix",
"(",
")",
")",
";",
"return",
"$",
"validator",
"->",
"filtrateLi... | Return all tags matching the versionRegex and prefix
@param string $versionRegex
@return array | [
"Return",
"all",
"tags",
"matching",
"the",
"versionRegex",
"and",
"prefix"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Version/Persister/VcsTagPersister.php#L102-L107 |
liip/RMT | src/Liip/RMT/Changelog/Formatter/SemanticChangelogFormatter.php | SemanticChangelogFormatter.getNewLines | protected function getNewLines($type, $version, $comment)
{
list($major, $minor, $patch) = explode('.', $version);
if ($type == 'major') {
$title = "version $major $comment";
return array_merge(
array(
'',
strtoupper($title),
str_pad('', strlen($title), '='),
),
$this->getNewLines('minor', $version, $comment)
);
} elseif ($type == 'minor') {
return array_merge(
array(
'',
" Version $major.$minor - $comment",
),
$this->getNewLines('patch', $version, 'initial release')
);
} else { //patch
$date = $this->getFormattedDate();
return array(
" $date $version $comment",
);
}
} | php | protected function getNewLines($type, $version, $comment)
{
list($major, $minor, $patch) = explode('.', $version);
if ($type == 'major') {
$title = "version $major $comment";
return array_merge(
array(
'',
strtoupper($title),
str_pad('', strlen($title), '='),
),
$this->getNewLines('minor', $version, $comment)
);
} elseif ($type == 'minor') {
return array_merge(
array(
'',
" Version $major.$minor - $comment",
),
$this->getNewLines('patch', $version, 'initial release')
);
} else { //patch
$date = $this->getFormattedDate();
return array(
" $date $version $comment",
);
}
} | [
"protected",
"function",
"getNewLines",
"(",
"$",
"type",
",",
"$",
"version",
",",
"$",
"comment",
")",
"{",
"list",
"(",
"$",
"major",
",",
"$",
"minor",
",",
"$",
"patch",
")",
"=",
"explode",
"(",
"'.'",
",",
"$",
"version",
")",
";",
"if",
"... | Return the new formatted lines for the given variables
@param string $type The version type, could be major, minor, patch
@param string $version The new version number
@param string $comment The user comment
@return array An array of new lines | [
"Return",
"the",
"new",
"formatted",
"lines",
"for",
"the",
"given",
"variables"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Changelog/Formatter/SemanticChangelogFormatter.php#L95-L124 |
liip/RMT | src/Liip/RMT/Changelog/Formatter/SemanticChangelogFormatter.php | SemanticChangelogFormatter.findPositionToInsert | protected function findPositionToInsert($lines, $type)
{
// Major are always inserted at the top
if ($type == 'major') {
return 0;
}
// Minor must be inserted one line above the first major section
if ($type == 'minor') {
foreach ($lines as $pos => $line) {
if (preg_match('/^=======/', $line)) {
return $pos + 1;
}
}
}
// Patch should go directly after the first minor
if ($type == 'patch') {
foreach ($lines as $pos => $line) {
if (preg_match('/Version\s\d+\.\d+\s\-/', $line)) {
return $pos + 1;
}
}
}
throw new \Liip\RMT\Exception('Invalid changelog formatting');
} | php | protected function findPositionToInsert($lines, $type)
{
// Major are always inserted at the top
if ($type == 'major') {
return 0;
}
// Minor must be inserted one line above the first major section
if ($type == 'minor') {
foreach ($lines as $pos => $line) {
if (preg_match('/^=======/', $line)) {
return $pos + 1;
}
}
}
// Patch should go directly after the first minor
if ($type == 'patch') {
foreach ($lines as $pos => $line) {
if (preg_match('/Version\s\d+\.\d+\s\-/', $line)) {
return $pos + 1;
}
}
}
throw new \Liip\RMT\Exception('Invalid changelog formatting');
} | [
"protected",
"function",
"findPositionToInsert",
"(",
"$",
"lines",
",",
"$",
"type",
")",
"{",
"// Major are always inserted at the top",
"if",
"(",
"$",
"type",
"==",
"'major'",
")",
"{",
"return",
"0",
";",
"}",
"// Minor must be inserted one line above the first m... | Return the position where to insert new lines according to the type of insertion
@param array $lines Existing lines
@param string $type Release type
@return int The position where to insert
@throws \Liip\RMT\Exception | [
"Return",
"the",
"position",
"where",
"to",
"insert",
"new",
"lines",
"according",
"to",
"the",
"type",
"of",
"insertion"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Changelog/Formatter/SemanticChangelogFormatter.php#L136-L162 |
liip/RMT | src/Liip/RMT/Command/InitCommand.php | InitCommand.configure | protected function configure()
{
$this->setName('init');
$this->setDescription('Setup a new project configuration in the current directory');
$this->setHelp('The <comment>init</comment> interactive task can be used to setup a new project');
// Add an option to force re-creation of the config file
$this->getDefinition()->addOption(new InputOption('force', null, InputOption::VALUE_NONE, 'Force update of the config file'));
// Create an information collector and configure the different information request
$this->informationCollector = new InformationCollector();
$this->informationCollector->registerRequests(array(
new InformationRequest('configonly', array(
'description' => 'if you want to skip creation of the RMT convenience script',
'type' => 'yes-no',
'command_argument' => true,
'interactive' => true,
'default' => 'n',
)),
new InformationRequest('vcs', array(
'description' => 'The VCS system to use',
'type' => 'choice',
'choices' => array('git', 'hg', 'none'),
'choices_shortcuts' => array('g' => 'git', 'h' => 'hg', 'n' => 'none'),
'default' => 'none',
)),
new InformationRequest('generator', array(
'description' => 'The generator to use for version incrementing',
'type' => 'choice',
'choices' => array('semantic-versioning', 'basic-increment'),
'choices_shortcuts' => array('s' => 'semantic-versioning', 'b' => 'basic-increment'),
)),
new InformationRequest('persister', array(
'description' => 'The strategy to use to persist the current version value',
'type' => 'choice',
'choices' => array('vcs-tag', 'changelog'),
'choices_shortcuts' => array('t' => 'vcs-tag', 'c' => 'changelog'),
'command_argument' => true,
'interactive' => true,
)),
));
foreach ($this->informationCollector->getCommandOptions() as $option) {
$this->getDefinition()->addOption($option);
}
} | php | protected function configure()
{
$this->setName('init');
$this->setDescription('Setup a new project configuration in the current directory');
$this->setHelp('The <comment>init</comment> interactive task can be used to setup a new project');
// Add an option to force re-creation of the config file
$this->getDefinition()->addOption(new InputOption('force', null, InputOption::VALUE_NONE, 'Force update of the config file'));
// Create an information collector and configure the different information request
$this->informationCollector = new InformationCollector();
$this->informationCollector->registerRequests(array(
new InformationRequest('configonly', array(
'description' => 'if you want to skip creation of the RMT convenience script',
'type' => 'yes-no',
'command_argument' => true,
'interactive' => true,
'default' => 'n',
)),
new InformationRequest('vcs', array(
'description' => 'The VCS system to use',
'type' => 'choice',
'choices' => array('git', 'hg', 'none'),
'choices_shortcuts' => array('g' => 'git', 'h' => 'hg', 'n' => 'none'),
'default' => 'none',
)),
new InformationRequest('generator', array(
'description' => 'The generator to use for version incrementing',
'type' => 'choice',
'choices' => array('semantic-versioning', 'basic-increment'),
'choices_shortcuts' => array('s' => 'semantic-versioning', 'b' => 'basic-increment'),
)),
new InformationRequest('persister', array(
'description' => 'The strategy to use to persist the current version value',
'type' => 'choice',
'choices' => array('vcs-tag', 'changelog'),
'choices_shortcuts' => array('t' => 'vcs-tag', 'c' => 'changelog'),
'command_argument' => true,
'interactive' => true,
)),
));
foreach ($this->informationCollector->getCommandOptions() as $option) {
$this->getDefinition()->addOption($option);
}
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'init'",
")",
";",
"$",
"this",
"->",
"setDescription",
"(",
"'Setup a new project configuration in the current directory'",
")",
";",
"$",
"this",
"->",
"setHelp",
"(",
"'T... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/InitCommand.php#L47-L91 |
liip/RMT | src/Liip/RMT/Command/InitCommand.php | InitCommand.initialize | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
$this->informationCollector->handleCommandInput($input);
$this->getOutput()->writeBigTitle('Welcome to Release Management Tool initialization');
$this->getOutput()->writeEmptyLine();
// Security check for the config
$configPath = $this->getApplication()->getConfigFilePath();
if ($configPath !== null && file_exists($configPath) && $input->getOption('force') !== true) {
throw new \Exception("A config file already exist ($configPath), if you want to regenerate it, use the --force option");
}
// Guessing elements path
$this->buildPaths($configPath);
// disable the creation of the conveniance script when within a phar
if (extension_loaded('phar') && \Phar::running()) {
$this->informationCollector->setValueFor('configonly', 'y');
}
} | php | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
$this->informationCollector->handleCommandInput($input);
$this->getOutput()->writeBigTitle('Welcome to Release Management Tool initialization');
$this->getOutput()->writeEmptyLine();
// Security check for the config
$configPath = $this->getApplication()->getConfigFilePath();
if ($configPath !== null && file_exists($configPath) && $input->getOption('force') !== true) {
throw new \Exception("A config file already exist ($configPath), if you want to regenerate it, use the --force option");
}
// Guessing elements path
$this->buildPaths($configPath);
// disable the creation of the conveniance script when within a phar
if (extension_loaded('phar') && \Phar::running()) {
$this->informationCollector->setValueFor('configonly', 'y');
}
} | [
"protected",
"function",
"initialize",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"parent",
"::",
"initialize",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"this",
"->",
"informationCollector",
"->",
"hand... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/InitCommand.php#L96-L117 |
liip/RMT | src/Liip/RMT/Command/InitCommand.php | InitCommand.interact | protected function interact(InputInterface $input, OutputInterface $output)
{
parent::interact($input, $output);
// Fill up questions
if ($this->informationCollector->hasMissingInformation()) {
foreach ($this->informationCollector->getInteractiveQuestions() as $name => $question) {
$answer = $this->getOutput()->askQuestion($question, null, $this->input);
$this->informationCollector->setValueFor($name, $answer);
$this->getOutput()->writeEmptyLine();
}
}
} | php | protected function interact(InputInterface $input, OutputInterface $output)
{
parent::interact($input, $output);
// Fill up questions
if ($this->informationCollector->hasMissingInformation()) {
foreach ($this->informationCollector->getInteractiveQuestions() as $name => $question) {
$answer = $this->getOutput()->askQuestion($question, null, $this->input);
$this->informationCollector->setValueFor($name, $answer);
$this->getOutput()->writeEmptyLine();
}
}
} | [
"protected",
"function",
"interact",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"parent",
"::",
"interact",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"// Fill up questions",
"if",
"(",
"$",
"this",
"->",
"i... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/InitCommand.php#L122-L134 |
liip/RMT | src/Liip/RMT/Command/InitCommand.php | InitCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
if ($this->informationCollector->getValueFor('configonly') == 'n') {
// Create the executable task inside the project home
$this->getOutput()->writeln("Creation of the new executable <info>{$this->executablePath}</info>");
file_put_contents(
$this->executablePath,
"#!/usr/bin/env php\n".
"<?php\n".
"define('RMT_ROOT_DIR', __DIR__);\n".
"require '{$this->commandPath}';\n"
);
chmod('RMT', 0755);
}
// Create the config file from a template
$this->getOutput()->writeln("Creation of the config file <info>{$this->configPath}</info>");
$template = $this->informationCollector->getValueFor('vcs') == 'none' ?
__DIR__.'/../Config/templates/no-vcs-config.yml.tmpl' :
__DIR__.'/../Config/templates/default-vcs-config.yml.tmpl'
;
$config = file_get_contents($template);
$generator = $this->informationCollector->getValueFor('generator');
foreach (array(
'generator' => $generator == 'semantic-versioning' ?
'semantic # More complex versionning (semantic)' : 'simple # Same simple versionning',
'vcs' => $this->informationCollector->getValueFor('vcs'),
'persister' => $this->informationCollector->getValueFor('persister'),
'changelog-format' => $generator == 'semantic-versioning' ? 'semantic' : 'simple',
) as $key => $value) {
$config = str_replace("%%$key%%", $value, $config);
}
file_put_contents($this->configPath, $config);
// Confirmation
$this->getOutput()->writeBigTitle('Success, you can start using RMT by calling "RMT release"');
$this->getOutput()->writeEmptyLine();
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
if ($this->informationCollector->getValueFor('configonly') == 'n') {
// Create the executable task inside the project home
$this->getOutput()->writeln("Creation of the new executable <info>{$this->executablePath}</info>");
file_put_contents(
$this->executablePath,
"#!/usr/bin/env php\n".
"<?php\n".
"define('RMT_ROOT_DIR', __DIR__);\n".
"require '{$this->commandPath}';\n"
);
chmod('RMT', 0755);
}
// Create the config file from a template
$this->getOutput()->writeln("Creation of the config file <info>{$this->configPath}</info>");
$template = $this->informationCollector->getValueFor('vcs') == 'none' ?
__DIR__.'/../Config/templates/no-vcs-config.yml.tmpl' :
__DIR__.'/../Config/templates/default-vcs-config.yml.tmpl'
;
$config = file_get_contents($template);
$generator = $this->informationCollector->getValueFor('generator');
foreach (array(
'generator' => $generator == 'semantic-versioning' ?
'semantic # More complex versionning (semantic)' : 'simple # Same simple versionning',
'vcs' => $this->informationCollector->getValueFor('vcs'),
'persister' => $this->informationCollector->getValueFor('persister'),
'changelog-format' => $generator == 'semantic-versioning' ? 'semantic' : 'simple',
) as $key => $value) {
$config = str_replace("%%$key%%", $value, $config);
}
file_put_contents($this->configPath, $config);
// Confirmation
$this->getOutput()->writeBigTitle('Success, you can start using RMT by calling "RMT release"');
$this->getOutput()->writeEmptyLine();
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"informationCollector",
"->",
"getValueFor",
"(",
"'configonly'",
")",
"==",
"'n'",
")",
"{",
"// Create the... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/InitCommand.php#L139-L176 |
liip/RMT | src/Liip/RMT/Command/BaseCommand.php | BaseCommand.run | public function run(InputInterface $input, OutputInterface $output)
{
// Store the input and output for easier usage
$this->input = $input;
if (!$output instanceof Output) {
throw new \InvalidArgumentException('Not the expected output type');
}
$this->output = $output;
$dialogHelper = class_exists('Symfony\Component\Console\Helper\QuestionHelper')
? $this->getHelperSet()->get('question')
: $this->getHelperSet()->get('dialog')
;
$this->output->setDialogHelper($dialogHelper);
$this->output->setFormatterHelper($this->getHelperSet()->get('formatter'));
Context::getInstance()->setService('input', $this->input);
Context::getInstance()->setService('output', $this->output);
parent::run($input, $output);
} | php | public function run(InputInterface $input, OutputInterface $output)
{
// Store the input and output for easier usage
$this->input = $input;
if (!$output instanceof Output) {
throw new \InvalidArgumentException('Not the expected output type');
}
$this->output = $output;
$dialogHelper = class_exists('Symfony\Component\Console\Helper\QuestionHelper')
? $this->getHelperSet()->get('question')
: $this->getHelperSet()->get('dialog')
;
$this->output->setDialogHelper($dialogHelper);
$this->output->setFormatterHelper($this->getHelperSet()->get('formatter'));
Context::getInstance()->setService('input', $this->input);
Context::getInstance()->setService('output', $this->output);
parent::run($input, $output);
} | [
"public",
"function",
"run",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"// Store the input and output for easier usage",
"$",
"this",
"->",
"input",
"=",
"$",
"input",
";",
"if",
"(",
"!",
"$",
"output",
"instanceof",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Command/BaseCommand.php#L41-L59 |
liip/RMT | src/Liip/RMT/Action/BaseAction.php | BaseAction.executeCommandInProcess | public function executeCommandInProcess($cmd, $timeout = null){
Context::get('output')->write("<comment>$cmd</comment>\n\n");
$process = new Process($cmd);
if ($timeout !== null) {
$process->setTimeout($timeout);
}
$process->run(function ($type, $buffer) {
Context::get('output')->write($buffer);
});
return $process;
} | php | public function executeCommandInProcess($cmd, $timeout = null){
Context::get('output')->write("<comment>$cmd</comment>\n\n");
$process = new Process($cmd);
if ($timeout !== null) {
$process->setTimeout($timeout);
}
$process->run(function ($type, $buffer) {
Context::get('output')->write($buffer);
});
return $process;
} | [
"public",
"function",
"executeCommandInProcess",
"(",
"$",
"cmd",
",",
"$",
"timeout",
"=",
"null",
")",
"{",
"Context",
"::",
"get",
"(",
"'output'",
")",
"->",
"write",
"(",
"\"<comment>$cmd</comment>\\n\\n\"",
")",
";",
"$",
"process",
"=",
"new",
"Proces... | Execute a command and render the output through the classical indented output
@param string $cmd
@param float|null $timeout
@return Process | [
"Execute",
"a",
"command",
"and",
"render",
"the",
"output",
"through",
"the",
"classical",
"indented",
"output"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/BaseAction.php#L69-L81 |
liip/RMT | src/Liip/RMT/Action/UpdateVersionClassAction.php | UpdateVersionClassAction.updateFile | protected function updateFile($filename)
{
$current = Context::getParam('current-version');
$next = Context::getParam('new-version');
$content = file_get_contents($filename);
if (false === strpos($content, $current)) {
throw new Exception('The version class ' . $filename . " does not contain the current version $current");
}
if (isset($this->options['pattern'])) {
$current = str_replace('%version%', $current, $this->options['pattern']);
$next = str_replace('%version%', $next, $this->options['pattern']);
}
$content = str_replace($current, $next, $content);
if (false === strpos($content, $next)) {
throw new Exception('The version class ' . $filename . " could not be updated with version $next");
}
file_put_contents($filename, $content);
} | php | protected function updateFile($filename)
{
$current = Context::getParam('current-version');
$next = Context::getParam('new-version');
$content = file_get_contents($filename);
if (false === strpos($content, $current)) {
throw new Exception('The version class ' . $filename . " does not contain the current version $current");
}
if (isset($this->options['pattern'])) {
$current = str_replace('%version%', $current, $this->options['pattern']);
$next = str_replace('%version%', $next, $this->options['pattern']);
}
$content = str_replace($current, $next, $content);
if (false === strpos($content, $next)) {
throw new Exception('The version class ' . $filename . " could not be updated with version $next");
}
file_put_contents($filename, $content);
} | [
"protected",
"function",
"updateFile",
"(",
"$",
"filename",
")",
"{",
"$",
"current",
"=",
"Context",
"::",
"getParam",
"(",
"'current-version'",
")",
";",
"$",
"next",
"=",
"Context",
"::",
"getParam",
"(",
"'new-version'",
")",
";",
"$",
"content",
"=",... | will update a given filename with the current version
@param string $filename
@throws \Liip\RMT\Exception | [
"will",
"update",
"a",
"given",
"filename",
"with",
"the",
"current",
"version"
] | train | https://github.com/liip/RMT/blob/1fc8903958e4b0781def91e8ecaa8d97811c3c56/src/Liip/RMT/Action/UpdateVersionClassAction.php#L65-L83 |
bramus/ansi-php | src/Traits/EscapeSequences/SGR.php | SGR.sgr | public function sgr($data = array())
{
// Write data to the writer
$this->writer->write(
new \Bramus\Ansi\ControlSequences\EscapeSequences\SGR($data)
);
// Afford chaining
return $this;
} | php | public function sgr($data = array())
{
// Write data to the writer
$this->writer->write(
new \Bramus\Ansi\ControlSequences\EscapeSequences\SGR($data)
);
// Afford chaining
return $this;
} | [
"public",
"function",
"sgr",
"(",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"// Write data to the writer",
"$",
"this",
"->",
"writer",
"->",
"write",
"(",
"new",
"\\",
"Bramus",
"\\",
"Ansi",
"\\",
"ControlSequences",
"\\",
"EscapeSequences",
"\\",
"... | Manually use SGR (Select Graphic Rendition)
@param array $parameterByte Parameter byte to the SGR Escape Code
@return Ansi self, for chaining | [
"Manually",
"use",
"SGR",
"(",
"Select",
"Graphic",
"Rendition",
")"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Traits/EscapeSequences/SGR.php#L17-L26 |
bramus/ansi-php | src/Writers/StreamWriter.php | StreamWriter.setStream | public function setStream($stream = null)
{
// String passed in? Try converting it to a stream
if (is_string($stream)) {
$stream = @fopen($stream, 'a');
}
// Make sure the stream is a resource
if (!is_resource($stream)) {
throw new \InvalidArgumentException('Invalid Stream');
}
// Store it
$this->stream = $stream;
// Afford chaining
return $this;
} | php | public function setStream($stream = null)
{
// String passed in? Try converting it to a stream
if (is_string($stream)) {
$stream = @fopen($stream, 'a');
}
// Make sure the stream is a resource
if (!is_resource($stream)) {
throw new \InvalidArgumentException('Invalid Stream');
}
// Store it
$this->stream = $stream;
// Afford chaining
return $this;
} | [
"public",
"function",
"setStream",
"(",
"$",
"stream",
"=",
"null",
")",
"{",
"// String passed in? Try converting it to a stream",
"if",
"(",
"is_string",
"(",
"$",
"stream",
")",
")",
"{",
"$",
"stream",
"=",
"@",
"fopen",
"(",
"$",
"stream",
",",
"'a'",
... | Set the stream to write to
@param mixed $stream Stream to write to | [
"Set",
"the",
"stream",
"to",
"write",
"to"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Writers/StreamWriter.php#L37-L54 |
bramus/ansi-php | src/Writers/BufferWriter.php | BufferWriter.flush | public function flush($resetAfterwards = true)
{
// Get buffer contents
$buffer = $this->buffer;
// Clear buffer contents
if ($resetAfterwards) {
$this->clear();
}
// Return data that was flushed
return $buffer;
} | php | public function flush($resetAfterwards = true)
{
// Get buffer contents
$buffer = $this->buffer;
// Clear buffer contents
if ($resetAfterwards) {
$this->clear();
}
// Return data that was flushed
return $buffer;
} | [
"public",
"function",
"flush",
"(",
"$",
"resetAfterwards",
"=",
"true",
")",
"{",
"// Get buffer contents",
"$",
"buffer",
"=",
"$",
"this",
"->",
"buffer",
";",
"// Clear buffer contents",
"if",
"(",
"$",
"resetAfterwards",
")",
"{",
"$",
"this",
"->",
"cl... | Get/Flush the data
@param boolean $resetAfterwards Reset the data afterwards?
@return string The data | [
"Get",
"/",
"Flush",
"the",
"data"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Writers/BufferWriter.php#L35-L47 |
bramus/ansi-php | src/Traits/EscapeSequences/ED.php | ED.ed | public function ed($data)
{
// Write data to the writer
$this->writer->write(
new \Bramus\Ansi\ControlSequences\EscapeSequences\ED($data)
);
// Afford chaining
return $this;
} | php | public function ed($data)
{
// Write data to the writer
$this->writer->write(
new \Bramus\Ansi\ControlSequences\EscapeSequences\ED($data)
);
// Afford chaining
return $this;
} | [
"public",
"function",
"ed",
"(",
"$",
"data",
")",
"{",
"// Write data to the writer",
"$",
"this",
"->",
"writer",
"->",
"write",
"(",
"new",
"\\",
"Bramus",
"\\",
"Ansi",
"\\",
"ControlSequences",
"\\",
"EscapeSequences",
"\\",
"ED",
"(",
"$",
"data",
")... | Manually use ED (Select Graphic Rendition)
@param array $parameterByte Parameter byte to the SGR Escape Code
@return Ansi self, for chaining | [
"Manually",
"use",
"ED",
"(",
"Select",
"Graphic",
"Rendition",
")"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Traits/EscapeSequences/ED.php#L17-L26 |
bramus/ansi-php | src/Traits/EscapeSequences/EL.php | EL.el | public function el($data)
{
// Write data to the writer
$this->writer->write(
new \Bramus\Ansi\ControlSequences\EscapeSequences\EL($data)
);
// Afford chaining
return $this;
} | php | public function el($data)
{
// Write data to the writer
$this->writer->write(
new \Bramus\Ansi\ControlSequences\EscapeSequences\EL($data)
);
// Afford chaining
return $this;
} | [
"public",
"function",
"el",
"(",
"$",
"data",
")",
"{",
"// Write data to the writer",
"$",
"this",
"->",
"writer",
"->",
"write",
"(",
"new",
"\\",
"Bramus",
"\\",
"Ansi",
"\\",
"ControlSequences",
"\\",
"EscapeSequences",
"\\",
"EL",
"(",
"$",
"data",
")... | Manually use EL (ERASE IN LINE)
@param array $parameterByte Parameter byte to the EL Escape Code
@return Ansi self, for chaining | [
"Manually",
"use",
"EL",
"(",
"ERASE",
"IN",
"LINE",
")"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Traits/EscapeSequences/EL.php#L17-L26 |
bramus/ansi-php | src/ControlSequences/Traits/HasParameterBytes.php | HasParameterBytes.getParameterBytes | public function getParameterBytes($asString = true)
{
if ($asString === true) {
return implode($this->parameterBytes);
} else {
return $this->parameterBytes;
}
} | php | public function getParameterBytes($asString = true)
{
if ($asString === true) {
return implode($this->parameterBytes);
} else {
return $this->parameterBytes;
}
} | [
"public",
"function",
"getParameterBytes",
"(",
"$",
"asString",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"asString",
"===",
"true",
")",
"{",
"return",
"implode",
"(",
"$",
"this",
"->",
"parameterBytes",
")",
";",
"}",
"else",
"{",
"return",
"$",
"this... | Get the Parameter Byte
@param bool $asString As a string, or as an array?
@return Base self, for chaining | [
"Get",
"the",
"Parameter",
"Byte"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/ControlSequences/Traits/HasParameterBytes.php#L44-L51 |
bramus/ansi-php | src/Ansi.php | Ansi.flush | public function flush($resetAfterwards = true)
{
if ($this->writer instanceof Writers\FlushableInterface) {
return $this->writer->flush($resetAfterwards);
} else {
throw new \Exception('Flushing a non FlushableInterface is not possible');
}
} | php | public function flush($resetAfterwards = true)
{
if ($this->writer instanceof Writers\FlushableInterface) {
return $this->writer->flush($resetAfterwards);
} else {
throw new \Exception('Flushing a non FlushableInterface is not possible');
}
} | [
"public",
"function",
"flush",
"(",
"$",
"resetAfterwards",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"writer",
"instanceof",
"Writers",
"\\",
"FlushableInterface",
")",
"{",
"return",
"$",
"this",
"->",
"writer",
"->",
"flush",
"(",
"$",
"res... | Flush the contents of the writer
@param $resetAfterwards Reset the writer contents after flushing?
@return string The writer contents | [
"Flush",
"the",
"contents",
"of",
"the",
"writer"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Ansi.php#L76-L83 |
bramus/ansi-php | src/Ansi.php | Ansi.e | public function e($resetAfterwards = true)
{
try {
// Get the contents and echo them
echo $this->flush($resetAfterwards);
// Afford chaining
return $this;
} catch (\Exception $e) {
throw $e;
}
} | php | public function e($resetAfterwards = true)
{
try {
// Get the contents and echo them
echo $this->flush($resetAfterwards);
// Afford chaining
return $this;
} catch (\Exception $e) {
throw $e;
}
} | [
"public",
"function",
"e",
"(",
"$",
"resetAfterwards",
"=",
"true",
")",
"{",
"try",
"{",
"// Get the contents and echo them",
"echo",
"$",
"this",
"->",
"flush",
"(",
"$",
"resetAfterwards",
")",
";",
"// Afford chaining",
"return",
"$",
"this",
";",
"}",
... | Echo the contents of the writer
@param $resetAfterwards Reset the writer contents after flushing?
@return Ansi self, for chaining | [
"Echo",
"the",
"contents",
"of",
"the",
"writer"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Ansi.php#L99-L110 |
bramus/ansi-php | src/Writers/ProxyWriter.php | ProxyWriter.flush | public function flush($resetAfterwards = true)
{
// Get the data from the buffer
$data = parent::flush($resetAfterwards);
// Write the data to the writer we are proxying for
$this->writer->write($data);
// Return the data
return $data;
} | php | public function flush($resetAfterwards = true)
{
// Get the data from the buffer
$data = parent::flush($resetAfterwards);
// Write the data to the writer we are proxying for
$this->writer->write($data);
// Return the data
return $data;
} | [
"public",
"function",
"flush",
"(",
"$",
"resetAfterwards",
"=",
"true",
")",
"{",
"// Get the data from the buffer",
"$",
"data",
"=",
"parent",
"::",
"flush",
"(",
"$",
"resetAfterwards",
")",
";",
"// Write the data to the writer we are proxying for",
"$",
"this",
... | Get/Flush the data
@param boolean $resetAfterwards Reset the data afterwards?
@return string The data | [
"Get",
"/",
"Flush",
"the",
"data"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/Writers/ProxyWriter.php#L49-L59 |
bramus/ansi-php | src/ControlSequences/Base.php | Base.setControlSequenceIntroducer | public function setControlSequenceIntroducer($controlSequenceIntroducer)
{
// Make sure it's a ControlFunction instance
if (is_string($controlSequenceIntroducer)) {
$controlSequenceIntroducer = new ControlFunction($controlSequenceIntroducer);
}
// @TODO: Check Validity
$this->controlSequenceIntroducer = $controlSequenceIntroducer;
return $this;
} | php | public function setControlSequenceIntroducer($controlSequenceIntroducer)
{
// Make sure it's a ControlFunction instance
if (is_string($controlSequenceIntroducer)) {
$controlSequenceIntroducer = new ControlFunction($controlSequenceIntroducer);
}
// @TODO: Check Validity
$this->controlSequenceIntroducer = $controlSequenceIntroducer;
return $this;
} | [
"public",
"function",
"setControlSequenceIntroducer",
"(",
"$",
"controlSequenceIntroducer",
")",
"{",
"// Make sure it's a ControlFunction instance",
"if",
"(",
"is_string",
"(",
"$",
"controlSequenceIntroducer",
")",
")",
"{",
"$",
"controlSequenceIntroducer",
"=",
"new",... | Set the control sequence introducer
@param \Bramus\Ansi\ControlFunction $controlSequenceIntroducer A ControlFunction that acts as the Control Sequence Introducer (CSI)
@return ControlSequence self, for chaining | [
"Set",
"the",
"control",
"sequence",
"introducer"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/ControlSequences/Base.php#L36-L47 |
bramus/ansi-php | src/ControlSequences/Base.php | Base.get | public function get()
{
$toReturn = '';
// Append CSI
$toReturn = $this->controlSequenceIntroducer->get().'[';
// Append Parameter Byte (if any)
if (isset($this->parameterBytes) && sizeof((array) $this->parameterBytes) > 0) {
$toReturn .= implode($this->parameterBytes, ';');
}
// Append Intermediate Bytes (if any)
if (isset($this->intermediateBytes) && sizeof((array) $this->intermediateBytes) > 0) {
$toReturn .= implode($this->intermediateBytes, ';'); // @TODO: Verify that ';' is the glue for intermediate bytes
}
// Append Final Byte (if any)
if (isset($this->finalByte)) {
$toReturn .= $this->getFinalByte();
}
return $toReturn;
} | php | public function get()
{
$toReturn = '';
// Append CSI
$toReturn = $this->controlSequenceIntroducer->get().'[';
// Append Parameter Byte (if any)
if (isset($this->parameterBytes) && sizeof((array) $this->parameterBytes) > 0) {
$toReturn .= implode($this->parameterBytes, ';');
}
// Append Intermediate Bytes (if any)
if (isset($this->intermediateBytes) && sizeof((array) $this->intermediateBytes) > 0) {
$toReturn .= implode($this->intermediateBytes, ';'); // @TODO: Verify that ';' is the glue for intermediate bytes
}
// Append Final Byte (if any)
if (isset($this->finalByte)) {
$toReturn .= $this->getFinalByte();
}
return $toReturn;
} | [
"public",
"function",
"get",
"(",
")",
"{",
"$",
"toReturn",
"=",
"''",
";",
"// Append CSI",
"$",
"toReturn",
"=",
"$",
"this",
"->",
"controlSequenceIntroducer",
"->",
"get",
"(",
")",
".",
"'['",
";",
"// Append Parameter Byte (if any)",
"if",
"(",
"isset... | Build and return the ANSI Code
@return string The ANSI Code | [
"Build",
"and",
"return",
"the",
"ANSI",
"Code"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/ControlSequences/Base.php#L62-L85 |
bramus/ansi-php | src/ControlSequences/Traits/HasIntermediateBytes.php | HasIntermediateBytes.getIntermediateBytes | public function getIntermediateBytes($asString = true)
{
if ($asString === true) {
return implode($this->intermediateBytes);
} else {
return $this->intermediateBytes;
}
} | php | public function getIntermediateBytes($asString = true)
{
if ($asString === true) {
return implode($this->intermediateBytes);
} else {
return $this->intermediateBytes;
}
} | [
"public",
"function",
"getIntermediateBytes",
"(",
"$",
"asString",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"asString",
"===",
"true",
")",
"{",
"return",
"implode",
"(",
"$",
"this",
"->",
"intermediateBytes",
")",
";",
"}",
"else",
"{",
"return",
"$",
... | Get the Intermediate Byte
@param bool $asString As a string, or as an array?
@return Base self, for chaining | [
"Get",
"the",
"Intermediate",
"Byte"
] | train | https://github.com/bramus/ansi-php/blob/79d30c30651b0c6f23cf85503c779c72ac74ab8a/src/ControlSequences/Traits/HasIntermediateBytes.php#L44-L51 |
faustbrian/Laravel-Commentable | src/Models/Comment.php | Comment.createComment | public function createComment(Model $commentable, $data, Model $creator): self
{
return $commentable->comments()->create(array_merge($data, [
'creator_id' => $creator->getAuthIdentifier(),
'creator_type' => $creator->getMorphClass(),
]));
} | php | public function createComment(Model $commentable, $data, Model $creator): self
{
return $commentable->comments()->create(array_merge($data, [
'creator_id' => $creator->getAuthIdentifier(),
'creator_type' => $creator->getMorphClass(),
]));
} | [
"public",
"function",
"createComment",
"(",
"Model",
"$",
"commentable",
",",
"$",
"data",
",",
"Model",
"$",
"creator",
")",
":",
"self",
"{",
"return",
"$",
"commentable",
"->",
"comments",
"(",
")",
"->",
"create",
"(",
"array_merge",
"(",
"$",
"data"... | @param Model $commentable
@param $data
@param Model $creator
@return static | [
"@param",
"Model",
"$commentable",
"@param",
"$data",
"@param",
"Model",
"$creator"
] | train | https://github.com/faustbrian/Laravel-Commentable/blob/45a82e816499bb7bcb574013394bf68abdf9df7c/src/Models/Comment.php#L60-L66 |
faustbrian/Laravel-Commentable | src/Traits/HasComments.php | HasComments.comment | public function comment($data, Model $creator, Model $parent = null)
{
$commentableModel = $this->commentableModel();
$comment = (new $commentableModel())->createComment($this, $data, $creator);
if (!empty($parent)) {
$parent->appendNode($comment);
}
return $comment;
} | php | public function comment($data, Model $creator, Model $parent = null)
{
$commentableModel = $this->commentableModel();
$comment = (new $commentableModel())->createComment($this, $data, $creator);
if (!empty($parent)) {
$parent->appendNode($comment);
}
return $comment;
} | [
"public",
"function",
"comment",
"(",
"$",
"data",
",",
"Model",
"$",
"creator",
",",
"Model",
"$",
"parent",
"=",
"null",
")",
"{",
"$",
"commentableModel",
"=",
"$",
"this",
"->",
"commentableModel",
"(",
")",
";",
"$",
"comment",
"=",
"(",
"new",
... | @param $data
@param Model $creator
@param Model|null $parent
@return static | [
"@param",
"$data",
"@param",
"Model",
"$creator",
"@param",
"Model|null",
"$parent"
] | train | https://github.com/faustbrian/Laravel-Commentable/blob/45a82e816499bb7bcb574013394bf68abdf9df7c/src/Traits/HasComments.php#L45-L56 |
faustbrian/Laravel-Commentable | src/Traits/HasComments.php | HasComments.updateComment | public function updateComment($id, $data, Model $parent = null)
{
$commentableModel = $this->commentableModel();
$comment = (new $commentableModel())->updateComment($id, $data);
if (!empty($parent)) {
$parent->appendNode($comment);
}
return $comment;
} | php | public function updateComment($id, $data, Model $parent = null)
{
$commentableModel = $this->commentableModel();
$comment = (new $commentableModel())->updateComment($id, $data);
if (!empty($parent)) {
$parent->appendNode($comment);
}
return $comment;
} | [
"public",
"function",
"updateComment",
"(",
"$",
"id",
",",
"$",
"data",
",",
"Model",
"$",
"parent",
"=",
"null",
")",
"{",
"$",
"commentableModel",
"=",
"$",
"this",
"->",
"commentableModel",
"(",
")",
";",
"$",
"comment",
"=",
"(",
"new",
"$",
"co... | @param $id
@param $data
@param Model|null $parent
@return mixed | [
"@param",
"$id",
"@param",
"$data",
"@param",
"Model|null",
"$parent"
] | train | https://github.com/faustbrian/Laravel-Commentable/blob/45a82e816499bb7bcb574013394bf68abdf9df7c/src/Traits/HasComments.php#L65-L76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.