repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
drupal-code-builder/drupal-code-builder | Generator/PHPClassFile.php | PHPClassFile.fileContents | protected function fileContents() {
// File contents are built up.
$file_contents = array_merge(
$this->file_header(),
$this->code_header(),
$this->code_body(),
array(
$this->code_footer(),
)
);
return $file_contents;
} | php | protected function fileContents() {
// File contents are built up.
$file_contents = array_merge(
$this->file_header(),
$this->code_header(),
$this->code_body(),
array(
$this->code_footer(),
)
);
return $file_contents;
} | [
"protected",
"function",
"fileContents",
"(",
")",
"{",
"// File contents are built up.",
"$",
"file_contents",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"file_header",
"(",
")",
",",
"$",
"this",
"->",
"code_header",
"(",
")",
",",
"$",
"this",
"->",
"cod... | Return the contents of the file.
Helper for subclasses. Serves to concatenate standard pieces of the file.
@return
An array of text strings, in the correct order for concatenation. | [
"Return",
"the",
"contents",
"of",
"the",
"file",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PHPClassFile.php#L152-L164 | train |
drupal-code-builder/drupal-code-builder | Generator/PHPClassFile.php | PHPClassFile.classCodeBody | protected function classCodeBody() {
$code_body = array();
// Class body always has at least one blank line.
$code_body[] = '';
// Let the class collect its section blocks.
$this->collectSectionBlocks();
$section_types = [
// These are the names of class properties.
// TODO: change these to being roles in the child components.
'traits',
'constants',
'properties',
'constructor',
'functions',
];
foreach ($section_types as $section_type) {
$section_blocks = $this->getSectionBlocks($section_type);
$code_body = array_merge($code_body, $this->mergeSectionCode($section_blocks));
}
// Indent all the class code.
// TODO: is there a nice way of doing indents?
$code_body = array_map(function ($line) {
return empty($line) ? $line : ' ' . $line;
}, $code_body);
return $code_body;
} | php | protected function classCodeBody() {
$code_body = array();
// Class body always has at least one blank line.
$code_body[] = '';
// Let the class collect its section blocks.
$this->collectSectionBlocks();
$section_types = [
// These are the names of class properties.
// TODO: change these to being roles in the child components.
'traits',
'constants',
'properties',
'constructor',
'functions',
];
foreach ($section_types as $section_type) {
$section_blocks = $this->getSectionBlocks($section_type);
$code_body = array_merge($code_body, $this->mergeSectionCode($section_blocks));
}
// Indent all the class code.
// TODO: is there a nice way of doing indents?
$code_body = array_map(function ($line) {
return empty($line) ? $line : ' ' . $line;
}, $code_body);
return $code_body;
} | [
"protected",
"function",
"classCodeBody",
"(",
")",
"{",
"$",
"code_body",
"=",
"array",
"(",
")",
";",
"// Class body always has at least one blank line.",
"$",
"code_body",
"[",
"]",
"=",
"''",
";",
"// Let the class collect its section blocks.",
"$",
"this",
"->",
... | Return the body of the class's code. | [
"Return",
"the",
"body",
"of",
"the",
"class",
"s",
"code",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PHPClassFile.php#L268-L298 | train |
drupal-code-builder/drupal-code-builder | Generator/PHPClassFile.php | PHPClassFile.getSectionBlocks | protected function getSectionBlocks($section_type) {
if ($section_type == 'constructor' && isset($this->constructor)) {
// TODO: remove this special casing.
$this->constructor = [$this->constructor];
}
$code_blocks = [];
if (!empty($this->{$section_type})) {
foreach ($this->{$section_type} as $component_name => $lines) {
$code_blocks[] = $lines;
}
}
return $code_blocks;
} | php | protected function getSectionBlocks($section_type) {
if ($section_type == 'constructor' && isset($this->constructor)) {
// TODO: remove this special casing.
$this->constructor = [$this->constructor];
}
$code_blocks = [];
if (!empty($this->{$section_type})) {
foreach ($this->{$section_type} as $component_name => $lines) {
$code_blocks[] = $lines;
}
}
return $code_blocks;
} | [
"protected",
"function",
"getSectionBlocks",
"(",
"$",
"section_type",
")",
"{",
"if",
"(",
"$",
"section_type",
"==",
"'constructor'",
"&&",
"isset",
"(",
"$",
"this",
"->",
"constructor",
")",
")",
"{",
"// TODO: remove this special casing.",
"$",
"this",
"->"... | Returns the section blocks for the given section.
Helper for classCodeBody(). We consider that class code is made up of sections such as
properties, constructor, methods. Each section has multiple blocks, i.e. the multiple
properties or methods (the constructor is a special case).
For each type of section, we assemble an array of the blocks, where each block is an
array of code lines.
Merging these items, and merging the different sections takes place in
mergeSectionCode(), which takes care of spacing between items and spacing between
different sections.
@param string $section_type
A section type is a string identifying the type of the section, e.g. 'functions'.
@return array
An array of blocks | [
"Returns",
"the",
"section",
"blocks",
"for",
"the",
"given",
"section",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PHPClassFile.php#L334-L348 | train |
drupal-code-builder/drupal-code-builder | Generator/PHPClassFile.php | PHPClassFile.mergeSectionCode | protected function mergeSectionCode($section_blocks) {
$code = [];
foreach ($section_blocks as $block) {
$code = array_merge($code, $block);
// Blank line after each block.
$code[] = '';
}
return $code;
} | php | protected function mergeSectionCode($section_blocks) {
$code = [];
foreach ($section_blocks as $block) {
$code = array_merge($code, $block);
// Blank line after each block.
$code[] = '';
}
return $code;
} | [
"protected",
"function",
"mergeSectionCode",
"(",
"$",
"section_blocks",
")",
"{",
"$",
"code",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"section_blocks",
"as",
"$",
"block",
")",
"{",
"$",
"code",
"=",
"array_merge",
"(",
"$",
"code",
",",
"$",
"block... | Merge an array of blocks for a section.
@param $section_blocks
An array of section blocks. Each block is itself an array of code lines. There should
be no
@return
An array of code lines. | [
"Merge",
"an",
"array",
"of",
"blocks",
"for",
"a",
"section",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PHPClassFile.php#L360-L370 | train |
drupal-code-builder/drupal-code-builder | Generator/PHPClassFile.php | PHPClassFile.createBlocksFromMethodData | protected function createBlocksFromMethodData($methods_data) {
foreach ($methods_data as $interface_method_name => $interface_method_data) {
$function_code = [];
$function_doc = $this->docBlock('{@inheritdoc}');
$function_code = array_merge($function_code, $function_doc);
// Trim the semicolon from the end of the interface method.
$method_declaration = substr($interface_method_data['declaration'], 0, -1);
$function_code[] = "$method_declaration {";
// Add a comment with the method's first line of docblock, so the user
// has something more informative than '{@inheritdoc}' to go on!
// Babysit documentation that is missing a final full stop, so PHP
// Codesniffer doesn't complain in our own tests, and we output correctly
// formatted code ourselves.
// (This can happen either if the full stop is missing, or if the first
// line overruns to two, in which case our analysis will have truncated
// the sentence.)
if (substr($interface_method_data['description'], -1) != '.') {
$interface_method_data['description'] .= '.';
}
$function_code[] = ' // ' . $interface_method_data['description'];
$function_code[] = '}';
// Add to the functions section array for the parent to merge.
$this->functions[] = $function_code;
}
} | php | protected function createBlocksFromMethodData($methods_data) {
foreach ($methods_data as $interface_method_name => $interface_method_data) {
$function_code = [];
$function_doc = $this->docBlock('{@inheritdoc}');
$function_code = array_merge($function_code, $function_doc);
// Trim the semicolon from the end of the interface method.
$method_declaration = substr($interface_method_data['declaration'], 0, -1);
$function_code[] = "$method_declaration {";
// Add a comment with the method's first line of docblock, so the user
// has something more informative than '{@inheritdoc}' to go on!
// Babysit documentation that is missing a final full stop, so PHP
// Codesniffer doesn't complain in our own tests, and we output correctly
// formatted code ourselves.
// (This can happen either if the full stop is missing, or if the first
// line overruns to two, in which case our analysis will have truncated
// the sentence.)
if (substr($interface_method_data['description'], -1) != '.') {
$interface_method_data['description'] .= '.';
}
$function_code[] = ' // ' . $interface_method_data['description'];
$function_code[] = '}';
// Add to the functions section array for the parent to merge.
$this->functions[] = $function_code;
}
} | [
"protected",
"function",
"createBlocksFromMethodData",
"(",
"$",
"methods_data",
")",
"{",
"foreach",
"(",
"$",
"methods_data",
"as",
"$",
"interface_method_name",
"=>",
"$",
"interface_method_data",
")",
"{",
"$",
"function_code",
"=",
"[",
"]",
";",
"$",
"func... | Create blocks in the 'function' section from data describing methods.
@param $methods_data
An array of method data as returned by reporting. | [
"Create",
"blocks",
"in",
"the",
"function",
"section",
"from",
"data",
"describing",
"methods",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PHPClassFile.php#L491-L520 | train |
drupal-code-builder/drupal-code-builder | Task/Generate.php | Generate.validateComponentDataValue | public function validateComponentDataValue($property_name, $property_info, $component_data) {
if (isset($property_info['validation'])) {
$validate_callback = $property_info['validation'];
$result = $validate_callback($property_name, $property_info, $component_data);
// Fill in the placeholder array if the callback returned just a string.
if (is_string($result)) {
$result = [$result, []];
}
return $result;
}
} | php | public function validateComponentDataValue($property_name, $property_info, $component_data) {
if (isset($property_info['validation'])) {
$validate_callback = $property_info['validation'];
$result = $validate_callback($property_name, $property_info, $component_data);
// Fill in the placeholder array if the callback returned just a string.
if (is_string($result)) {
$result = [$result, []];
}
return $result;
}
} | [
"public",
"function",
"validateComponentDataValue",
"(",
"$",
"property_name",
",",
"$",
"property_info",
",",
"$",
"component_data",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"property_info",
"[",
"'validation'",
"]",
")",
")",
"{",
"$",
"validate_callback",
"=... | Validates a value for a property.
Validation is optional; UIs may perform it if it improves UX to do so as
a separate step from calling generateComponent().
Note that this does not recurse; UIs should take care of this.
@param $property_name
The name of the property.
@param $property_info
The definition for this property, from getRootComponentDataInfo().
@param $component_data
The array of component data for the component that the property is a part
of.
@return array|null
If validation failed, an array whose first element is a message string,
and whose second element is an array of translation placeholders (which
may be empty). If the validation succeeded, NULL is returned. | [
"Validates",
"a",
"value",
"for",
"a",
"property",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate.php#L168-L180 | train |
drupal-code-builder/drupal-code-builder | Task/Generate.php | Generate.generateComponent | public function generateComponent($component_data, $existing_module_files = []) {
// Add the top-level component to the data.
$component_type = $this->base;
$component_data['base'] = $component_type;
// The component name is just the same as the type for the base generator.
$component_name = $component_type;
// Assemble the component list from the request data.
$component_collection = $this->getHelper('ComponentCollector')->assembleComponentList($component_data);
// Backward-compatiblity.
// TODO: replace this.
$this->component_list = $component_collection->getComponents();
\DrupalCodeBuilder\Factory::getEnvironment()->log(array_keys($this->component_list), "Complete component list names");
// Let each component detect whether it already exists in the given module
// files.
$this->detectExistence($this->component_list, $existing_module_files);
// Now assemble them into a tree.
// Calls containingComponent() on everything and puts it into a 2-D array
// of parent => [children].
// TODO: replace use of $tree with accessor on the collection.
$tree = $component_collection->assembleContainmentTree();
\DrupalCodeBuilder\Factory::getEnvironment()->log($tree, "Component tree");
$files_assembled = $this->component_list = $this->getHelper('FileAssembler')->generateFiles(
$component_data,
$component_collection
);
return $files_assembled;
} | php | public function generateComponent($component_data, $existing_module_files = []) {
// Add the top-level component to the data.
$component_type = $this->base;
$component_data['base'] = $component_type;
// The component name is just the same as the type for the base generator.
$component_name = $component_type;
// Assemble the component list from the request data.
$component_collection = $this->getHelper('ComponentCollector')->assembleComponentList($component_data);
// Backward-compatiblity.
// TODO: replace this.
$this->component_list = $component_collection->getComponents();
\DrupalCodeBuilder\Factory::getEnvironment()->log(array_keys($this->component_list), "Complete component list names");
// Let each component detect whether it already exists in the given module
// files.
$this->detectExistence($this->component_list, $existing_module_files);
// Now assemble them into a tree.
// Calls containingComponent() on everything and puts it into a 2-D array
// of parent => [children].
// TODO: replace use of $tree with accessor on the collection.
$tree = $component_collection->assembleContainmentTree();
\DrupalCodeBuilder\Factory::getEnvironment()->log($tree, "Component tree");
$files_assembled = $this->component_list = $this->getHelper('FileAssembler')->generateFiles(
$component_data,
$component_collection
);
return $files_assembled;
} | [
"public",
"function",
"generateComponent",
"(",
"$",
"component_data",
",",
"$",
"existing_module_files",
"=",
"[",
"]",
")",
"{",
"// Add the top-level component to the data.",
"$",
"component_type",
"=",
"$",
"this",
"->",
"base",
";",
"$",
"component_data",
"[",
... | Generate the files for a component.
@param $component_data
An associative array of data for the component. Values depend on the
component class. For details, see the constructor of the generator, of the
form DrupalCodeBuilder\Generator\COMPONENT, e.g.
DrupalCodeBuilder\Generator\Module::__construct().
@param $existing_module_files
(optional) An array of existing files for this module. Keys should be
file paths relative to the module, values absolute paths.
@return
A files array whose keys are filepaths (relative to the module folder) and
values are the code destined for each file.
@throws \DrupalCodeBuilder\Exception\InvalidInputException
Throws an exception if the given data is invalid. | [
"Generate",
"the",
"files",
"for",
"a",
"component",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate.php#L201-L235 | train |
drupal-code-builder/drupal-code-builder | Task/Generate.php | Generate.detectExistence | protected function detectExistence($component_list, $existing_module_files) {
foreach ($component_list as $name => $component) {
$component->detectExistence($existing_module_files);
}
} | php | protected function detectExistence($component_list, $existing_module_files) {
foreach ($component_list as $name => $component) {
$component->detectExistence($existing_module_files);
}
} | [
"protected",
"function",
"detectExistence",
"(",
"$",
"component_list",
",",
"$",
"existing_module_files",
")",
"{",
"foreach",
"(",
"$",
"component_list",
"as",
"$",
"name",
"=>",
"$",
"component",
")",
"{",
"$",
"component",
"->",
"detectExistence",
"(",
"$"... | Lets each component determine whether it is already in existing files.
Existence is determined at the component level, rather than the file level,
because one component may want to add to several files, and several
components may want to add to the same file. For example, a service may
exist, but other components might want to add services and therefore add
code to the services.yml file.
@param $component_list
The component list.
@param $existing_module_files
The array of existing file names. | [
"Lets",
"each",
"component",
"determine",
"whether",
"it",
"is",
"already",
"in",
"existing",
"files",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate.php#L251-L255 | train |
drupal-code-builder/drupal-code-builder | Generator/Info5.php | Info5.file_body | function file_body() {
$lines = array();
$lines['name'] = $this->component_data['readable_name'];
$lines['description'] = $this->component_data['short_description'];
if (!empty( $this->component_data['module_dependencies'])) {
$lines['dependencies'] = implode(' ', $this->component_data['module_dependencies']);
}
if (!empty( $this->component_data['module_package'])) {
$lines['package'] = $this->component_data['module_package'];
}
$info = $this->process_info_lines($lines);
return $info;
} | php | function file_body() {
$lines = array();
$lines['name'] = $this->component_data['readable_name'];
$lines['description'] = $this->component_data['short_description'];
if (!empty( $this->component_data['module_dependencies'])) {
$lines['dependencies'] = implode(' ', $this->component_data['module_dependencies']);
}
if (!empty( $this->component_data['module_package'])) {
$lines['package'] = $this->component_data['module_package'];
}
$info = $this->process_info_lines($lines);
return $info;
} | [
"function",
"file_body",
"(",
")",
"{",
"$",
"lines",
"=",
"array",
"(",
")",
";",
"$",
"lines",
"[",
"'name'",
"]",
"=",
"$",
"this",
"->",
"component_data",
"[",
"'readable_name'",
"]",
";",
"$",
"lines",
"[",
"'description'",
"]",
"=",
"$",
"this"... | Create lines of file body for Drupal 5. | [
"Create",
"lines",
"of",
"file",
"body",
"for",
"Drupal",
"5",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Info5.php#L13-L28 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/FileAssembler.php | FileAssembler.generateFiles | public function generateFiles($component_data, ComponentCollection $component_collection) {
$component_list = $component_collection->getComponents();
// Let each file component in the tree gather data from its own children.
$this->collectFileContents($component_collection);
// Build files.
// Get info on files. All components that wish to provide a file should have
// registered themselves as first-level children of the root component.
$files = $this->collectFiles($component_collection);
// Filter files according to the requested build list.
if (isset($component_data['requested_build'])) {
$component_collection->getRootComponent()->applyBuildListFilter($files, $component_data['requested_build'], $component_data);
}
// Then we assemble the files into a simple array of full filename and
// contents.
$files_assembled = $this->assembleFiles($component_collection, $files);
return $files_assembled;
} | php | public function generateFiles($component_data, ComponentCollection $component_collection) {
$component_list = $component_collection->getComponents();
// Let each file component in the tree gather data from its own children.
$this->collectFileContents($component_collection);
// Build files.
// Get info on files. All components that wish to provide a file should have
// registered themselves as first-level children of the root component.
$files = $this->collectFiles($component_collection);
// Filter files according to the requested build list.
if (isset($component_data['requested_build'])) {
$component_collection->getRootComponent()->applyBuildListFilter($files, $component_data['requested_build'], $component_data);
}
// Then we assemble the files into a simple array of full filename and
// contents.
$files_assembled = $this->assembleFiles($component_collection, $files);
return $files_assembled;
} | [
"public",
"function",
"generateFiles",
"(",
"$",
"component_data",
",",
"ComponentCollection",
"$",
"component_collection",
")",
"{",
"$",
"component_list",
"=",
"$",
"component_collection",
"->",
"getComponents",
"(",
")",
";",
"// Let each file component in the tree gat... | Generate code files.
@param $component_data
The component data from the initial request.
@param \DrupalCodeBuilder\Generator\Collection\ComponentCollection $component_collection
The component collection.
@return
An array of files ready for output. Keys are the filepath and filename
relative to the module folder (eg, 'foo.module', 'tests/module.test');
values are strings of the contents for each file. | [
"Generate",
"code",
"files",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/FileAssembler.php#L27-L48 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/FileAssembler.php | FileAssembler.collectFiles | protected function collectFiles(ComponentCollection $component_collection) {
$file_info = array();
// Components which provide a file should have registered themselves as
// children of the root component.
$file_components = $component_collection->getContainmentTreeChildren($component_collection->getRootComponent());
foreach ($file_components as $id => $child_component) {
// Don't get files for existing components.
// TODO! This is quick and dirty! It's a lot more complicated than this,
// for instance with components that affect other files.
// Currently the only component that will set this is Info, to make
// adding code to existing modules look like it works!
if ($child_component->exists) {
continue;
}
$file_info_item = $child_component->getFileInfo();
if (is_array($file_info_item)) {
// Prepend the component_base_path to the path.
if (!empty($child_component->component_data['component_base_path'])) {
if (empty($file_info_item['path'])) {
$file_info_item['path'] = $child_component->component_data['component_base_path'];
}
else {
$file_info_item['path'] = $child_component->component_data['component_base_path']
. '/'
. $file_info_item['path'];
}
}
// Add the source component ID.
$file_info_item['source_component_id'] = $id;
$file_info[$id] = $file_info_item;
}
}
return $file_info;
} | php | protected function collectFiles(ComponentCollection $component_collection) {
$file_info = array();
// Components which provide a file should have registered themselves as
// children of the root component.
$file_components = $component_collection->getContainmentTreeChildren($component_collection->getRootComponent());
foreach ($file_components as $id => $child_component) {
// Don't get files for existing components.
// TODO! This is quick and dirty! It's a lot more complicated than this,
// for instance with components that affect other files.
// Currently the only component that will set this is Info, to make
// adding code to existing modules look like it works!
if ($child_component->exists) {
continue;
}
$file_info_item = $child_component->getFileInfo();
if (is_array($file_info_item)) {
// Prepend the component_base_path to the path.
if (!empty($child_component->component_data['component_base_path'])) {
if (empty($file_info_item['path'])) {
$file_info_item['path'] = $child_component->component_data['component_base_path'];
}
else {
$file_info_item['path'] = $child_component->component_data['component_base_path']
. '/'
. $file_info_item['path'];
}
}
// Add the source component ID.
$file_info_item['source_component_id'] = $id;
$file_info[$id] = $file_info_item;
}
}
return $file_info;
} | [
"protected",
"function",
"collectFiles",
"(",
"ComponentCollection",
"$",
"component_collection",
")",
"{",
"$",
"file_info",
"=",
"array",
"(",
")",
";",
"// Components which provide a file should have registered themselves as",
"// children of the root component.",
"$",
"file... | Collect file data from components.
This assembles an array, keyed by an arbitrary ID for the file, whose
values are arrays with the following properties:
- 'body': An array of lines of content for the file.
- 'path': The path for the file, relative to the module folder.
- 'filename': The filename for the file.
@param $component_list
The component list.
@return
An array of file info, keyed by arbitrary file ID. | [
"Collect",
"file",
"data",
"from",
"components",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/FileAssembler.php#L82-L120 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/FileAssembler.php | FileAssembler.assembleFiles | protected function assembleFiles(ComponentCollection $component_collection, $files) {
$return = array();
foreach ($files as $file_id => $file_info) {
if (!empty($file_info['path'])) {
$filepath = $file_info['path'] . '/' . $file_info['filename'];
}
else {
$filepath = $file_info['filename'];
}
$code = implode("\n", $file_info['body']);
// Replace tokens in file contents and file path.
// We get the tokens from the root component that was the nearest
// requester.
// TODO: consider changing this to be nearest root component; though
// would require a change to File::containingComponent() among other
// things.
$file_component = $component_collection->getComponent($file_info['source_component_id']);
$closest_requesting_root = $component_collection->getClosestRequestingRootComponent($file_component);
$variables = $closest_requesting_root->getReplacements();
$code = strtr($code, $variables);
$filepath = strtr($filepath, $variables);
$return[$filepath] = $code;
}
return $return;
} | php | protected function assembleFiles(ComponentCollection $component_collection, $files) {
$return = array();
foreach ($files as $file_id => $file_info) {
if (!empty($file_info['path'])) {
$filepath = $file_info['path'] . '/' . $file_info['filename'];
}
else {
$filepath = $file_info['filename'];
}
$code = implode("\n", $file_info['body']);
// Replace tokens in file contents and file path.
// We get the tokens from the root component that was the nearest
// requester.
// TODO: consider changing this to be nearest root component; though
// would require a change to File::containingComponent() among other
// things.
$file_component = $component_collection->getComponent($file_info['source_component_id']);
$closest_requesting_root = $component_collection->getClosestRequestingRootComponent($file_component);
$variables = $closest_requesting_root->getReplacements();
$code = strtr($code, $variables);
$filepath = strtr($filepath, $variables);
$return[$filepath] = $code;
}
return $return;
} | [
"protected",
"function",
"assembleFiles",
"(",
"ComponentCollection",
"$",
"component_collection",
",",
"$",
"files",
")",
"{",
"$",
"return",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file_id",
"=>",
"$",
"file_info",
")",
"{"... | Assemble file info into filename and code.
@param \DrupalCodeBuilder\Generator\Collection\ComponentCollection $component_collection
The component collection.
@param $files
An array of file info, as compiled by collectFiles().
@return
An array of files ready for output. Keys are the filepath and filename
relative to the module folder (eg, 'foo.module', 'tests/module.test');
values are strings of the contents for each file. | [
"Assemble",
"file",
"info",
"into",
"filename",
"and",
"code",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/FileAssembler.php#L135-L164 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.assembleComponentList | public function assembleComponentList($component_data) {
// Reset all class properties. We don't normally run this twice, but
// probably needed for tests.
$this->requested_data_record = [];
$this->component_collection = new \DrupalCodeBuilder\Generator\Collection\ComponentCollection;
// Fiddly different handling for the type in the root component...
$component_type = $component_data['base'];
$component_data['component_type'] = $component_type;
// The name for the root component is its root name, which will be the
// name of the Drupal extension.
$this->getComponentsFromData($component_data['root_name'], $component_data, NULL);
return $this->component_collection;
} | php | public function assembleComponentList($component_data) {
// Reset all class properties. We don't normally run this twice, but
// probably needed for tests.
$this->requested_data_record = [];
$this->component_collection = new \DrupalCodeBuilder\Generator\Collection\ComponentCollection;
// Fiddly different handling for the type in the root component...
$component_type = $component_data['base'];
$component_data['component_type'] = $component_type;
// The name for the root component is its root name, which will be the
// name of the Drupal extension.
$this->getComponentsFromData($component_data['root_name'], $component_data, NULL);
return $this->component_collection;
} | [
"public",
"function",
"assembleComponentList",
"(",
"$",
"component_data",
")",
"{",
"// Reset all class properties. We don't normally run this twice, but",
"// probably needed for tests.",
"$",
"this",
"->",
"requested_data_record",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"... | Get the list of required components for an initial request.
This iterates down the tree of component requests: starting with the root
component, each component may request further components, and then those
components may request more, and so on.
Generator classes should implement requiredComponents() to return the list
of component types they require, possibly depending on incoming data.
Obviously, it's important that eventually this process terminate with
generators that return an empty array for requiredComponents().
@param $component_data
The requested component data.
@return \DrupalCodeBuilder\Generator\Collection\ComponentCollection
The collection of components. | [
"Get",
"the",
"list",
"of",
"required",
"components",
"for",
"an",
"initial",
"request",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L126-L142 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.acquireDataFromRequestingComponent | protected function acquireDataFromRequestingComponent(&$component_data, $component_data_info, $requesting_component) {
// Get the requesting component's data info.
if ($requesting_component) {
$requesting_component_data_info = $this->dataInfoGatherer->getComponentDataInfo($requesting_component->getType(), TRUE);
}
// Initialize a map of property acquisition aliases in the requesting
// component. This is lazily computed if we find no other way to find the
// acquired property.
$requesting_component_alias_map = NULL;
// Allow the new generator to acquire properties from the requester.
foreach ($component_data_info as $property_name => $property_info) {
if (empty($property_info['acquired'])) {
continue;
}
if (!$requesting_component) {
throw new \Exception("Component $name needs to acquire property '$property_name' but there is no requesting component.");
}
$acquired_value = NULL;
if (isset($property_info['acquired_from'])) {
// If the current property says it is acquired from something else,
// use that.
$acquired_value = $requesting_component->getComponentDataValue($property_info['acquired_from']);
}
elseif (array_key_exists($property_name, $requesting_component_data_info)) {
// Get the value from the property of the same name, if one exists.
$acquired_value = $requesting_component->getComponentDataValue($property_name);
}
else {
// Finally, try to find an acquisition alias.
if (is_null($requesting_component_alias_map)) {
// Lazily build a map of aliases that exist in the requesting
// component's data info, now that we need it.
$requesting_component_alias_map = [];
foreach ($requesting_component_data_info as $requesting_component_property_name => $requesting_component_property_info) {
if (!isset($requesting_component_property_info['acquired_alias'])) {
continue;
}
// Create a map of the current data's property name => the
// requesting component's property name.
$requesting_component_alias_map[$requesting_component_property_info['acquired_alias']] = $requesting_component_property_name;
}
}
if (isset($requesting_component_alias_map[$property_name])) {
$acquired_value = $requesting_component->getComponentDataValue($requesting_component_alias_map[$property_name]);
}
}
if (!isset($acquired_value)) {
throw new \Exception("Unable to acquire value for property $property_name.");
}
$component_data[$property_name] = $acquired_value;
}
} | php | protected function acquireDataFromRequestingComponent(&$component_data, $component_data_info, $requesting_component) {
// Get the requesting component's data info.
if ($requesting_component) {
$requesting_component_data_info = $this->dataInfoGatherer->getComponentDataInfo($requesting_component->getType(), TRUE);
}
// Initialize a map of property acquisition aliases in the requesting
// component. This is lazily computed if we find no other way to find the
// acquired property.
$requesting_component_alias_map = NULL;
// Allow the new generator to acquire properties from the requester.
foreach ($component_data_info as $property_name => $property_info) {
if (empty($property_info['acquired'])) {
continue;
}
if (!$requesting_component) {
throw new \Exception("Component $name needs to acquire property '$property_name' but there is no requesting component.");
}
$acquired_value = NULL;
if (isset($property_info['acquired_from'])) {
// If the current property says it is acquired from something else,
// use that.
$acquired_value = $requesting_component->getComponentDataValue($property_info['acquired_from']);
}
elseif (array_key_exists($property_name, $requesting_component_data_info)) {
// Get the value from the property of the same name, if one exists.
$acquired_value = $requesting_component->getComponentDataValue($property_name);
}
else {
// Finally, try to find an acquisition alias.
if (is_null($requesting_component_alias_map)) {
// Lazily build a map of aliases that exist in the requesting
// component's data info, now that we need it.
$requesting_component_alias_map = [];
foreach ($requesting_component_data_info as $requesting_component_property_name => $requesting_component_property_info) {
if (!isset($requesting_component_property_info['acquired_alias'])) {
continue;
}
// Create a map of the current data's property name => the
// requesting component's property name.
$requesting_component_alias_map[$requesting_component_property_info['acquired_alias']] = $requesting_component_property_name;
}
}
if (isset($requesting_component_alias_map[$property_name])) {
$acquired_value = $requesting_component->getComponentDataValue($requesting_component_alias_map[$property_name]);
}
}
if (!isset($acquired_value)) {
throw new \Exception("Unable to acquire value for property $property_name.");
}
$component_data[$property_name] = $acquired_value;
}
} | [
"protected",
"function",
"acquireDataFromRequestingComponent",
"(",
"&",
"$",
"component_data",
",",
"$",
"component_data_info",
",",
"$",
"requesting_component",
")",
"{",
"// Get the requesting component's data info.",
"if",
"(",
"$",
"requesting_component",
")",
"{",
"... | Acquire additional data from the requesting component.
Helper for getComponentsFromData().
@param &$component_data
The component data array. On the first call, this is the entire array; on
recursive calls this is the local data subset.
@param $component_data_info
The component data info for the data being processed.
@param $requesting_component
The component data info for the component that is requesting the current
data, or NULL if there is none.
@throws \Exception
Throws an exception if a property has the 'acquired' attribute, but
there is no requesting component present. | [
"Acquire",
"additional",
"data",
"from",
"the",
"requesting",
"component",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L362-L422 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.processComponentData | protected function processComponentData(&$component_data, &$component_data_info) {
// Work over each property.
foreach ($component_data_info as $property_name => &$property_info) {
// Set defaults for properties that don't have a value yet.
$this->setComponentDataPropertyDefault($property_name, $property_info, $component_data);
// Set values from a preset.
// We do this after defaults, so preset properties can have a default
// value. Note this means that presets can only affect properties that
// come after them in the property info order.
if (isset($property_info['presets'])) {
$this->setPresetValues($property_name, $component_data_info, $component_data);
}
// Allow each property to apply its processing callback. Note that this
// may set or alter other properties in the component data array, and may
// also make changes to the property info.
$this->applyComponentDataPropertyProcessing($property_name, $property_info, $component_data);
}
// Clear the loop reference, otherwise PHP does Bad Things.
unset($property_info);
// Recurse into compound properties.
// We do this last to allow the parent property to have default and
// processing applied to the child data as a whole.
// (TODO: test this!)
foreach ($component_data_info as $property_name => $property_info) {
// Only work with compound properties.
if ($property_info['format'] != 'compound') {
continue;
}
// Don't work with component child properties, as the generator will
// handle this.
if (isset($property_info['component_type'])) {
continue;
}
if (!isset($component_data[$property_name])) {
// Skip if no data for this property.
continue;
}
foreach ($component_data[$property_name] as $delta => &$item_data) {
$this->processComponentData($item_data, $property_info['properties']);
}
}
} | php | protected function processComponentData(&$component_data, &$component_data_info) {
// Work over each property.
foreach ($component_data_info as $property_name => &$property_info) {
// Set defaults for properties that don't have a value yet.
$this->setComponentDataPropertyDefault($property_name, $property_info, $component_data);
// Set values from a preset.
// We do this after defaults, so preset properties can have a default
// value. Note this means that presets can only affect properties that
// come after them in the property info order.
if (isset($property_info['presets'])) {
$this->setPresetValues($property_name, $component_data_info, $component_data);
}
// Allow each property to apply its processing callback. Note that this
// may set or alter other properties in the component data array, and may
// also make changes to the property info.
$this->applyComponentDataPropertyProcessing($property_name, $property_info, $component_data);
}
// Clear the loop reference, otherwise PHP does Bad Things.
unset($property_info);
// Recurse into compound properties.
// We do this last to allow the parent property to have default and
// processing applied to the child data as a whole.
// (TODO: test this!)
foreach ($component_data_info as $property_name => $property_info) {
// Only work with compound properties.
if ($property_info['format'] != 'compound') {
continue;
}
// Don't work with component child properties, as the generator will
// handle this.
if (isset($property_info['component_type'])) {
continue;
}
if (!isset($component_data[$property_name])) {
// Skip if no data for this property.
continue;
}
foreach ($component_data[$property_name] as $delta => &$item_data) {
$this->processComponentData($item_data, $property_info['properties']);
}
}
} | [
"protected",
"function",
"processComponentData",
"(",
"&",
"$",
"component_data",
",",
"&",
"$",
"component_data_info",
")",
"{",
"// Work over each property.",
"foreach",
"(",
"$",
"component_data_info",
"as",
"$",
"property_name",
"=>",
"&",
"$",
"property_info",
... | Recursively process component data prior instantiating components.
Performs final processing for the component data:
- sets default values on empty properties. To prevent a default being set
and keep the component a property represents absent, set it to FALSE.
- sets values forced or suggested by other properties' presets.
- performs additional processing that a property may require
@param &$component_data
The component data array. On the first call, this is the entire array; on
recursive calls this is the local data subset.
@param &$component_data_info
The component data info for the data being processed. Passed by reference,
to allow property processing callbacks to make changes. | [
"Recursively",
"process",
"component",
"data",
"prior",
"instantiating",
"components",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L440-L487 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.setPresetValues | protected function setPresetValues($property_name, &$component_data_info, &$component_data_local) {
if (empty($component_data_local[$property_name])) {
return;
}
// Treat the selected preset as an array, even if it's single-valued.
if ($component_data_info[$property_name]['format'] == 'array') {
$preset_keys = $component_data_local[$property_name];
$multiple_presets = TRUE;
}
else {
$preset_keys = [$component_data_local[$property_name]];
$multiple_presets = FALSE;
}
// First, gather up the values that the selected preset items want to set.
// We will then apply them to the data.
$forced_values = [];
$suggested_values = [];
foreach ($preset_keys as $preset_key) {
$selected_preset_info = $component_data_info[$property_name]['presets'][$preset_key];
// Ensure these are both preset as at least empty arrays.
// TODO: handle filling this in in ComponentDataInfoGatherer?
// TODO: testing should cover that it's ok to have these absent.
$selected_preset_info['data'] += [
'force' => [],
'suggest' => [],
];
// Values which are forced by the preset.
foreach ($selected_preset_info['data']['force'] as $forced_property_name => $forced_data) {
// Literal value. (This is the only type we support at the moment.)
if (isset($forced_data['value'])) {
$this->collectPresetValue(
$forced_values,
$multiple_presets,
$forced_property_name,
$component_data_info[$forced_property_name],
$forced_data['value']
);
}
// TODO: processed value, using chain of processing instructions.
}
// Values which are only suggested by the preset.
foreach ($selected_preset_info['data']['suggest'] as $suggested_property_name => $suggested_data) {
// Literal value. (This is the only type we support at the moment.)
if (isset($suggested_data['value'])) {
$this->collectPresetValue(
$suggested_values,
$multiple_presets,
$suggested_property_name,
$component_data_info[$suggested_property_name],
$suggested_data['value']
);
}
// TODO: processed value, using chain of processing instructions.
}
}
// Set the collected data values into the actual component data, if
// applicable.
foreach ($forced_values as $forced_property_name => $forced_data) {
$component_data_local[$forced_property_name] = $forced_data;
}
foreach ($suggested_values as $suggested_property_name => $suggested_data) {
// Suggested values from the preset only get set if there is nothing
// already set there in the incoming data.
// TODO: boolean FALSE counts as non-empty for a boolean property in
// other places! ARGH!
if (!empty($component_data_local[$suggested_property_name])) {
continue;
}
$component_data_local[$suggested_property_name] = $suggested_data;
}
} | php | protected function setPresetValues($property_name, &$component_data_info, &$component_data_local) {
if (empty($component_data_local[$property_name])) {
return;
}
// Treat the selected preset as an array, even if it's single-valued.
if ($component_data_info[$property_name]['format'] == 'array') {
$preset_keys = $component_data_local[$property_name];
$multiple_presets = TRUE;
}
else {
$preset_keys = [$component_data_local[$property_name]];
$multiple_presets = FALSE;
}
// First, gather up the values that the selected preset items want to set.
// We will then apply them to the data.
$forced_values = [];
$suggested_values = [];
foreach ($preset_keys as $preset_key) {
$selected_preset_info = $component_data_info[$property_name]['presets'][$preset_key];
// Ensure these are both preset as at least empty arrays.
// TODO: handle filling this in in ComponentDataInfoGatherer?
// TODO: testing should cover that it's ok to have these absent.
$selected_preset_info['data'] += [
'force' => [],
'suggest' => [],
];
// Values which are forced by the preset.
foreach ($selected_preset_info['data']['force'] as $forced_property_name => $forced_data) {
// Literal value. (This is the only type we support at the moment.)
if (isset($forced_data['value'])) {
$this->collectPresetValue(
$forced_values,
$multiple_presets,
$forced_property_name,
$component_data_info[$forced_property_name],
$forced_data['value']
);
}
// TODO: processed value, using chain of processing instructions.
}
// Values which are only suggested by the preset.
foreach ($selected_preset_info['data']['suggest'] as $suggested_property_name => $suggested_data) {
// Literal value. (This is the only type we support at the moment.)
if (isset($suggested_data['value'])) {
$this->collectPresetValue(
$suggested_values,
$multiple_presets,
$suggested_property_name,
$component_data_info[$suggested_property_name],
$suggested_data['value']
);
}
// TODO: processed value, using chain of processing instructions.
}
}
// Set the collected data values into the actual component data, if
// applicable.
foreach ($forced_values as $forced_property_name => $forced_data) {
$component_data_local[$forced_property_name] = $forced_data;
}
foreach ($suggested_values as $suggested_property_name => $suggested_data) {
// Suggested values from the preset only get set if there is nothing
// already set there in the incoming data.
// TODO: boolean FALSE counts as non-empty for a boolean property in
// other places! ARGH!
if (!empty($component_data_local[$suggested_property_name])) {
continue;
}
$component_data_local[$suggested_property_name] = $suggested_data;
}
} | [
"protected",
"function",
"setPresetValues",
"(",
"$",
"property_name",
",",
"&",
"$",
"component_data_info",
",",
"&",
"$",
"component_data_local",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"component_data_local",
"[",
"$",
"property_name",
"]",
")",
")",
"{",
... | Sets values from a presets property into other properties.
@param string $property_name
The name of the preset property.
@param $component_data_info
The component info array, or for child properties, the info array for the
current data.
@param &$component_data_local
The array of component data, or for child properties, the item array that
immediately contains the property. In other words, this array would have
a key $property_name if data has been supplied for this property. | [
"Sets",
"values",
"from",
"a",
"presets",
"property",
"into",
"other",
"properties",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L502-L583 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.collectPresetValue | protected function collectPresetValue(
&$collected_data,
$multiple_presets,
$target_property_name,
$target_property_info,
$preset_property_data
) {
// Check the format of the value is compatible with multiple presets.
if ($multiple_presets) {
if (!in_array($target_property_info['format'], ['array', 'compound'])) {
// TODO: check cardinality is allowable as well!
// TODO: give the preset name! ARGH another parameter :(
throw new \Exception("Multiple presets not compatible with single-valued properties, with target property {$target_property_name}.");
}
}
if (isset($collected_data[$target_property_name])) {
// Merge the data. The check above should have covered that this is
// allowed.
$collected_data[$target_property_name] = array_merge($collected_data[$target_property_name], $preset_property_data);
}
else {
$collected_data[$target_property_name] = $preset_property_data;
}
} | php | protected function collectPresetValue(
&$collected_data,
$multiple_presets,
$target_property_name,
$target_property_info,
$preset_property_data
) {
// Check the format of the value is compatible with multiple presets.
if ($multiple_presets) {
if (!in_array($target_property_info['format'], ['array', 'compound'])) {
// TODO: check cardinality is allowable as well!
// TODO: give the preset name! ARGH another parameter :(
throw new \Exception("Multiple presets not compatible with single-valued properties, with target property {$target_property_name}.");
}
}
if (isset($collected_data[$target_property_name])) {
// Merge the data. The check above should have covered that this is
// allowed.
$collected_data[$target_property_name] = array_merge($collected_data[$target_property_name], $preset_property_data);
}
else {
$collected_data[$target_property_name] = $preset_property_data;
}
} | [
"protected",
"function",
"collectPresetValue",
"(",
"&",
"$",
"collected_data",
",",
"$",
"multiple_presets",
",",
"$",
"target_property_name",
",",
"$",
"target_property_info",
",",
"$",
"preset_property_data",
")",
"{",
"// Check the format of the value is compatible with... | Collect values for presets.
Helper for setPresetValues(). Merges values from multiple presets so that
they can be set into the actual component data in one go.
@param array &$collected_data
The data collected from presets so far. Further data for this call should
be added to this.
@param bool $multiple_presets
Whether the current preset property is multi-valued or not.
@param string $target_property_name
The name of the property to set from the preset.
@param array $target_property_info
The property info array of the target property.
@param mixed $preset_property_data
The value from the preset for the target property. | [
"Collect",
"values",
"for",
"presets",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L603-L627 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.applyComponentDataPropertyProcessing | protected function applyComponentDataPropertyProcessing($property_name, &$property_info, &$component_data_local) {
if (!isset($property_info['processing'])) {
// No processing: nothing to do.
return;
}
if (empty($component_data_local[$property_name]) && empty($property_info['process_empty'])) {
// Don't apply to an empty property, unless forced to.
return;
}
$processing_callback = $property_info['processing'];
$processing_callback($component_data_local[$property_name], $component_data_local, $property_name, $property_info);
} | php | protected function applyComponentDataPropertyProcessing($property_name, &$property_info, &$component_data_local) {
if (!isset($property_info['processing'])) {
// No processing: nothing to do.
return;
}
if (empty($component_data_local[$property_name]) && empty($property_info['process_empty'])) {
// Don't apply to an empty property, unless forced to.
return;
}
$processing_callback = $property_info['processing'];
$processing_callback($component_data_local[$property_name], $component_data_local, $property_name, $property_info);
} | [
"protected",
"function",
"applyComponentDataPropertyProcessing",
"(",
"$",
"property_name",
",",
"&",
"$",
"property_info",
",",
"&",
"$",
"component_data_local",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"property_info",
"[",
"'processing'",
"]",
")",
")",
... | Applies the processing callback for a property in component data.
Helper for processComponentData().
@param $property_name
The name of the property. For child properties, this is the name of just
the child property.
@param &$property_info
The property info array for the property. Passed by reference, as
the processing callback takes this by reference and may make changes.
@param &$component_data_local
The array of component data, or for child properties, the item array that
immediately contains the property. In other words, this array would have
a key $property_name if data has been supplied for this property. | [
"Applies",
"the",
"processing",
"callback",
"for",
"a",
"property",
"in",
"component",
"data",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L711-L725 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentCollector.php | ComponentCollector.debug | protected function debug($chain, $message, $indent_char = ' ') {
if (!self::DEBUG) {
return;
}
dump(str_repeat($indent_char, count($chain)) . ' ' . implode(':', $chain) . ': ' . $message);
} | php | protected function debug($chain, $message, $indent_char = ' ') {
if (!self::DEBUG) {
return;
}
dump(str_repeat($indent_char, count($chain)) . ' ' . implode(':', $chain) . ': ' . $message);
} | [
"protected",
"function",
"debug",
"(",
"$",
"chain",
",",
"$",
"message",
",",
"$",
"indent_char",
"=",
"' '",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"DEBUG",
")",
"{",
"return",
";",
"}",
"dump",
"(",
"str_repeat",
"(",
"$",
"indent_char",
",",
"... | Output debug message, with indentation for the current iteration.
@param string[] $chain
The current chain of component names.
@param string $message
A message to output. | [
"Output",
"debug",
"message",
"with",
"indentation",
"for",
"the",
"current",
"iteration",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentCollector.php#L735-L741 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.getPluginManagerServices | protected function getPluginManagerServices() {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
// Get the definitions of services from the container.
$definitions = $container_builder->getDefinitions();
// Filter them down to the ones that are plugin managers.
$plugin_manager_service_ids = [];
foreach ($definitions as $service_id => $definition) {
// Skip any deprecated service.
if ($definition->isDeprecated()) {
continue;
}
// Assume that any service whose name is of the form plugin.manager.FOO
// is a plugin type manager.
if (strpos($service_id, 'plugin.manager.') === 0) {
$plugin_manager_service_ids[] = $service_id;
continue;
}
// Skip the entity type manager: these don't behave at all like normal
// plugins.
if ($service_id == 'entity_type.manager') {
continue;
}
// Find any plugin managers which don't conform to the pattern for the
// service name, but do inherit from the DefaultPluginManager class.
$service_class = $definition->getClass();
if (is_subclass_of($service_class, \Drupal\Core\Plugin\DefaultPluginManager::class)) {
$plugin_manager_service_ids[] = $service_id;
}
}
// Filter out a blacklist of known broken plugin types.
$plugin_manager_service_ids = array_diff($plugin_manager_service_ids, [
// https://www.drupal.org/project/ctools/issues/2938586
'plugin.manager.ctools.relationship',
]);
//drush_print_r($plugin_manager_service_ids);
// Developer trapdoor: just process the block plugin type, to make terminal
// debug output easier to read through.
//$plugin_manager_service_ids = array('plugin.manager.block');
return $plugin_manager_service_ids;
} | php | protected function getPluginManagerServices() {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
// Get the definitions of services from the container.
$definitions = $container_builder->getDefinitions();
// Filter them down to the ones that are plugin managers.
$plugin_manager_service_ids = [];
foreach ($definitions as $service_id => $definition) {
// Skip any deprecated service.
if ($definition->isDeprecated()) {
continue;
}
// Assume that any service whose name is of the form plugin.manager.FOO
// is a plugin type manager.
if (strpos($service_id, 'plugin.manager.') === 0) {
$plugin_manager_service_ids[] = $service_id;
continue;
}
// Skip the entity type manager: these don't behave at all like normal
// plugins.
if ($service_id == 'entity_type.manager') {
continue;
}
// Find any plugin managers which don't conform to the pattern for the
// service name, but do inherit from the DefaultPluginManager class.
$service_class = $definition->getClass();
if (is_subclass_of($service_class, \Drupal\Core\Plugin\DefaultPluginManager::class)) {
$plugin_manager_service_ids[] = $service_id;
}
}
// Filter out a blacklist of known broken plugin types.
$plugin_manager_service_ids = array_diff($plugin_manager_service_ids, [
// https://www.drupal.org/project/ctools/issues/2938586
'plugin.manager.ctools.relationship',
]);
//drush_print_r($plugin_manager_service_ids);
// Developer trapdoor: just process the block plugin type, to make terminal
// debug output easier to read through.
//$plugin_manager_service_ids = array('plugin.manager.block');
return $plugin_manager_service_ids;
} | [
"protected",
"function",
"getPluginManagerServices",
"(",
")",
"{",
"$",
"container_builder",
"=",
"$",
"this",
"->",
"containerBuilderGetter",
"->",
"getContainerBuilder",
"(",
")",
";",
"// Get the definitions of services from the container.",
"$",
"definitions",
"=",
"... | Detects services which are plugin managers.
@return
An array of service IDs of all the services which we detected to be plugin
managers. | [
"Detects",
"services",
"which",
"are",
"plugin",
"managers",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L136-L185 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.gatherPluginTypeInfo | protected function gatherPluginTypeInfo($job_list) {
// Assemble a basic array of plugin type data, that we will successively add
// data to.
$plugin_type_data = array();
foreach ($job_list as $job) {
$plugin_manager_service_id = $job['service_id'];
$plugin_type_id = $job['type_id'];
// Get the class name for the service.
// Babysit modules that don't define services properly!
// (I'm looking at Physical.)
try {
$service = \Drupal::service($plugin_manager_service_id);
}
catch (\Throwable $ex) {
continue;
}
$service = \Drupal::service($plugin_manager_service_id);
$service_class_name = get_class($service);
$service_component_namespace = $this->getClassComponentNamespace($service_class_name);
$plugin_type_data[$plugin_type_id] = [
'type_id' => $plugin_type_id,
'service_id' => $plugin_manager_service_id,
'service_class_name' => $service_class_name,
'service_component_namespace' => $service_component_namespace,
// Plugin module may replace this if present.
'type_label' => $plugin_type_id,
];
// Add data from the plugin type manager service.
// This gets us the subdirectory, interface, and annotation name.
$this->addPluginTypeServiceData($plugin_type_data[$plugin_type_id]);
// Try to detect a base class for plugins
$this->addPluginBaseClass($plugin_type_data[$plugin_type_id]);
// Try to detect a config schema prefix.
$this->addConfigSchemaPrefix($plugin_type_data[$plugin_type_id]);
// Add data about the factory method of the base class, if any.
$this->addConstructionData($plugin_type_data[$plugin_type_id]);
// Do the large arrays last, so they are last in the stored data so it's
// easier to read.
// Add data from the plugin annotation class.
$this->addPluginAnnotationData($plugin_type_data[$plugin_type_id]);
// Add data from the plugin interface (which the manager service gave us).
$this->addPluginMethods($plugin_type_data[$plugin_type_id]);
}
// Get plugin type information if Plugin module is present.
// We get data on all plugin types in one go, so this handles the whole
// data.
$this->addPluginModuleData($plugin_type_data);
//drush_print_r($plugin_type_data);
return $plugin_type_data;
} | php | protected function gatherPluginTypeInfo($job_list) {
// Assemble a basic array of plugin type data, that we will successively add
// data to.
$plugin_type_data = array();
foreach ($job_list as $job) {
$plugin_manager_service_id = $job['service_id'];
$plugin_type_id = $job['type_id'];
// Get the class name for the service.
// Babysit modules that don't define services properly!
// (I'm looking at Physical.)
try {
$service = \Drupal::service($plugin_manager_service_id);
}
catch (\Throwable $ex) {
continue;
}
$service = \Drupal::service($plugin_manager_service_id);
$service_class_name = get_class($service);
$service_component_namespace = $this->getClassComponentNamespace($service_class_name);
$plugin_type_data[$plugin_type_id] = [
'type_id' => $plugin_type_id,
'service_id' => $plugin_manager_service_id,
'service_class_name' => $service_class_name,
'service_component_namespace' => $service_component_namespace,
// Plugin module may replace this if present.
'type_label' => $plugin_type_id,
];
// Add data from the plugin type manager service.
// This gets us the subdirectory, interface, and annotation name.
$this->addPluginTypeServiceData($plugin_type_data[$plugin_type_id]);
// Try to detect a base class for plugins
$this->addPluginBaseClass($plugin_type_data[$plugin_type_id]);
// Try to detect a config schema prefix.
$this->addConfigSchemaPrefix($plugin_type_data[$plugin_type_id]);
// Add data about the factory method of the base class, if any.
$this->addConstructionData($plugin_type_data[$plugin_type_id]);
// Do the large arrays last, so they are last in the stored data so it's
// easier to read.
// Add data from the plugin annotation class.
$this->addPluginAnnotationData($plugin_type_data[$plugin_type_id]);
// Add data from the plugin interface (which the manager service gave us).
$this->addPluginMethods($plugin_type_data[$plugin_type_id]);
}
// Get plugin type information if Plugin module is present.
// We get data on all plugin types in one go, so this handles the whole
// data.
$this->addPluginModuleData($plugin_type_data);
//drush_print_r($plugin_type_data);
return $plugin_type_data;
} | [
"protected",
"function",
"gatherPluginTypeInfo",
"(",
"$",
"job_list",
")",
"{",
"// Assemble a basic array of plugin type data, that we will successively add",
"// data to.",
"$",
"plugin_type_data",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"job_list",
"as",
"$"... | Detects information about plugin types from the plugin manager services.
@param $job_list
A numeric array whose values are arrays containing:
- 'service_id': The service ID of the plugin type manager.
- 'type_id': The derived ID of the plugin type.
@return
The assembled plugin type data. This is an array keyed by plugin type ID.
Values are arrays with the following properties:
- 'type_id': The plugin type ID. We take this to be the name of the
plugin manager service for that type, with the 'plugin.manager.'
prefix removed.
- 'type_label': A label for the plugin type. If Plugin module is present
then this is the label from the definition there, if found. Otherwise,
this duplicates the plugin type ID.
- 'service_id': The ID of the service for the plugin type's manager.
- 'discovery': The plugin's discovery class, as a fully-qualified
class name (without the initial '\').
- 'alter_hook_name': The short name of the alter hook for this plugin
type.
- 'subdir': The subdirectory of /src that plugin classes must go in.
E.g., 'Plugin/Filter'.
- 'plugin_interface': The interface that plugin classes must implement,
as a qualified name (but without initial '\').
- 'plugin_definition_annotation_name': The class that the plugin
annotation uses, as a qualified name (but without initial '\').
E.g, 'Drupal\filter\Annotation\Filter'.
- 'plugin_interface_methods': An array of methods that the plugin's
interface has. This is keyed by the method name, with each value an
array with these properties:
- 'name': The method name.
- 'declaration': The method declaration line from the interface.
- 'description': The text from the first line of the docblock.
- 'plugin_properties: Properties that the plugin class may declare in
its annotation. These are deduced from the class properties of the
plugin type's annotation class. An array keyed by the property name,
whose values are arrays with these properties:
- 'name': The name of the property.
- 'description': The description, taken from the docblock of the class
property on the annotation class.
- 'type': The data type.
- 'annotation_id_only': Boolean indicating whether the annotation
consists of only the plugin ID.
- 'construction': An array of injected service parameters for the plugin
base class. Each item has:
- 'type': The typehint.
- 'name': The parameter name, without the $.
- 'extraction': The code for getting the service from the container.
- 'constructor_fixed_parameters': An array of the fixed parameters for
plugin base class __construct(). This is only set if they differ from
the standard ones.
- 'type': The typehint.
- 'name': The parameter name, without the $.
- 'extraction': The code for getting the value to pass in from the
parameters passed to create().
- 'config_schema_prefix': The prefix to use for creating a config schema
ID for plugins of this type. The ID should be formed by appending the
plugin ID with a '.'.
- 'yaml_file_suffix': The suffix for YAML plugin files.
- 'yaml_properties': The default properties for plugins declared in YAML
files. An array whose keys are property names and values are the
default values.
- 'broken_plugins': (internal) An array of any plugins which could not
be correctly loaded. Keys are plugin IDs; values are a brief reason.
Due to the difficult nature of analysing the code for plugin types, some
of these properties may be empty if they could not be deduced. | [
"Detects",
"information",
"about",
"plugin",
"types",
"from",
"the",
"plugin",
"manager",
"services",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L257-L318 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addPluginTypeServiceData | protected function addPluginTypeServiceData(&$data) {
// Get a reflection for the plugin manager service.
$service = \Drupal::service($data['service_id']);
$reflection = new \ReflectionClass($service);
// Determine the alter hook name.
if ($reflection->hasProperty('alterHook')) {
$property_alter_hook = $reflection->getProperty('alterHook');
$property_alter_hook->setAccessible(TRUE);
$alter_hook_name = $property_alter_hook->getValue($service);
if (!empty($alter_hook_name)) {
$data['alter_hook_name'] = $alter_hook_name . '_alter';
}
}
// Determine the plugin discovery type.
// Get the discovery object from the plugin manager.
$method_getDiscovery = $reflection->getMethod('getDiscovery');
$method_getDiscovery->setAccessible(TRUE);
$discovery = $method_getDiscovery->invoke($service);
$class_dicovery = new \ReflectionClass($discovery);
// This is typically decorated at least once, for derivative discover.
// Ascend up the chain of decorated objects to the innermost discovery
// object.
while ($class_dicovery->hasProperty('decorated')) {
$property_decorated = $class_dicovery->getProperty('decorated');
$property_decorated->setAccessible(TRUE);
$discovery = $property_decorated->getValue($discovery);
$class_dicovery = new \ReflectionClass($discovery);
}
$inner_discovery_class = get_class($discovery);
// See if the plugin type's discovery class inherits from one of the ones
// we handle.
$known_discovery_classes = [
'Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery',
'Drupal\Core\Plugin\Discovery\YamlDiscovery',
// We don't handle this type; only migrations use it. But we don't want
// to ascend the class hierarchy for this type as then we'll get
// YamlDiscovery and the analysis for that will fail.
'Drupal\Core\Plugin\Discovery\YamlDirectoryDiscovery',
];
if (in_array($inner_discovery_class, $known_discovery_classes)) {
$data['discovery'] = $inner_discovery_class;
}
else {
$discovery_class = $inner_discovery_class;
while ($discovery_class = get_parent_class($discovery_class)) {
if (in_array($discovery_class, $known_discovery_classes)) {
$data['discovery'] = $discovery_class;
break;
}
}
// We didn't find a class we know in the parents: just set the inner
// discovery class.
if (!isset($data['discovery'])) {
$data['discovery'] = $inner_discovery_class;
}
}
// Get more data from the service, depending on the discovery type of the
// plugin.
$discovery_pieces = explode('\\', $data['discovery']);
$discovery_short_name = array_pop($discovery_pieces);
// Add in empty properties from the different discovery types analyses so
// they are always present.
$discovery_dependent_properties = [
'subdir',
'plugin_interface',
'plugin_definition_annotation_name',
'yaml_file_suffix',
'yaml_properties',
'annotation_id_only',
];
foreach ($discovery_dependent_properties as $property) {
$data[$property] = NULL;
}
switch ($discovery_short_name) {
case 'AnnotatedClassDiscovery':
$this->addPluginTypeServiceDataAnnotated($data, $service, $discovery);
break;
case 'YamlDiscovery':
$this->addPluginTypeServiceDataYaml($data, $service, $discovery);
break;
}
} | php | protected function addPluginTypeServiceData(&$data) {
// Get a reflection for the plugin manager service.
$service = \Drupal::service($data['service_id']);
$reflection = new \ReflectionClass($service);
// Determine the alter hook name.
if ($reflection->hasProperty('alterHook')) {
$property_alter_hook = $reflection->getProperty('alterHook');
$property_alter_hook->setAccessible(TRUE);
$alter_hook_name = $property_alter_hook->getValue($service);
if (!empty($alter_hook_name)) {
$data['alter_hook_name'] = $alter_hook_name . '_alter';
}
}
// Determine the plugin discovery type.
// Get the discovery object from the plugin manager.
$method_getDiscovery = $reflection->getMethod('getDiscovery');
$method_getDiscovery->setAccessible(TRUE);
$discovery = $method_getDiscovery->invoke($service);
$class_dicovery = new \ReflectionClass($discovery);
// This is typically decorated at least once, for derivative discover.
// Ascend up the chain of decorated objects to the innermost discovery
// object.
while ($class_dicovery->hasProperty('decorated')) {
$property_decorated = $class_dicovery->getProperty('decorated');
$property_decorated->setAccessible(TRUE);
$discovery = $property_decorated->getValue($discovery);
$class_dicovery = new \ReflectionClass($discovery);
}
$inner_discovery_class = get_class($discovery);
// See if the plugin type's discovery class inherits from one of the ones
// we handle.
$known_discovery_classes = [
'Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery',
'Drupal\Core\Plugin\Discovery\YamlDiscovery',
// We don't handle this type; only migrations use it. But we don't want
// to ascend the class hierarchy for this type as then we'll get
// YamlDiscovery and the analysis for that will fail.
'Drupal\Core\Plugin\Discovery\YamlDirectoryDiscovery',
];
if (in_array($inner_discovery_class, $known_discovery_classes)) {
$data['discovery'] = $inner_discovery_class;
}
else {
$discovery_class = $inner_discovery_class;
while ($discovery_class = get_parent_class($discovery_class)) {
if (in_array($discovery_class, $known_discovery_classes)) {
$data['discovery'] = $discovery_class;
break;
}
}
// We didn't find a class we know in the parents: just set the inner
// discovery class.
if (!isset($data['discovery'])) {
$data['discovery'] = $inner_discovery_class;
}
}
// Get more data from the service, depending on the discovery type of the
// plugin.
$discovery_pieces = explode('\\', $data['discovery']);
$discovery_short_name = array_pop($discovery_pieces);
// Add in empty properties from the different discovery types analyses so
// they are always present.
$discovery_dependent_properties = [
'subdir',
'plugin_interface',
'plugin_definition_annotation_name',
'yaml_file_suffix',
'yaml_properties',
'annotation_id_only',
];
foreach ($discovery_dependent_properties as $property) {
$data[$property] = NULL;
}
switch ($discovery_short_name) {
case 'AnnotatedClassDiscovery':
$this->addPluginTypeServiceDataAnnotated($data, $service, $discovery);
break;
case 'YamlDiscovery':
$this->addPluginTypeServiceDataYaml($data, $service, $discovery);
break;
}
} | [
"protected",
"function",
"addPluginTypeServiceData",
"(",
"&",
"$",
"data",
")",
"{",
"// Get a reflection for the plugin manager service.",
"$",
"service",
"=",
"\\",
"Drupal",
"::",
"service",
"(",
"$",
"data",
"[",
"'service_id'",
"]",
")",
";",
"$",
"reflectio... | Adds plugin type information from the plugin type manager service.
This adds:
- subdir
- alter_hook_name
- ... further properties specific to different discovery types.
@param &$data
The data for a single plugin type. | [
"Adds",
"plugin",
"type",
"information",
"from",
"the",
"plugin",
"type",
"manager",
"service",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L331-L422 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addPluginTypeServiceDataAnnotated | protected function addPluginTypeServiceDataAnnotated(&$data, $service, $discovery) {
$reflection = new \ReflectionClass($service);
// Get the properties that the plugin manager constructor sets.
// E.g., most plugin managers pass this to the parent:
// parent::__construct('Plugin/Block', $namespaces, $module_handler, 'Drupal\Core\Block\BlockPluginInterface', 'Drupal\Core\Block\Annotation\Block');
// See Drupal\Core\Plugin\DefaultPluginManager
// The list of properties we want to grab out of the plugin manager
// => the key in the plugin type data array we want to set this into.
$plugin_manager_properties = [
'subdir' => 'subdir',
'pluginInterface' => 'plugin_interface',
'pluginDefinitionAnnotationName' => 'plugin_definition_annotation_name',
];
foreach ($plugin_manager_properties as $property_name => $data_key) {
if (!$reflection->hasProperty($property_name)) {
// plugin.manager.menu.link is different.
$data[$data_key] = '';
continue;
}
$property = $reflection->getProperty($property_name);
$property->setAccessible(TRUE);
$data[$data_key] = $property->getValue($service);
}
} | php | protected function addPluginTypeServiceDataAnnotated(&$data, $service, $discovery) {
$reflection = new \ReflectionClass($service);
// Get the properties that the plugin manager constructor sets.
// E.g., most plugin managers pass this to the parent:
// parent::__construct('Plugin/Block', $namespaces, $module_handler, 'Drupal\Core\Block\BlockPluginInterface', 'Drupal\Core\Block\Annotation\Block');
// See Drupal\Core\Plugin\DefaultPluginManager
// The list of properties we want to grab out of the plugin manager
// => the key in the plugin type data array we want to set this into.
$plugin_manager_properties = [
'subdir' => 'subdir',
'pluginInterface' => 'plugin_interface',
'pluginDefinitionAnnotationName' => 'plugin_definition_annotation_name',
];
foreach ($plugin_manager_properties as $property_name => $data_key) {
if (!$reflection->hasProperty($property_name)) {
// plugin.manager.menu.link is different.
$data[$data_key] = '';
continue;
}
$property = $reflection->getProperty($property_name);
$property->setAccessible(TRUE);
$data[$data_key] = $property->getValue($service);
}
} | [
"protected",
"function",
"addPluginTypeServiceDataAnnotated",
"(",
"&",
"$",
"data",
",",
"$",
"service",
",",
"$",
"discovery",
")",
"{",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"service",
")",
";",
"// Get the properties that the plugin... | Analyse the plugin type manager service for annotated plugins.
This adds:
- subdir
- plugin_interface
- plugin_definition_annotation_name
@param &$data
The data for a single plugin type.
@param $service
The plugin manager service.
@param $discovery
The plugin discovery object. | [
"Analyse",
"the",
"plugin",
"type",
"manager",
"service",
"for",
"annotated",
"plugins",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L439-L464 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addPluginTypeServiceDataYaml | protected function addPluginTypeServiceDataYaml(&$data, $service, $discovery) {
$service_reflection = new \ReflectionClass($service);
$property = $service_reflection->getProperty('defaults');
$property->setAccessible(TRUE);
$defaults = $property->getValue($service);
// YAML plugins don't specify their ID; it's generated automatically.
unset($defaults['id']);
$data['yaml_properties'] = $defaults;
// The YAML discovery wraps another discovery object.
$discovery_reflection = new \ReflectionClass($discovery);
$property = $discovery_reflection->getProperty('discovery');
$property->setAccessible(TRUE);
$wrapped_discovery = $property->getValue($discovery);
$wrapped_discovery_reflection = new \ReflectionClass($wrapped_discovery);
$property = $wrapped_discovery_reflection->getProperty('name');
$property->setAccessible(TRUE);
$name = $property->getValue($wrapped_discovery);
$data['yaml_file_suffix'] = $name;
} | php | protected function addPluginTypeServiceDataYaml(&$data, $service, $discovery) {
$service_reflection = new \ReflectionClass($service);
$property = $service_reflection->getProperty('defaults');
$property->setAccessible(TRUE);
$defaults = $property->getValue($service);
// YAML plugins don't specify their ID; it's generated automatically.
unset($defaults['id']);
$data['yaml_properties'] = $defaults;
// The YAML discovery wraps another discovery object.
$discovery_reflection = new \ReflectionClass($discovery);
$property = $discovery_reflection->getProperty('discovery');
$property->setAccessible(TRUE);
$wrapped_discovery = $property->getValue($discovery);
$wrapped_discovery_reflection = new \ReflectionClass($wrapped_discovery);
$property = $wrapped_discovery_reflection->getProperty('name');
$property->setAccessible(TRUE);
$name = $property->getValue($wrapped_discovery);
$data['yaml_file_suffix'] = $name;
} | [
"protected",
"function",
"addPluginTypeServiceDataYaml",
"(",
"&",
"$",
"data",
",",
"$",
"service",
",",
"$",
"discovery",
")",
"{",
"$",
"service_reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"service",
")",
";",
"$",
"property",
"=",
"$",
... | Analyse the plugin type manager service for YAML plugins.
This adds:
- yaml_file_suffix
- yaml_properties
@param &$data
The data for a single plugin type.
@param $service
The plugin manager service.
@param $discovery
The plugin discovery object. | [
"Analyse",
"the",
"plugin",
"type",
"manager",
"service",
"for",
"YAML",
"plugins",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L480-L503 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addPluginAnnotationData | protected function addPluginAnnotationData(&$data) {
$data['plugin_properties'] = [];
if (!isset($data['plugin_definition_annotation_name'])) {
return;
}
if (!class_exists($data['plugin_definition_annotation_name'])) {
return;
}
// Detect whether the annotation is just an ID.
if (is_a($data['plugin_definition_annotation_name'], \Drupal\Component\Annotation\PluginID::class, TRUE)) {
$data['annotation_id_only'] = TRUE;
}
else {
$data['annotation_id_only'] = FALSE;
}
// Get a reflection class for the annotation class.
// Each property of the annotation class describes a property for the
// plugin annotation.
$annotation_reflection = new \ReflectionClass($data['plugin_definition_annotation_name']);
$properties_reflection = $annotation_reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
foreach ($properties_reflection as $property_reflection) {
// Assemble data about this annotation property.
$annotation_property_data = array();
$annotation_property_data['name'] = $property_reflection->name;
// Get the docblock for the property, so we can figure out whether the
// annotation property requires translation, and also add detail to the
// annotation code.
$property_docblock = $property_reflection->getDocComment();
$property_docblock_lines = explode("\n", $property_docblock);
foreach ($property_docblock_lines as $line) {
if (substr($line, 0, 3) == '/**') {
continue;
}
// Take the first actual docblock line to be the description.
if (!isset($annotation_property_data['description']) && substr($line, 0, 5) == ' * ') {
$annotation_property_data['description'] = substr($line, 5);
}
// Look for a @var token, to tell us the type of the property.
if (substr($line, 0, 10) == ' * @var ') {
$annotation_property_data['type'] = substr($line, 10);
}
}
$data['plugin_properties'][$property_reflection->name] = $annotation_property_data;
}
} | php | protected function addPluginAnnotationData(&$data) {
$data['plugin_properties'] = [];
if (!isset($data['plugin_definition_annotation_name'])) {
return;
}
if (!class_exists($data['plugin_definition_annotation_name'])) {
return;
}
// Detect whether the annotation is just an ID.
if (is_a($data['plugin_definition_annotation_name'], \Drupal\Component\Annotation\PluginID::class, TRUE)) {
$data['annotation_id_only'] = TRUE;
}
else {
$data['annotation_id_only'] = FALSE;
}
// Get a reflection class for the annotation class.
// Each property of the annotation class describes a property for the
// plugin annotation.
$annotation_reflection = new \ReflectionClass($data['plugin_definition_annotation_name']);
$properties_reflection = $annotation_reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
foreach ($properties_reflection as $property_reflection) {
// Assemble data about this annotation property.
$annotation_property_data = array();
$annotation_property_data['name'] = $property_reflection->name;
// Get the docblock for the property, so we can figure out whether the
// annotation property requires translation, and also add detail to the
// annotation code.
$property_docblock = $property_reflection->getDocComment();
$property_docblock_lines = explode("\n", $property_docblock);
foreach ($property_docblock_lines as $line) {
if (substr($line, 0, 3) == '/**') {
continue;
}
// Take the first actual docblock line to be the description.
if (!isset($annotation_property_data['description']) && substr($line, 0, 5) == ' * ') {
$annotation_property_data['description'] = substr($line, 5);
}
// Look for a @var token, to tell us the type of the property.
if (substr($line, 0, 10) == ' * @var ') {
$annotation_property_data['type'] = substr($line, 10);
}
}
$data['plugin_properties'][$property_reflection->name] = $annotation_property_data;
}
} | [
"protected",
"function",
"addPluginAnnotationData",
"(",
"&",
"$",
"data",
")",
"{",
"$",
"data",
"[",
"'plugin_properties'",
"]",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"'plugin_definition_annotation_name'",
"]",
")",
")",
"{"... | Analyse the plugin annotation class.
This adds:
- 'plugin_properties': The properties from the annotation class.
- 'annotation_id_only': Boolean indicating whether the annotation consists
of only the plugin ID.
@param &$data
The data for a single plugin type. | [
"Analyse",
"the",
"plugin",
"annotation",
"class",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L516-L568 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addConfigSchemaPrefix | protected function addConfigSchemaPrefix(&$data) {
if (!is_subclass_of($data['plugin_interface'], \Drupal\Core\Field\PluginSettingsInterface::class)
&& !is_subclass_of($data['plugin_interface'], \Drupal\Component\Plugin\ConfigurablePluginInterface::class)
) {
// Only look at configurable plugins, whose interface inherits from
// ConfigurablePluginInterface.
// (Field module uses the equivalent, deprecated PluginSettingsInterface.)
return;
}
$service = \Drupal::service($data['service_id']);
$plugin_definitions = $service->getDefinitions();
$plugin_ids = array_keys($plugin_definitions);
// Use the last piece of the service name to filter potential config schema
// keys by. This is to prevent false positives from a plugin with the same
// ID but of a different type. E.g., there is a config schema item
// 'views.field.file_size' and a field.formatter plugin 'file_size'. By
// expecting 'formatter' in config keys we filter this out.
$service_pieces = explode('.', $data['service_id']);
$last_service_piece = end($service_pieces);
$typed_config_manager = \Drupal::service('config.typed');
$config_schema_definitions = $typed_config_manager->getDefinitions();
$config_schema_ids = array_keys($config_schema_definitions);
$plugin_schema_roots = [];
// Try to find a key for each plugin.
foreach ($plugin_ids as $plugin_id) {
// Get all schema IDs that end with the plugin ID.
$candidate_schema_ids = preg_grep("@\.{$plugin_id}\$@", $config_schema_ids);
// Further filter by the last piece of the plugin manager service ID.
// E.g. for 'plugin.manager.field.formatter' we filter by 'formatter'.
// Force a boundary before (rather than a '.'), as condition plugins have
// schema of the form 'condition.plugin.request_path',
// Don't force a '.' after, as filter plugins have schema of the form
// 'filter_settings.filter_html'.
$candidate_schema_ids = preg_grep("@\b{$last_service_piece}@", $candidate_schema_ids);
if (count($candidate_schema_ids) != 1) {
// Skip this plugin if we found no potential schema IDs, or if we found
// more than one, so we don't deal with an ambiguous result.
continue;
}
$plugin_schema_id = reset($candidate_schema_ids);
// We are interested in the schema ID prefix, which we expect to find
// before the plugin ID.
$plugin_schema_root = preg_replace("@{$plugin_id}\$@", '', $plugin_schema_id);
$plugin_schema_roots[] = $plugin_schema_root;
}
// We found no schema IDs for the plugins: nothing to do.
if (empty($plugin_schema_roots)) {
return;
}
// There's no common prefix: bail.
if (count(array_unique($plugin_schema_roots)) != 1) {
return;
}
$common_schema_prefix = reset($plugin_schema_roots);
$data['config_schema_prefix'] = $common_schema_prefix;
} | php | protected function addConfigSchemaPrefix(&$data) {
if (!is_subclass_of($data['plugin_interface'], \Drupal\Core\Field\PluginSettingsInterface::class)
&& !is_subclass_of($data['plugin_interface'], \Drupal\Component\Plugin\ConfigurablePluginInterface::class)
) {
// Only look at configurable plugins, whose interface inherits from
// ConfigurablePluginInterface.
// (Field module uses the equivalent, deprecated PluginSettingsInterface.)
return;
}
$service = \Drupal::service($data['service_id']);
$plugin_definitions = $service->getDefinitions();
$plugin_ids = array_keys($plugin_definitions);
// Use the last piece of the service name to filter potential config schema
// keys by. This is to prevent false positives from a plugin with the same
// ID but of a different type. E.g., there is a config schema item
// 'views.field.file_size' and a field.formatter plugin 'file_size'. By
// expecting 'formatter' in config keys we filter this out.
$service_pieces = explode('.', $data['service_id']);
$last_service_piece = end($service_pieces);
$typed_config_manager = \Drupal::service('config.typed');
$config_schema_definitions = $typed_config_manager->getDefinitions();
$config_schema_ids = array_keys($config_schema_definitions);
$plugin_schema_roots = [];
// Try to find a key for each plugin.
foreach ($plugin_ids as $plugin_id) {
// Get all schema IDs that end with the plugin ID.
$candidate_schema_ids = preg_grep("@\.{$plugin_id}\$@", $config_schema_ids);
// Further filter by the last piece of the plugin manager service ID.
// E.g. for 'plugin.manager.field.formatter' we filter by 'formatter'.
// Force a boundary before (rather than a '.'), as condition plugins have
// schema of the form 'condition.plugin.request_path',
// Don't force a '.' after, as filter plugins have schema of the form
// 'filter_settings.filter_html'.
$candidate_schema_ids = preg_grep("@\b{$last_service_piece}@", $candidate_schema_ids);
if (count($candidate_schema_ids) != 1) {
// Skip this plugin if we found no potential schema IDs, or if we found
// more than one, so we don't deal with an ambiguous result.
continue;
}
$plugin_schema_id = reset($candidate_schema_ids);
// We are interested in the schema ID prefix, which we expect to find
// before the plugin ID.
$plugin_schema_root = preg_replace("@{$plugin_id}\$@", '', $plugin_schema_id);
$plugin_schema_roots[] = $plugin_schema_root;
}
// We found no schema IDs for the plugins: nothing to do.
if (empty($plugin_schema_roots)) {
return;
}
// There's no common prefix: bail.
if (count(array_unique($plugin_schema_roots)) != 1) {
return;
}
$common_schema_prefix = reset($plugin_schema_roots);
$data['config_schema_prefix'] = $common_schema_prefix;
} | [
"protected",
"function",
"addConfigSchemaPrefix",
"(",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"is_subclass_of",
"(",
"$",
"data",
"[",
"'plugin_interface'",
"]",
",",
"\\",
"Drupal",
"\\",
"Core",
"\\",
"Field",
"\\",
"PluginSettingsInterface",
"::",
"c... | Deduces the config schema ID prefix for configurable plugin types.
@param array $data
The array of data for the plugin type. | [
"Deduces",
"the",
"config",
"schema",
"ID",
"prefix",
"for",
"configurable",
"plugin",
"types",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L820-L889 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addPluginMethods | protected function addPluginMethods(&$data) {
// Set an empty array at the least.
$data['plugin_interface_methods'] = [];
if (empty($data['plugin_interface'])) {
// If we didn't find an interface for the plugin, we can't do anything
// here.
return;
}
// Analyze the interface, if there is one.
$reflection = new \ReflectionClass($data['plugin_interface']);
$methods = $reflection->getMethods();
$data['plugin_interface_methods'] = [];
// Check each method from the plugin interface for suitability.
foreach ($methods as $method_reflection) {
// Start by assuming we won't include it.
$include_method = FALSE;
// Get the actual class/interface that declares the method, as the
// plugin interface will in most cases inherit from one or more
// interfaces.
$declaring_class = $method_reflection->getDeclaringClass()->getName();
// Get the namespace of the component the class belongs to.
$declaring_class_component_namespace = $this->getClassComponentNamespace($declaring_class);
if ($declaring_class_component_namespace == $data['service_component_namespace']) {
// The plugin interface method is declared in the same component as
// the plugin manager service.
// Add it to the list of methods a plugin should implement.
$include_method = TRUE;
}
else {
// The plugin interface method is declared in a namespace other
// than the plugin manager. Therefore it's something from a base
// interface, e.g. from PluginInspectionInterface, and we shouldn't
// add it to the list of methods a plugin should implement...
// except for a few special cases.
if ($declaring_class == 'Drupal\Core\Plugin\PluginFormInterface') {
$include_method = TRUE;
}
if ($declaring_class == 'Drupal\Core\Cache\CacheableDependencyInterface') {
$include_method = TRUE;
}
}
if ($include_method) {
$data['plugin_interface_methods'][$method_reflection->getName()] = $this->methodCollector->getMethodData($method_reflection);
}
}
} | php | protected function addPluginMethods(&$data) {
// Set an empty array at the least.
$data['plugin_interface_methods'] = [];
if (empty($data['plugin_interface'])) {
// If we didn't find an interface for the plugin, we can't do anything
// here.
return;
}
// Analyze the interface, if there is one.
$reflection = new \ReflectionClass($data['plugin_interface']);
$methods = $reflection->getMethods();
$data['plugin_interface_methods'] = [];
// Check each method from the plugin interface for suitability.
foreach ($methods as $method_reflection) {
// Start by assuming we won't include it.
$include_method = FALSE;
// Get the actual class/interface that declares the method, as the
// plugin interface will in most cases inherit from one or more
// interfaces.
$declaring_class = $method_reflection->getDeclaringClass()->getName();
// Get the namespace of the component the class belongs to.
$declaring_class_component_namespace = $this->getClassComponentNamespace($declaring_class);
if ($declaring_class_component_namespace == $data['service_component_namespace']) {
// The plugin interface method is declared in the same component as
// the plugin manager service.
// Add it to the list of methods a plugin should implement.
$include_method = TRUE;
}
else {
// The plugin interface method is declared in a namespace other
// than the plugin manager. Therefore it's something from a base
// interface, e.g. from PluginInspectionInterface, and we shouldn't
// add it to the list of methods a plugin should implement...
// except for a few special cases.
if ($declaring_class == 'Drupal\Core\Plugin\PluginFormInterface') {
$include_method = TRUE;
}
if ($declaring_class == 'Drupal\Core\Cache\CacheableDependencyInterface') {
$include_method = TRUE;
}
}
if ($include_method) {
$data['plugin_interface_methods'][$method_reflection->getName()] = $this->methodCollector->getMethodData($method_reflection);
}
}
} | [
"protected",
"function",
"addPluginMethods",
"(",
"&",
"$",
"data",
")",
"{",
"// Set an empty array at the least.",
"$",
"data",
"[",
"'plugin_interface_methods'",
"]",
"=",
"[",
"]",
";",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"'plugin_interface'",
"]",
... | Adds list of methods for the plugin based on the plugin interface.
@param &$data
The data for a single plugin type. | [
"Adds",
"list",
"of",
"methods",
"for",
"the",
"plugin",
"based",
"on",
"the",
"plugin",
"interface",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L897-L950 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.addPluginModuleData | protected function addPluginModuleData(&$plugin_type_data) {
// Bail if Plugin module isn't present.
if (!\Drupal::hasService('plugin.plugin_type_manager')) {
return;
}
// This gets us labels for the plugin types which are declared to Plugin
// module.
$plugin_types = \Drupal::service('plugin.plugin_type_manager')->getPluginTypes();
// We need to re-key these by the service ID, as Plugin module uses IDs for
// plugin types which don't always the ID we use for them based on the
// plugin manager service ID, , e.g. views_access vs views.access.
// Unfortunately, there's no accessor for this, so some reflection hackery
// is required until https://www.drupal.org/node/2907862 is fixed.
$reflection = new \ReflectionProperty(\Drupal\plugin\PluginType\PluginType::class, 'pluginManagerServiceId');
$reflection->setAccessible(TRUE);
foreach ($plugin_types as $plugin_type) {
// Get the service ID from the reflection, and then our ID.
$plugin_manager_service_id = $reflection->getValue($plugin_type);
$plugin_type_id = substr($plugin_manager_service_id, strlen('plugin.manager.'));
if (!isset($plugin_type_data[$plugin_type_id])) {
continue;
}
// Replace the default label with the one from Plugin module, casting it
// to a string so we don't have to deal with TranslatableMarkup objects.
$plugin_type_data[$plugin_type_id]['type_label'] = (string) $plugin_type->getLabel();
}
} | php | protected function addPluginModuleData(&$plugin_type_data) {
// Bail if Plugin module isn't present.
if (!\Drupal::hasService('plugin.plugin_type_manager')) {
return;
}
// This gets us labels for the plugin types which are declared to Plugin
// module.
$plugin_types = \Drupal::service('plugin.plugin_type_manager')->getPluginTypes();
// We need to re-key these by the service ID, as Plugin module uses IDs for
// plugin types which don't always the ID we use for them based on the
// plugin manager service ID, , e.g. views_access vs views.access.
// Unfortunately, there's no accessor for this, so some reflection hackery
// is required until https://www.drupal.org/node/2907862 is fixed.
$reflection = new \ReflectionProperty(\Drupal\plugin\PluginType\PluginType::class, 'pluginManagerServiceId');
$reflection->setAccessible(TRUE);
foreach ($plugin_types as $plugin_type) {
// Get the service ID from the reflection, and then our ID.
$plugin_manager_service_id = $reflection->getValue($plugin_type);
$plugin_type_id = substr($plugin_manager_service_id, strlen('plugin.manager.'));
if (!isset($plugin_type_data[$plugin_type_id])) {
continue;
}
// Replace the default label with the one from Plugin module, casting it
// to a string so we don't have to deal with TranslatableMarkup objects.
$plugin_type_data[$plugin_type_id]['type_label'] = (string) $plugin_type->getLabel();
}
} | [
"protected",
"function",
"addPluginModuleData",
"(",
"&",
"$",
"plugin_type_data",
")",
"{",
"// Bail if Plugin module isn't present.",
"if",
"(",
"!",
"\\",
"Drupal",
"::",
"hasService",
"(",
"'plugin.plugin_type_manager'",
")",
")",
"{",
"return",
";",
"}",
"// Th... | Adds plugin type information from Plugin module if present.
@param &$plugin_type_data
The array of data for all plugin types. | [
"Adds",
"plugin",
"type",
"information",
"from",
"Plugin",
"module",
"if",
"present",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L1131-L1162 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/PluginTypesCollector.php | PluginTypesCollector.getClassComponentNamespace | protected function getClassComponentNamespace($class_name) {
$pieces = explode('\\', $class_name);
if (!isset($pieces[1])) {
// We don't know about something that is in the global namespace.
return '';
}
if ($pieces[1] == 'Core' || $pieces[1] == 'Component') {
return implode('\\', array_slice($pieces, 0, 3));
}
else {
return implode('\\', array_slice($pieces, 0, 2));
}
} | php | protected function getClassComponentNamespace($class_name) {
$pieces = explode('\\', $class_name);
if (!isset($pieces[1])) {
// We don't know about something that is in the global namespace.
return '';
}
if ($pieces[1] == 'Core' || $pieces[1] == 'Component') {
return implode('\\', array_slice($pieces, 0, 3));
}
else {
return implode('\\', array_slice($pieces, 0, 2));
}
} | [
"protected",
"function",
"getClassComponentNamespace",
"(",
"$",
"class_name",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"class_name",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"pieces",
"[",
"1",
"]",
")",
")",
"{",
"// We d... | Gets the namespace for the component a class is in.
This is either a module namespace, or a core component namespace, e.g.:
- 'Drupal\foo'
- 'Drupal\Core\Foo'
- 'Drupal\Component\Foo'
@param string $class_name
The class name.
@return string
The namespace, or an empty string if nothing found. | [
"Gets",
"the",
"namespace",
"for",
"the",
"component",
"a",
"class",
"is",
"in",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/PluginTypesCollector.php#L1178-L1192 | train |
drupal-code-builder/drupal-code-builder | Factory.php | Factory.getTask | public static function getTask($task_type, $task_options = NULL) {
if (!isset(self::$environment)) {
throw new \Exception("Environment not set.");
}
$task_class = self::getTaskClass($task_type);
// Set the environment handler on the task handler too.
$task_handler = new $task_class(self::$environment, $task_options);
// Find out what sanity level the task handler needs.
$required_sanity = $task_handler->getSanityLevel();
//dsm($required_sanity);
// Check the environment for the required sanity level.
self::$environment->verifyEnvironment($required_sanity);
return $task_handler;
} | php | public static function getTask($task_type, $task_options = NULL) {
if (!isset(self::$environment)) {
throw new \Exception("Environment not set.");
}
$task_class = self::getTaskClass($task_type);
// Set the environment handler on the task handler too.
$task_handler = new $task_class(self::$environment, $task_options);
// Find out what sanity level the task handler needs.
$required_sanity = $task_handler->getSanityLevel();
//dsm($required_sanity);
// Check the environment for the required sanity level.
self::$environment->verifyEnvironment($required_sanity);
return $task_handler;
} | [
"public",
"static",
"function",
"getTask",
"(",
"$",
"task_type",
",",
"$",
"task_options",
"=",
"NULL",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"environment",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Environment not s... | Get a new task handler.
This creates a new task handler object as requested, sets the environment
handler on it, then checks the environment for the environment level the
task declares that it needs.
@param $task_type
The type of task. This should the the name of a class in the
DrupalCodeBuilder\Task namespace, without the Drupal core version suffix.
May be one of:
- 'Collect': Collect and process data on available hooks.
- 'ReportHookData':
- ... others TODO.
@param $task_options
(optional) A further parameter to pass to the task's constructor. Its
nature (or necessity) depends on the task.
@return
A new task handler object, which implements DrupalCodeBuilderTaskInterface.
@throws \DrupalCodeBuilder\Exception\SanityException
Throws an exception if the environment is not in a state that is ready for
the requested task, for example, if no hook data has been downloaded. | [
"Get",
"a",
"new",
"task",
"handler",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Factory.php#L136-L154 | train |
drupal-code-builder/drupal-code-builder | Factory.php | Factory.getTaskClass | public static function getTaskClass($task_type) {
$type = ucfirst($task_type);
$version = self::$environment->getCoreMajorVersion();
$versioned_class = "DrupalCodeBuilder\\Task\\$task_type$version";
$common_class = "DrupalCodeBuilder\\Task\\$task_type";
if (class_exists($versioned_class)) {
$class = $versioned_class;
}
elseif (class_exists($common_class)) {
$class = $common_class;
}
else {
throw new InvalidInputException("Task class not found.");
}
return $class;
} | php | public static function getTaskClass($task_type) {
$type = ucfirst($task_type);
$version = self::$environment->getCoreMajorVersion();
$versioned_class = "DrupalCodeBuilder\\Task\\$task_type$version";
$common_class = "DrupalCodeBuilder\\Task\\$task_type";
if (class_exists($versioned_class)) {
$class = $versioned_class;
}
elseif (class_exists($common_class)) {
$class = $common_class;
}
else {
throw new InvalidInputException("Task class not found.");
}
return $class;
} | [
"public",
"static",
"function",
"getTaskClass",
"(",
"$",
"task_type",
")",
"{",
"$",
"type",
"=",
"ucfirst",
"(",
"$",
"task_type",
")",
";",
"$",
"version",
"=",
"self",
"::",
"$",
"environment",
"->",
"getCoreMajorVersion",
"(",
")",
";",
"$",
"versio... | Helper function to get the desired Task class.
@param $task_type
The type of the task. This is the class name without the Drupal core
version suffix.
@return
A fully qualified class name for the type and, if it exists, version, e.g.
'DrupalCodeBuilder\Task\Collect7'.
@throws
Throws \DrupalCodeBuilder\Exception\InvalidInputException if the task type
does not correspond to a Task class. | [
"Helper",
"function",
"to",
"get",
"the",
"desired",
"Task",
"class",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Factory.php#L171-L189 | train |
drupal-code-builder/drupal-code-builder | Generator/API.php | API.hook_code | function hook_code($hook_short_name, $parameters_string) {
$parameters = explode(', ', $parameters_string);
$parameters_doc_lines = array();
foreach ($parameters as $parameter) {
$parameters_doc_lines[] = " * @param $parameter\n" .
" * TODO: document this parameter.";
}
if (!empty($parameters_doc_lines)) {
$parameters_doc = " *\n" . implode("\n", $parameters_doc_lines);
}
return <<<EOT
/**
* TODO: write summary line.
*
* TODO: longer description.
$parameters_doc
*
* @return
* TODO: Document return value if there is one.
*/
function hook_$hook_short_name($parameters_string) {
// TODO: write sample code.
}
EOT;
} | php | function hook_code($hook_short_name, $parameters_string) {
$parameters = explode(', ', $parameters_string);
$parameters_doc_lines = array();
foreach ($parameters as $parameter) {
$parameters_doc_lines[] = " * @param $parameter\n" .
" * TODO: document this parameter.";
}
if (!empty($parameters_doc_lines)) {
$parameters_doc = " *\n" . implode("\n", $parameters_doc_lines);
}
return <<<EOT
/**
* TODO: write summary line.
*
* TODO: longer description.
$parameters_doc
*
* @return
* TODO: Document return value if there is one.
*/
function hook_$hook_short_name($parameters_string) {
// TODO: write sample code.
}
EOT;
} | [
"function",
"hook_code",
"(",
"$",
"hook_short_name",
",",
"$",
"parameters_string",
")",
"{",
"$",
"parameters",
"=",
"explode",
"(",
"', '",
",",
"$",
"parameters_string",
")",
";",
"$",
"parameters_doc_lines",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
... | Create the code for a single hook.
@param $hook_short_name
The short name of the hook, i.e., without the 'hook_' prefix.
@param $parameters_string
A string of the hook's parameters.
@return
A string of formatted code for inclusion in the api.php file. | [
"Create",
"the",
"code",
"for",
"a",
"single",
"hook",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/API.php#L106-L132 | train |
drupal-code-builder/drupal-code-builder | Task/AnalyzeModule.php | AnalyzeModule.getFiles | public function getFiles($module_root_name) {
$filepath = $this->environment->getExtensionPath('module', $module_root_name);
//$old_dir = getcwd();
//chdir($filepath);
$files = scandir($filepath);
foreach ($files as $filename) {
$ext = substr(strrchr($filename, '.'), 1);
if (in_array($ext, array('module', 'install', 'inc'))) {
$module_files[] = $filepath . '/' . $filename;
}
}
return $module_files;
} | php | public function getFiles($module_root_name) {
$filepath = $this->environment->getExtensionPath('module', $module_root_name);
//$old_dir = getcwd();
//chdir($filepath);
$files = scandir($filepath);
foreach ($files as $filename) {
$ext = substr(strrchr($filename, '.'), 1);
if (in_array($ext, array('module', 'install', 'inc'))) {
$module_files[] = $filepath . '/' . $filename;
}
}
return $module_files;
} | [
"public",
"function",
"getFiles",
"(",
"$",
"module_root_name",
")",
"{",
"$",
"filepath",
"=",
"$",
"this",
"->",
"environment",
"->",
"getExtensionPath",
"(",
"'module'",
",",
"$",
"module_root_name",
")",
";",
"//$old_dir = getcwd();",
"//chdir($filepath);",
"$... | Helper function to get all the code files for a given module
TODO: does drush have this?
@param $module_root_name
The root name of a module, eg 'node', 'taxonomy'.
@return
A flat array of filenames. | [
"Helper",
"function",
"to",
"get",
"all",
"the",
"code",
"files",
"for",
"a",
"given",
"module"
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/AnalyzeModule.php#L31-L46 | train |
drupal-code-builder/drupal-code-builder | Task/AnalyzeModule.php | AnalyzeModule.getFileFunctions | public function getFileFunctions($file) {
$code = file_get_contents($file);
//drush_print($code);
$matches = array();
$pattern = "/^function (\w+)/m";
preg_match_all($pattern, $code, $matches);
return $matches[1];
} | php | public function getFileFunctions($file) {
$code = file_get_contents($file);
//drush_print($code);
$matches = array();
$pattern = "/^function (\w+)/m";
preg_match_all($pattern, $code, $matches);
return $matches[1];
} | [
"public",
"function",
"getFileFunctions",
"(",
"$",
"file",
")",
"{",
"$",
"code",
"=",
"file_get_contents",
"(",
"$",
"file",
")",
";",
"//drush_print($code);",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"$",
"pattern",
"=",
"\"/^function (\\w+)/m\"",
";"... | Helper function to get all function names from a file.
@param $file
A complete filename from the Drupal root, eg 'modules/user/user.module'. | [
"Helper",
"function",
"to",
"get",
"all",
"function",
"names",
"from",
"a",
"file",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/AnalyzeModule.php#L54-L63 | train |
drupal-code-builder/drupal-code-builder | Task/AnalyzeModule.php | AnalyzeModule.getInventedHooks | public function getInventedHooks($module_root_name) {
// Get the module's folder.
$module_folder = $this->environment->getExtensionPath('module', $module_root_name);
// Bail if the folder doesn't exist yet: there is nothing to do.
if (!file_exists($module_folder)) {
return array();
}
// An array of short hook names that we'll populate from what we extract
// from the files.
$hooks = array();
// Only consider hooks which are invented by this module: it is legitimate
// for modules to invoke hooks invented by other modules. We assume the
// module follows the convention of using its name as a prefix.
$hook_prefix = $module_root_name . '_';
foreach ($this->getFolderIterator($module_folder) as $filename => $object) {
//print_r("$filename\n");
$contents = file_get_contents("$filename");
// List of patterns to match on.
// They should all have capturing groups for:
// - 1. hook name
// - 2. optional parameters
$hook_invocation_patterns = array(
// module_invoke_all() calls (the key here is arbitrary).
'module_invoke_all' => array(
// The pattern for this item.
'pattern' =>
"/
module_invoke_all \(
' ( $hook_prefix \w+ ) ' # Hook name, with the hook prefix.
(?:
, \s*
(
[^)]* # Capture further parameters: anything up to the closing ')'.
)
)? # The further parameters are optional.
/x",
),
// module_invoke() calls.
'module_invoke' => array(
'pattern' =>
"/
module_invoke \(
[^,]+ # The \$module parameter.
, \s*
' ( $hook_prefix \w+ ) ' # Hook name, with the hook prefix.
(?:
, \s*
(
[^)]* # Capture further parameters: anything up to the closing ')'.
)
)? # The further parameters are optional.
/x",
),
// drupal_alter() calls.
'drupal_alter' => array(
'pattern' =>
"/
drupal_alter \(
' ( $hook_prefix \w+ ) ' # Hook name, with the hook prefix.
(?:
, \s*
(
[^)]* # Capture further parameters: anything up to the closing ')'.
)
)? # The further parameters are optional.
/x",
// A process callback to apply to each hook name the pattern finds.
// This is because the hook name in drupal_alter() needs a suffix to
// be added to it.
'process callback' => function ($hook_name) {
return $hook_name . '_alter';
},
),
);
// Process the file for each pattern.
foreach ($hook_invocation_patterns as $pattern_info) {
$pattern = $pattern_info['pattern'];
$matches = array();
preg_match_all($pattern, $contents, $matches);
// Matches are:
// - 1: the first parameter, which is the hook short name.
// - 2: the remaining parameters, if any.
// If we get matches, turn then into keyed arrays and merge them into
// the cumulative array. This removes duplicates (caused by a hook being
// invoked in different files).
if (!empty($matches[1])) {
//drush_print_r($matches);
$file_hooks = array_combine($matches[1], $matches[2]);
//drush_print_r($file_hooks);
foreach ($file_hooks as $hook_short_name => $parameters) {
// Perform additional processing on the hook short name, if needed.
if (isset($pattern_info['process callback'])) {
$hook_short_name = $pattern_info['process callback']($hook_short_name);
}
// If this hook is already in our list, we take the longest parameters
// string, on the assumption that this may be more complete if some
// parameters are options.
if (isset($hooks[$hook_short_name])) {
// Replace the existing hook if the new parameters are longer.
if (strlen($parameters) > strlen($hooks[$hook_short_name])) {
$hooks[$hook_short_name] = $parameters;
}
}
else {
$hooks[$hook_short_name] = $parameters;
}
}
}
}
}
//drush_print_r($hooks);
return $hooks;
} | php | public function getInventedHooks($module_root_name) {
// Get the module's folder.
$module_folder = $this->environment->getExtensionPath('module', $module_root_name);
// Bail if the folder doesn't exist yet: there is nothing to do.
if (!file_exists($module_folder)) {
return array();
}
// An array of short hook names that we'll populate from what we extract
// from the files.
$hooks = array();
// Only consider hooks which are invented by this module: it is legitimate
// for modules to invoke hooks invented by other modules. We assume the
// module follows the convention of using its name as a prefix.
$hook_prefix = $module_root_name . '_';
foreach ($this->getFolderIterator($module_folder) as $filename => $object) {
//print_r("$filename\n");
$contents = file_get_contents("$filename");
// List of patterns to match on.
// They should all have capturing groups for:
// - 1. hook name
// - 2. optional parameters
$hook_invocation_patterns = array(
// module_invoke_all() calls (the key here is arbitrary).
'module_invoke_all' => array(
// The pattern for this item.
'pattern' =>
"/
module_invoke_all \(
' ( $hook_prefix \w+ ) ' # Hook name, with the hook prefix.
(?:
, \s*
(
[^)]* # Capture further parameters: anything up to the closing ')'.
)
)? # The further parameters are optional.
/x",
),
// module_invoke() calls.
'module_invoke' => array(
'pattern' =>
"/
module_invoke \(
[^,]+ # The \$module parameter.
, \s*
' ( $hook_prefix \w+ ) ' # Hook name, with the hook prefix.
(?:
, \s*
(
[^)]* # Capture further parameters: anything up to the closing ')'.
)
)? # The further parameters are optional.
/x",
),
// drupal_alter() calls.
'drupal_alter' => array(
'pattern' =>
"/
drupal_alter \(
' ( $hook_prefix \w+ ) ' # Hook name, with the hook prefix.
(?:
, \s*
(
[^)]* # Capture further parameters: anything up to the closing ')'.
)
)? # The further parameters are optional.
/x",
// A process callback to apply to each hook name the pattern finds.
// This is because the hook name in drupal_alter() needs a suffix to
// be added to it.
'process callback' => function ($hook_name) {
return $hook_name . '_alter';
},
),
);
// Process the file for each pattern.
foreach ($hook_invocation_patterns as $pattern_info) {
$pattern = $pattern_info['pattern'];
$matches = array();
preg_match_all($pattern, $contents, $matches);
// Matches are:
// - 1: the first parameter, which is the hook short name.
// - 2: the remaining parameters, if any.
// If we get matches, turn then into keyed arrays and merge them into
// the cumulative array. This removes duplicates (caused by a hook being
// invoked in different files).
if (!empty($matches[1])) {
//drush_print_r($matches);
$file_hooks = array_combine($matches[1], $matches[2]);
//drush_print_r($file_hooks);
foreach ($file_hooks as $hook_short_name => $parameters) {
// Perform additional processing on the hook short name, if needed.
if (isset($pattern_info['process callback'])) {
$hook_short_name = $pattern_info['process callback']($hook_short_name);
}
// If this hook is already in our list, we take the longest parameters
// string, on the assumption that this may be more complete if some
// parameters are options.
if (isset($hooks[$hook_short_name])) {
// Replace the existing hook if the new parameters are longer.
if (strlen($parameters) > strlen($hooks[$hook_short_name])) {
$hooks[$hook_short_name] = $parameters;
}
}
else {
$hooks[$hook_short_name] = $parameters;
}
}
}
}
}
//drush_print_r($hooks);
return $hooks;
} | [
"public",
"function",
"getInventedHooks",
"(",
"$",
"module_root_name",
")",
"{",
"// Get the module's folder.",
"$",
"module_folder",
"=",
"$",
"this",
"->",
"environment",
"->",
"getExtensionPath",
"(",
"'module'",
",",
"$",
"module_root_name",
")",
";",
"// Bail ... | Get the hooks that a module invents, i.e., the ones it should document.
@param $module_root_name
The module root name.
@return
An array of hooks and their parameters. The hooks are deduced from the
calls to functions such as module_invoke_all(), and the probable
parameters are taken from the variables passed to the call. The keys of
the array are hook short names; the values are the parameters string,
with separating commas but without the outer parentheses. E.g.:
'foo_insert' => '$foo, $bar'
These may not be complete if invocations omit any optional parameters. | [
"Get",
"the",
"hooks",
"that",
"a",
"module",
"invents",
"i",
".",
"e",
".",
"the",
"ones",
"it",
"should",
"document",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/AnalyzeModule.php#L80-L203 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/ServicesCollector.php | ServicesCollector.collect | public function collect($job_list) {
$all_services = $this->getAllServices();
$static_container_services = $this->getStaticContainerServices();
// Filter out anything from the static inspection, to remove deprecated
// services, and also in case some non-services snuck in.
$static_container_services = array_intersect_key($static_container_services, $all_services);
// Replace the definitions from the container with the hopefully better
// data from the static Drupal class.
$all_services = array_merge($all_services, $static_container_services);
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$static_container_services = array_intersect_key($static_container_services, $this->testingServiceNames);
$all_services = array_intersect_key($all_services, $this->testingServiceNames);
}
$return = [
'primary' => $static_container_services,
'all' => $all_services,
];
return $return;
} | php | public function collect($job_list) {
$all_services = $this->getAllServices();
$static_container_services = $this->getStaticContainerServices();
// Filter out anything from the static inspection, to remove deprecated
// services, and also in case some non-services snuck in.
$static_container_services = array_intersect_key($static_container_services, $all_services);
// Replace the definitions from the container with the hopefully better
// data from the static Drupal class.
$all_services = array_merge($all_services, $static_container_services);
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$static_container_services = array_intersect_key($static_container_services, $this->testingServiceNames);
$all_services = array_intersect_key($all_services, $this->testingServiceNames);
}
$return = [
'primary' => $static_container_services,
'all' => $all_services,
];
return $return;
} | [
"public",
"function",
"collect",
"(",
"$",
"job_list",
")",
"{",
"$",
"all_services",
"=",
"$",
"this",
"->",
"getAllServices",
"(",
")",
";",
"$",
"static_container_services",
"=",
"$",
"this",
"->",
"getStaticContainerServices",
"(",
")",
";",
"// Filter out... | Get definitions of services.
@return array
An array containing:
- 'primary': The major services in use.
- 'all': All services.
Each value is itself an array of service data, keyed by service ID, where
each value is an array containing:
- 'id': The service ID.
- 'label': A label for the service.
- 'description': A longer description for the service.
- 'class': The fully-qualified class that is defined for the service.
- 'interface': The fully-qualified interface that the service class
implements, with the initial '\'. | [
"Get",
"definitions",
"of",
"services",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/ServicesCollector.php#L83-L107 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/ServicesCollector.php | ServicesCollector.getAllServices | protected function getAllServices() {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
$definitions = $container_builder->getDefinitions();
// Get an array of all the tags which are used by service collectors, so
// we can filter out the services with those tags.
$collector_tags = [];
$collectors_info = $container_builder->findTaggedServiceIds('service_collector');
foreach ($collectors_info as $service_name => $tag_infos) {
// A single service collector service can collect on more than one tag.
foreach ($tag_infos as $tag_info) {
$tag = $tag_info['tag'];
$collector_tags[$tag] = TRUE;
}
}
$data = [];
foreach ($definitions as $service_id => $definition) {
// Skip services from Drush.
if (substr($service_id, 0, strlen('drush.')) == 'drush.') {
continue;
}
if (substr($service_id, - strlen('.commands')) == '.commands') {
continue;
}
// Skip proxy services.
if (substr($service_id, 0, strlen('drupal.proxy_original_service.')) == 'drupal.proxy_original_service.') {
continue;
}
// Skip any services which are tagged for a collector, as they should not
// be directly used by anything else.
if (array_intersect_key($collector_tags, $definition->getTags())) {
continue;
}
// Skip any services which are marked as deprecated.
if ($definition->isDeprecated()) {
continue;
}
// Skip entity.manager, which is not marked as deprecated, but is.
if ($service_id == 'entity.manager') {
continue;
}
$service_class = $definition->getClass();
// Skip if no class defined, class_loader apparently, WTF?!.
if (empty($service_class)) {
continue;
}
// Skip if the class isn't loadable by PHP without causing a fatal, as we
// can't work with just an ID to generate things like injection.
// (The case of a service class whose parent does not exist happens if
// a module Foo provides a service for module Bar's collection with a
// service tag. Metatag module is one such example.)
if (!$this->codeAnalyser->classIsUsable($service_class)) {
continue;
}
// Skip if the clas doesn't exist.
// The service class can sometimes actually be an interface, as with
// cache services. (This is not documented!)
if (!(class_exists($service_class) || interface_exists($service_class))) {
continue;
}
// Get the short class name to use as a label.
$service_class_pieces = explode('\\', $service_class);
$service_short_class = array_pop($service_class_pieces);
// If the class is in fact secretly an interface (this is the case for
// cache services!) then remove the 'Interface' suffix.
$service_short_class = preg_replace('/Interface$/', '', $service_short_class);
$label = CaseString::pascal($service_short_class)->sentence();
$data[$service_id] = [
'id' => $service_id,
'label' => $label,
'static_method' => '', // Not used.
'class' => '\\' . $service_class,
'interface' => $this->getServiceInterface($service_class),
'description' => "The {$label} service",
];
}
ksort($data);
return $data;
} | php | protected function getAllServices() {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
$definitions = $container_builder->getDefinitions();
// Get an array of all the tags which are used by service collectors, so
// we can filter out the services with those tags.
$collector_tags = [];
$collectors_info = $container_builder->findTaggedServiceIds('service_collector');
foreach ($collectors_info as $service_name => $tag_infos) {
// A single service collector service can collect on more than one tag.
foreach ($tag_infos as $tag_info) {
$tag = $tag_info['tag'];
$collector_tags[$tag] = TRUE;
}
}
$data = [];
foreach ($definitions as $service_id => $definition) {
// Skip services from Drush.
if (substr($service_id, 0, strlen('drush.')) == 'drush.') {
continue;
}
if (substr($service_id, - strlen('.commands')) == '.commands') {
continue;
}
// Skip proxy services.
if (substr($service_id, 0, strlen('drupal.proxy_original_service.')) == 'drupal.proxy_original_service.') {
continue;
}
// Skip any services which are tagged for a collector, as they should not
// be directly used by anything else.
if (array_intersect_key($collector_tags, $definition->getTags())) {
continue;
}
// Skip any services which are marked as deprecated.
if ($definition->isDeprecated()) {
continue;
}
// Skip entity.manager, which is not marked as deprecated, but is.
if ($service_id == 'entity.manager') {
continue;
}
$service_class = $definition->getClass();
// Skip if no class defined, class_loader apparently, WTF?!.
if (empty($service_class)) {
continue;
}
// Skip if the class isn't loadable by PHP without causing a fatal, as we
// can't work with just an ID to generate things like injection.
// (The case of a service class whose parent does not exist happens if
// a module Foo provides a service for module Bar's collection with a
// service tag. Metatag module is one such example.)
if (!$this->codeAnalyser->classIsUsable($service_class)) {
continue;
}
// Skip if the clas doesn't exist.
// The service class can sometimes actually be an interface, as with
// cache services. (This is not documented!)
if (!(class_exists($service_class) || interface_exists($service_class))) {
continue;
}
// Get the short class name to use as a label.
$service_class_pieces = explode('\\', $service_class);
$service_short_class = array_pop($service_class_pieces);
// If the class is in fact secretly an interface (this is the case for
// cache services!) then remove the 'Interface' suffix.
$service_short_class = preg_replace('/Interface$/', '', $service_short_class);
$label = CaseString::pascal($service_short_class)->sentence();
$data[$service_id] = [
'id' => $service_id,
'label' => $label,
'static_method' => '', // Not used.
'class' => '\\' . $service_class,
'interface' => $this->getServiceInterface($service_class),
'description' => "The {$label} service",
];
}
ksort($data);
return $data;
} | [
"protected",
"function",
"getAllServices",
"(",
")",
"{",
"$",
"container_builder",
"=",
"$",
"this",
"->",
"containerBuilderGetter",
"->",
"getContainerBuilder",
"(",
")",
";",
"$",
"definitions",
"=",
"$",
"container_builder",
"->",
"getDefinitions",
"(",
")",
... | Get data on all services from the container builder.
@return [type] [description] | [
"Get",
"data",
"on",
"all",
"services",
"from",
"the",
"container",
"builder",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/ServicesCollector.php#L127-L221 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/ServicesCollector.php | ServicesCollector.getServiceInterface | protected function getServiceInterface($service_class) {
$reflection = new \ReflectionClass($service_class);
// This can get us more than one interface, if the declared interface has
// parents. We only want one, so we need to go hacking in the code itself.
$file = $reflection->getFileName();
// If there's no file, as apparently some services have as their class
// ArrayObject (WTF?!).
if (empty($file)) {
return '';
}
$start_line = $reflection->getStartLine();
$spl = new \SplFileObject($file);
$spl->seek($start_line - 1);
$service_declaration_line = $spl->current();
// Extract the interface from the declaration. We expect a service class
// to only name one interface in its declaration!
$matches = [];
preg_match("@implements (\w+)@", $service_declaration_line, $matches);
if (!isset($matches[1])) {
return '';
}
$interface_short_name = $matches[1];
// Find the fully-qualified interface name in the array of interfaces
// obtained from the reflection.
$interfaces = $reflection->getInterfaces();
foreach (array_keys($interfaces) as $interface) {
if (substr($interface, -(strlen($interface_short_name) + 1)) == '\\' . $interface_short_name) {
// The reflection doesn't give the initial '\'.
$full_interface_name = '\\' . $interface;
return $full_interface_name;
}
}
return '';
} | php | protected function getServiceInterface($service_class) {
$reflection = new \ReflectionClass($service_class);
// This can get us more than one interface, if the declared interface has
// parents. We only want one, so we need to go hacking in the code itself.
$file = $reflection->getFileName();
// If there's no file, as apparently some services have as their class
// ArrayObject (WTF?!).
if (empty($file)) {
return '';
}
$start_line = $reflection->getStartLine();
$spl = new \SplFileObject($file);
$spl->seek($start_line - 1);
$service_declaration_line = $spl->current();
// Extract the interface from the declaration. We expect a service class
// to only name one interface in its declaration!
$matches = [];
preg_match("@implements (\w+)@", $service_declaration_line, $matches);
if (!isset($matches[1])) {
return '';
}
$interface_short_name = $matches[1];
// Find the fully-qualified interface name in the array of interfaces
// obtained from the reflection.
$interfaces = $reflection->getInterfaces();
foreach (array_keys($interfaces) as $interface) {
if (substr($interface, -(strlen($interface_short_name) + 1)) == '\\' . $interface_short_name) {
// The reflection doesn't give the initial '\'.
$full_interface_name = '\\' . $interface;
return $full_interface_name;
}
}
return '';
} | [
"protected",
"function",
"getServiceInterface",
"(",
"$",
"service_class",
")",
"{",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"service_class",
")",
";",
"// This can get us more than one interface, if the declared interface has",
"// parents. We only ... | Extracts the interface from the service class using reflection.
This expects a service to only implement a single interface.
@param string $service_class
The fully-qualified class name of the service.
@return string
The fully-qualified name of the interface with the initial '\', or an
empty string if no interface was found. | [
"Extracts",
"the",
"interface",
"from",
"the",
"service",
"class",
"using",
"reflection",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/ServicesCollector.php#L235-L276 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/ServicesCollector.php | ServicesCollector.getStaticContainerServices | protected function getStaticContainerServices() {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
// We can get service IDs from the container,
$static_container_reflection = new \ReflectionClass('\Drupal');
$filename = $static_container_reflection->getFileName();
$source = file($filename);
$methods = $static_container_reflection->getMethods();
$service_definitions = [];
foreach ($methods as $method) {
$name = $method->getName();
// Skip any which have parameters: the service getter methods have no
// parameters.
if ($method->getNumberOfParameters() > 0) {
continue;
}
$start_line = $method->getStartLine();
$end_line = $method->getEndLine();
// Skip any which have more than 2 lines: the service getter methods have
// only 1 line of code.
if ($end_line - $start_line > 2) {
continue;
}
// Get the single code line.
$code_line = $source[$start_line];
// Extract the service ID from the call to getContainer().
$matches = [];
$code_line_regex = "@return static::getContainer\(\)->get\('([\w.]+)'\);@";
if (!preg_match($code_line_regex, $code_line, $matches)) {
continue;
}
$service_id = $matches[1];
$docblock = $method->getDocComment();
// Extract the interface for the service from the docblock @return.
$matches = [];
preg_match("[@return (.+)]", $docblock, $matches);
$interface = $matches[1];
// Extract a description from the docblock first line.
$docblock_lines = explode("\n", $docblock);
$doc_first_line = $docblock_lines[1];
$matches = [];
preg_match("@(the (.*))\.@", $doc_first_line, $matches);
$description = ucfirst($matches[1]);
$label = ucfirst($matches[2]);
$definition = $container_builder->getDefinition($service_id);
$service_definition = [
'id' => $service_id,
'label' => $label,
'static_method' => $name, // not used.
'class' => '\\' . $definition->getClass(),
'interface' => $interface,
'description' => $description,
];
$service_definitions[$service_id] = $service_definition;
}
// Sort by ID.
ksort($service_definitions);
return $service_definitions;
} | php | protected function getStaticContainerServices() {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
// We can get service IDs from the container,
$static_container_reflection = new \ReflectionClass('\Drupal');
$filename = $static_container_reflection->getFileName();
$source = file($filename);
$methods = $static_container_reflection->getMethods();
$service_definitions = [];
foreach ($methods as $method) {
$name = $method->getName();
// Skip any which have parameters: the service getter methods have no
// parameters.
if ($method->getNumberOfParameters() > 0) {
continue;
}
$start_line = $method->getStartLine();
$end_line = $method->getEndLine();
// Skip any which have more than 2 lines: the service getter methods have
// only 1 line of code.
if ($end_line - $start_line > 2) {
continue;
}
// Get the single code line.
$code_line = $source[$start_line];
// Extract the service ID from the call to getContainer().
$matches = [];
$code_line_regex = "@return static::getContainer\(\)->get\('([\w.]+)'\);@";
if (!preg_match($code_line_regex, $code_line, $matches)) {
continue;
}
$service_id = $matches[1];
$docblock = $method->getDocComment();
// Extract the interface for the service from the docblock @return.
$matches = [];
preg_match("[@return (.+)]", $docblock, $matches);
$interface = $matches[1];
// Extract a description from the docblock first line.
$docblock_lines = explode("\n", $docblock);
$doc_first_line = $docblock_lines[1];
$matches = [];
preg_match("@(the (.*))\.@", $doc_first_line, $matches);
$description = ucfirst($matches[1]);
$label = ucfirst($matches[2]);
$definition = $container_builder->getDefinition($service_id);
$service_definition = [
'id' => $service_id,
'label' => $label,
'static_method' => $name, // not used.
'class' => '\\' . $definition->getClass(),
'interface' => $interface,
'description' => $description,
];
$service_definitions[$service_id] = $service_definition;
}
// Sort by ID.
ksort($service_definitions);
return $service_definitions;
} | [
"protected",
"function",
"getStaticContainerServices",
"(",
")",
"{",
"$",
"container_builder",
"=",
"$",
"this",
"->",
"containerBuilderGetter",
"->",
"getContainerBuilder",
"(",
")",
";",
"// We can get service IDs from the container,",
"$",
"static_container_reflection",
... | Get data on services from the static container.
This examines the \Drupal static helper using reflection, and extracts
data from the helper methods that return services.
@return array
An array of service data. | [
"Get",
"data",
"on",
"services",
"from",
"the",
"static",
"container",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/ServicesCollector.php#L287-L359 | train |
drupal-code-builder/drupal-code-builder | Storage/StorageBase.php | StorageBase.delete | public function delete($key) {
$directory = $this->environment->getHooksDirectory();
$data_file = "$directory/{$key}_processed.php";
if (file_exists($data_file)) {
unlink($data_file);
}
} | php | public function delete($key) {
$directory = $this->environment->getHooksDirectory();
$data_file = "$directory/{$key}_processed.php";
if (file_exists($data_file)) {
unlink($data_file);
}
} | [
"public",
"function",
"delete",
"(",
"$",
"key",
")",
"{",
"$",
"directory",
"=",
"$",
"this",
"->",
"environment",
"->",
"getHooksDirectory",
"(",
")",
";",
"$",
"data_file",
"=",
"\"$directory/{$key}_processed.php\"",
";",
"if",
"(",
"file_exists",
"(",
"$... | Deletes a data file, if it exists.
Does not give any indication if the deletion failed.
@param string $key
The indentifier for the data, e.g. 'hooks'. | [
"Deletes",
"a",
"data",
"file",
"if",
"it",
"exists",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Storage/StorageBase.php#L63-L70 | train |
drupal-code-builder/drupal-code-builder | Generator/Render/FluentMethodCall.php | FluentMethodCall.getCodeLines | public function getCodeLines() {
// Add a terminal ';' to the last of the fluent method calls.
$this->lines[count($this->lines) - 1] .= ';';
$this->lines = $this->indentCodeLines($this->lines);
return $this->lines;
} | php | public function getCodeLines() {
// Add a terminal ';' to the last of the fluent method calls.
$this->lines[count($this->lines) - 1] .= ';';
$this->lines = $this->indentCodeLines($this->lines);
return $this->lines;
} | [
"public",
"function",
"getCodeLines",
"(",
")",
"{",
"// Add a terminal ';' to the last of the fluent method calls.",
"$",
"this",
"->",
"lines",
"[",
"count",
"(",
"$",
"this",
"->",
"lines",
")",
"-",
"1",
"]",
".=",
"';'",
";",
"$",
"this",
"->",
"lines",
... | Completes rendering and returns the code lines.
@return string[]
The code lines, indented and with a final ';'. | [
"Completes",
"rendering",
"and",
"returns",
"the",
"code",
"lines",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Render/FluentMethodCall.php#L111-L118 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/DataTypesCollector.php | DataTypesCollector.collect | public function collect($job_list) {
// TODO: is there an API for reading this file? Where?
$definition_file = 'core/config/schema/core.data_types.schema.yml';
$yml = file_get_contents($definition_file);
$value = Yaml::parse($yml);
$data_types = [];
foreach ($value as $type => $definition_item) {
// Skip the special types.
if ($type == 'undefined' || $type == 'ignore') {
continue;
}
// Skip compound types, until we figure out which ones we want.
if (isset($definition_item['mapping'])) {
continue;
}
if (isset($definition_item['sequence'])) {
continue;
}
// Skip types with a wildcard in the name.
if (strpos($type, '*') !== FALSE) {
continue;
}
// Skip types that are to do with fields.
if (substr($type, 0, strlen('field.')) == 'field.') {
continue;
}
// Skip types that don't seem like they should be used for config
// entities (??).
if (substr($type, - strlen('settings')) == 'settings') {
continue;
}
if (strpos($type, 'date_format') !== FALSE) {
continue;
}
$data_types[$type] = [
'type' => $type,
'label' => $definition_item['label'],
];
}
ksort($data_types);
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$data_types = array_intersect_key($data_types, $this->testingDataTypes);
}
return $data_types;
} | php | public function collect($job_list) {
// TODO: is there an API for reading this file? Where?
$definition_file = 'core/config/schema/core.data_types.schema.yml';
$yml = file_get_contents($definition_file);
$value = Yaml::parse($yml);
$data_types = [];
foreach ($value as $type => $definition_item) {
// Skip the special types.
if ($type == 'undefined' || $type == 'ignore') {
continue;
}
// Skip compound types, until we figure out which ones we want.
if (isset($definition_item['mapping'])) {
continue;
}
if (isset($definition_item['sequence'])) {
continue;
}
// Skip types with a wildcard in the name.
if (strpos($type, '*') !== FALSE) {
continue;
}
// Skip types that are to do with fields.
if (substr($type, 0, strlen('field.')) == 'field.') {
continue;
}
// Skip types that don't seem like they should be used for config
// entities (??).
if (substr($type, - strlen('settings')) == 'settings') {
continue;
}
if (strpos($type, 'date_format') !== FALSE) {
continue;
}
$data_types[$type] = [
'type' => $type,
'label' => $definition_item['label'],
];
}
ksort($data_types);
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$data_types = array_intersect_key($data_types, $this->testingDataTypes);
}
return $data_types;
} | [
"public",
"function",
"collect",
"(",
"$",
"job_list",
")",
"{",
"// TODO: is there an API for reading this file? Where?",
"$",
"definition_file",
"=",
"'core/config/schema/core.data_types.schema.yml'",
";",
"$",
"yml",
"=",
"file_get_contents",
"(",
"$",
"definition_file",
... | Collect data on data types.
@return array
An array keyed by the type ID, where the value is an array with:
- 'type': The type ID.
- 'label': The label. | [
"Collect",
"data",
"on",
"data",
"types",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/DataTypesCollector.php#L59-L113 | train |
drupal-code-builder/drupal-code-builder | Generator/Plugin.php | Plugin.getClassDocBlockLines | protected function getClassDocBlockLines() {
$docblock_lines = parent::getClassDocBlockLines();
// Do not include the annotation if this plugin is a class override.
if (!empty($this->component_data['replace_parent_plugin'])) {
return $docblock_lines;
}
$docblock_lines[] = '';
$docblock_lines = array_merge($docblock_lines, $this->classAnnotation());
return $docblock_lines;
} | php | protected function getClassDocBlockLines() {
$docblock_lines = parent::getClassDocBlockLines();
// Do not include the annotation if this plugin is a class override.
if (!empty($this->component_data['replace_parent_plugin'])) {
return $docblock_lines;
}
$docblock_lines[] = '';
$docblock_lines = array_merge($docblock_lines, $this->classAnnotation());
return $docblock_lines;
} | [
"protected",
"function",
"getClassDocBlockLines",
"(",
")",
"{",
"$",
"docblock_lines",
"=",
"parent",
"::",
"getClassDocBlockLines",
"(",
")",
";",
"// Do not include the annotation if this plugin is a class override.",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
... | Procudes the docblock for the class. | [
"Procudes",
"the",
"docblock",
"for",
"the",
"class",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Plugin.php#L288-L301 | train |
drupal-code-builder/drupal-code-builder | Generator/Plugin.php | Plugin.classAnnotation | function classAnnotation() {
$annotation_class_path = explode('\\', $this->component_data['plugin_type_data']['plugin_definition_annotation_name']);
$annotation_class = array_pop($annotation_class_path);
// Special case: annotation that's just the plugin ID.
if (!empty($this->component_data['plugin_type_data']['annotation_id_only'])) {
$annotation = ClassAnnotation::{$annotation_class}($this->component_data['plugin_name']);
$annotation_lines = $annotation->render();
return $annotation_lines;
}
$annotation_variables = $this->component_data['plugin_type_data']['plugin_properties'];
$annotation_data = [];
foreach ($annotation_variables as $annotation_variable => $annotation_variable_info) {
if ($annotation_variable == 'id') {
$annotation_data['id'] = $this->component_data['plugin_name'];
continue;
}
// Hacky workaround for https://github.com/drupal-code-builder/drupal-code-builder/issues/97.
if (isset($annotation_variable_info['type']) && $annotation_variable_info['type'] == '\Drupal\Core\Annotation\Translation') {
// The annotation property value is translated.
$annotation_data[$annotation_variable] = ClassAnnotation::Translation("TODO: replace this with a value");
continue;
}
// It's a plain string.
$annotation_data[$annotation_variable] = "TODO: replace this with a value";
}
$annotation = ClassAnnotation::{$annotation_class}($annotation_data);
$annotation_lines = $annotation->render();
return $annotation_lines;
} | php | function classAnnotation() {
$annotation_class_path = explode('\\', $this->component_data['plugin_type_data']['plugin_definition_annotation_name']);
$annotation_class = array_pop($annotation_class_path);
// Special case: annotation that's just the plugin ID.
if (!empty($this->component_data['plugin_type_data']['annotation_id_only'])) {
$annotation = ClassAnnotation::{$annotation_class}($this->component_data['plugin_name']);
$annotation_lines = $annotation->render();
return $annotation_lines;
}
$annotation_variables = $this->component_data['plugin_type_data']['plugin_properties'];
$annotation_data = [];
foreach ($annotation_variables as $annotation_variable => $annotation_variable_info) {
if ($annotation_variable == 'id') {
$annotation_data['id'] = $this->component_data['plugin_name'];
continue;
}
// Hacky workaround for https://github.com/drupal-code-builder/drupal-code-builder/issues/97.
if (isset($annotation_variable_info['type']) && $annotation_variable_info['type'] == '\Drupal\Core\Annotation\Translation') {
// The annotation property value is translated.
$annotation_data[$annotation_variable] = ClassAnnotation::Translation("TODO: replace this with a value");
continue;
}
// It's a plain string.
$annotation_data[$annotation_variable] = "TODO: replace this with a value";
}
$annotation = ClassAnnotation::{$annotation_class}($annotation_data);
$annotation_lines = $annotation->render();
return $annotation_lines;
} | [
"function",
"classAnnotation",
"(",
")",
"{",
"$",
"annotation_class_path",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"this",
"->",
"component_data",
"[",
"'plugin_type_data'",
"]",
"[",
"'plugin_definition_annotation_name'",
"]",
")",
";",
"$",
"annotation_class",
... | Produces the plugin class annotation lines.
@return
An array of lines suitable for docBlock(). | [
"Produces",
"the",
"plugin",
"class",
"annotation",
"lines",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Plugin.php#L309-L346 | train |
drupal-code-builder/drupal-code-builder | Generator/PluginTrait.php | PluginTrait.getPluginTypePropertyDefinition | protected static function getPluginTypePropertyDefinition() {
return [
'label' => 'Plugin type',
'description' => "The identifier of the plugin type. This can be either the manager service name with the 'plugin.manager.' prefix removed, " .
' or the subdirectory name.',
'required' => TRUE,
'options' => function(&$property_info) {
$mb_task_handler_report_plugins = \DrupalCodeBuilder\Factory::getTask('ReportPluginData');
$options = $mb_task_handler_report_plugins->listPluginNamesOptions(static::$discoveryType);
return $options;
},
'processing' => function($value, &$component_data, $property_name, &$property_info) {
// Validate the plugin type, and find it if given a folder rather than
// a type.
$task_report_plugins = \DrupalCodeBuilder\Factory::getTask('ReportPluginData');
$plugin_types_data = $task_report_plugins->listPluginData(static::$discoveryType);
// Try to find the intended plugin type.
if (isset($plugin_types_data[$value])) {
$plugin_data = $plugin_types_data[$value];
}
else {
// Convert a namespace separator into a directory separator.
$value = str_replace('\\', '/', $value);
$plugin_types_data_by_subdirectory = $task_report_plugins->listPluginDataBySubdirectory();
if (isset($plugin_types_data_by_subdirectory[$value])) {
$plugin_data = $plugin_types_data_by_subdirectory[$value];
// Set the plugin ID in the the property.
$component_data[$property_name] = $plugin_data['type_id'];
}
else {
// Nothing found. Throw exception.
$discovery_type = static::$discoveryType;
throw new InvalidInputException("Plugin type {$value} not found in list of {$discovery_type} plugins.");
}
}
// Set the plugin type data.
// Bit of a cheat, as undeclared data property!
$component_data['plugin_type_data'] = $plugin_data;
// Set the relative qualified class name.
// The full class name will be of the form:
// \Drupal\{MODULE}\Plugin\{PLUGINTYPE}\{PLUGINNAME}
// where PLUGINNAME has any derivative prefix stripped.
if (strpos($component_data['plugin_name'], ':') === FALSE) {
$plugin_id = $component_data['plugin_name'];
}
else {
list (, $plugin_id) = explode(':', $component_data['plugin_name']);
}
$plugin_id_pascal = CaseString::snake($plugin_id)->pascal();
$component_data['plugin_name'];
$plugin_id_without_prefix = $component_data['plugin_name'];
$component_data['relative_class_name'] = array_merge(
// Plugin subdirectory.
self::pathToNamespacePieces($plugin_data['subdir']),
// Plugin ID.
[ $plugin_id_pascal ]
);
},
];
} | php | protected static function getPluginTypePropertyDefinition() {
return [
'label' => 'Plugin type',
'description' => "The identifier of the plugin type. This can be either the manager service name with the 'plugin.manager.' prefix removed, " .
' or the subdirectory name.',
'required' => TRUE,
'options' => function(&$property_info) {
$mb_task_handler_report_plugins = \DrupalCodeBuilder\Factory::getTask('ReportPluginData');
$options = $mb_task_handler_report_plugins->listPluginNamesOptions(static::$discoveryType);
return $options;
},
'processing' => function($value, &$component_data, $property_name, &$property_info) {
// Validate the plugin type, and find it if given a folder rather than
// a type.
$task_report_plugins = \DrupalCodeBuilder\Factory::getTask('ReportPluginData');
$plugin_types_data = $task_report_plugins->listPluginData(static::$discoveryType);
// Try to find the intended plugin type.
if (isset($plugin_types_data[$value])) {
$plugin_data = $plugin_types_data[$value];
}
else {
// Convert a namespace separator into a directory separator.
$value = str_replace('\\', '/', $value);
$plugin_types_data_by_subdirectory = $task_report_plugins->listPluginDataBySubdirectory();
if (isset($plugin_types_data_by_subdirectory[$value])) {
$plugin_data = $plugin_types_data_by_subdirectory[$value];
// Set the plugin ID in the the property.
$component_data[$property_name] = $plugin_data['type_id'];
}
else {
// Nothing found. Throw exception.
$discovery_type = static::$discoveryType;
throw new InvalidInputException("Plugin type {$value} not found in list of {$discovery_type} plugins.");
}
}
// Set the plugin type data.
// Bit of a cheat, as undeclared data property!
$component_data['plugin_type_data'] = $plugin_data;
// Set the relative qualified class name.
// The full class name will be of the form:
// \Drupal\{MODULE}\Plugin\{PLUGINTYPE}\{PLUGINNAME}
// where PLUGINNAME has any derivative prefix stripped.
if (strpos($component_data['plugin_name'], ':') === FALSE) {
$plugin_id = $component_data['plugin_name'];
}
else {
list (, $plugin_id) = explode(':', $component_data['plugin_name']);
}
$plugin_id_pascal = CaseString::snake($plugin_id)->pascal();
$component_data['plugin_name'];
$plugin_id_without_prefix = $component_data['plugin_name'];
$component_data['relative_class_name'] = array_merge(
// Plugin subdirectory.
self::pathToNamespacePieces($plugin_data['subdir']),
// Plugin ID.
[ $plugin_id_pascal ]
);
},
];
} | [
"protected",
"static",
"function",
"getPluginTypePropertyDefinition",
"(",
")",
"{",
"return",
"[",
"'label'",
"=>",
"'Plugin type'",
",",
"'description'",
"=>",
"\"The identifier of the plugin type. This can be either the manager service name with the 'plugin.manager.' prefix removed,... | Provides the property definition for the plugin type property.
@return array
A property definition array. | [
"Provides",
"the",
"property",
"definition",
"for",
"the",
"plugin",
"type",
"property",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PluginTrait.php#L21-L89 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentDataInfoGatherer.php | ComponentDataInfoGatherer.getComponentDataInfo | public function getComponentDataInfo($component_type, $include_internal = FALSE) {
$properties = $this->classHandler->getComponentDataDefinition($component_type);
$properties_processed = $this->processPropertyList($properties, $include_internal);
return $properties_processed;
} | php | public function getComponentDataInfo($component_type, $include_internal = FALSE) {
$properties = $this->classHandler->getComponentDataDefinition($component_type);
$properties_processed = $this->processPropertyList($properties, $include_internal);
return $properties_processed;
} | [
"public",
"function",
"getComponentDataInfo",
"(",
"$",
"component_type",
",",
"$",
"include_internal",
"=",
"FALSE",
")",
"{",
"$",
"properties",
"=",
"$",
"this",
"->",
"classHandler",
"->",
"getComponentDataDefinition",
"(",
"$",
"component_type",
")",
";",
"... | Get a list of the properties that are required in the component data.
This adds in default values, recurses into child components, and filters
out computed values so they are not available to UIs.
@param $component_type
The component type to get properties for. Compound properties are
recursed into.
@param $include_internal
(optional) Boolean indicating whether to include internal properties.
These are the properties marked as either 'computed' or 'internal'.
Defaults to FALSE.
@return
An array containing information about the properties this component needs
in its $component_data array. Keys are the names of properties. Each value
is an array of information for the property.
@see BaseGenerator::componentDataDefinition()
@see BaseGenerator::prepareComponentDataProperty()
@see BaseGenerator::processComponentData() | [
"Get",
"a",
"list",
"of",
"the",
"properties",
"that",
"are",
"required",
"in",
"the",
"component",
"data",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentDataInfoGatherer.php#L87-L93 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentDataInfoGatherer.php | ComponentDataInfoGatherer.processPropertyList | protected function processPropertyList($properties, $include_internal) {
$return = [];
// Track the primary property so we can check there is not more than one.
$primary = NULL;
foreach ($properties as $property_name => $property_info) {
// Check there is no more than one property set as primary.
if (!empty($property_info['primary'])) {
assert(is_null($primary), "Property {$primary} already set as primary, but so is {$property_name}.");
$primary = $property_name;
}
// Skip computed and internal if not requested.
if (!$include_internal) {
if (!empty($property_info['computed']) ||
!empty($property_info['internal']) ||
!empty($property_info['acquired'])
) {
continue;
}
}
// Add defaults.
// We add these for internal properties as well, even though UIs won't
// see them, for our own convenience of not having to check whether
// keys such as 'format' are set.
$this->componentDataInfoAddDefaults($property_info);
// Expand compound properties..
if ($property_info['format'] == 'compound') {
if (isset($property_info['component_type'])) {
// Properties that use a generator.
$component_type = $property_info['component_type'];
// Recurse to get the child properties.
$child_properties = $this->getComponentDataInfo($component_type, $include_internal);
$property_info['properties'] = $child_properties;
}
else {
// Recurse into the child properties list.
$property_info['properties'] = $this->processPropertyList($property_info['properties'], $include_internal);
}
}
$return[$property_name] = $property_info;
}
return $return;
} | php | protected function processPropertyList($properties, $include_internal) {
$return = [];
// Track the primary property so we can check there is not more than one.
$primary = NULL;
foreach ($properties as $property_name => $property_info) {
// Check there is no more than one property set as primary.
if (!empty($property_info['primary'])) {
assert(is_null($primary), "Property {$primary} already set as primary, but so is {$property_name}.");
$primary = $property_name;
}
// Skip computed and internal if not requested.
if (!$include_internal) {
if (!empty($property_info['computed']) ||
!empty($property_info['internal']) ||
!empty($property_info['acquired'])
) {
continue;
}
}
// Add defaults.
// We add these for internal properties as well, even though UIs won't
// see them, for our own convenience of not having to check whether
// keys such as 'format' are set.
$this->componentDataInfoAddDefaults($property_info);
// Expand compound properties..
if ($property_info['format'] == 'compound') {
if (isset($property_info['component_type'])) {
// Properties that use a generator.
$component_type = $property_info['component_type'];
// Recurse to get the child properties.
$child_properties = $this->getComponentDataInfo($component_type, $include_internal);
$property_info['properties'] = $child_properties;
}
else {
// Recurse into the child properties list.
$property_info['properties'] = $this->processPropertyList($property_info['properties'], $include_internal);
}
}
$return[$property_name] = $property_info;
}
return $return;
} | [
"protected",
"function",
"processPropertyList",
"(",
"$",
"properties",
",",
"$",
"include_internal",
")",
"{",
"$",
"return",
"=",
"[",
"]",
";",
"// Track the primary property so we can check there is not more than one.",
"$",
"primary",
"=",
"NULL",
";",
"foreach",
... | Process a property list to add default keys and filter out internals.
@param $properties
A property list, in the foramt returned from componentDataDefinition().
@param $include_internal
(optional) The parameter from getComponentDataInfo().
@return
The given property list, with defaults filled in and internal properties
removed if requested. | [
"Process",
"a",
"property",
"list",
"to",
"add",
"default",
"keys",
"and",
"filter",
"out",
"internals",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentDataInfoGatherer.php#L107-L158 | train |
drupal-code-builder/drupal-code-builder | Generator/PHPInterfaceFile.php | PHPInterfaceFile.class_declaration | function class_declaration() {
$line = '';
$line .= "interface {$this->component_data['plain_class_name']}";
if ($this->component_data['parent_interface_names']) {
$line .= ' extends ';
$line .= implode(', ', $this->component_data['parent_interface_names']);
}
$line .= ' {';
return [
$line,
];
} | php | function class_declaration() {
$line = '';
$line .= "interface {$this->component_data['plain_class_name']}";
if ($this->component_data['parent_interface_names']) {
$line .= ' extends ';
$line .= implode(', ', $this->component_data['parent_interface_names']);
}
$line .= ' {';
return [
$line,
];
} | [
"function",
"class_declaration",
"(",
")",
"{",
"$",
"line",
"=",
"''",
";",
"$",
"line",
".=",
"\"interface {$this->component_data['plain_class_name']}\"",
";",
"if",
"(",
"$",
"this",
"->",
"component_data",
"[",
"'parent_interface_names'",
"]",
")",
"{",
"$",
... | Produces the interface declaration. | [
"Produces",
"the",
"interface",
"declaration",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/PHPInterfaceFile.php#L38-L50 | train |
drupal-code-builder/drupal-code-builder | Task/Collect.php | Collect.getJobList | public function getJobList() {
$job_list = [];
foreach ($this->collectorClassNames as $collector_class_name) {
// Get the list of jobs from each collector.
$collector_helper = $this->getHelper($collector_class_name);
$collector_job_list = $collector_helper->getJobList();
if (is_null($collector_job_list)) {
// Collector doesn't support jobs: create just a single job for it.
$job_list[] = [
'collector' => $collector_class_name,
'process_label' => $collector_helper->getReportingKey(),
// A singleton job is by definition the last one.
// Simpler to do this and have the analysis waste time trying to load
// a temporary file than add special handling for singleton jobs.
'last' => TRUE,
];
}
else {
array_walk($collector_job_list, function(&$item) use ($collector_class_name) {
$item['collector'] = $collector_class_name;
});
// Mark the final one so we know when to write the data to the
// permanent location.
$keys = array_keys($collector_job_list);
$last_index = end($keys);
$collector_job_list[$last_index]['last'] = TRUE;
$job_list = array_merge($job_list, $collector_job_list);
}
}
return $job_list;
} | php | public function getJobList() {
$job_list = [];
foreach ($this->collectorClassNames as $collector_class_name) {
// Get the list of jobs from each collector.
$collector_helper = $this->getHelper($collector_class_name);
$collector_job_list = $collector_helper->getJobList();
if (is_null($collector_job_list)) {
// Collector doesn't support jobs: create just a single job for it.
$job_list[] = [
'collector' => $collector_class_name,
'process_label' => $collector_helper->getReportingKey(),
// A singleton job is by definition the last one.
// Simpler to do this and have the analysis waste time trying to load
// a temporary file than add special handling for singleton jobs.
'last' => TRUE,
];
}
else {
array_walk($collector_job_list, function(&$item) use ($collector_class_name) {
$item['collector'] = $collector_class_name;
});
// Mark the final one so we know when to write the data to the
// permanent location.
$keys = array_keys($collector_job_list);
$last_index = end($keys);
$collector_job_list[$last_index]['last'] = TRUE;
$job_list = array_merge($job_list, $collector_job_list);
}
}
return $job_list;
} | [
"public",
"function",
"getJobList",
"(",
")",
"{",
"$",
"job_list",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"collectorClassNames",
"as",
"$",
"collector_class_name",
")",
"{",
"// Get the list of jobs from each collector.",
"$",
"collector_helper",
... | Get the list of analysis jobs, to use for incremental analysis.
@return array
A numeric array of jobs. Each job is itself an array, whose details are
internal except for the following keys:
- 'process_label': A human-readable string describing the process being
run. This should be the same for each job from a particular collector.
- 'item_label': A human-readable string for the particular item. This
will be empty if the process has only a single job. | [
"Get",
"the",
"list",
"of",
"analysis",
"jobs",
"to",
"use",
"for",
"incremental",
"analysis",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect.php#L53-L88 | train |
drupal-code-builder/drupal-code-builder | Task/Collect.php | Collect.collectComponentDataIncremental | public function collectComponentDataIncremental($job_list, &$results) {
// Populate an array of incremental data that we collect for the given job
// list, so array_merge() works.
$incremental_data = array_fill_keys($this->collectorClassNames, []);
// Keep track of any jobs which are the last for their collector, so we
// know to write to the real storage file rather than temporary.
$final_jobs = [];
// Group the jobs by collector.
$grouped_jobs = [];
foreach ($job_list as $job) {
$collector_class_name = $job['collector'];
$grouped_jobs[$collector_class_name][] = $job;
}
// Pass each set of jobs to its respective collective.
foreach ($grouped_jobs as $collector_class_name => $jobs) {
$collector_helper = $this->getHelper($collector_class_name);
$incremental_data[$collector_class_name] = $collector_helper->collect($jobs);
$last_job = end($jobs);
if (!empty($last_job['last'])) {
$final_jobs[$collector_class_name] = TRUE;
}
}
// Save the data for each collector.
$storage = $this->environment->getStorage();
foreach ($incremental_data as $collector_name => $collector_incremental_data) {
// We have a key for every collector in $incremental_data, but have not
// necessarily run jobs for that collector in this batch. Skip if empty.
if (empty($collector_incremental_data)) {
continue;
}
$collector_helper = $this->getHelper($collector_name);
$storage_key = $collector_helper->getSaveDataKey();
$temporary_storage_key = $storage_key . '_temporary';
// Merge what we've just collected for this collector with what we've
// collected on previous calls to this method.
$data = $storage->retrieve($temporary_storage_key);
$data = $collector_helper->mergeComponentData($data, $collector_incremental_data);
if (isset($final_jobs[$collector_name])) {
// We've done the final job for this collector. Store the data
// accumulated so far into the permanent file, and clean up the
// temporary file.
$storage->store($storage_key, $data);
$storage->delete($temporary_storage_key);
// Add the count to the results.
$collector_count = $collector_helper->getDataCount($data);
$results[$collector_helper->getReportingKey()] = $collector_count;
}
else {
$storage->store($temporary_storage_key, $data);
}
}
} | php | public function collectComponentDataIncremental($job_list, &$results) {
// Populate an array of incremental data that we collect for the given job
// list, so array_merge() works.
$incremental_data = array_fill_keys($this->collectorClassNames, []);
// Keep track of any jobs which are the last for their collector, so we
// know to write to the real storage file rather than temporary.
$final_jobs = [];
// Group the jobs by collector.
$grouped_jobs = [];
foreach ($job_list as $job) {
$collector_class_name = $job['collector'];
$grouped_jobs[$collector_class_name][] = $job;
}
// Pass each set of jobs to its respective collective.
foreach ($grouped_jobs as $collector_class_name => $jobs) {
$collector_helper = $this->getHelper($collector_class_name);
$incremental_data[$collector_class_name] = $collector_helper->collect($jobs);
$last_job = end($jobs);
if (!empty($last_job['last'])) {
$final_jobs[$collector_class_name] = TRUE;
}
}
// Save the data for each collector.
$storage = $this->environment->getStorage();
foreach ($incremental_data as $collector_name => $collector_incremental_data) {
// We have a key for every collector in $incremental_data, but have not
// necessarily run jobs for that collector in this batch. Skip if empty.
if (empty($collector_incremental_data)) {
continue;
}
$collector_helper = $this->getHelper($collector_name);
$storage_key = $collector_helper->getSaveDataKey();
$temporary_storage_key = $storage_key . '_temporary';
// Merge what we've just collected for this collector with what we've
// collected on previous calls to this method.
$data = $storage->retrieve($temporary_storage_key);
$data = $collector_helper->mergeComponentData($data, $collector_incremental_data);
if (isset($final_jobs[$collector_name])) {
// We've done the final job for this collector. Store the data
// accumulated so far into the permanent file, and clean up the
// temporary file.
$storage->store($storage_key, $data);
$storage->delete($temporary_storage_key);
// Add the count to the results.
$collector_count = $collector_helper->getDataCount($data);
$results[$collector_helper->getReportingKey()] = $collector_count;
}
else {
$storage->store($temporary_storage_key, $data);
}
}
} | [
"public",
"function",
"collectComponentDataIncremental",
"(",
"$",
"job_list",
",",
"&",
"$",
"results",
")",
"{",
"// Populate an array of incremental data that we collect for the given job",
"// list, so array_merge() works.",
"$",
"incremental_data",
"=",
"array_fill_keys",
"(... | Perform a batch of incremental analysis.
@param array $job_list
A subset of the job list returned by getJobList().
@param array &$results
An array of results, passed by reference, into which an ongoing summary
of the analysis is set. Once all jobs have been passed into successive
calls of this method, this parameter will be identical to the return
value of collectComponentData(). | [
"Perform",
"a",
"batch",
"of",
"incremental",
"analysis",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect.php#L101-L164 | train |
drupal-code-builder/drupal-code-builder | Task/Collect.php | Collect.collectComponentData | public function collectComponentData() {
$result = [];
// Allow each of our declared collectors to perform its work.
foreach ($this->collectorClassNames as $collector_class_name) {
$collector_helper = $this->getHelper($collector_class_name);
// Get the list of jobs.
// (In 3.3.x, this list will be exposed to the API, so UIs can run the
// analysis in batches.)
$job_list = $collector_helper->getJobList();
$collector_data = $collector_helper->collect($job_list);
// Save the data.
$this->environment->getStorage()->store($collector_helper->getSaveDataKey(), $collector_data);
// Add the count to the results.
$count = $collector_helper->getDataCount($collector_data);
$result[$collector_helper->getReportingKey()] = $count;
}
return $result;
} | php | public function collectComponentData() {
$result = [];
// Allow each of our declared collectors to perform its work.
foreach ($this->collectorClassNames as $collector_class_name) {
$collector_helper = $this->getHelper($collector_class_name);
// Get the list of jobs.
// (In 3.3.x, this list will be exposed to the API, so UIs can run the
// analysis in batches.)
$job_list = $collector_helper->getJobList();
$collector_data = $collector_helper->collect($job_list);
// Save the data.
$this->environment->getStorage()->store($collector_helper->getSaveDataKey(), $collector_data);
// Add the count to the results.
$count = $collector_helper->getDataCount($collector_data);
$result[$collector_helper->getReportingKey()] = $count;
}
return $result;
} | [
"public",
"function",
"collectComponentData",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"// Allow each of our declared collectors to perform its work.",
"foreach",
"(",
"$",
"this",
"->",
"collectorClassNames",
"as",
"$",
"collector_class_name",
")",
"{",
"$",... | Collect data about Drupal components from the current site's codebase.
@return array
An array summarizing the collected data. Each key is a label, each value
is a count of that type of item. | [
"Collect",
"data",
"about",
"Drupal",
"components",
"from",
"the",
"current",
"site",
"s",
"codebase",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect.php#L173-L197 | train |
drupal-code-builder/drupal-code-builder | Environment/VersionHelper6.php | VersionHelper6.directoryPath | function directoryPath(&$directory) {
if (substr($directory, 0, 1) != '/') {
// Relative, and so assumed to be in Drupal's files folder: prepend this to
// the given directory.
// sanity check. need to verify /files exists before we do anything. see http://drupal.org/node/367138
$files = file_create_path();
file_check_directory($files, FILE_CREATE_DIRECTORY);
$directory = file_create_path($directory);
}
} | php | function directoryPath(&$directory) {
if (substr($directory, 0, 1) != '/') {
// Relative, and so assumed to be in Drupal's files folder: prepend this to
// the given directory.
// sanity check. need to verify /files exists before we do anything. see http://drupal.org/node/367138
$files = file_create_path();
file_check_directory($files, FILE_CREATE_DIRECTORY);
$directory = file_create_path($directory);
}
} | [
"function",
"directoryPath",
"(",
"&",
"$",
"directory",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"directory",
",",
"0",
",",
"1",
")",
"!=",
"'/'",
")",
"{",
"// Relative, and so assumed to be in Drupal's files folder: prepend this to",
"// the given directory.",
"... | Transforms a path into a path within the site files folder, if needed.
Eg, turns 'foo' into 'sites/default/foo'.
Absolute paths are unchanged. | [
"Transforms",
"a",
"path",
"into",
"a",
"path",
"within",
"the",
"site",
"files",
"folder",
"if",
"needed",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Environment/VersionHelper6.php#L20-L29 | train |
drupal-code-builder/drupal-code-builder | Environment/VersionHelper6.php | VersionHelper6.prepareDirectory | function prepareDirectory($directory) {
// Because we may have an absolute path whose base folders are not writable
// we can't use the standard recursive D6 pattern.
$pieces = explode('/', $directory);
// Work up through the folder's parentage until we find a directory that exists.
// (Or in other words, backwards in the array of pieces.)
$length = count($pieces);
for ($i = 0; $i < $length; $i++) {
//print $pieces[$length - $i];
$slice = array_slice($pieces, 0, $length - $i);
$path_slice = implode('/', $slice);
if (file_exists($path_slice)) {
$status = file_check_directory($path_slice, FILE_CREATE_DIRECTORY);
break;
}
}
// If we go right the way along to the base and still can't create a directory...
if ($i == $length) {
throw new \Exception(strtr("The directory !path cannot be created or is not writable", array(
'!path' => htmlspecialchars($path_slice, ENT_QUOTES, 'UTF-8'),
)));
}
// print "status: $status for $path_slice - i: $i\n";
// Now work back down (or in other words, along the array of pieces).
for ($j = $length - $i; $j < $length; $j++) {
$slice[] = $pieces[$j];
$path_slice = implode('/', $slice);
//print "$path_slice\n";
$status = file_check_directory($path_slice, FILE_CREATE_DIRECTORY);
}
if (!$status) {
throw new \Exception("The hooks directory cannot be created or is not writable.");
}
} | php | function prepareDirectory($directory) {
// Because we may have an absolute path whose base folders are not writable
// we can't use the standard recursive D6 pattern.
$pieces = explode('/', $directory);
// Work up through the folder's parentage until we find a directory that exists.
// (Or in other words, backwards in the array of pieces.)
$length = count($pieces);
for ($i = 0; $i < $length; $i++) {
//print $pieces[$length - $i];
$slice = array_slice($pieces, 0, $length - $i);
$path_slice = implode('/', $slice);
if (file_exists($path_slice)) {
$status = file_check_directory($path_slice, FILE_CREATE_DIRECTORY);
break;
}
}
// If we go right the way along to the base and still can't create a directory...
if ($i == $length) {
throw new \Exception(strtr("The directory !path cannot be created or is not writable", array(
'!path' => htmlspecialchars($path_slice, ENT_QUOTES, 'UTF-8'),
)));
}
// print "status: $status for $path_slice - i: $i\n";
// Now work back down (or in other words, along the array of pieces).
for ($j = $length - $i; $j < $length; $j++) {
$slice[] = $pieces[$j];
$path_slice = implode('/', $slice);
//print "$path_slice\n";
$status = file_check_directory($path_slice, FILE_CREATE_DIRECTORY);
}
if (!$status) {
throw new \Exception("The hooks directory cannot be created or is not writable.");
}
} | [
"function",
"prepareDirectory",
"(",
"$",
"directory",
")",
"{",
"// Because we may have an absolute path whose base folders are not writable",
"// we can't use the standard recursive D6 pattern.",
"$",
"pieces",
"=",
"explode",
"(",
"'/'",
",",
"$",
"directory",
")",
";",
"/... | Check that the directory exists and is writable, creating it if needed.
@throws
Exception | [
"Check",
"that",
"the",
"directory",
"exists",
"and",
"is",
"writable",
"creating",
"it",
"if",
"needed",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Environment/VersionHelper6.php#L37-L74 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/ServiceTagTypesCollector.php | ServiceTagTypesCollector.collect | public function collect($job_list) {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
$collectors_info = $this->getCollectorServiceIds($container_builder);
$data = [];
// Declare event subscriber services. These don't have collectors in Drupal
// as they are native to Symfony, so we need to declare explicitly.
$data['event_subscriber'] = [
'label' => 'Event subscriber',
'interface' => 'Symfony\Component\EventDispatcher\EventSubscriberInterface',
'methods' => $this->methodCollector->collectMethods('Symfony\Component\EventDispatcher\EventSubscriberInterface'),
// TODO: services of this type should go in the EventSubscriber namespace.
];
foreach ($collectors_info as $service_name => $tag_infos) {
// Sloppy array structure...
$collector_type = $tag_infos['collector_type'];
unset($tag_infos['collector_type']);
$service_definition = $container_builder->getDefinition($service_name);
$service_class = $service_definition->getClass();
// A single service collector service can collect on more than one tag.
foreach ($tag_infos as $tag_info) {
$tag = $tag_info['tag'];
if ($collector_type == 'service_id_collector') {
// Service ID collectors don't give us anything but the service ID,
// so nothing can be detected about the interface collected services
// should use.
// The only example of a service collector using this tag
// in core is 'theme.negotiator', which is self-consuming: it expects
// its tagged services to implement its own interface. So all we can
// do is assume other implementations will do the same.
$service_class_reflection = new \ReflectionClass($service_class);
$label = CaseString::pascal($service_class_reflection->getShortName())->title();
// Hope there's only one interface...
$service_interfaces = $service_class_reflection->getInterfaceNames();
$collected_services_interface = array_shift($service_interfaces);
$interface_methods = $this->methodCollector->collectMethods($collected_services_interface);
}
else {
// Service collectors tell us what the container should call on the
// collector to add a tagged service, and so from that we can deduce
// the interface that tagged services must implement.
if (!isset($tag_info['call'])) {
// Shouldn't normally happen, but protected against badly-declated
// services.
continue;
}
$collecting_method = $tag_info['call'];
$collecting_methodR = new \ReflectionMethod($service_class, $collecting_method);
$collecting_method_paramR = $collecting_methodR->getParameters();
// TODO: skip if more than 1 param.
// getNumberOfParameters
$collected_services_interface = (string) $collecting_method_paramR[0]->getType();
if (!interface_exists($collected_services_interface)) {
// Shouldn't happen, as the typehint will be an interface the
// collected services must implement.
continue;
}
// Make a label from the interface name: take the short interface name,
// and remove an 'Interface' suffix, convert to title case.
$interface_pieces = explode('\\', $collected_services_interface);
$label = array_pop($interface_pieces);
$label = preg_replace('@Interface$@', '', $label);
$label = CaseString::pascal($label)->title();
$interface_methods = $this->methodCollector->collectMethods($collected_services_interface);
}
$data[$tag] = [
'label' => $label,
'collector_type' => $collector_type,
'interface' => $collected_services_interface,
'methods' => $interface_methods,
];
}
}
// Sort by ID.
ksort($data);
return $data;
} | php | public function collect($job_list) {
$container_builder = $this->containerBuilderGetter->getContainerBuilder();
$collectors_info = $this->getCollectorServiceIds($container_builder);
$data = [];
// Declare event subscriber services. These don't have collectors in Drupal
// as they are native to Symfony, so we need to declare explicitly.
$data['event_subscriber'] = [
'label' => 'Event subscriber',
'interface' => 'Symfony\Component\EventDispatcher\EventSubscriberInterface',
'methods' => $this->methodCollector->collectMethods('Symfony\Component\EventDispatcher\EventSubscriberInterface'),
// TODO: services of this type should go in the EventSubscriber namespace.
];
foreach ($collectors_info as $service_name => $tag_infos) {
// Sloppy array structure...
$collector_type = $tag_infos['collector_type'];
unset($tag_infos['collector_type']);
$service_definition = $container_builder->getDefinition($service_name);
$service_class = $service_definition->getClass();
// A single service collector service can collect on more than one tag.
foreach ($tag_infos as $tag_info) {
$tag = $tag_info['tag'];
if ($collector_type == 'service_id_collector') {
// Service ID collectors don't give us anything but the service ID,
// so nothing can be detected about the interface collected services
// should use.
// The only example of a service collector using this tag
// in core is 'theme.negotiator', which is self-consuming: it expects
// its tagged services to implement its own interface. So all we can
// do is assume other implementations will do the same.
$service_class_reflection = new \ReflectionClass($service_class);
$label = CaseString::pascal($service_class_reflection->getShortName())->title();
// Hope there's only one interface...
$service_interfaces = $service_class_reflection->getInterfaceNames();
$collected_services_interface = array_shift($service_interfaces);
$interface_methods = $this->methodCollector->collectMethods($collected_services_interface);
}
else {
// Service collectors tell us what the container should call on the
// collector to add a tagged service, and so from that we can deduce
// the interface that tagged services must implement.
if (!isset($tag_info['call'])) {
// Shouldn't normally happen, but protected against badly-declated
// services.
continue;
}
$collecting_method = $tag_info['call'];
$collecting_methodR = new \ReflectionMethod($service_class, $collecting_method);
$collecting_method_paramR = $collecting_methodR->getParameters();
// TODO: skip if more than 1 param.
// getNumberOfParameters
$collected_services_interface = (string) $collecting_method_paramR[0]->getType();
if (!interface_exists($collected_services_interface)) {
// Shouldn't happen, as the typehint will be an interface the
// collected services must implement.
continue;
}
// Make a label from the interface name: take the short interface name,
// and remove an 'Interface' suffix, convert to title case.
$interface_pieces = explode('\\', $collected_services_interface);
$label = array_pop($interface_pieces);
$label = preg_replace('@Interface$@', '', $label);
$label = CaseString::pascal($label)->title();
$interface_methods = $this->methodCollector->collectMethods($collected_services_interface);
}
$data[$tag] = [
'label' => $label,
'collector_type' => $collector_type,
'interface' => $collected_services_interface,
'methods' => $interface_methods,
];
}
}
// Sort by ID.
ksort($data);
return $data;
} | [
"public",
"function",
"collect",
"(",
"$",
"job_list",
")",
"{",
"$",
"container_builder",
"=",
"$",
"this",
"->",
"containerBuilderGetter",
"->",
"getContainerBuilder",
"(",
")",
";",
"$",
"collectors_info",
"=",
"$",
"this",
"->",
"getCollectorServiceIds",
"("... | Collect data on tagged services.
@return
An array whose keys are service tags, and whose values arrays containing:
- 'label': A label for the tag.
- 'interface': The fully-qualified name (without leading slash) of the
interface that each tagged service must implement.
- 'methods': An array of the methods of this interface, in the same
format as returned by MethodCollector::collectMethods(). | [
"Collect",
"data",
"on",
"tagged",
"services",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/ServiceTagTypesCollector.php#L80-L175 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/ServiceTagTypesCollector.php | ServiceTagTypesCollector.getCollectorServiceIds | protected function getCollectorServiceIds(\Symfony\Component\DependencyInjection\TaggedContainerInterface $container_builder) {
// Get the details of all service collector services.
// Note that the docs for this method are completely wrong.
// Also, there are TWO possible tags for collectors, and the lazy version,
// 'service_id_collector', doesn't specify any data such as the 'call'
// property.
$service_collectors_info = $container_builder->findTaggedServiceIds('service_collector');
$service_id_collectors_info = $container_builder->findTaggedServiceIds('service_id_collector');
array_walk($service_collectors_info, function(&$item) {
$item['collector_type'] = 'service_collector';
});
array_walk($service_id_collectors_info, function(&$item) {
$item['collector_type'] = 'service_id_collector';
});
// We're going to assume that there is no collecting service that uses BOTH
// systems to collect two tags, that would be crazy.
$collectors_info = $service_collectors_info + $service_id_collectors_info;
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$collectors_info = array_intersect_key($collectors_info, $this->testingServiceCollectorNames);
}
return $collectors_info;
} | php | protected function getCollectorServiceIds(\Symfony\Component\DependencyInjection\TaggedContainerInterface $container_builder) {
// Get the details of all service collector services.
// Note that the docs for this method are completely wrong.
// Also, there are TWO possible tags for collectors, and the lazy version,
// 'service_id_collector', doesn't specify any data such as the 'call'
// property.
$service_collectors_info = $container_builder->findTaggedServiceIds('service_collector');
$service_id_collectors_info = $container_builder->findTaggedServiceIds('service_id_collector');
array_walk($service_collectors_info, function(&$item) {
$item['collector_type'] = 'service_collector';
});
array_walk($service_id_collectors_info, function(&$item) {
$item['collector_type'] = 'service_id_collector';
});
// We're going to assume that there is no collecting service that uses BOTH
// systems to collect two tags, that would be crazy.
$collectors_info = $service_collectors_info + $service_id_collectors_info;
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$collectors_info = array_intersect_key($collectors_info, $this->testingServiceCollectorNames);
}
return $collectors_info;
} | [
"protected",
"function",
"getCollectorServiceIds",
"(",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"DependencyInjection",
"\\",
"TaggedContainerInterface",
"$",
"container_builder",
")",
"{",
"// Get the details of all service collector services.",
"// Note that the docs for this me... | Gets the names of all service collector services from the container.
@param \Symfony\Component\DependencyInjection\TaggedContainerInterface $container_builder
The container.
@return string[]
An array of data about services. Structure is as follows:
@code
"path_processor_manager" => array:2 [
"collector_type" => "service_collector"
0 => array:2 [
"tag" => "path_processor_inbound"
"call" => "addInbound"
]
1 => array:2 [
"tag" => "path_processor_outbound"
"call" => "addOutbound"
]
]
@endcode | [
"Gets",
"the",
"names",
"of",
"all",
"service",
"collector",
"services",
"from",
"the",
"container",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/ServiceTagTypesCollector.php#L199-L225 | train |
drupal-code-builder/drupal-code-builder | Generator/Info7.php | Info7.file_body | function file_body() {
$lines = array();
$lines['name'] = $this->component_data['readable_name'];
$lines['description'] = $this->component_data['short_description'];
if (!empty( $this->component_data['module_dependencies'])) {
// For lines which form a set with the same key and array markers,
// simply make an array.
foreach ( $this->component_data['module_dependencies'] as $dependency) {
$lines['dependencies'][] = $dependency;
}
}
if (!empty( $this->component_data['module_package'])) {
$lines['package'] = $this->component_data['module_package'];
}
$lines['core'] = "7.x";
if (!empty($this->extraLines)) {
// Add a blank line before the extra lines.
$lines[] = '';
$lines = array_merge($lines, $this->extraLines);
}
$info = $this->process_info_lines($lines);
return $info;
} | php | function file_body() {
$lines = array();
$lines['name'] = $this->component_data['readable_name'];
$lines['description'] = $this->component_data['short_description'];
if (!empty( $this->component_data['module_dependencies'])) {
// For lines which form a set with the same key and array markers,
// simply make an array.
foreach ( $this->component_data['module_dependencies'] as $dependency) {
$lines['dependencies'][] = $dependency;
}
}
if (!empty( $this->component_data['module_package'])) {
$lines['package'] = $this->component_data['module_package'];
}
$lines['core'] = "7.x";
if (!empty($this->extraLines)) {
// Add a blank line before the extra lines.
$lines[] = '';
$lines = array_merge($lines, $this->extraLines);
}
$info = $this->process_info_lines($lines);
return $info;
} | [
"function",
"file_body",
"(",
")",
"{",
"$",
"lines",
"=",
"array",
"(",
")",
";",
"$",
"lines",
"[",
"'name'",
"]",
"=",
"$",
"this",
"->",
"component_data",
"[",
"'readable_name'",
"]",
";",
"$",
"lines",
"[",
"'description'",
"]",
"=",
"$",
"this"... | Create lines of file body for Drupal 7. | [
"Create",
"lines",
"of",
"file",
"body",
"for",
"Drupal",
"7",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Info7.php#L13-L39 | train |
drupal-code-builder/drupal-code-builder | Generator/Module.php | Module.applyBuildListFilter | public function applyBuildListFilter(&$files, $build_list, $component_data) {
// Case 1: everything was requested: don't filter!
if (isset($build_list['all'])) {
return;
}
$build_list = array_keys($build_list);
foreach ($files as $key => $file_info) {
if (!array_intersect($file_info['build_list_tags'], $build_list)) {
unset($files[$key]);
}
}
} | php | public function applyBuildListFilter(&$files, $build_list, $component_data) {
// Case 1: everything was requested: don't filter!
if (isset($build_list['all'])) {
return;
}
$build_list = array_keys($build_list);
foreach ($files as $key => $file_info) {
if (!array_intersect($file_info['build_list_tags'], $build_list)) {
unset($files[$key]);
}
}
} | [
"public",
"function",
"applyBuildListFilter",
"(",
"&",
"$",
"files",
",",
"$",
"build_list",
",",
"$",
"component_data",
")",
"{",
"// Case 1: everything was requested: don't filter!",
"if",
"(",
"isset",
"(",
"$",
"build_list",
"[",
"'all'",
"]",
")",
")",
"{"... | Filter the file info array to just the requested build list.
WARNING: the keys in the $files array will be changing soon!
@param &$files
The array of built file info.
@param $build_list
The build list parameter from the original Generate component data.
@param $component_data
The original component data. | [
"Filter",
"the",
"file",
"info",
"array",
"to",
"just",
"the",
"requested",
"build",
"list",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Module.php#L423-L436 | train |
drupal-code-builder/drupal-code-builder | Generator/Module.php | Module.getReplacements | function getReplacements() {
// Get old style variable names.
$module_data = $this->component_data;
return array(
'%module' => $module_data['root_name'],
'%Module' => ucfirst($module_data['readable_name']),
'%description' => str_replace("'", "\'", $module_data['short_description']),
'%name' => !empty($module_data['readable_name']) ? str_replace("'", "\'", $module_data['readable_name']) : $module_data['root_name'],
'%help' => !empty($module_data['module_help_text']) ? str_replace('"', '\"', $module_data['module_help_text']) : 'TODO: Create admin help text.',
'%readable' => str_replace("'", "\'", $module_data['readable_name']),
);
} | php | function getReplacements() {
// Get old style variable names.
$module_data = $this->component_data;
return array(
'%module' => $module_data['root_name'],
'%Module' => ucfirst($module_data['readable_name']),
'%description' => str_replace("'", "\'", $module_data['short_description']),
'%name' => !empty($module_data['readable_name']) ? str_replace("'", "\'", $module_data['readable_name']) : $module_data['root_name'],
'%help' => !empty($module_data['module_help_text']) ? str_replace('"', '\"', $module_data['module_help_text']) : 'TODO: Create admin help text.',
'%readable' => str_replace("'", "\'", $module_data['readable_name']),
);
} | [
"function",
"getReplacements",
"(",
")",
"{",
"// Get old style variable names.",
"$",
"module_data",
"=",
"$",
"this",
"->",
"component_data",
";",
"return",
"array",
"(",
"'%module'",
"=>",
"$",
"module_data",
"[",
"'root_name'",
"]",
",",
"'%Module'",
"=>",
"... | Provides replacement strings for tokens in code body.
@return
An array of tokens to replacements, suitable for use by strtr(). | [
"Provides",
"replacement",
"strings",
"for",
"tokens",
"in",
"code",
"body",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Module.php#L445-L457 | train |
drupal-code-builder/drupal-code-builder | Utility/CodeAnalysis/Method.php | Method.getBody | public function getBody() {
$filename = $this->getFileName();
$start_line = $this->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block
$end_line = $this->getEndLine();
$length = $end_line - $start_line;
$file_source = file($filename);
$body = implode("", array_slice($file_source, $start_line, $length));
return $body;
} | php | public function getBody() {
$filename = $this->getFileName();
$start_line = $this->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block
$end_line = $this->getEndLine();
$length = $end_line - $start_line;
$file_source = file($filename);
$body = implode("", array_slice($file_source, $start_line, $length));
return $body;
} | [
"public",
"function",
"getBody",
"(",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"getFileName",
"(",
")",
";",
"$",
"start_line",
"=",
"$",
"this",
"->",
"getStartLine",
"(",
")",
"-",
"1",
";",
"// it's actually - 1, otherwise you wont get the functio... | Gets the body code of the method.
@return string
The body of the method's code. | [
"Gets",
"the",
"body",
"code",
"of",
"the",
"method",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Utility/CodeAnalysis/Method.php#L18-L27 | train |
drupal-code-builder/drupal-code-builder | Utility/CodeAnalysis/Method.php | Method.getParamData | public function getParamData() {
$data = [];
$parameter_reflections = $this->getParameters();
$docblock_types = $this->getDocblockParams();
foreach ($parameter_reflections as $parameter_reflection) {
$name = $parameter_reflection->getName();
// Get the typehint. We try the reflection first, which gives us class
// and interface typehints and 'array'. If that gets nothing, we scrape
// it from the docblock so that we have something to generate docblocks
// with.
$type = (string) $parameter_reflection->getType();
if (empty($type)) {
if (isset($docblock_types[$name])) {
$type = $docblock_types[$name];
}
else {
// Account for badly-written docs where we couldn't extract a type.
$type = '';
}
}
$data[] = [
'type' => $type,
'name' => $name,
];
}
return $data;
} | php | public function getParamData() {
$data = [];
$parameter_reflections = $this->getParameters();
$docblock_types = $this->getDocblockParams();
foreach ($parameter_reflections as $parameter_reflection) {
$name = $parameter_reflection->getName();
// Get the typehint. We try the reflection first, which gives us class
// and interface typehints and 'array'. If that gets nothing, we scrape
// it from the docblock so that we have something to generate docblocks
// with.
$type = (string) $parameter_reflection->getType();
if (empty($type)) {
if (isset($docblock_types[$name])) {
$type = $docblock_types[$name];
}
else {
// Account for badly-written docs where we couldn't extract a type.
$type = '';
}
}
$data[] = [
'type' => $type,
'name' => $name,
];
}
return $data;
} | [
"public",
"function",
"getParamData",
"(",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"parameter_reflections",
"=",
"$",
"this",
"->",
"getParameters",
"(",
")",
";",
"$",
"docblock_types",
"=",
"$",
"this",
"->",
"getDocblockParams",
"(",
")",
";",... | Returns an array of parameter names and types.
Types are deduced from reflection, with a fallback to the documented type
for native types (e.g. 'int') which Drupal doesn't yet typehint for.
@return array
A numeric array where each item is an array containing:
- 'type': The typehint for the parameter.
- 'name': The name of the parameter without the leading '$'. | [
"Returns",
"an",
"array",
"of",
"parameter",
"names",
"and",
"types",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Utility/CodeAnalysis/Method.php#L40-L72 | train |
drupal-code-builder/drupal-code-builder | Utility/CodeAnalysis/Method.php | Method.getDocblockParams | public function getDocblockParams() {
$docblock = $this->getDocComment();
$matches = [];
preg_match_all('/\* @param (?P<type>\S+) \$(?P<name>\w+)/', $docblock, $matches, PREG_SET_ORDER);
// TODO: complain if no match.
$param_data = [];
foreach ($matches as $match_set) {
$param_data[$match_set['name']] = $match_set['type'];
}
return $param_data;
} | php | public function getDocblockParams() {
$docblock = $this->getDocComment();
$matches = [];
preg_match_all('/\* @param (?P<type>\S+) \$(?P<name>\w+)/', $docblock, $matches, PREG_SET_ORDER);
// TODO: complain if no match.
$param_data = [];
foreach ($matches as $match_set) {
$param_data[$match_set['name']] = $match_set['type'];
}
return $param_data;
} | [
"public",
"function",
"getDocblockParams",
"(",
")",
"{",
"$",
"docblock",
"=",
"$",
"this",
"->",
"getDocComment",
"(",
")",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"preg_match_all",
"(",
"'/\\* @param (?P<type>\\S+) \\$(?P<name>\\w+)/'",
",",
"$",
"docblock",... | Extract parameter types from the docblock.
@return
An array keyed by the parameter name (without the initial $), whose
values are the type in the docblock, such as 'mixed', 'int', or an
interface. (Although note that interface typehints which are also used
in the actual code are best detected with reflection). | [
"Extract",
"parameter",
"types",
"from",
"the",
"docblock",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Utility/CodeAnalysis/Method.php#L83-L97 | train |
drupal-code-builder/drupal-code-builder | Generator/YMLFile.php | YMLFile.getYamlBody | protected function getYamlBody($yaml_data_array) {
$yaml_parser = new \Symfony\Component\Yaml\Yaml;
$yaml_parser_inline_switch_level = $this->component_data['yaml_inline_level'];
if ($this->component_data['line_break_between_blocks']) {
$body = [];
foreach (range(0, count($yaml_data_array) -1 ) as $index) {
$yaml_slice = array_slice($yaml_data_array, $index, 1);
// Each YAML piece comes with a terminal newline, so when these are
// joined there will be the desired blank line between each section.
$body[] = $yaml_parser->dump($yaml_slice, $yaml_parser_inline_switch_level, static::YAML_INDENT);
}
}
else {
$yaml = $yaml_parser->dump($yaml_data_array, $yaml_parser_inline_switch_level, static::YAML_INDENT);
$this->expandInlineItems($yaml_data_array, $yaml);
// Because the yaml is all built for us, this is just a singleton array.
$body = array($yaml);
}
//drush_print_r($yaml);
return $body;
} | php | protected function getYamlBody($yaml_data_array) {
$yaml_parser = new \Symfony\Component\Yaml\Yaml;
$yaml_parser_inline_switch_level = $this->component_data['yaml_inline_level'];
if ($this->component_data['line_break_between_blocks']) {
$body = [];
foreach (range(0, count($yaml_data_array) -1 ) as $index) {
$yaml_slice = array_slice($yaml_data_array, $index, 1);
// Each YAML piece comes with a terminal newline, so when these are
// joined there will be the desired blank line between each section.
$body[] = $yaml_parser->dump($yaml_slice, $yaml_parser_inline_switch_level, static::YAML_INDENT);
}
}
else {
$yaml = $yaml_parser->dump($yaml_data_array, $yaml_parser_inline_switch_level, static::YAML_INDENT);
$this->expandInlineItems($yaml_data_array, $yaml);
// Because the yaml is all built for us, this is just a singleton array.
$body = array($yaml);
}
//drush_print_r($yaml);
return $body;
} | [
"protected",
"function",
"getYamlBody",
"(",
"$",
"yaml_data_array",
")",
"{",
"$",
"yaml_parser",
"=",
"new",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Yaml",
"\\",
"Yaml",
";",
"$",
"yaml_parser_inline_switch_level",
"=",
"$",
"this",
"->",
"component_data",
... | Get the YAML body for the file.
@param $yaml_data_array
An array of data to convert to YAML.
@return
An array containing the YAML string. | [
"Get",
"the",
"YAML",
"body",
"for",
"the",
"file",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/YMLFile.php#L100-L127 | train |
drupal-code-builder/drupal-code-builder | Generator/YMLFile.php | YMLFile.expandInlineItems | protected function expandInlineItems($yaml_data_array, &$yaml) {
if (empty($this->component_data['inline_levels_extra'])) {
return;
}
foreach ($this->component_data['inline_levels_extra'] as $extra_expansion_rule) {
// The rule address may use wildcards. Get a list of actual properties
// to expand.
$rule_address = $extra_expansion_rule['address'];
$properties_to_expand = [];
// Iterate recursively through the whole YAML data structure.
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($yaml_data_array), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
$depth = $iterator->getDepth();
if ($depth != count($rule_address) - 1) {
// The current item's depth does not match the rule's address: skip.
// Note that the iterator's notion of depth is zero-based.
continue;
}
// Get the address of the iterator's current location.
// See https://stackoverflow.com/questions/7590662/walk-array-recursively-and-print-the-path-of-the-walk
$current_address = [];
for ($i = 0; $i <= $depth; $i++) {
$current_address[] = $iterator->getSubIterator($i)->key();
}
// Compare the current address with the rule address.
for ($i = 0; $i <= $depth; $i++) {
if ($rule_address[$i] == '*') {
// Wildcard matches anything: pass this level.
continue;
}
if ($rule_address[$i] != $current_address[$i]) {
// There is a mismatch: give up on this item in the iterator and
// move on to the next.
continue 2;
}
}
// If we are still here, all levels of the current address passed the
// comparison with the rule address: the address is valid.
$properties_to_expand[] = $current_address;
}
foreach ($properties_to_expand as $property) {
// Get the value for the property.
$value = NestedArray::getValue($yaml_data_array, $property);
// Create a YAML subarray that has the key for the value.
$key = end($property);
$yaml_data_sub_array = [
$key => $value,
];
$yaml_parser = new \Symfony\Component\Yaml\Yaml;
$original = $yaml_parser->dump($yaml_data_sub_array, 1, static::YAML_INDENT);
$replacement = $yaml_parser->dump($yaml_data_sub_array, 2, static::YAML_INDENT);
// We need to put the right indent at the front of all lines.
// The indent is one level less than the level of the address, which
// itself is one less than the count of the address array.
$indent = str_repeat(' ', static::YAML_INDENT * (count($property) - 2));
$original = $indent . $original;
$replacement = preg_replace('@^@m', $indent, $replacement);
// Replace the inlined original YAML text with the multi-line
// replacement.
// WARNING: this is a bit dicey, as we might be replacing multiple
// instances of this data, at ANY level!
// However, since the only use of this so far is for services.yml
// file tags, that's not a problem: YAGNI.
// A better way to do this -- but far more complicated -- might be to
// replace the data with a placeholder token before we generate the
// YAML, so we are sure we are replacing the right thing.
$yaml = str_replace($original, $replacement, $yaml);
}
}
} | php | protected function expandInlineItems($yaml_data_array, &$yaml) {
if (empty($this->component_data['inline_levels_extra'])) {
return;
}
foreach ($this->component_data['inline_levels_extra'] as $extra_expansion_rule) {
// The rule address may use wildcards. Get a list of actual properties
// to expand.
$rule_address = $extra_expansion_rule['address'];
$properties_to_expand = [];
// Iterate recursively through the whole YAML data structure.
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($yaml_data_array), \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
$depth = $iterator->getDepth();
if ($depth != count($rule_address) - 1) {
// The current item's depth does not match the rule's address: skip.
// Note that the iterator's notion of depth is zero-based.
continue;
}
// Get the address of the iterator's current location.
// See https://stackoverflow.com/questions/7590662/walk-array-recursively-and-print-the-path-of-the-walk
$current_address = [];
for ($i = 0; $i <= $depth; $i++) {
$current_address[] = $iterator->getSubIterator($i)->key();
}
// Compare the current address with the rule address.
for ($i = 0; $i <= $depth; $i++) {
if ($rule_address[$i] == '*') {
// Wildcard matches anything: pass this level.
continue;
}
if ($rule_address[$i] != $current_address[$i]) {
// There is a mismatch: give up on this item in the iterator and
// move on to the next.
continue 2;
}
}
// If we are still here, all levels of the current address passed the
// comparison with the rule address: the address is valid.
$properties_to_expand[] = $current_address;
}
foreach ($properties_to_expand as $property) {
// Get the value for the property.
$value = NestedArray::getValue($yaml_data_array, $property);
// Create a YAML subarray that has the key for the value.
$key = end($property);
$yaml_data_sub_array = [
$key => $value,
];
$yaml_parser = new \Symfony\Component\Yaml\Yaml;
$original = $yaml_parser->dump($yaml_data_sub_array, 1, static::YAML_INDENT);
$replacement = $yaml_parser->dump($yaml_data_sub_array, 2, static::YAML_INDENT);
// We need to put the right indent at the front of all lines.
// The indent is one level less than the level of the address, which
// itself is one less than the count of the address array.
$indent = str_repeat(' ', static::YAML_INDENT * (count($property) - 2));
$original = $indent . $original;
$replacement = preg_replace('@^@m', $indent, $replacement);
// Replace the inlined original YAML text with the multi-line
// replacement.
// WARNING: this is a bit dicey, as we might be replacing multiple
// instances of this data, at ANY level!
// However, since the only use of this so far is for services.yml
// file tags, that's not a problem: YAGNI.
// A better way to do this -- but far more complicated -- might be to
// replace the data with a placeholder token before we generate the
// YAML, so we are sure we are replacing the right thing.
$yaml = str_replace($original, $replacement, $yaml);
}
}
} | [
"protected",
"function",
"expandInlineItems",
"(",
"$",
"yaml_data_array",
",",
"&",
"$",
"yaml",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"component_data",
"[",
"'inline_levels_extra'",
"]",
")",
")",
"{",
"return",
";",
"}",
"foreach",
"(",
... | Change specified YAML properties from inlined to expanded.
We need this because some Drupal YAML files have variable levels of
inlining, and Symfony's YAML dumper does not support this, nor plan to:
see https://github.com/symfony/symfony/issues/19014#event-688175812.
For example, a services.yml file has 'arguments' and 'tags' at the same
level, but while 'arguments' is inlined, 'tags' is expanded, and inlined
one level lower:
@code
forum_manager:
class: Drupal\forum\ForumManager
arguments: ['@config.factory', '@entity.manager', '@database', '@string_translation', '@comment.manager']
tags:
- { name: backend_overridable }
@endcode
The properties to expand are specified in the 'inline_levels_extra'
component data. This is an array of rules, keyed by an arbitrary name,
where each rule is an array consisting of:
- 'address': An address array of the property or properties to expand.
This supports verbatim address pieces, and a '*' for a wildcard.
- 'level': NOT YET USED.
TODO: this is not currently run for YAML which puts line breaks between
blocks: there's no use case for this yet.
@param array $yaml_data_array
The original YAML data array.
@param string &$yaml
The generated YAML text. | [
"Change",
"specified",
"YAML",
"properties",
"from",
"inlined",
"to",
"expanded",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/YMLFile.php#L163-L243 | train |
drupal-code-builder/drupal-code-builder | Task/ReportHookDataFolder.php | ReportHookDataFolder.lastUpdatedDate | public function lastUpdatedDate() {
$directory = $this->environment->getHooksDirectory();
$hooks_file = "$directory/hooks_processed.php";
if (file_exists($hooks_file)) {
$timestamp = filemtime($hooks_file);
return $timestamp;
}
} | php | public function lastUpdatedDate() {
$directory = $this->environment->getHooksDirectory();
$hooks_file = "$directory/hooks_processed.php";
if (file_exists($hooks_file)) {
$timestamp = filemtime($hooks_file);
return $timestamp;
}
} | [
"public",
"function",
"lastUpdatedDate",
"(",
")",
"{",
"$",
"directory",
"=",
"$",
"this",
"->",
"environment",
"->",
"getHooksDirectory",
"(",
")",
";",
"$",
"hooks_file",
"=",
"\"$directory/hooks_processed.php\"",
";",
"if",
"(",
"file_exists",
"(",
"$",
"h... | Get the timestamp of the last hook data upate.
@return
A unix timestamp, or NULL if the hooks have never been collected. | [
"Get",
"the",
"timestamp",
"of",
"the",
"last",
"hook",
"data",
"upate",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/ReportHookDataFolder.php#L31-L38 | train |
drupal-code-builder/drupal-code-builder | Task/ReportHookDataFolder.php | ReportHookDataFolder.listHookFiles | public function listHookFiles() {
$directory = $this->environment->getHooksDirectory();
$files = array();
// No need to verify $directory; our sanity check has taken care of it.
$dh = opendir($directory);
while (($file = readdir($dh)) !== FALSE) {
// Ignore files that don't make sense to include.
// System files and cruft.
// TODO: replace all the .foo with one of the arcane PHP string checking functions
if (in_array($file, array('.', '..', '.DS_Store', 'CVS', 'hooks_processed.php'))) {
continue;
}
// Our own processed files.
if (strpos($file, '_processed.php')) {
continue;
}
$files[] = $file;
}
closedir($dh);
return $files;
} | php | public function listHookFiles() {
$directory = $this->environment->getHooksDirectory();
$files = array();
// No need to verify $directory; our sanity check has taken care of it.
$dh = opendir($directory);
while (($file = readdir($dh)) !== FALSE) {
// Ignore files that don't make sense to include.
// System files and cruft.
// TODO: replace all the .foo with one of the arcane PHP string checking functions
if (in_array($file, array('.', '..', '.DS_Store', 'CVS', 'hooks_processed.php'))) {
continue;
}
// Our own processed files.
if (strpos($file, '_processed.php')) {
continue;
}
$files[] = $file;
}
closedir($dh);
return $files;
} | [
"public",
"function",
"listHookFiles",
"(",
")",
"{",
"$",
"directory",
"=",
"$",
"this",
"->",
"environment",
"->",
"getHooksDirectory",
"(",
")",
";",
"$",
"files",
"=",
"array",
"(",
")",
";",
"// No need to verify $directory; our sanity check has taken care of i... | Get a list of all collected hook api.php files.
@return
A flat array of filenames, relative to the hooks directory. If no files
are present, an empty array is returned. | [
"Get",
"a",
"list",
"of",
"all",
"collected",
"hook",
"api",
".",
"php",
"files",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/ReportHookDataFolder.php#L47-L71 | train |
drupal-code-builder/drupal-code-builder | Generator/Profile.php | Profile.componentDataDefinition | public static function componentDataDefinition() {
$component_data_definition = parent::componentDataDefinition();
$component_data_definition['base'] = [
'internal' => TRUE,
'default' => 'profile',
'process_default' => TRUE,
];
$component_data_definition['root_name'] = [
'label' => 'Profile machine name',
'default' => 'myprofile',
] + $component_data_definition['root_name'];
$component_data_definition += [
'readable_name' => array(
'label' => 'Profile readable name',
'default' => function($component_data) {
return ucfirst(str_replace('_', ' ', $component_data['root_name']));
},
'required' => FALSE,
),
'short_description' => array(
'label' => 'Profile .info file description',
'default' => 'TODO: Description of profile',
'required' => FALSE,
),
];
return $component_data_definition;
} | php | public static function componentDataDefinition() {
$component_data_definition = parent::componentDataDefinition();
$component_data_definition['base'] = [
'internal' => TRUE,
'default' => 'profile',
'process_default' => TRUE,
];
$component_data_definition['root_name'] = [
'label' => 'Profile machine name',
'default' => 'myprofile',
] + $component_data_definition['root_name'];
$component_data_definition += [
'readable_name' => array(
'label' => 'Profile readable name',
'default' => function($component_data) {
return ucfirst(str_replace('_', ' ', $component_data['root_name']));
},
'required' => FALSE,
),
'short_description' => array(
'label' => 'Profile .info file description',
'default' => 'TODO: Description of profile',
'required' => FALSE,
),
];
return $component_data_definition;
} | [
"public",
"static",
"function",
"componentDataDefinition",
"(",
")",
"{",
"$",
"component_data_definition",
"=",
"parent",
"::",
"componentDataDefinition",
"(",
")",
";",
"$",
"component_data_definition",
"[",
"'base'",
"]",
"=",
"[",
"'internal'",
"=>",
"TRUE",
"... | This can't be a class property due to use of closures.
@return
An array that defines the data this component needs to operate. This
includes:
- data that must be specified by the user
- data that may be specified by the user, but can be computed or take from
defaults
- data that should not be specified by the user, as it is computed from
other input. | [
"This",
"can",
"t",
"be",
"a",
"class",
"property",
"due",
"to",
"use",
"of",
"closures",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Generator/Profile.php#L34-L63 | train |
drupal-code-builder/drupal-code-builder | Task/Collect/FieldTypesCollector.php | FieldTypesCollector.collect | public function collect($job_list) {
$plugin_manager = \Drupal::service('plugin.manager.field.field_type');
$plugin_definitions = $plugin_manager->getDefinitions();
$field_types_data = [];
foreach ($plugin_definitions as $plugin_id => $plugin_definition) {
$field_types_data[$plugin_id] = [
'type' => $plugin_id,
// Labels and descriptions need to be stringified from
// TranslatableMarkup.
'label' => (string) $plugin_definition['label'],
// Some field types brokenly don't define a description.
'description' => (string) ( $plugin_definition['description'] ?? $plugin_definition['label'] ),
// Some of the weirder plugins don't have these.
'default_widget' => $plugin_definition['default_widget'] ?? '',
'default_formatter' => $plugin_definition['default_formatter'] ?? '',
];
}
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$field_types_data = array_intersect_key($field_types_data, $this->testingFieldTypes);
}
uasort($field_types_data, function($a, $b) {
return strcmp($a['label'], $b['label']);
});
return $field_types_data;
} | php | public function collect($job_list) {
$plugin_manager = \Drupal::service('plugin.manager.field.field_type');
$plugin_definitions = $plugin_manager->getDefinitions();
$field_types_data = [];
foreach ($plugin_definitions as $plugin_id => $plugin_definition) {
$field_types_data[$plugin_id] = [
'type' => $plugin_id,
// Labels and descriptions need to be stringified from
// TranslatableMarkup.
'label' => (string) $plugin_definition['label'],
// Some field types brokenly don't define a description.
'description' => (string) ( $plugin_definition['description'] ?? $plugin_definition['label'] ),
// Some of the weirder plugins don't have these.
'default_widget' => $plugin_definition['default_widget'] ?? '',
'default_formatter' => $plugin_definition['default_formatter'] ?? '',
];
}
// Filter for testing sample data collection.
if (!empty($this->environment->sample_data_write)) {
$field_types_data = array_intersect_key($field_types_data, $this->testingFieldTypes);
}
uasort($field_types_data, function($a, $b) {
return strcmp($a['label'], $b['label']);
});
return $field_types_data;
} | [
"public",
"function",
"collect",
"(",
"$",
"job_list",
")",
"{",
"$",
"plugin_manager",
"=",
"\\",
"Drupal",
"::",
"service",
"(",
"'plugin.manager.field.field_type'",
")",
";",
"$",
"plugin_definitions",
"=",
"$",
"plugin_manager",
"->",
"getDefinitions",
"(",
... | Gets definitions of field types.
@return array
An array whose keys are the field types, and whose values are arrays
containing:
- 'type': The field type, that is, the field type plugin ID.
- 'label': The field type label.
- 'description': The field type description.
- 'default_widget': The default widget plugin ID.
- 'default_formatter': The default formatter plugin ID. | [
"Gets",
"definitions",
"of",
"field",
"types",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Collect/FieldTypesCollector.php#L62-L92 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentClassHandler.php | ComponentClassHandler.getGenerator | public function getGenerator($component_type, $component_data) {
$class = $this->getGeneratorClass($component_type);
if (!class_exists($class)) {
throw new \DrupalCodeBuilder\Exception\InvalidInputException(strtr("Invalid component type !type.", array(
'!type' => htmlspecialchars($component_type, ENT_QUOTES, 'UTF-8'),
)));
}
$generator = new $class($component_data);
// Quick hack for the benefit of the Hooks generator.
$generator->classHandlerHelper = $this;
return $generator;
} | php | public function getGenerator($component_type, $component_data) {
$class = $this->getGeneratorClass($component_type);
if (!class_exists($class)) {
throw new \DrupalCodeBuilder\Exception\InvalidInputException(strtr("Invalid component type !type.", array(
'!type' => htmlspecialchars($component_type, ENT_QUOTES, 'UTF-8'),
)));
}
$generator = new $class($component_data);
// Quick hack for the benefit of the Hooks generator.
$generator->classHandlerHelper = $this;
return $generator;
} | [
"public",
"function",
"getGenerator",
"(",
"$",
"component_type",
",",
"$",
"component_data",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getGeneratorClass",
"(",
"$",
"component_type",
")",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"class",
")",... | Generator factory.
@param $component_type
The type of the component. This is use to build the class name: see
getGeneratorClass().
@param $component_data
An array of data for the component. This is passed to the generator's
__construct().
@return
A generator object, with the component name and data set on it, as well
as a reference to this task handler.
@throws \DrupalCodeBuilder\Exception\InvalidInputException
Throws an exception if the given component type does not correspond to
a component class. | [
"Generator",
"factory",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentClassHandler.php#L53-L68 | train |
drupal-code-builder/drupal-code-builder | Task/Generate/ComponentClassHandler.php | ComponentClassHandler.getGeneratorClass | public function getGeneratorClass($type) {
$type = ucfirst($type);
if (!isset($this->classes[$type])) {
$version = \DrupalCodeBuilder\Factory::getEnvironment()->getCoreMajorVersion();
$class = 'DrupalCodeBuilder\\Generator\\' . $type . $version;
// If there is no version-specific class, use the base class.
if (!class_exists($class)) {
$class = 'DrupalCodeBuilder\\Generator\\' . $type;
}
$this->classes[$type] = $class;
}
return $this->classes[$type];
} | php | public function getGeneratorClass($type) {
$type = ucfirst($type);
if (!isset($this->classes[$type])) {
$version = \DrupalCodeBuilder\Factory::getEnvironment()->getCoreMajorVersion();
$class = 'DrupalCodeBuilder\\Generator\\' . $type . $version;
// If there is no version-specific class, use the base class.
if (!class_exists($class)) {
$class = 'DrupalCodeBuilder\\Generator\\' . $type;
}
$this->classes[$type] = $class;
}
return $this->classes[$type];
} | [
"public",
"function",
"getGeneratorClass",
"(",
"$",
"type",
")",
"{",
"$",
"type",
"=",
"ucfirst",
"(",
"$",
"type",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"classes",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"version",
"=",... | Helper function to get the desired Generator class.
@param $type
The type of the component. This is the name of the class, without the
version suffix. For classes in camel case, the string given here may be
all in lower case.
@return
A fully qualified class name for the type and, if it exists, version, e.g.
'DrupalCodeBuilder\Generator\Info6'. | [
"Helper",
"function",
"to",
"get",
"the",
"desired",
"Generator",
"class",
"."
] | 7a9b9895218c729cd5f4c1dba75010f53c7da92e | https://github.com/drupal-code-builder/drupal-code-builder/blob/7a9b9895218c729cd5f4c1dba75010f53c7da92e/Task/Generate/ComponentClassHandler.php#L82-L98 | train |
IndraGunawan/api-rate-limit-bundle | EventListener/RateLimitListener.php | RateLimitListener.createRateLimitExceededException | protected function createRateLimitExceededException(Request $request)
{
$config = $this->exceptionConfig;
$class = $config['custom_exception'] ?? RateLimitExceededException::class;
$username = null;
if (null !== $token = $this->tokenStorage->getToken()) {
if (is_object($token->getUser())) {
$username = $token->getUsername();
}
}
return new $class($config['status_code'], $config['message'], $request->getClientIp(), $username);
} | php | protected function createRateLimitExceededException(Request $request)
{
$config = $this->exceptionConfig;
$class = $config['custom_exception'] ?? RateLimitExceededException::class;
$username = null;
if (null !== $token = $this->tokenStorage->getToken()) {
if (is_object($token->getUser())) {
$username = $token->getUsername();
}
}
return new $class($config['status_code'], $config['message'], $request->getClientIp(), $username);
} | [
"protected",
"function",
"createRateLimitExceededException",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"exceptionConfig",
";",
"$",
"class",
"=",
"$",
"config",
"[",
"'custom_exception'",
"]",
"??",
"RateLimitExceededExceptio... | Returns an RateLimitExceededException.
@param Request $request
@return RateLimitExceededException | [
"Returns",
"an",
"RateLimitExceededException",
"."
] | 1096ebfe1b181d6b6e38ccf58884ab871b41c47b | https://github.com/IndraGunawan/api-rate-limit-bundle/blob/1096ebfe1b181d6b6e38ccf58884ab871b41c47b/EventListener/RateLimitListener.php#L87-L100 | train |
ckdarby/PHP-UptimeRobot | src/UptimeRobot/API.php | API.request | public function request($resource, $args = array())
{
$url = $this->buildUrl($resource, $args);
$curl = curl_init($url);
curl_setopt_array($curl, $this->options);
$this->contents = curl_exec($curl);
$this->setDebug($curl);
if (curl_errno($curl) > 0) {
throw new \Exception('There was an error while making the request');
}
$jsonDecodeContent = json_decode($this->contents, true);
if(is_null($jsonDecodeContent)) {
throw new \Exception('Unable to decode JSON response');
}
return $jsonDecodeContent;
} | php | public function request($resource, $args = array())
{
$url = $this->buildUrl($resource, $args);
$curl = curl_init($url);
curl_setopt_array($curl, $this->options);
$this->contents = curl_exec($curl);
$this->setDebug($curl);
if (curl_errno($curl) > 0) {
throw new \Exception('There was an error while making the request');
}
$jsonDecodeContent = json_decode($this->contents, true);
if(is_null($jsonDecodeContent)) {
throw new \Exception('Unable to decode JSON response');
}
return $jsonDecodeContent;
} | [
"public",
"function",
"request",
"(",
"$",
"resource",
",",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"buildUrl",
"(",
"$",
"resource",
",",
"$",
"args",
")",
";",
"$",
"curl",
"=",
"curl_init",
"(",
"$",
... | Makes curl call to the url & returns output.
@param string $resource The resource of the api
@param array $args Array of options for the query query
@return array json_decoded contents
@throws \Exception If the curl request fails | [
"Makes",
"curl",
"call",
"to",
"the",
"url",
"&",
"returns",
"output",
"."
] | d90129522bd5daa4227a5390ef5a12ab78d76880 | https://github.com/ckdarby/PHP-UptimeRobot/blob/d90129522bd5daa4227a5390ef5a12ab78d76880/src/UptimeRobot/API.php#L55-L76 | train |
ckdarby/PHP-UptimeRobot | src/UptimeRobot/API.php | API.getOptions | private function getOptions($options)
{
$conf = [
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true
];
if (isset($options['timeout'])) {
$conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
}
if (isset($options['connect_timeout'])) {
$conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
}
return $conf;
} | php | private function getOptions($options)
{
$conf = [
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true
];
if (isset($options['timeout'])) {
$conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
}
if (isset($options['connect_timeout'])) {
$conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
}
return $conf;
} | [
"private",
"function",
"getOptions",
"(",
"$",
"options",
")",
"{",
"$",
"conf",
"=",
"[",
"CURLOPT_HEADER",
"=>",
"false",
",",
"CURLOPT_RETURNTRANSFER",
"=>",
"true",
",",
"CURLOPT_SSL_VERIFYPEER",
"=>",
"false",
",",
"CURLOPT_FOLLOWLOCATION",
"=>",
"true",
"]... | Get options for curl.
@param $options
@return array | [
"Get",
"options",
"for",
"curl",
"."
] | d90129522bd5daa4227a5390ef5a12ab78d76880 | https://github.com/ckdarby/PHP-UptimeRobot/blob/d90129522bd5daa4227a5390ef5a12ab78d76880/src/UptimeRobot/API.php#L85-L102 | train |
ckdarby/PHP-UptimeRobot | src/UptimeRobot/API.php | API.buildUrl | private function buildUrl($resource, $args)
{
//Merge args(apiKey, Format, noJsonCallback)
$args = array_merge($args, $this->args);
$query = http_build_query($args);
$url = $this->url;
$url .= $resource . '?' . $query;
return $url;
} | php | private function buildUrl($resource, $args)
{
//Merge args(apiKey, Format, noJsonCallback)
$args = array_merge($args, $this->args);
$query = http_build_query($args);
$url = $this->url;
$url .= $resource . '?' . $query;
return $url;
} | [
"private",
"function",
"buildUrl",
"(",
"$",
"resource",
",",
"$",
"args",
")",
"{",
"//Merge args(apiKey, Format, noJsonCallback)",
"$",
"args",
"=",
"array_merge",
"(",
"$",
"args",
",",
"$",
"this",
"->",
"args",
")",
";",
"$",
"query",
"=",
"http_build_q... | Builds the url for the curl request.
@param string $resource The resource of the api
@param array $args Array of options for the query query
@return string Finalized Url | [
"Builds",
"the",
"url",
"for",
"the",
"curl",
"request",
"."
] | d90129522bd5daa4227a5390ef5a12ab78d76880 | https://github.com/ckdarby/PHP-UptimeRobot/blob/d90129522bd5daa4227a5390ef5a12ab78d76880/src/UptimeRobot/API.php#L112-L122 | train |
ckdarby/PHP-UptimeRobot | src/UptimeRobot/API.php | API.setDebug | private function setDebug($curl)
{
$this->debug = [
'errorNum' => curl_errno($curl),
'error' => curl_error($curl),
'info' => curl_getinfo($curl),
'raw' => $this->contents,
];
} | php | private function setDebug($curl)
{
$this->debug = [
'errorNum' => curl_errno($curl),
'error' => curl_error($curl),
'info' => curl_getinfo($curl),
'raw' => $this->contents,
];
} | [
"private",
"function",
"setDebug",
"(",
"$",
"curl",
")",
"{",
"$",
"this",
"->",
"debug",
"=",
"[",
"'errorNum'",
"=>",
"curl_errno",
"(",
"$",
"curl",
")",
",",
"'error'",
"=>",
"curl_error",
"(",
"$",
"curl",
")",
",",
"'info'",
"=>",
"curl_getinfo"... | Sets debug information from last curl.
@param resource $curl Curl handle | [
"Sets",
"debug",
"information",
"from",
"last",
"curl",
"."
] | d90129522bd5daa4227a5390ef5a12ab78d76880 | https://github.com/ckdarby/PHP-UptimeRobot/blob/d90129522bd5daa4227a5390ef5a12ab78d76880/src/UptimeRobot/API.php#L129-L137 | train |
IAkumaI/SphinxsearchBundle | Search/Sphinxsearch.php | Sphinxsearch.addQuery | public function addQuery($query, array $indexes)
{
if (empty($indexes)) {
throw new EmptyIndexException('Try to search with empty indexes');
}
$this->sphinx->addQuery($query, implode(' ', $indexes));
} | php | public function addQuery($query, array $indexes)
{
if (empty($indexes)) {
throw new EmptyIndexException('Try to search with empty indexes');
}
$this->sphinx->addQuery($query, implode(' ', $indexes));
} | [
"public",
"function",
"addQuery",
"(",
"$",
"query",
",",
"array",
"$",
"indexes",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"indexes",
")",
")",
"{",
"throw",
"new",
"EmptyIndexException",
"(",
"'Try to search with empty indexes'",
")",
";",
"}",
"$",
"this... | Adds a query to a multi-query batch
@param string $query Search query
@param array $indexes Index list to perform the search
@throws EmptyIndexException If $indexes is empty | [
"Adds",
"a",
"query",
"to",
"a",
"multi",
"-",
"query",
"batch"
] | cf622949f64a7d10b5e5abc9e4d95f280095e43d | https://github.com/IAkumaI/SphinxsearchBundle/blob/cf622949f64a7d10b5e5abc9e4d95f280095e43d/Search/Sphinxsearch.php#L213-L220 | train |
IAkumaI/SphinxsearchBundle | Doctrine/Bridge.php | Bridge.getEntityManager | public function getEntityManager()
{
if ($this->em === null) {
$this->setEntityManager($this->container->get('doctrine')->getManager($this->emName));
}
return $this->em;
} | php | public function getEntityManager()
{
if ($this->em === null) {
$this->setEntityManager($this->container->get('doctrine')->getManager($this->emName));
}
return $this->em;
} | [
"public",
"function",
"getEntityManager",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"em",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"setEntityManager",
"(",
"$",
"this",
"->",
"container",
"->",
"get",
"(",
"'doctrine'",
")",
"->",
"getManager",
"... | Get an EntityManager
@return EntityManager | [
"Get",
"an",
"EntityManager"
] | cf622949f64a7d10b5e5abc9e4d95f280095e43d | https://github.com/IAkumaI/SphinxsearchBundle/blob/cf622949f64a7d10b5e5abc9e4d95f280095e43d/Doctrine/Bridge.php#L58-L65 | train |
IAkumaI/SphinxsearchBundle | Doctrine/Bridge.php | Bridge.setEntityManager | public function setEntityManager(EntityManager $em)
{
if ($this->em !== null) {
throw new \LogicException('Entity manager can only be set before any results are fetched');
}
$this->em = $em;
} | php | public function setEntityManager(EntityManager $em)
{
if ($this->em !== null) {
throw new \LogicException('Entity manager can only be set before any results are fetched');
}
$this->em = $em;
} | [
"public",
"function",
"setEntityManager",
"(",
"EntityManager",
"$",
"em",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"em",
"!==",
"null",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'Entity manager can only be set before any results are fetched'",
")",
"... | Set an EntityManager
@param EntityManager $em
@throws LogicException If entity manager already set | [
"Set",
"an",
"EntityManager"
] | cf622949f64a7d10b5e5abc9e4d95f280095e43d | https://github.com/IAkumaI/SphinxsearchBundle/blob/cf622949f64a7d10b5e5abc9e4d95f280095e43d/Doctrine/Bridge.php#L74-L81 | train |
Shipu/laratie | src/Support/Stub.php | Stub.save | public function save($path, $filename)
{
if (!file_exists($path)) {
$this->makeDirectory($path);
}
return file_put_contents($path . '/' . $filename, $this->getContents());
} | php | public function save($path, $filename)
{
if (!file_exists($path)) {
$this->makeDirectory($path);
}
return file_put_contents($path . '/' . $filename, $this->getContents());
} | [
"public",
"function",
"save",
"(",
"$",
"path",
",",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"$",
"this",
"->",
"makeDirectory",
"(",
"$",
"path",
")",
";",
"}",
"return",
"file_put_contents",
"(",
... | Save stub to specific path.
@param string $path
@param string $filename
@return bool | [
"Save",
"stub",
"to",
"specific",
"path",
"."
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Support/Stub.php#L70-L77 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.requiredTaskAndInputs | protected function requiredTaskAndInputs()
{
$this->vendor = $this->setVendor();
$this->package = $this->setPackage();
if (blank($this->vendor)) {
$this->vendor = !blank($this->config->get('tie.vendor')) ? $this->config->get('tie.vendor') : snake_case(strtolower($this->ask('Vendor Name?')));
} else {
$vendor = explode('/', $this->vendor);
if (isset($vendor[1])) {
$this->package = $vendor[1];
$this->vendor = $vendor[0];
}
}
if (blank($this->package)) {
$this->package = strtolower($this->ask('Your Package Name?'));
}
$this->package = $this->package;
$this->makeBaseDirectory();
$this->configureNamespace();
} | php | protected function requiredTaskAndInputs()
{
$this->vendor = $this->setVendor();
$this->package = $this->setPackage();
if (blank($this->vendor)) {
$this->vendor = !blank($this->config->get('tie.vendor')) ? $this->config->get('tie.vendor') : snake_case(strtolower($this->ask('Vendor Name?')));
} else {
$vendor = explode('/', $this->vendor);
if (isset($vendor[1])) {
$this->package = $vendor[1];
$this->vendor = $vendor[0];
}
}
if (blank($this->package)) {
$this->package = strtolower($this->ask('Your Package Name?'));
}
$this->package = $this->package;
$this->makeBaseDirectory();
$this->configureNamespace();
} | [
"protected",
"function",
"requiredTaskAndInputs",
"(",
")",
"{",
"$",
"this",
"->",
"vendor",
"=",
"$",
"this",
"->",
"setVendor",
"(",
")",
";",
"$",
"this",
"->",
"package",
"=",
"$",
"this",
"->",
"setPackage",
"(",
")",
";",
"if",
"(",
"blank",
"... | Modify or Getting inputs | [
"Modify",
"or",
"Getting",
"inputs"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L87-L109 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.makeBaseDirectory | public function makeBaseDirectory()
{
$this->path = $this->config->get('tie.root') . '/' . $this->vendor . '/' . $this->package;
$this->makeDir($this->path);
} | php | public function makeBaseDirectory()
{
$this->path = $this->config->get('tie.root') . '/' . $this->vendor . '/' . $this->package;
$this->makeDir($this->path);
} | [
"public",
"function",
"makeBaseDirectory",
"(",
")",
"{",
"$",
"this",
"->",
"path",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'tie.root'",
")",
".",
"'/'",
".",
"$",
"this",
"->",
"vendor",
".",
"'/'",
".",
"$",
"this",
"->",
"package",
... | Make package development base directory | [
"Make",
"package",
"development",
"base",
"directory"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L118-L123 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.configureNamespace | public function configureNamespace()
{
$this->namespace = (!blank($this->config->get('tie.rootNamespace')) ? $this->config->get('tie.rootNamespace') : studly_case($this->vendor)) . '\\' . studly_case($this->package) . '\\';
} | php | public function configureNamespace()
{
$this->namespace = (!blank($this->config->get('tie.rootNamespace')) ? $this->config->get('tie.rootNamespace') : studly_case($this->vendor)) . '\\' . studly_case($this->package) . '\\';
} | [
"public",
"function",
"configureNamespace",
"(",
")",
"{",
"$",
"this",
"->",
"namespace",
"=",
"(",
"!",
"blank",
"(",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'tie.rootNamespace'",
")",
")",
"?",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
... | Making package namespace | [
"Making",
"package",
"namespace"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L142-L145 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.generateStubFile | public function generateStubFile($location, $fileFullName, $configuration)
{
$fileName = str_replace([ 'VENDOR_NAME', 'VENDOR_NAME_LOWER', 'PACKAGE_NAME', 'PACKAGE_NAME_LOWER' ], [
studly_case($this->vendor),
strtolower($this->vendor),
studly_case($this->package),
strtolower($this->package),
], $this->filesystem->name($fileFullName));
$fileExtension = $this->filesystem->extension($fileFullName);
if (blank($fileExtension)) {
$fileExtension = data_get($configuration, 'extension', 'php');
}
$suffix = data_get($configuration, 'suffix', '');
$prefix = data_get($configuration, 'prefix', '');
$namespace = data_get($configuration, 'namespace', '');
$fileName = $this->fileNameCaseConvention($prefix . $fileName . $suffix, $configuration);
$this->makeDir($location);
Stub::create(
$this->findingStub($this->stubKey),
$this->replaceStubString($fileName, $namespace)
)->save($location, $fileName . '.' . $fileExtension);
} | php | public function generateStubFile($location, $fileFullName, $configuration)
{
$fileName = str_replace([ 'VENDOR_NAME', 'VENDOR_NAME_LOWER', 'PACKAGE_NAME', 'PACKAGE_NAME_LOWER' ], [
studly_case($this->vendor),
strtolower($this->vendor),
studly_case($this->package),
strtolower($this->package),
], $this->filesystem->name($fileFullName));
$fileExtension = $this->filesystem->extension($fileFullName);
if (blank($fileExtension)) {
$fileExtension = data_get($configuration, 'extension', 'php');
}
$suffix = data_get($configuration, 'suffix', '');
$prefix = data_get($configuration, 'prefix', '');
$namespace = data_get($configuration, 'namespace', '');
$fileName = $this->fileNameCaseConvention($prefix . $fileName . $suffix, $configuration);
$this->makeDir($location);
Stub::create(
$this->findingStub($this->stubKey),
$this->replaceStubString($fileName, $namespace)
)->save($location, $fileName . '.' . $fileExtension);
} | [
"public",
"function",
"generateStubFile",
"(",
"$",
"location",
",",
"$",
"fileFullName",
",",
"$",
"configuration",
")",
"{",
"$",
"fileName",
"=",
"str_replace",
"(",
"[",
"'VENDOR_NAME'",
",",
"'VENDOR_NAME_LOWER'",
",",
"'PACKAGE_NAME'",
",",
"'PACKAGE_NAME_LO... | Generate stub file and save specific location
@param $location
@param $fileFullName
@param $configuration | [
"Generate",
"stub",
"file",
"and",
"save",
"specific",
"location"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L156-L180 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.fileNameCaseConvention | public function fileNameCaseConvention($name, $case = 'studly')
{
if (is_array($case)) {
$case = data_get($case, 'case', 'studly');
}
switch ($case) {
case 'studly':
return studly_case($name);
case 'lower':
return strtolower($name);
case 'upper':
return strtoupper($name);
case 'snake':
return snake_case($name);
case 'title':
return title_case($name);
case 'camel':
return camel_case($name);
case 'kebab':
return kebab_case($name);
}
return $name;
} | php | public function fileNameCaseConvention($name, $case = 'studly')
{
if (is_array($case)) {
$case = data_get($case, 'case', 'studly');
}
switch ($case) {
case 'studly':
return studly_case($name);
case 'lower':
return strtolower($name);
case 'upper':
return strtoupper($name);
case 'snake':
return snake_case($name);
case 'title':
return title_case($name);
case 'camel':
return camel_case($name);
case 'kebab':
return kebab_case($name);
}
return $name;
} | [
"public",
"function",
"fileNameCaseConvention",
"(",
"$",
"name",
",",
"$",
"case",
"=",
"'studly'",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"case",
")",
")",
"{",
"$",
"case",
"=",
"data_get",
"(",
"$",
"case",
",",
"'case'",
",",
"'studly'",
")"... | File name case convention
@param $name
@param string $case
@return string | [
"File",
"name",
"case",
"convention"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L189-L213 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.findingStub | public function findingStub($stubName)
{
$stubRoots = $this->config->get('tie.stubs.path');
foreach ($stubRoots as $stubRoot) {
$stub = $stubRoot . '/' . $stubName . '.stub';
if ($this->filesystem->exists($stub)) {
return $stub;
}
}
return '';
} | php | public function findingStub($stubName)
{
$stubRoots = $this->config->get('tie.stubs.path');
foreach ($stubRoots as $stubRoot) {
$stub = $stubRoot . '/' . $stubName . '.stub';
if ($this->filesystem->exists($stub)) {
return $stub;
}
}
return '';
} | [
"public",
"function",
"findingStub",
"(",
"$",
"stubName",
")",
"{",
"$",
"stubRoots",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'tie.stubs.path'",
")",
";",
"foreach",
"(",
"$",
"stubRoots",
"as",
"$",
"stubRoot",
")",
"{",
"$",
"stub",
"="... | Finding multi location stub
@param $stubName
@return string | [
"Finding",
"multi",
"location",
"stub"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L221-L232 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.replaceStubString | protected function replaceStubString($className, $namespace)
{
return array_merge([
'VENDOR_NAME_LOWER' => strtolower($this->vendor),
'VENDOR_NAME' => studly_case($this->vendor),
'PACKAGE_NAME_LOWER' => strtolower($this->package),
'PACKAGE_NAME' => studly_case($this->package),
'DummyClass' => studly_case($className),
'DummyTarget' => strtolower($className),
'DummyNamespace' => $this->namespace . $namespace,
'DummyRootNamespace' => $this->laravel->getNamespace(),
], $this->config->get('tie.stubs.replace'));
} | php | protected function replaceStubString($className, $namespace)
{
return array_merge([
'VENDOR_NAME_LOWER' => strtolower($this->vendor),
'VENDOR_NAME' => studly_case($this->vendor),
'PACKAGE_NAME_LOWER' => strtolower($this->package),
'PACKAGE_NAME' => studly_case($this->package),
'DummyClass' => studly_case($className),
'DummyTarget' => strtolower($className),
'DummyNamespace' => $this->namespace . $namespace,
'DummyRootNamespace' => $this->laravel->getNamespace(),
], $this->config->get('tie.stubs.replace'));
} | [
"protected",
"function",
"replaceStubString",
"(",
"$",
"className",
",",
"$",
"namespace",
")",
"{",
"return",
"array_merge",
"(",
"[",
"'VENDOR_NAME_LOWER'",
"=>",
"strtolower",
"(",
"$",
"this",
"->",
"vendor",
")",
",",
"'VENDOR_NAME'",
"=>",
"studly_case",
... | Replace dummy name to real name
@param $className
@param $namespace
@return array | [
"Replace",
"dummy",
"name",
"to",
"real",
"name"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L241-L253 | train |
Shipu/laratie | src/Consoles/BaseCommand.php | BaseCommand.addingNamespaceInComposer | public function addingNamespaceInComposer($namespace, $path, $output = 'composer.json')
{
$file = base_path('composer.json');
$data = json_decode($this->filesystem->get($file), true);
$rootStub = $this->config->get('tie.stubs.root');
if(is_array($rootStub)) {
$rootStub = data_get($this->config->get($rootStub), 'path', '');
}
$path = str_replace(base_path().'/', '', $path) . '/' . $rootStub;
$data["autoload"]["psr-4"] = array_merge($data["autoload"]["psr-4"], [ $namespace => $path ]);
$this->filesystem->put(base_path($output), json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
} | php | public function addingNamespaceInComposer($namespace, $path, $output = 'composer.json')
{
$file = base_path('composer.json');
$data = json_decode($this->filesystem->get($file), true);
$rootStub = $this->config->get('tie.stubs.root');
if(is_array($rootStub)) {
$rootStub = data_get($this->config->get($rootStub), 'path', '');
}
$path = str_replace(base_path().'/', '', $path) . '/' . $rootStub;
$data["autoload"]["psr-4"] = array_merge($data["autoload"]["psr-4"], [ $namespace => $path ]);
$this->filesystem->put(base_path($output), json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
} | [
"public",
"function",
"addingNamespaceInComposer",
"(",
"$",
"namespace",
",",
"$",
"path",
",",
"$",
"output",
"=",
"'composer.json'",
")",
"{",
"$",
"file",
"=",
"base_path",
"(",
"'composer.json'",
")",
";",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"t... | Package namespace adding in composer
@param $namespace
@param $path
@param string $output
@internal param $key | [
"Package",
"namespace",
"adding",
"in",
"composer"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/BaseCommand.php#L263-L277 | train |
Shipu/laratie | src/Consoles/TieResourceCommand.php | TieResourceCommand.createStubs | public function createStubs()
{
foreach ($this->options() as $stubKey => $fileName) {
if(!blank($fileName) && $fileName) {
$this->resourceName = $fileName;
$this->stubKey = $stubKey;
if($stubKey == 'key') {
$this->stubKey = $fileName;
$this->resourceName = strtolower($this->ask('Enter your file name'));
}
$configuration = $this->config->get('tie.stubs.structure.' . $this->stubKey);
$this->createStubFiles($configuration);
}
}
} | php | public function createStubs()
{
foreach ($this->options() as $stubKey => $fileName) {
if(!blank($fileName) && $fileName) {
$this->resourceName = $fileName;
$this->stubKey = $stubKey;
if($stubKey == 'key') {
$this->stubKey = $fileName;
$this->resourceName = strtolower($this->ask('Enter your file name'));
}
$configuration = $this->config->get('tie.stubs.structure.' . $this->stubKey);
$this->createStubFiles($configuration);
}
}
} | [
"public",
"function",
"createStubs",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"options",
"(",
")",
"as",
"$",
"stubKey",
"=>",
"$",
"fileName",
")",
"{",
"if",
"(",
"!",
"blank",
"(",
"$",
"fileName",
")",
"&&",
"$",
"fileName",
")",
"{",
... | Eligible stub config | [
"Eligible",
"stub",
"config"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/TieResourceCommand.php#L82-L96 | train |
Shipu/laratie | src/Consoles/TieResourceCommand.php | TieResourceCommand.createStubFiles | public function createStubFiles($configuration)
{
$stubPathLocation = $this->path . '/' . data_get($configuration, 'path', $configuration);
$this->generateStubFile($stubPathLocation, $this->resourceName, $configuration);
$this->comment("Successfully Create ".$this->resourceName." Resource");
$this->comment("Path Location ".$stubPathLocation);
$this->output->writeln('');
} | php | public function createStubFiles($configuration)
{
$stubPathLocation = $this->path . '/' . data_get($configuration, 'path', $configuration);
$this->generateStubFile($stubPathLocation, $this->resourceName, $configuration);
$this->comment("Successfully Create ".$this->resourceName." Resource");
$this->comment("Path Location ".$stubPathLocation);
$this->output->writeln('');
} | [
"public",
"function",
"createStubFiles",
"(",
"$",
"configuration",
")",
"{",
"$",
"stubPathLocation",
"=",
"$",
"this",
"->",
"path",
".",
"'/'",
".",
"data_get",
"(",
"$",
"configuration",
",",
"'path'",
",",
"$",
"configuration",
")",
";",
"$",
"this",
... | Create Stub File
@param $configuration | [
"Create",
"Stub",
"File"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/TieResourceCommand.php#L103-L110 | train |
Shipu/laratie | src/Consoles/TieCommand.php | TieCommand.makeDefaultPackageStructure | public function makeDefaultPackageStructure()
{
$default = $this->config->get('tie.stubs.default');
if (!blank($default)) {
foreach ($default as $stubKey) {
$this->stubKey = $stubKey;
$configuration = $this->config->get('tie.stubs.structure.' . $stubKey);
if (is_array($configuration)) {
$this->createStubFiles($configuration);
} else {
$this->makeDir($this->path . '/' . $configuration);
}
}
}
} | php | public function makeDefaultPackageStructure()
{
$default = $this->config->get('tie.stubs.default');
if (!blank($default)) {
foreach ($default as $stubKey) {
$this->stubKey = $stubKey;
$configuration = $this->config->get('tie.stubs.structure.' . $stubKey);
if (is_array($configuration)) {
$this->createStubFiles($configuration);
} else {
$this->makeDir($this->path . '/' . $configuration);
}
}
}
} | [
"public",
"function",
"makeDefaultPackageStructure",
"(",
")",
"{",
"$",
"default",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'tie.stubs.default'",
")",
";",
"if",
"(",
"!",
"blank",
"(",
"$",
"default",
")",
")",
"{",
"foreach",
"(",
"$",
"... | Default configuration package structure | [
"Default",
"configuration",
"package",
"structure"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/TieCommand.php#L63-L77 | train |
Shipu/laratie | src/Consoles/TieCommand.php | TieCommand.createStubFiles | public function createStubFiles($configuration)
{
$stubPathLocation = $this->path . '/' . data_get($configuration, 'path', '');
if (isset($configuration['files'])) {
foreach ($configuration['files'] as $file) {
$this->generateStubFile($stubPathLocation, $file, $configuration);
}
}
} | php | public function createStubFiles($configuration)
{
$stubPathLocation = $this->path . '/' . data_get($configuration, 'path', '');
if (isset($configuration['files'])) {
foreach ($configuration['files'] as $file) {
$this->generateStubFile($stubPathLocation, $file, $configuration);
}
}
} | [
"public",
"function",
"createStubFiles",
"(",
"$",
"configuration",
")",
"{",
"$",
"stubPathLocation",
"=",
"$",
"this",
"->",
"path",
".",
"'/'",
".",
"data_get",
"(",
"$",
"configuration",
",",
"'path'",
",",
"''",
")",
";",
"if",
"(",
"isset",
"(",
... | Create default configuration folder and files
@param $configuration | [
"Create",
"default",
"configuration",
"folder",
"and",
"files"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/TieCommand.php#L84-L92 | train |
Shipu/laratie | src/Consoles/TieCommand.php | TieCommand.endingTask | public function endingTask()
{
$this->alert("Successfully Create ".$this->vendor.'/'.$this->package." Package");
$this->comment(str_repeat('*', 65));
$this->comment(' Package: '.$this->package);
$this->output->writeln('');
$this->line(' Namespace: '.htmlentities($this->namespace));
$this->output->writeln('');
$this->comment(' Path Location: '.$this->path);
$this->comment(str_repeat('*', 65));
$this->output->writeln('');
$this->alert("Run: composer dump-autoload");
} | php | public function endingTask()
{
$this->alert("Successfully Create ".$this->vendor.'/'.$this->package." Package");
$this->comment(str_repeat('*', 65));
$this->comment(' Package: '.$this->package);
$this->output->writeln('');
$this->line(' Namespace: '.htmlentities($this->namespace));
$this->output->writeln('');
$this->comment(' Path Location: '.$this->path);
$this->comment(str_repeat('*', 65));
$this->output->writeln('');
$this->alert("Run: composer dump-autoload");
} | [
"public",
"function",
"endingTask",
"(",
")",
"{",
"$",
"this",
"->",
"alert",
"(",
"\"Successfully Create \"",
".",
"$",
"this",
"->",
"vendor",
".",
"'/'",
".",
"$",
"this",
"->",
"package",
".",
"\" Package\"",
")",
";",
"$",
"this",
"->",
"comment",
... | After successfully creating task | [
"After",
"successfully",
"creating",
"task"
] | 45a73521467ab18a9bb56b53a287cff6f5a0b63a | https://github.com/Shipu/laratie/blob/45a73521467ab18a9bb56b53a287cff6f5a0b63a/src/Consoles/TieCommand.php#L97-L109 | train |
EmanueleMinotto/PlaceholdItProvider | PlaceholdItProvider.php | PlaceholdItProvider.imageUrl | public static function imageUrl($size, $format = 'gif', array $colors = [], $text = null)
{
// $colors should be 100 or 100x100
// but can be ['height' => 100, 'width' => 100]
// or ['w' => 100, 'h' => 100]
if (is_array($size)) {
ksort($size);
$size = implode('x', $size);
}
$base = 'http://placehold.it/'.$size.'.'.trim($format, '.');
// $colors should be ['background', 'text']
// but can be ['text' => '000', 'background' => 'fff']
// or ['txt' => '000', 'bg' => 'fff']
// or ['foreground' => '000', 'background' => 'fff']
// or ['fg' => '000', 'bg' => 'fff']
ksort($colors);
if (2 === count($colors)) {
$base .= '/'.implode('/', $colors);
}
if ($text) {
$base .= '?'.http_build_query([
'text' => $text,
]);
}
return $base;
} | php | public static function imageUrl($size, $format = 'gif', array $colors = [], $text = null)
{
// $colors should be 100 or 100x100
// but can be ['height' => 100, 'width' => 100]
// or ['w' => 100, 'h' => 100]
if (is_array($size)) {
ksort($size);
$size = implode('x', $size);
}
$base = 'http://placehold.it/'.$size.'.'.trim($format, '.');
// $colors should be ['background', 'text']
// but can be ['text' => '000', 'background' => 'fff']
// or ['txt' => '000', 'bg' => 'fff']
// or ['foreground' => '000', 'background' => 'fff']
// or ['fg' => '000', 'bg' => 'fff']
ksort($colors);
if (2 === count($colors)) {
$base .= '/'.implode('/', $colors);
}
if ($text) {
$base .= '?'.http_build_query([
'text' => $text,
]);
}
return $base;
} | [
"public",
"static",
"function",
"imageUrl",
"(",
"$",
"size",
",",
"$",
"format",
"=",
"'gif'",
",",
"array",
"$",
"colors",
"=",
"[",
"]",
",",
"$",
"text",
"=",
"null",
")",
"{",
"// $colors should be 100 or 100x100",
"// but can be ['height' => 100, 'width' =... | placehold.it image URL.
@param int|string|array $size Height is optional, if no height is specified the image will be a square.
@param string $format Adding an image file extension will render the image in the proper format.
@param array $colors An array containing background color and foreground color.
@param string $text Custom text can be entered using a query string at the very end of the url.
@return string | [
"placehold",
".",
"it",
"image",
"URL",
"."
] | 0d5b70ad56f26735c8caab83529befb8250841fa | https://github.com/EmanueleMinotto/PlaceholdItProvider/blob/0d5b70ad56f26735c8caab83529befb8250841fa/PlaceholdItProvider.php#L26-L56 | train |
noam148/yii2-image-resize | ImageResize.php | ImageResize.getUrl | public function getUrl($filePath, $width, $height, $mode = "outbound", $quality = null, $fileName = null) {
//get original file
$normalizePath = FileHelper::normalizePath(Yii::getAlias($filePath));
//get cache url
$filesUrls = [];
foreach ($this->cachePath as $cachePath)
{
$cacheUrl = Yii::getAlias($cachePath);
//generate file
$resizedFilePath = self::generateImage($normalizePath, $width, $height, $mode, $quality, $fileName);
//get resized file
$normalizeResizedFilePath = FileHelper::normalizePath($resizedFilePath);
$resizedFileName = pathinfo($normalizeResizedFilePath, PATHINFO_BASENAME);
//get url
$sFileUrl = Url::to('@web/' . $cacheUrl . '/' . substr($resizedFileName, 0, 2) . '/' . $resizedFileName, $this->absoluteUrl);
//return path
$filesUrls[] = $sFileUrl;
}
return $filesUrls[0];
} | php | public function getUrl($filePath, $width, $height, $mode = "outbound", $quality = null, $fileName = null) {
//get original file
$normalizePath = FileHelper::normalizePath(Yii::getAlias($filePath));
//get cache url
$filesUrls = [];
foreach ($this->cachePath as $cachePath)
{
$cacheUrl = Yii::getAlias($cachePath);
//generate file
$resizedFilePath = self::generateImage($normalizePath, $width, $height, $mode, $quality, $fileName);
//get resized file
$normalizeResizedFilePath = FileHelper::normalizePath($resizedFilePath);
$resizedFileName = pathinfo($normalizeResizedFilePath, PATHINFO_BASENAME);
//get url
$sFileUrl = Url::to('@web/' . $cacheUrl . '/' . substr($resizedFileName, 0, 2) . '/' . $resizedFileName, $this->absoluteUrl);
//return path
$filesUrls[] = $sFileUrl;
}
return $filesUrls[0];
} | [
"public",
"function",
"getUrl",
"(",
"$",
"filePath",
",",
"$",
"width",
",",
"$",
"height",
",",
"$",
"mode",
"=",
"\"outbound\"",
",",
"$",
"quality",
"=",
"null",
",",
"$",
"fileName",
"=",
"null",
")",
"{",
"//get original file \r",
"$",
"normalizePa... | Creates and caches the image and returns URL from resized file.
@param string $filePath to original file
@param integer $width
@param integer $height
@param string $mode
@param integer $quality (1 - 100 quality)
@param string $fileName (custome filename)
@return string | [
"Creates",
"and",
"caches",
"the",
"image",
"and",
"returns",
"URL",
"from",
"resized",
"file",
"."
] | 32c5adf7211e06cefc6861a2164855573e968038 | https://github.com/noam148/yii2-image-resize/blob/32c5adf7211e06cefc6861a2164855573e968038/ImageResize.php#L167-L188 | train |
noam148/yii2-image-resize | ImageResize.php | ImageResize.getCropRectangle | private function getCropRectangle($image, $targetBox, $horzMode, $vertMode)
{
$imageBox = $image->getSize();
$kw = $imageBox->getWidth() / $targetBox->getWidth();
$kh = $imageBox->getHeight() / $targetBox->getHeight();
$x = $y = $w = $h = 0;
if($kh > $kw) {
$x = 0;
$w = $imageBox->getWidth();
$h = $targetBox->getHeight() * $kw;
switch ($vertMode) {
case self::CROP_TOP:
$y = 0;
break;
case self::CROP_BOTTOM:
$y = $imageBox->getHeight() - $h;
break;
case self::CROP_CENTER:
$y = ($imageBox->getHeight() - $h) / 2;
break;
}
} else {
$y = 0;
$h = $imageBox->getHeight();
$w = $targetBox->getWidth() * $kh;
switch ($horzMode) {
case self::CROP_LEFT:
$x = 0;
break;
case self::CROP_RIGHT:
$x = $imageBox->getWidth() - $w;
break;
case self::CROP_CENTER:
$x = ($imageBox->getWidth() - $w) / 2;
break;
}
}
return [$x, $y, $w, $h];
} | php | private function getCropRectangle($image, $targetBox, $horzMode, $vertMode)
{
$imageBox = $image->getSize();
$kw = $imageBox->getWidth() / $targetBox->getWidth();
$kh = $imageBox->getHeight() / $targetBox->getHeight();
$x = $y = $w = $h = 0;
if($kh > $kw) {
$x = 0;
$w = $imageBox->getWidth();
$h = $targetBox->getHeight() * $kw;
switch ($vertMode) {
case self::CROP_TOP:
$y = 0;
break;
case self::CROP_BOTTOM:
$y = $imageBox->getHeight() - $h;
break;
case self::CROP_CENTER:
$y = ($imageBox->getHeight() - $h) / 2;
break;
}
} else {
$y = 0;
$h = $imageBox->getHeight();
$w = $targetBox->getWidth() * $kh;
switch ($horzMode) {
case self::CROP_LEFT:
$x = 0;
break;
case self::CROP_RIGHT:
$x = $imageBox->getWidth() - $w;
break;
case self::CROP_CENTER:
$x = ($imageBox->getWidth() - $w) / 2;
break;
}
}
return [$x, $y, $w, $h];
} | [
"private",
"function",
"getCropRectangle",
"(",
"$",
"image",
",",
"$",
"targetBox",
",",
"$",
"horzMode",
",",
"$",
"vertMode",
")",
"{",
"$",
"imageBox",
"=",
"$",
"image",
"->",
"getSize",
"(",
")",
";",
"$",
"kw",
"=",
"$",
"imageBox",
"->",
"get... | Get crop rectangle for custom thumbnail mode
@param ImageInterface $image
@param Box $targetBox
@param string $horzMode
@param string $vertMode
@return int[] | [
"Get",
"crop",
"rectangle",
"for",
"custom",
"thumbnail",
"mode"
] | 32c5adf7211e06cefc6861a2164855573e968038 | https://github.com/noam148/yii2-image-resize/blob/32c5adf7211e06cefc6861a2164855573e968038/ImageResize.php#L212-L250 | train |
giansalex/greenter-core | src/Core/Model/Perception/Perception.php | Perception.getName | public function getName()
{
$parts = [
$this->company->getRuc(),
'40',
$this->getSerie(),
$this->getCorrelativo(),
];
return join('-', $parts);
} | php | public function getName()
{
$parts = [
$this->company->getRuc(),
'40',
$this->getSerie(),
$this->getCorrelativo(),
];
return join('-', $parts);
} | [
"public",
"function",
"getName",
"(",
")",
"{",
"$",
"parts",
"=",
"[",
"$",
"this",
"->",
"company",
"->",
"getRuc",
"(",
")",
",",
"'40'",
",",
"$",
"this",
"->",
"getSerie",
"(",
")",
",",
"$",
"this",
"->",
"getCorrelativo",
"(",
")",
",",
"]... | Get FileName without extension.
@return string | [
"Get",
"FileName",
"without",
"extension",
"."
] | 024d6db507968f56af906e21a026d0c0d8fe9af1 | https://github.com/giansalex/greenter-core/blob/024d6db507968f56af906e21a026d0c0d8fe9af1/src/Core/Model/Perception/Perception.php#L308-L318 | train |
mpyw/co | src/Internal/ControlUtils.php | ControlUtils.getWrapperGenerator | public static function getWrapperGenerator(array $yieldables, callable $filter)
{
$gens = [];
foreach ($yieldables as $yieldable) {
$gens[(string)$yieldable['value']] = $filter($yieldable['value']);
}
yield CoInterface::RETURN_WITH => (yield $gens);
// @codeCoverageIgnoreStart
} | php | public static function getWrapperGenerator(array $yieldables, callable $filter)
{
$gens = [];
foreach ($yieldables as $yieldable) {
$gens[(string)$yieldable['value']] = $filter($yieldable['value']);
}
yield CoInterface::RETURN_WITH => (yield $gens);
// @codeCoverageIgnoreStart
} | [
"public",
"static",
"function",
"getWrapperGenerator",
"(",
"array",
"$",
"yieldables",
",",
"callable",
"$",
"filter",
")",
"{",
"$",
"gens",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"yieldables",
"as",
"$",
"yieldable",
")",
"{",
"$",
"gens",
"[",
"(... | Wrap yieldables with specified filter function.
@param array $yieldables
@param callable $filter self::reverse or self::fail.
@return \Generator | [
"Wrap",
"yieldables",
"with",
"specified",
"filter",
"function",
"."
] | 1ab101b8ef5feb634a028d385aadeba23da18dca | https://github.com/mpyw/co/blob/1ab101b8ef5feb634a028d385aadeba23da18dca/src/Internal/ControlUtils.php#L36-L44 | train |
mpyw/co | src/Internal/ControlUtils.php | ControlUtils.reverse | public static function reverse($yieldable)
{
try {
$result = (yield $yieldable);
} catch (\RuntimeException $e) {
yield CoInterface::RETURN_WITH => $e;
}
throw new ControlException($result);
} | php | public static function reverse($yieldable)
{
try {
$result = (yield $yieldable);
} catch (\RuntimeException $e) {
yield CoInterface::RETURN_WITH => $e;
}
throw new ControlException($result);
} | [
"public",
"static",
"function",
"reverse",
"(",
"$",
"yieldable",
")",
"{",
"try",
"{",
"$",
"result",
"=",
"(",
"yield",
"$",
"yieldable",
")",
";",
"}",
"catch",
"(",
"\\",
"RuntimeException",
"$",
"e",
")",
"{",
"yield",
"CoInterface",
"::",
"RETURN... | Handle success as ControlException, failure as resolved.
@param mixed $yieldable
@return \Generator | [
"Handle",
"success",
"as",
"ControlException",
"failure",
"as",
"resolved",
"."
] | 1ab101b8ef5feb634a028d385aadeba23da18dca | https://github.com/mpyw/co/blob/1ab101b8ef5feb634a028d385aadeba23da18dca/src/Internal/ControlUtils.php#L52-L60 | train |
mpyw/co | src/Co.php | Co.wait | public static function wait($value, array $options = [])
{
try {
if (self::$self) {
throw new \BadMethodCallException('Co::wait() is already running. Use Co::async() instead.');
}
self::$self = new self;
self::$self->options = new CoOption($options);
self::$self->pool = new Pool(self::$self->options);
return self::$self->start($value);
} finally {
self::$self = null;
}
// @codeCoverageIgnoreStart
} | php | public static function wait($value, array $options = [])
{
try {
if (self::$self) {
throw new \BadMethodCallException('Co::wait() is already running. Use Co::async() instead.');
}
self::$self = new self;
self::$self->options = new CoOption($options);
self::$self->pool = new Pool(self::$self->options);
return self::$self->start($value);
} finally {
self::$self = null;
}
// @codeCoverageIgnoreStart
} | [
"public",
"static",
"function",
"wait",
"(",
"$",
"value",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"try",
"{",
"if",
"(",
"self",
"::",
"$",
"self",
")",
"{",
"throw",
"new",
"\\",
"BadMethodCallException",
"(",
"'Co::wait() is already run... | Wait until value is recursively resolved to return it.
This function call must be atomic.
@param mixed $value
@param array $options
@return mixed | [
"Wait",
"until",
"value",
"is",
"recursively",
"resolved",
"to",
"return",
"it",
".",
"This",
"function",
"call",
"must",
"be",
"atomic",
"."
] | 1ab101b8ef5feb634a028d385aadeba23da18dca | https://github.com/mpyw/co/blob/1ab101b8ef5feb634a028d385aadeba23da18dca/src/Co.php#L67-L81 | train |
mpyw/co | src/Co.php | Co.start | private function start($value, $wait = true, $throw = null)
{
$return = null;
// For convenience, all values are wrapped into generator
$con = YieldableUtils::normalize($this->getRootGenerator($throw, $value, $return));
$promise = $this->processGeneratorContainerRunning($con);
if ($promise instanceof ExtendedPromiseInterface) {
// This is actually 100% true; just used for unwrapping Exception thrown.
$promise->done();
}
// We have to wait $return only if $wait
if ($wait) {
$this->pool->wait();
return $return;
}
} | php | private function start($value, $wait = true, $throw = null)
{
$return = null;
// For convenience, all values are wrapped into generator
$con = YieldableUtils::normalize($this->getRootGenerator($throw, $value, $return));
$promise = $this->processGeneratorContainerRunning($con);
if ($promise instanceof ExtendedPromiseInterface) {
// This is actually 100% true; just used for unwrapping Exception thrown.
$promise->done();
}
// We have to wait $return only if $wait
if ($wait) {
$this->pool->wait();
return $return;
}
} | [
"private",
"function",
"start",
"(",
"$",
"value",
",",
"$",
"wait",
"=",
"true",
",",
"$",
"throw",
"=",
"null",
")",
"{",
"$",
"return",
"=",
"null",
";",
"// For convenience, all values are wrapped into generator",
"$",
"con",
"=",
"YieldableUtils",
"::",
... | Start resovling.
@param mixed $value
@param bool $wait
@param mixed $throw Used for Co::async() overrides.
@param mixed If $wait, return resolved value. | [
"Start",
"resovling",
"."
] | 1ab101b8ef5feb634a028d385aadeba23da18dca | https://github.com/mpyw/co/blob/1ab101b8ef5feb634a028d385aadeba23da18dca/src/Co.php#L127-L142 | train |
mpyw/co | src/Co.php | Co.processGeneratorContainer | private function processGeneratorContainer(GeneratorContainer $gc)
{
return $gc->valid()
? $this->processGeneratorContainerRunning($gc)
: $this->processGeneratorContainerDone($gc);
} | php | private function processGeneratorContainer(GeneratorContainer $gc)
{
return $gc->valid()
? $this->processGeneratorContainerRunning($gc)
: $this->processGeneratorContainerDone($gc);
} | [
"private",
"function",
"processGeneratorContainer",
"(",
"GeneratorContainer",
"$",
"gc",
")",
"{",
"return",
"$",
"gc",
"->",
"valid",
"(",
")",
"?",
"$",
"this",
"->",
"processGeneratorContainerRunning",
"(",
"$",
"gc",
")",
":",
"$",
"this",
"->",
"proces... | Handle resolving generators.
@param GeneratorContainer $gc
@return PromiseInterface | [
"Handle",
"resolving",
"generators",
"."
] | 1ab101b8ef5feb634a028d385aadeba23da18dca | https://github.com/mpyw/co/blob/1ab101b8ef5feb634a028d385aadeba23da18dca/src/Co.php#L149-L154 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.