repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/Uploader.php
Uploader.saveFileToTmpDir
public function saveFileToTmpDir($fileId) { $baseTmpPath = $this->getBaseTmpPath(); $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath)); if (!$result) { throw new LocalizedException( __('File can not be saved to the destination folder.') ); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); $result['url'] = $this->getBaseUrl() . $this->getFilePath($baseTmpPath, $result['file']); if (isset($result['file'])) { try { $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->coreFileStorageDatabase->saveFile($relativePath); } catch (\Exception $e) { $this->logger->critical($e); throw new LocalizedException( __('Something went wrong while saving the file(s).') ); } } return $result; }
php
public function saveFileToTmpDir($fileId) { $baseTmpPath = $this->getBaseTmpPath(); $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath)); if (!$result) { throw new LocalizedException( __('File can not be saved to the destination folder.') ); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); $result['url'] = $this->getBaseUrl() . $this->getFilePath($baseTmpPath, $result['file']); if (isset($result['file'])) { try { $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->coreFileStorageDatabase->saveFile($relativePath); } catch (\Exception $e) { $this->logger->critical($e); throw new LocalizedException( __('Something went wrong while saving the file(s).') ); } } return $result; }
[ "public", "function", "saveFileToTmpDir", "(", "$", "fileId", ")", "{", "$", "baseTmpPath", "=", "$", "this", "->", "getBaseTmpPath", "(", ")", ";", "$", "uploader", "=", "$", "this", "->", "uploaderFactory", "->", "create", "(", "[", "'fileId'", "=>", "...
Checking file for save and save it to tmp dir @param string $fileId @return string[] @throws \Magento\Framework\Exception\LocalizedException
[ "Checking", "file", "for", "save", "and", "save", "it", "to", "tmp", "dir" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/Uploader.php#L265-L301
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Block/Adminhtml/Stores/Edit/Buttons/Generic.php
Generic.getStockistId
public function getStockistId() { try { return $this->stockistRepository->getById( $this->context->getRequest()->getParam('stockist_id') )->getId(); } catch (NoSuchEntityException $e) { return null; } }
php
public function getStockistId() { try { return $this->stockistRepository->getById( $this->context->getRequest()->getParam('stockist_id') )->getId(); } catch (NoSuchEntityException $e) { return null; } }
[ "public", "function", "getStockistId", "(", ")", "{", "try", "{", "return", "$", "this", "->", "stockistRepository", "->", "getById", "(", "$", "this", "->", "context", "->", "getRequest", "(", ")", "->", "getParam", "(", "'stockist_id'", ")", ")", "->", ...
Return Stockist page ID @return int|null
[ "Return", "Stockist", "page", "ID" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Block/Adminhtml/Stores/Edit/Buttons/Generic.php#L54-L63
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/StockistRepository.php
StockistRepository.save
public function save(StockistInterface $stockist) { /** @var StockistInterface|\Magento\Framework\Model\AbstractModel $stockist */ if ($stockist->getStoreId() == "") { $storeId = $this->storeManager->getStore()->getId(); $stockist->setStoreId($storeId); } try { $this->resource->save($stockist); } catch (\Exception $exception) { throw new CouldNotSaveException(__( 'Could not save the store: %1', $exception->getMessage() )); } return $stockist; }
php
public function save(StockistInterface $stockist) { /** @var StockistInterface|\Magento\Framework\Model\AbstractModel $stockist */ if ($stockist->getStoreId() == "") { $storeId = $this->storeManager->getStore()->getId(); $stockist->setStoreId($storeId); } try { $this->resource->save($stockist); } catch (\Exception $exception) { throw new CouldNotSaveException(__( 'Could not save the store: %1', $exception->getMessage() )); } return $stockist; }
[ "public", "function", "save", "(", "StockistInterface", "$", "stockist", ")", "{", "/** @var StockistInterface|\\Magento\\Framework\\Model\\AbstractModel $stockist */", "if", "(", "$", "stockist", "->", "getStoreId", "(", ")", "==", "\"\"", ")", "{", "$", "storeId", "...
Save page. @param \Limesharp\Stockists\Api\Data\StockistInterface $stockist @return \Limesharp\Stockists\Api\Data\StockistInterface @throws \Magento\Framework\Exception\LocalizedException
[ "Save", "page", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/StockistRepository.php#L96-L112
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/StockistRepository.php
StockistRepository.getById
public function getById($stockistId) { if (!isset($this->instances[$stockistId])) { /** @var \Limesharp\Stockists\Api\Data\StockistInterface|\Magento\Framework\Model\AbstractModel $stockist */ $stockist = $this->stockistInterfaceFactory->create(); $this->resource->load($stockist, $stockistId); if (!$stockist->getId()) { throw new NoSuchEntityException(__('Requested stockist doesn\'t exist')); } $this->instances[$stockistId] = $stockist; } return $this->instances[$stockistId];; }
php
public function getById($stockistId) { if (!isset($this->instances[$stockistId])) { /** @var \Limesharp\Stockists\Api\Data\StockistInterface|\Magento\Framework\Model\AbstractModel $stockist */ $stockist = $this->stockistInterfaceFactory->create(); $this->resource->load($stockist, $stockistId); if (!$stockist->getId()) { throw new NoSuchEntityException(__('Requested stockist doesn\'t exist')); } $this->instances[$stockistId] = $stockist; } return $this->instances[$stockistId];; }
[ "public", "function", "getById", "(", "$", "stockistId", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "instances", "[", "$", "stockistId", "]", ")", ")", "{", "/** @var \\Limesharp\\Stockists\\Api\\Data\\StockistInterface|\\Magento\\Framework\\Model\\Abs...
Retrieve Stockist. @param int $stockistId @return \Limesharp\Stockists\Api\Data\StockistInterface @throws \Magento\Framework\Exception\LocalizedException
[ "Retrieve", "Stockist", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/StockistRepository.php#L121-L137
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/StockistRepository.php
StockistRepository.getList
public function getList(SearchCriteriaInterface $searchCriteria) { /** @var \Limesharp\Stockists\Api\Data\StockistSearchResultsInterface $searchResults */ $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($searchCriteria); /** @var \Limesharp\Stockists\Model\ResourceModel\Stores\Collection $collection */ $collection = $this->stockistCollectionFactory->create(); //Add filters from root filter group to the collection /** @var FilterGroup $group */ foreach ($searchCriteria->getFilterGroups() as $group) { $this->addFilterGroupToCollection($group, $collection); } $sortOrders = $searchCriteria->getSortOrders(); /** @var SortOrder $sortOrder */ if ($sortOrders) { foreach ($searchCriteria->getSortOrders() as $sortOrder) { $field = $sortOrder->getField(); $collection->addOrder( $field, ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC' ); } } else { // set a default sorting order since this method is used constantly in many // different blocks $field = 'stockist_id'; $collection->addOrder($field, 'ASC'); } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); /** @var \Limesharp\Stockists\Api\Data\StockistInterface[] $stockists */ $stockists = []; /** @var \Limesharp\Stockists\Model\Stores $stockist */ foreach ($collection as $stockist) { /** @var \Limesharp\Stockists\Api\Data\StockistInterface $stockistDataObject */ $stockistDataObject = $this->stockistInterfaceFactory->create(); $this->dataObjectHelper->populateWithArray($stockistDataObject, $stockist->getData(), StockistInterface::class); $stockists[] = $stockistDataObject; } $searchResults->setTotalCount($collection->getSize()); return $searchResults->setItems($stockists); }
php
public function getList(SearchCriteriaInterface $searchCriteria) { /** @var \Limesharp\Stockists\Api\Data\StockistSearchResultsInterface $searchResults */ $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($searchCriteria); /** @var \Limesharp\Stockists\Model\ResourceModel\Stores\Collection $collection */ $collection = $this->stockistCollectionFactory->create(); //Add filters from root filter group to the collection /** @var FilterGroup $group */ foreach ($searchCriteria->getFilterGroups() as $group) { $this->addFilterGroupToCollection($group, $collection); } $sortOrders = $searchCriteria->getSortOrders(); /** @var SortOrder $sortOrder */ if ($sortOrders) { foreach ($searchCriteria->getSortOrders() as $sortOrder) { $field = $sortOrder->getField(); $collection->addOrder( $field, ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC' ); } } else { // set a default sorting order since this method is used constantly in many // different blocks $field = 'stockist_id'; $collection->addOrder($field, 'ASC'); } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); /** @var \Limesharp\Stockists\Api\Data\StockistInterface[] $stockists */ $stockists = []; /** @var \Limesharp\Stockists\Model\Stores $stockist */ foreach ($collection as $stockist) { /** @var \Limesharp\Stockists\Api\Data\StockistInterface $stockistDataObject */ $stockistDataObject = $this->stockistInterfaceFactory->create(); $this->dataObjectHelper->populateWithArray($stockistDataObject, $stockist->getData(), StockistInterface::class); $stockists[] = $stockistDataObject; } $searchResults->setTotalCount($collection->getSize()); return $searchResults->setItems($stockists); }
[ "public", "function", "getList", "(", "SearchCriteriaInterface", "$", "searchCriteria", ")", "{", "/** @var \\Limesharp\\Stockists\\Api\\Data\\StockistSearchResultsInterface $searchResults */", "$", "searchResults", "=", "$", "this", "->", "searchResultsFactory", "->", "create", ...
Retrieve pages matching the specified criteria. @param SearchCriteriaInterface $searchCriteria @return \Limesharp\Stockists\Api\Data\StockistSearchResultsInterface @throws \Magento\Framework\Exception\LocalizedException
[ "Retrieve", "pages", "matching", "the", "specified", "criteria", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/StockistRepository.php#L146-L190
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/StockistRepository.php
StockistRepository.delete
public function delete(StockistInterface $stockist) { /** @var \Limesharp\Stockists\Api\Data\StockistInterface|\Magento\Framework\Model\AbstractModel $stockist */ $id = $stockist->getId(); try { unset($this->instances[$id]); $this->resource->delete($stockist); } catch (ValidatorException $e) { throw new CouldNotSaveException(__($e->getMessage())); } catch (\Exception $e) { throw new StateException( __('Unable to remove stockist %1', $id) ); } unset($this->instances[$id]); return true; }
php
public function delete(StockistInterface $stockist) { /** @var \Limesharp\Stockists\Api\Data\StockistInterface|\Magento\Framework\Model\AbstractModel $stockist */ $id = $stockist->getId(); try { unset($this->instances[$id]); $this->resource->delete($stockist); } catch (ValidatorException $e) { throw new CouldNotSaveException(__($e->getMessage())); } catch (\Exception $e) { throw new StateException( __('Unable to remove stockist %1', $id) ); } unset($this->instances[$id]); return true; }
[ "public", "function", "delete", "(", "StockistInterface", "$", "stockist", ")", "{", "/** @var \\Limesharp\\Stockists\\Api\\Data\\StockistInterface|\\Magento\\Framework\\Model\\AbstractModel $stockist */", "$", "id", "=", "$", "stockist", "->", "getId", "(", ")", ";", "try", ...
Delete stockist. @param \Limesharp\Stockists\Api\Data\StockistInterface $stockist @return bool true on success @throws \Magento\Framework\Exception\LocalizedException
[ "Delete", "stockist", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/StockistRepository.php#L199-L215
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Model/StockistRepository.php
StockistRepository.addFilterGroupToCollection
public function addFilterGroupToCollection(FilterGroup $filterGroup, Collection $collection) { $fields = []; $conditions = []; foreach ($filterGroup->getFilters() as $filter) { $condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq'; $fields[] = $filter->getField(); $conditions[] = [$condition => $filter->getValue()]; } if ($fields) { $collection->addFieldToFilter($fields, $conditions); } return $this; }
php
public function addFilterGroupToCollection(FilterGroup $filterGroup, Collection $collection) { $fields = []; $conditions = []; foreach ($filterGroup->getFilters() as $filter) { $condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq'; $fields[] = $filter->getField(); $conditions[] = [$condition => $filter->getValue()]; } if ($fields) { $collection->addFieldToFilter($fields, $conditions); } return $this; }
[ "public", "function", "addFilterGroupToCollection", "(", "FilterGroup", "$", "filterGroup", ",", "Collection", "$", "collection", ")", "{", "$", "fields", "=", "[", "]", ";", "$", "conditions", "=", "[", "]", ";", "foreach", "(", "$", "filterGroup", "->", ...
Helper function that adds a FilterGroup to the collection. @param FilterGroup $filterGroup @param Collection $collection @return $this @throws \Magento\Framework\Exception\InputException
[ "Helper", "function", "that", "adds", "a", "FilterGroup", "to", "the", "collection", "." ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Model/StockistRepository.php#L239-L252
ClaudiuCreanga/magento2-store-locator-stockists-extension
src/Ui/Component/Listing/Column/StockistActions.php
StockistActions.prepareDataSource
public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { if (isset($item['stockist_id'])) { $item[$this->getData('name')] = [ 'edit' => [ 'href' => $this->_urlBuilder->getUrl( static::URL_PATH_EDIT, [ 'stockist_id' => $item['stockist_id'] ] ), 'label' => __('Edit') ], 'delete' => [ 'href' => $this->_urlBuilder->getUrl( static::URL_PATH_DELETE, [ 'stockist_id' => $item['stockist_id'] ] ), 'label' => __('Delete'), 'confirm' => [ 'title' => __('Delete "${ $.$data.name }"'), 'message' => __('Are you sure you wan\'t to delete the Store "${ $.$data.name }" ?') ] ] ]; } } } return $dataSource; }
php
public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as & $item) { if (isset($item['stockist_id'])) { $item[$this->getData('name')] = [ 'edit' => [ 'href' => $this->_urlBuilder->getUrl( static::URL_PATH_EDIT, [ 'stockist_id' => $item['stockist_id'] ] ), 'label' => __('Edit') ], 'delete' => [ 'href' => $this->_urlBuilder->getUrl( static::URL_PATH_DELETE, [ 'stockist_id' => $item['stockist_id'] ] ), 'label' => __('Delete'), 'confirm' => [ 'title' => __('Delete "${ $.$data.name }"'), 'message' => __('Are you sure you wan\'t to delete the Store "${ $.$data.name }" ?') ] ] ]; } } } return $dataSource; }
[ "public", "function", "prepareDataSource", "(", "array", "$", "dataSource", ")", "{", "if", "(", "isset", "(", "$", "dataSource", "[", "'data'", "]", "[", "'items'", "]", ")", ")", "{", "foreach", "(", "$", "dataSource", "[", "'data'", "]", "[", "'item...
Prepare Data Source @param array $dataSource @return array
[ "Prepare", "Data", "Source" ]
train
https://github.com/ClaudiuCreanga/magento2-store-locator-stockists-extension/blob/6dbef86fd8869b7796f8f2b55a40dde7a69caaaa/src/Ui/Component/Listing/Column/StockistActions.php#L78-L111
yiisoft/yii-bootstrap4
src/ActiveForm.php
ActiveForm.init
public function init(): void { if (!in_array($this->layout, [self::LAYOUT_DEFAULT, self::LAYOUT_HORIZONTAL, self::LAYOUT_INLINE])) { throw new InvalidConfigException('Invalid layout type: ' . $this->layout); } if ($this->layout === 'inline') { Html::addCssClass($this->options, 'form-inline'); } parent::init(); }
php
public function init(): void { if (!in_array($this->layout, [self::LAYOUT_DEFAULT, self::LAYOUT_HORIZONTAL, self::LAYOUT_INLINE])) { throw new InvalidConfigException('Invalid layout type: ' . $this->layout); } if ($this->layout === 'inline') { Html::addCssClass($this->options, 'form-inline'); } parent::init(); }
[ "public", "function", "init", "(", ")", ":", "void", "{", "if", "(", "!", "in_array", "(", "$", "this", "->", "layout", ",", "[", "self", "::", "LAYOUT_DEFAULT", ",", "self", "::", "LAYOUT_HORIZONTAL", ",", "self", "::", "LAYOUT_INLINE", "]", ")", ")",...
{@inheritdoc} @throws InvalidConfigException
[ "{" ]
train
https://github.com/yiisoft/yii-bootstrap4/blob/c47c36960421834843956af6a04220804952e09c/src/ActiveForm.php#L118-L128
yiisoft/yii-bootstrap4
src/Alert.php
Alert.init
public function init(): void { parent::init(); $this->initOptions(); echo Html::beginTag('div', $this->options) . "\n"; }
php
public function init(): void { parent::init(); $this->initOptions(); echo Html::beginTag('div', $this->options) . "\n"; }
[ "public", "function", "init", "(", ")", ":", "void", "{", "parent", "::", "init", "(", ")", ";", "$", "this", "->", "initOptions", "(", ")", ";", "echo", "Html", "::", "beginTag", "(", "'div'", ",", "$", "this", "->", "options", ")", ".", "\"\\n\""...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii-bootstrap4/blob/c47c36960421834843956af6a04220804952e09c/src/Alert.php#L74-L81
yiisoft/yii-bootstrap4
src/ToggleButtonGroup.php
ToggleButtonGroup.init
public function init(): void { parent::init(); $this->registerPlugin('button'); Html::addCssClass($this->options, ['btn-group']); $this->options['data-toggle'] = 'buttons'; }
php
public function init(): void { parent::init(); $this->registerPlugin('button'); Html::addCssClass($this->options, ['btn-group']); $this->options['data-toggle'] = 'buttons'; }
[ "public", "function", "init", "(", ")", ":", "void", "{", "parent", "::", "init", "(", ")", ";", "$", "this", "->", "registerPlugin", "(", "'button'", ")", ";", "Html", "::", "addCssClass", "(", "$", "this", "->", "options", ",", "[", "'btn-group'", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii-bootstrap4/blob/c47c36960421834843956af6a04220804952e09c/src/ToggleButtonGroup.php#L68-L74
yiisoft/yii-bootstrap4
src/Progress.php
Progress.renderBar
protected function renderBar($percent, $label = '', $options = []) { $options = array_merge($options, [ 'role' => 'progressbar', 'aria-valuenow' => $percent, 'aria-valuemin' => 0, 'aria-valuemax' => 100 ]); Html::addCssClass($options, ['widget' => 'progress-bar']); Html::addCssStyle($options, ['width' => $this->app->formatter->asPercent($percent / 100)], true); return Html::tag('div', $label, $options); }
php
protected function renderBar($percent, $label = '', $options = []) { $options = array_merge($options, [ 'role' => 'progressbar', 'aria-valuenow' => $percent, 'aria-valuemin' => 0, 'aria-valuemax' => 100 ]); Html::addCssClass($options, ['widget' => 'progress-bar']); Html::addCssStyle($options, ['width' => $this->app->formatter->asPercent($percent / 100)], true); return Html::tag('div', $label, $options); }
[ "protected", "function", "renderBar", "(", "$", "percent", ",", "$", "label", "=", "''", ",", "$", "options", "=", "[", "]", ")", "{", "$", "options", "=", "array_merge", "(", "$", "options", ",", "[", "'role'", "=>", "'progressbar'", ",", "'aria-value...
Generates a bar @param int $percent the percentage of the bar @param string $label , optional, the label to display at the bar @param array $options the HTML attributes of the bar @return string the rendering result.
[ "Generates", "a", "bar" ]
train
https://github.com/yiisoft/yii-bootstrap4/blob/c47c36960421834843956af6a04220804952e09c/src/Progress.php#L141-L153
yiisoft/yii-bootstrap4
src/Tabs.php
Tabs.init
public function init(): void { parent::init(); Html::addCssClass($this->options, ['widget' => 'nav', $this->navType]); Html::addCssClass($this->tabContentOptions, 'tab-content'); }
php
public function init(): void { parent::init(); Html::addCssClass($this->options, ['widget' => 'nav', $this->navType]); Html::addCssClass($this->tabContentOptions, 'tab-content'); }
[ "public", "function", "init", "(", ")", ":", "void", "{", "parent", "::", "init", "(", ")", ";", "Html", "::", "addCssClass", "(", "$", "this", "->", "options", ",", "[", "'widget'", "=>", "'nav'", ",", "$", "this", "->", "navType", "]", ")", ";", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii-bootstrap4/blob/c47c36960421834843956af6a04220804952e09c/src/Tabs.php#L139-L144
yiisoft/yii-bootstrap4
src/Tabs.php
Tabs.run
public function run() { $this->registerPlugin('tab'); $this->prepareItems($this->items); return Nav::widget([ 'dropdownClass' => $this->dropdownClass, 'options' => $this->options, 'items' => $this->items ]) . $this->renderPanes($this->panes); }
php
public function run() { $this->registerPlugin('tab'); $this->prepareItems($this->items); return Nav::widget([ 'dropdownClass' => $this->dropdownClass, 'options' => $this->options, 'items' => $this->items ]) . $this->renderPanes($this->panes); }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "registerPlugin", "(", "'tab'", ")", ";", "$", "this", "->", "prepareItems", "(", "$", "this", "->", "items", ")", ";", "return", "Nav", "::", "widget", "(", "[", "'dropdownClass'", "=>", ...
{@inheritdoc} @throws InvalidConfigException @throws \Exception
[ "{" ]
train
https://github.com/yiisoft/yii-bootstrap4/blob/c47c36960421834843956af6a04220804952e09c/src/Tabs.php#L151-L160
Symplify/PackageBuilder
src/Yaml/FileLoader/AbstractParameterMergingYamlFileLoader.php
AbstractParameterMergingYamlFileLoader.load
public function load($resource, $type = null): void { $path = $this->locator->locate($resource); /** @var mixed[]|null $content */ $content = $this->loadFile($path); $this->container->fileExists($path); // empty file if ($content === null) { return; } // imports: $this->parseImports($content, $path); $this->privatesCaller->callPrivateMethod($this, 'parseImports', $content, $path); // parameters if (isset($content[self::PARAMETERS_KEY])) { $this->ensureParametersIsArray($content, $path); foreach ($content[self::PARAMETERS_KEY] as $key => $value) { // $this->resolveServices($value, $path, true), $resolvedValue = $this->privatesCaller->callPrivateMethod( $this, 'resolveServices', $value, $path, true ); // only this section is different if ($this->container->hasParameter($key)) { $newValue = $this->parametersMerger->merge( $resolvedValue, $this->container->getParameter($key) ); $this->container->setParameter($key, $newValue); } else { $this->container->setParameter($key, $resolvedValue); } } } // extensions: $this->loadFromExtensions($content); $this->privatesCaller->callPrivateMethod($this, 'loadFromExtensions', $content); /** * services - not accessible, private parent properties, luckily not needed * - $this->anonymousServicesCount = 0; * - $this->anonymousServicesSuffix = ContainerBuilder::hash($path); */ $this->setCurrentDir(dirname($path)); try { // $this->parseDefinitions($content, $path); $this->privatesCaller->callPrivateMethod($this, 'parseDefinitions', $content, $path); } finally { $this->instanceof = []; } }
php
public function load($resource, $type = null): void { $path = $this->locator->locate($resource); /** @var mixed[]|null $content */ $content = $this->loadFile($path); $this->container->fileExists($path); // empty file if ($content === null) { return; } // imports: $this->parseImports($content, $path); $this->privatesCaller->callPrivateMethod($this, 'parseImports', $content, $path); // parameters if (isset($content[self::PARAMETERS_KEY])) { $this->ensureParametersIsArray($content, $path); foreach ($content[self::PARAMETERS_KEY] as $key => $value) { // $this->resolveServices($value, $path, true), $resolvedValue = $this->privatesCaller->callPrivateMethod( $this, 'resolveServices', $value, $path, true ); // only this section is different if ($this->container->hasParameter($key)) { $newValue = $this->parametersMerger->merge( $resolvedValue, $this->container->getParameter($key) ); $this->container->setParameter($key, $newValue); } else { $this->container->setParameter($key, $resolvedValue); } } } // extensions: $this->loadFromExtensions($content); $this->privatesCaller->callPrivateMethod($this, 'loadFromExtensions', $content); /** * services - not accessible, private parent properties, luckily not needed * - $this->anonymousServicesCount = 0; * - $this->anonymousServicesSuffix = ContainerBuilder::hash($path); */ $this->setCurrentDir(dirname($path)); try { // $this->parseDefinitions($content, $path); $this->privatesCaller->callPrivateMethod($this, 'parseDefinitions', $content, $path); } finally { $this->instanceof = []; } }
[ "public", "function", "load", "(", "$", "resource", ",", "$", "type", "=", "null", ")", ":", "void", "{", "$", "path", "=", "$", "this", "->", "locator", "->", "locate", "(", "$", "resource", ")", ";", "/** @var mixed[]|null $content */", "$", "content",...
Same as parent, just merging parameters instead overriding them @see https://github.com/Symplify/Symplify/pull/697 @param mixed $resource @param string|null $type
[ "Same", "as", "parent", "just", "merging", "parameters", "instead", "overriding", "them" ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/Yaml/FileLoader/AbstractParameterMergingYamlFileLoader.php#L50-L109
Symplify/PackageBuilder
src/HttpKernel/SimpleKernelTrait.php
SimpleKernelTrait.getUniqueKernelKey
private function getUniqueKernelKey(): string { if ($this->undescoredKernelName !== null) { return $this->undescoredKernelName; } $classParts = explode('\\', self::class); $bareClassName = array_pop($classParts); $bareClassNameWithoutSuffix = Strings::substring($bareClassName, 0, -strlen('Kernel')); $bareClassNameWithoutSuffix = lcfirst($bareClassNameWithoutSuffix); $this->undescoredKernelName = Strings::replace( $bareClassNameWithoutSuffix, '#[A-Z]#', function (array $matches): string { return '_' . strtolower($matches[0]); } ); return $this->undescoredKernelName; }
php
private function getUniqueKernelKey(): string { if ($this->undescoredKernelName !== null) { return $this->undescoredKernelName; } $classParts = explode('\\', self::class); $bareClassName = array_pop($classParts); $bareClassNameWithoutSuffix = Strings::substring($bareClassName, 0, -strlen('Kernel')); $bareClassNameWithoutSuffix = lcfirst($bareClassNameWithoutSuffix); $this->undescoredKernelName = Strings::replace( $bareClassNameWithoutSuffix, '#[A-Z]#', function (array $matches): string { return '_' . strtolower($matches[0]); } ); return $this->undescoredKernelName; }
[ "private", "function", "getUniqueKernelKey", "(", ")", ":", "string", "{", "if", "(", "$", "this", "->", "undescoredKernelName", "!==", "null", ")", "{", "return", "$", "this", "->", "undescoredKernelName", ";", "}", "$", "classParts", "=", "explode", "(", ...
E.g. "TokenRunnerKernel" => "token_runner"
[ "E", ".", "g", ".", "TokenRunnerKernel", "=", ">", "token_runner" ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/HttpKernel/SimpleKernelTrait.php#L47-L68
Symplify/PackageBuilder
src/Yaml/ParametersMerger.php
ParametersMerger.merge
public function merge($left, $right) { if (is_array($left) && is_array($right)) { foreach ($left as $key => $val) { if (is_int($key)) { $right[] = $val; } else { if (isset($right[$key])) { $val = $this->merge($val, $right[$key]); } $right[$key] = $val; } } return $right; } elseif ($left === null && is_array($right)) { return $right; } return $left; }
php
public function merge($left, $right) { if (is_array($left) && is_array($right)) { foreach ($left as $key => $val) { if (is_int($key)) { $right[] = $val; } else { if (isset($right[$key])) { $val = $this->merge($val, $right[$key]); } $right[$key] = $val; } } return $right; } elseif ($left === null && is_array($right)) { return $right; } return $left; }
[ "public", "function", "merge", "(", "$", "left", ",", "$", "right", ")", "{", "if", "(", "is_array", "(", "$", "left", ")", "&&", "is_array", "(", "$", "right", ")", ")", "{", "foreach", "(", "$", "left", "as", "$", "key", "=>", "$", "val", ")"...
Merges configurations. Left has higher priority than right one. @autor David Grudl (https://davidgrudl.com) @source https://github.com/nette/di/blob/8eb90721a131262f17663e50aee0032a62d0ef08/src/DI/Config/Helpers.php#L31 @param mixed $left @param mixed $right @return mixed[]|string
[ "Merges", "configurations", ".", "Left", "has", "higher", "priority", "than", "right", "one", "." ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/Yaml/ParametersMerger.php#L17-L36
Symplify/PackageBuilder
src/Yaml/ParametersMerger.php
ParametersMerger.mergeWithCombine
public function mergeWithCombine($left, $right) { if (is_array($left) && is_array($right)) { foreach ($left as $key => $val) { if (is_int($key)) { $right[] = $val; } else { if (isset($right[$key])) { $val = $this->mergeWithCombine($val, $right[$key]); } $right[$key] = $val; } } return $right; } elseif ($left === null && is_array($right)) { return $right; } if (! empty($right) && (array) $left !== (array) $right) { return $this->mergeWithCombine((array) $right, (array) $left); } return $left; }
php
public function mergeWithCombine($left, $right) { if (is_array($left) && is_array($right)) { foreach ($left as $key => $val) { if (is_int($key)) { $right[] = $val; } else { if (isset($right[$key])) { $val = $this->mergeWithCombine($val, $right[$key]); } $right[$key] = $val; } } return $right; } elseif ($left === null && is_array($right)) { return $right; } if (! empty($right) && (array) $left !== (array) $right) { return $this->mergeWithCombine((array) $right, (array) $left); } return $left; }
[ "public", "function", "mergeWithCombine", "(", "$", "left", ",", "$", "right", ")", "{", "if", "(", "is_array", "(", "$", "left", ")", "&&", "is_array", "(", "$", "right", ")", ")", "{", "foreach", "(", "$", "left", "as", "$", "key", "=>", "$", "...
The same as above, just with the case if both values being non-array, it will combined them to array: $this->mergeWithCombine(1, 2); // [1, 2] @param mixed $left @param mixed $right @return mixed[]|string
[ "The", "same", "as", "above", "just", "with", "the", "case", "if", "both", "values", "being", "non", "-", "array", "it", "will", "combined", "them", "to", "array", ":" ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/Yaml/ParametersMerger.php#L47-L70
Symplify/PackageBuilder
src/Console/Command/CommandNaming.php
CommandNaming.classToName
public static function classToName(string $class): string { $shortClassName = self::getShortClassName($class); $rawCommandName = Strings::substring($shortClassName, 0, -strlen('Command')); // ECSCommand => ecs for ($i = 0; $i < strlen($rawCommandName); ++$i) { if (ctype_upper($rawCommandName[$i]) && self::isFollowedByUpperCaseLetterOrNothing($rawCommandName, $i)) { $rawCommandName[$i] = strtolower($rawCommandName[$i]); } else { break; } } $rawCommandName = lcfirst($rawCommandName); return Strings::replace($rawCommandName, '#[A-Z]#', function (array $matches): string { return '-' . strtolower($matches[0]); }); }
php
public static function classToName(string $class): string { $shortClassName = self::getShortClassName($class); $rawCommandName = Strings::substring($shortClassName, 0, -strlen('Command')); // ECSCommand => ecs for ($i = 0; $i < strlen($rawCommandName); ++$i) { if (ctype_upper($rawCommandName[$i]) && self::isFollowedByUpperCaseLetterOrNothing($rawCommandName, $i)) { $rawCommandName[$i] = strtolower($rawCommandName[$i]); } else { break; } } $rawCommandName = lcfirst($rawCommandName); return Strings::replace($rawCommandName, '#[A-Z]#', function (array $matches): string { return '-' . strtolower($matches[0]); }); }
[ "public", "static", "function", "classToName", "(", "string", "$", "class", ")", ":", "string", "{", "$", "shortClassName", "=", "self", "::", "getShortClassName", "(", "$", "class", ")", ";", "$", "rawCommandName", "=", "Strings", "::", "substring", "(", ...
Converts: "SomeClass\SomeSuperCommand" → "some-super" "SomeClass\SOMESuperCommand" → "some-super"
[ "Converts", ":", "SomeClass", "\\", "SomeSuperCommand", "→", "some", "-", "super", "SomeClass", "\\", "SOMESuperCommand", "→", "some", "-", "super" ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/Console/Command/CommandNaming.php#L14-L33
Symplify/PackageBuilder
src/Console/HelpfulApplicationTrait.php
HelpfulApplicationTrait.cleanExtraCommandArgument
private function cleanExtraCommandArgument(Command $command): void { $arguments = $command->getDefinition()->getArguments(); if (! isset($arguments['command'])) { return; } unset($arguments['command']); $command->getDefinition()->setArguments($arguments); }
php
private function cleanExtraCommandArgument(Command $command): void { $arguments = $command->getDefinition()->getArguments(); if (! isset($arguments['command'])) { return; } unset($arguments['command']); $command->getDefinition()->setArguments($arguments); }
[ "private", "function", "cleanExtraCommandArgument", "(", "Command", "$", "command", ")", ":", "void", "{", "$", "arguments", "=", "$", "command", "->", "getDefinition", "(", ")", "->", "getArguments", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "ar...
Sometimes there is "command" argument, not really needed on fail of missing argument
[ "Sometimes", "there", "is", "command", "argument", "not", "really", "needed", "on", "fail", "of", "missing", "argument" ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/Console/HelpfulApplicationTrait.php#L45-L54
Symplify/PackageBuilder
src/DependencyInjection/CompilerPass/AutowireArrayParameterCompilerPass.php
AutowireArrayParameterCompilerPass.filterOutAbstractDefinitions
private function filterOutAbstractDefinitions(array $definitions): array { foreach ($definitions as $key => $definition) { if ($definition->isAbstract()) { unset($definitions[$key]); } } return $definitions; }
php
private function filterOutAbstractDefinitions(array $definitions): array { foreach ($definitions as $key => $definition) { if ($definition->isAbstract()) { unset($definitions[$key]); } } return $definitions; }
[ "private", "function", "filterOutAbstractDefinitions", "(", "array", "$", "definitions", ")", ":", "array", "{", "foreach", "(", "$", "definitions", "as", "$", "key", "=>", "$", "definition", ")", "{", "if", "(", "$", "definition", "->", "isAbstract", "(", ...
Abstract definitions cannot be the target of references @param Definition[] $definitions @return Definition[]
[ "Abstract", "definitions", "cannot", "be", "the", "target", "of", "references" ]
train
https://github.com/Symplify/PackageBuilder/blob/4f3a02afa8a5cd84a7169ce2d7394bb53e2b4f25/src/DependencyInjection/CompilerPass/AutowireArrayParameterCompilerPass.php#L201-L210
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.shouldColorize
static public function shouldColorize($colored = null) { return self::$_enabled === true || (self::$_enabled !== false && ($colored === true || ($colored !== false && Streams::isTty()))); }
php
static public function shouldColorize($colored = null) { return self::$_enabled === true || (self::$_enabled !== false && ($colored === true || ($colored !== false && Streams::isTty()))); }
[ "static", "public", "function", "shouldColorize", "(", "$", "colored", "=", "null", ")", "{", "return", "self", "::", "$", "_enabled", "===", "true", "||", "(", "self", "::", "$", "_enabled", "!==", "false", "&&", "(", "$", "colored", "===", "true", "|...
Check if we should colorize output based on local flags and shell type. Only check the shell type if `Colors::$_enabled` is null and `$colored` is null.
[ "Check", "if", "we", "should", "colorize", "output", "based", "on", "local", "flags", "and", "shell", "type", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L68-L73
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.color
static public function color($color) { if (!is_array($color)) { $color = compact('color'); } $color += array('color' => null, 'style' => null, 'background' => null); if ($color['color'] == 'reset') { return "\033[0m"; } $colors = array(); foreach (array('color', 'style', 'background') as $type) { $code = $color[$type]; if (isset(self::$_colors[$type][$code])) { $colors[] = self::$_colors[$type][$code]; } } if (empty($colors)) { $colors[] = 0; } return "\033[" . join(';', $colors) . "m"; }
php
static public function color($color) { if (!is_array($color)) { $color = compact('color'); } $color += array('color' => null, 'style' => null, 'background' => null); if ($color['color'] == 'reset') { return "\033[0m"; } $colors = array(); foreach (array('color', 'style', 'background') as $type) { $code = $color[$type]; if (isset(self::$_colors[$type][$code])) { $colors[] = self::$_colors[$type][$code]; } } if (empty($colors)) { $colors[] = 0; } return "\033[" . join(';', $colors) . "m"; }
[ "static", "public", "function", "color", "(", "$", "color", ")", "{", "if", "(", "!", "is_array", "(", "$", "color", ")", ")", "{", "$", "color", "=", "compact", "(", "'color'", ")", ";", "}", "$", "color", "+=", "array", "(", "'color'", "=>", "n...
Set the color. @param string $color The name of the color or style to set. @return string
[ "Set", "the", "color", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L81-L105
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.colorize
static public function colorize($string, $colored = null) { $passed = $string; if (!self::shouldColorize($colored)) { $return = self::decolorize( $passed, 2 /*keep_encodings*/ ); self::cacheString($passed, $return); return $return; } $md5 = md5($passed); if (isset(self::$_string_cache[$md5]['colorized'])) { return self::$_string_cache[$md5]['colorized']; } $string = str_replace('%%', '%¾', $string); foreach (self::getColors() as $key => $value) { $string = str_replace($key, self::color($value), $string); } $string = str_replace('%¾', '%', $string); self::cacheString($passed, $string); return $string; }
php
static public function colorize($string, $colored = null) { $passed = $string; if (!self::shouldColorize($colored)) { $return = self::decolorize( $passed, 2 /*keep_encodings*/ ); self::cacheString($passed, $return); return $return; } $md5 = md5($passed); if (isset(self::$_string_cache[$md5]['colorized'])) { return self::$_string_cache[$md5]['colorized']; } $string = str_replace('%%', '%¾', $string); foreach (self::getColors() as $key => $value) { $string = str_replace($key, self::color($value), $string); } $string = str_replace('%¾', '%', $string); self::cacheString($passed, $string); return $string; }
[ "static", "public", "function", "colorize", "(", "$", "string", ",", "$", "colored", "=", "null", ")", "{", "$", "passed", "=", "$", "string", ";", "if", "(", "!", "self", "::", "shouldColorize", "(", "$", "colored", ")", ")", "{", "$", "return", "...
Colorize a string using helpful string formatters. If the `Streams::$out` points to a TTY coloring will be enabled, otherwise disabled. You can control this check with the `$colored` parameter. @param string $string @param boolean $colored Force enable or disable the colorized output. If left as `null` the TTY will control coloring. @return string
[ "Colorize", "a", "string", "using", "helpful", "string", "formatters", ".", "If", "the", "Streams", "::", "$out", "points", "to", "a", "TTY", "coloring", "will", "be", "enabled", "otherwise", "disabled", ".", "You", "can", "control", "this", "check", "with",...
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L115-L139
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.decolorize
static public function decolorize( $string, $keep = 0 ) { if ( ! ( $keep & 1 ) ) { // Get rid of color tokens if they exist $string = str_replace('%%', '%¾', $string); $string = str_replace(array_keys(self::getColors()), '', $string); $string = str_replace('%¾', '%', $string); } if ( ! ( $keep & 2 ) ) { // Remove color encoding if it exists foreach (self::getColors() as $key => $value) { $string = str_replace(self::color($value), '', $string); } } return $string; }
php
static public function decolorize( $string, $keep = 0 ) { if ( ! ( $keep & 1 ) ) { // Get rid of color tokens if they exist $string = str_replace('%%', '%¾', $string); $string = str_replace(array_keys(self::getColors()), '', $string); $string = str_replace('%¾', '%', $string); } if ( ! ( $keep & 2 ) ) { // Remove color encoding if it exists foreach (self::getColors() as $key => $value) { $string = str_replace(self::color($value), '', $string); } } return $string; }
[ "static", "public", "function", "decolorize", "(", "$", "string", ",", "$", "keep", "=", "0", ")", "{", "if", "(", "!", "(", "$", "keep", "&", "1", ")", ")", "{", "// Get rid of color tokens if they exist", "$", "string", "=", "str_replace", "(", "'%%'",...
Remove color information from a string. @param string $string A string with color information. @param int $keep Optional. If the 1 bit is set, color tokens (eg "%n") won't be stripped. If the 2 bit is set, color encodings (ANSI escapes) won't be stripped. Default 0. @return string A string with color information removed.
[ "Remove", "color", "information", "from", "a", "string", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L148-L164
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.cacheString
static public function cacheString( $passed, $colorized, $deprecated = null ) { self::$_string_cache[md5($passed)] = array( 'passed' => $passed, 'colorized' => $colorized, 'decolorized' => self::decolorize($passed), // Not very useful but keep for BC. ); }
php
static public function cacheString( $passed, $colorized, $deprecated = null ) { self::$_string_cache[md5($passed)] = array( 'passed' => $passed, 'colorized' => $colorized, 'decolorized' => self::decolorize($passed), // Not very useful but keep for BC. ); }
[ "static", "public", "function", "cacheString", "(", "$", "passed", ",", "$", "colorized", ",", "$", "deprecated", "=", "null", ")", "{", "self", "::", "$", "_string_cache", "[", "md5", "(", "$", "passed", ")", "]", "=", "array", "(", "'passed'", "=>", ...
Cache the original, colorized, and decolorized versions of a string. @param string $passed The original string before colorization. @param string $colorized The string after running through self::colorize. @param string $deprecated Optional. Not used. Default null.
[ "Cache", "the", "original", "colorized", "and", "decolorized", "versions", "of", "a", "string", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L173-L179
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.width
static public function width( $string, $pre_colorized = false, $encoding = false ) { return strwidth( $pre_colorized || self::shouldColorize() ? self::decolorize( $string, $pre_colorized ? 1 /*keep_tokens*/ : 0 ) : $string, $encoding ); }
php
static public function width( $string, $pre_colorized = false, $encoding = false ) { return strwidth( $pre_colorized || self::shouldColorize() ? self::decolorize( $string, $pre_colorized ? 1 /*keep_tokens*/ : 0 ) : $string, $encoding ); }
[ "static", "public", "function", "width", "(", "$", "string", ",", "$", "pre_colorized", "=", "false", ",", "$", "encoding", "=", "false", ")", "{", "return", "strwidth", "(", "$", "pre_colorized", "||", "self", "::", "shouldColorize", "(", ")", "?", "sel...
Return the width (length in characters) of the string without color codes if enabled. @param string $string The string to measure. @param bool $pre_colorized Optional. Set if the string is pre-colorized. Default false. @param string|bool $encoding Optional. The encoding of the string. Default false. @return int
[ "Return", "the", "width", "(", "length", "in", "characters", ")", "of", "the", "string", "without", "color", "codes", "if", "enabled", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L199-L201
wp-cli/php-cli-tools
lib/cli/Colors.php
Colors.pad
static public function pad( $string, $length, $pre_colorized = false, $encoding = false, $pad_type = STR_PAD_RIGHT ) { $real_length = self::width( $string, $pre_colorized, $encoding ); $diff = strlen( $string ) - $real_length; $length += $diff; return str_pad( $string, $length, ' ', $pad_type ); }
php
static public function pad( $string, $length, $pre_colorized = false, $encoding = false, $pad_type = STR_PAD_RIGHT ) { $real_length = self::width( $string, $pre_colorized, $encoding ); $diff = strlen( $string ) - $real_length; $length += $diff; return str_pad( $string, $length, ' ', $pad_type ); }
[ "static", "public", "function", "pad", "(", "$", "string", ",", "$", "length", ",", "$", "pre_colorized", "=", "false", ",", "$", "encoding", "=", "false", ",", "$", "pad_type", "=", "STR_PAD_RIGHT", ")", "{", "$", "real_length", "=", "self", "::", "wi...
Pad the string to a certain display length. @param string $string The string to pad. @param int $length The display length. @param bool $pre_colorized Optional. Set if the string is pre-colorized. Default false. @param string|bool $encoding Optional. The encoding of the string. Default false. @param int $pad_type Optional. Can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT. @return string
[ "Pad", "the", "string", "to", "a", "certain", "display", "length", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Colors.php#L213-L219
wp-cli/php-cli-tools
lib/cli/notify/Spinner.php
Spinner.display
public function display($finish = false) { $msg = $this->_message; $idx = $this->_iteration++ % strlen($this->_chars); $char = $this->_chars[$idx]; $speed = number_format(round($this->speed())); $elapsed = $this->formatTime($this->elapsed()); Streams::out_padded($this->_format, compact('msg', 'char', 'elapsed', 'speed')); }
php
public function display($finish = false) { $msg = $this->_message; $idx = $this->_iteration++ % strlen($this->_chars); $char = $this->_chars[$idx]; $speed = number_format(round($this->speed())); $elapsed = $this->formatTime($this->elapsed()); Streams::out_padded($this->_format, compact('msg', 'char', 'elapsed', 'speed')); }
[ "public", "function", "display", "(", "$", "finish", "=", "false", ")", "{", "$", "msg", "=", "$", "this", "->", "_message", ";", "$", "idx", "=", "$", "this", "->", "_iteration", "++", "%", "strlen", "(", "$", "this", "->", "_chars", ")", ";", "...
Prints the current spinner position to `STDOUT` with the time elapsed and tick speed. @param boolean $finish `true` if this was called from `cli\Notify::finish()`, `false` otherwise. @see cli\out_padded() @see cli\Notify::formatTime() @see cli\Notify::speed()
[ "Prints", "the", "current", "spinner", "position", "to", "STDOUT", "with", "the", "time", "elapsed", "and", "tick", "speed", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/notify/Spinner.php#L36-L44
wp-cli/php-cli-tools
lib/cli/Progress.php
Progress.estimated
public function estimated() { $speed = $this->speed(); if (!$speed || !$this->elapsed()) { return 0; } $estimated = round($this->_total / $speed); return $estimated; }
php
public function estimated() { $speed = $this->speed(); if (!$speed || !$this->elapsed()) { return 0; } $estimated = round($this->_total / $speed); return $estimated; }
[ "public", "function", "estimated", "(", ")", "{", "$", "speed", "=", "$", "this", "->", "speed", "(", ")", ";", "if", "(", "!", "$", "speed", "||", "!", "$", "this", "->", "elapsed", "(", ")", ")", "{", "return", "0", ";", "}", "$", "estimated"...
Calculates the estimated total time for the tick count to reach the total ticks given. @return int The estimated total number of seconds for all ticks to be completed. This is not the estimated time left, but total. @see cli\Notify::speed() @see cli\Notify::elapsed()
[ "Calculates", "the", "estimated", "total", "time", "for", "the", "tick", "count", "to", "reach", "the", "total", "ticks", "given", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Progress.php#L93-L101
wp-cli/php-cli-tools
lib/cli/Progress.php
Progress.increment
public function increment($increment = 1) { $this->_current = min($this->_total, $this->_current + $increment); }
php
public function increment($increment = 1) { $this->_current = min($this->_total, $this->_current + $increment); }
[ "public", "function", "increment", "(", "$", "increment", "=", "1", ")", "{", "$", "this", "->", "_current", "=", "min", "(", "$", "this", "->", "_total", ",", "$", "this", "->", "_current", "+", "$", "increment", ")", ";", "}" ]
Increments are tick counter by the given amount. If no amount is provided, the ticker is incremented by 1. @param int $increment The amount to increment by.
[ "Increments", "are", "tick", "counter", "by", "the", "given", "amount", ".", "If", "no", "amount", "is", "provided", "the", "ticker", "is", "incremented", "by", "1", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Progress.php#L118-L120
wp-cli/php-cli-tools
lib/cli/arguments/Argument.php
Argument.exploded
public function exploded() { $exploded = array(); for ($i = strlen($this->_argument); $i > 0; $i--) { array_push($exploded, $this->_argument[$i - 1]); } $this->_argument = array_pop($exploded); $this->_raw = '-' . $this->_argument; return $exploded; }
php
public function exploded() { $exploded = array(); for ($i = strlen($this->_argument); $i > 0; $i--) { array_push($exploded, $this->_argument[$i - 1]); } $this->_argument = array_pop($exploded); $this->_raw = '-' . $this->_argument; return $exploded; }
[ "public", "function", "exploded", "(", ")", "{", "$", "exploded", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "strlen", "(", "$", "this", "->", "_argument", ")", ";", "$", "i", ">", "0", ";", "$", "i", "--", ")", "{", "array_push", ...
Returns all but the first character of the argument, removing them from the objects representation at the same time. @return array
[ "Returns", "all", "but", "the", "first", "character", "of", "the", "argument", "removing", "them", "from", "the", "objects", "representation", "at", "the", "same", "time", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/arguments/Argument.php#L126-L136
wp-cli/php-cli-tools
lib/cli/Table.php
Table.checkRow
protected function checkRow(array $row) { foreach ($row as $column => $str) { $width = Colors::width( $str, $this->isAsciiPreColorized( $column ) ); if (!isset($this->_width[$column]) || $width > $this->_width[$column]) { $this->_width[$column] = $width; } } return $row; }
php
protected function checkRow(array $row) { foreach ($row as $column => $str) { $width = Colors::width( $str, $this->isAsciiPreColorized( $column ) ); if (!isset($this->_width[$column]) || $width > $this->_width[$column]) { $this->_width[$column] = $width; } } return $row; }
[ "protected", "function", "checkRow", "(", "array", "$", "row", ")", "{", "foreach", "(", "$", "row", "as", "$", "column", "=>", "$", "str", ")", "{", "$", "width", "=", "Colors", "::", "width", "(", "$", "str", ",", "$", "this", "->", "isAsciiPreCo...
Loops through the row and sets the maximum width for each column. @param array $row The table row. @return array $row
[ "Loops", "through", "the", "row", "and", "sets", "the", "maximum", "width", "for", "each", "column", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Table.php#L103-L112
wp-cli/php-cli-tools
lib/cli/Table.php
Table.getDisplayLines
public function getDisplayLines() { $this->_renderer->setWidths($this->_width, $fallback = true); $border = $this->_renderer->border(); $out = array(); if (isset($border)) { $out[] = $border; } $out[] = $this->_renderer->row($this->_headers); if (isset($border)) { $out[] = $border; } foreach ($this->_rows as $row) { $row = $this->_renderer->row($row); $row = explode( PHP_EOL, $row ); $out = array_merge( $out, $row ); } if (isset($border)) { $out[] = $border; } if ($this->_footers) { $out[] = $this->_renderer->row($this->_footers); if (isset($border)) { $out[] = $border; } } return $out; }
php
public function getDisplayLines() { $this->_renderer->setWidths($this->_width, $fallback = true); $border = $this->_renderer->border(); $out = array(); if (isset($border)) { $out[] = $border; } $out[] = $this->_renderer->row($this->_headers); if (isset($border)) { $out[] = $border; } foreach ($this->_rows as $row) { $row = $this->_renderer->row($row); $row = explode( PHP_EOL, $row ); $out = array_merge( $out, $row ); } if (isset($border)) { $out[] = $border; } if ($this->_footers) { $out[] = $this->_renderer->row($this->_footers); if (isset($border)) { $out[] = $border; } } return $out; }
[ "public", "function", "getDisplayLines", "(", ")", "{", "$", "this", "->", "_renderer", "->", "setWidths", "(", "$", "this", "->", "_width", ",", "$", "fallback", "=", "true", ")", ";", "$", "border", "=", "$", "this", "->", "_renderer", "->", "border"...
Get the table lines to output. @see cli\Table::display() @see cli\Table::renderRow() @return array
[ "Get", "the", "table", "lines", "to", "output", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Table.php#L138-L168
wp-cli/php-cli-tools
lib/cli/Table.php
Table.sort
public function sort($column) { if (!isset($this->_headers[$column])) { trigger_error('No column with index ' . $column, E_USER_NOTICE); return; } usort($this->_rows, function($a, $b) use ($column) { return strcmp($a[$column], $b[$column]); }); }
php
public function sort($column) { if (!isset($this->_headers[$column])) { trigger_error('No column with index ' . $column, E_USER_NOTICE); return; } usort($this->_rows, function($a, $b) use ($column) { return strcmp($a[$column], $b[$column]); }); }
[ "public", "function", "sort", "(", "$", "column", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_headers", "[", "$", "column", "]", ")", ")", "{", "trigger_error", "(", "'No column with index '", ".", "$", "column", ",", "E_USER_NOTICE", ...
Sort the table by a column. Must be called before `cli\Table::display()`. @param int $column The index of the column to sort by.
[ "Sort", "the", "table", "by", "a", "column", ".", "Must", "be", "called", "before", "cli", "\\", "Table", "::", "display", "()", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Table.php#L175-L184
wp-cli/php-cli-tools
lib/cli/Table.php
Table.isAsciiPreColorized
private function isAsciiPreColorized( $column ) { if ( $this->_renderer instanceof Ascii ) { return $this->_renderer->isPreColorized( $column ); } return false; }
php
private function isAsciiPreColorized( $column ) { if ( $this->_renderer instanceof Ascii ) { return $this->_renderer->isPreColorized( $column ); } return false; }
[ "private", "function", "isAsciiPreColorized", "(", "$", "column", ")", "{", "if", "(", "$", "this", "->", "_renderer", "instanceof", "Ascii", ")", "{", "return", "$", "this", "->", "_renderer", "->", "isPreColorized", "(", "$", "column", ")", ";", "}", "...
Is a column in an Ascii table pre-colorized? @param int $column Column index to check. @return bool True if whole Ascii table is marked as pre-colorized, or if the individual column is pre-colorized; else false. @see cli\Ascii::isPreColorized()
[ "Is", "a", "column", "in", "an", "Ascii", "table", "pre", "-", "colorized?" ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Table.php#L251-L256
wp-cli/php-cli-tools
lib/cli/arguments/Lexer.php
Lexer.rewind
public function rewind() { $this->_shift(); if ($this->_first) { $this->_index = 0; $this->_first = false; } }
php
public function rewind() { $this->_shift(); if ($this->_first) { $this->_index = 0; $this->_first = false; } }
[ "public", "function", "rewind", "(", ")", "{", "$", "this", "->", "_shift", "(", ")", ";", "if", "(", "$", "this", "->", "_first", ")", "{", "$", "this", "->", "_index", "=", "0", ";", "$", "this", "->", "_first", "=", "false", ";", "}", "}" ]
Move forward 1 element and, if the method hasn't been called before, reset the cursor's position to 0.
[ "Move", "forward", "1", "element", "and", "if", "the", "method", "hasn", "t", "been", "called", "before", "reset", "the", "cursor", "s", "position", "to", "0", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/arguments/Lexer.php#L71-L77
wp-cli/php-cli-tools
lib/cli/tree/Markdown.php
Markdown.render
public function render(array $tree, $level = 0) { $output = ''; foreach ($tree as $label => $next) { if (is_string($next)) { $label = $next; } // Output the label $output .= sprintf("%s- %s\n", str_repeat(' ', $level * $this->_padding), $label); // Next level if (is_array($next)) { $output .= $this->render($next, $level + 1); } } return $output; }
php
public function render(array $tree, $level = 0) { $output = ''; foreach ($tree as $label => $next) { if (is_string($next)) { $label = $next; } // Output the label $output .= sprintf("%s- %s\n", str_repeat(' ', $level * $this->_padding), $label); // Next level if (is_array($next)) { $output .= $this->render($next, $level + 1); } } return $output; }
[ "public", "function", "render", "(", "array", "$", "tree", ",", "$", "level", "=", "0", ")", "{", "$", "output", "=", "''", ";", "foreach", "(", "$", "tree", "as", "$", "label", "=>", "$", "next", ")", "{", "if", "(", "is_string", "(", "$", "ne...
Renders the tree @param array $tree @param int $level Optional @return string
[ "Renders", "the", "tree" ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/tree/Markdown.php#L44-L68
wp-cli/php-cli-tools
lib/cli/table/Ascii.php
Ascii.setWidths
public function setWidths(array $widths, $fallback = false) { if ($fallback) { foreach ( $this->_widths as $index => $value ) { $widths[$index] = $value; } } $this->_widths = $widths; if ( is_null( $this->_constraintWidth ) ) { $this->_constraintWidth = (int) Shell::columns(); } $col_count = count( $widths ); $col_borders_count = $col_count ? ( ( $col_count - 1 ) * strlen( $this->_characters['border'] ) ) : 0; $table_borders_count = strlen( $this->_characters['border'] ) * 2; $col_padding_count = $col_count * strlen( $this->_characters['padding'] ) * 2; $max_width = $this->_constraintWidth - $col_borders_count - $table_borders_count - $col_padding_count; if ( $widths && $max_width && array_sum( $widths ) > $max_width ) { $avg = floor( $max_width / count( $widths ) ); $resize_widths = array(); $extra_width = 0; foreach( $widths as $width ) { if ( $width > $avg ) { $resize_widths[] = $width; } else { $extra_width = $extra_width + ( $avg - $width ); } } if ( ! empty( $resize_widths ) && $extra_width ) { $avg_extra_width = floor( $extra_width / count( $resize_widths ) ); foreach( $widths as &$width ) { if ( in_array( $width, $resize_widths ) ) { $width = $avg + $avg_extra_width; array_shift( $resize_widths ); // Last item gets the cake if ( empty( $resize_widths ) ) { $width = 0; // Zero it so not in sum. $width = $max_width - array_sum( $widths ); } } } } } $this->_widths = $widths; }
php
public function setWidths(array $widths, $fallback = false) { if ($fallback) { foreach ( $this->_widths as $index => $value ) { $widths[$index] = $value; } } $this->_widths = $widths; if ( is_null( $this->_constraintWidth ) ) { $this->_constraintWidth = (int) Shell::columns(); } $col_count = count( $widths ); $col_borders_count = $col_count ? ( ( $col_count - 1 ) * strlen( $this->_characters['border'] ) ) : 0; $table_borders_count = strlen( $this->_characters['border'] ) * 2; $col_padding_count = $col_count * strlen( $this->_characters['padding'] ) * 2; $max_width = $this->_constraintWidth - $col_borders_count - $table_borders_count - $col_padding_count; if ( $widths && $max_width && array_sum( $widths ) > $max_width ) { $avg = floor( $max_width / count( $widths ) ); $resize_widths = array(); $extra_width = 0; foreach( $widths as $width ) { if ( $width > $avg ) { $resize_widths[] = $width; } else { $extra_width = $extra_width + ( $avg - $width ); } } if ( ! empty( $resize_widths ) && $extra_width ) { $avg_extra_width = floor( $extra_width / count( $resize_widths ) ); foreach( $widths as &$width ) { if ( in_array( $width, $resize_widths ) ) { $width = $avg + $avg_extra_width; array_shift( $resize_widths ); // Last item gets the cake if ( empty( $resize_widths ) ) { $width = 0; // Zero it so not in sum. $width = $max_width - array_sum( $widths ); } } } } } $this->_widths = $widths; }
[ "public", "function", "setWidths", "(", "array", "$", "widths", ",", "$", "fallback", "=", "false", ")", "{", "if", "(", "$", "fallback", ")", "{", "foreach", "(", "$", "this", "->", "_widths", "as", "$", "index", "=>", "$", "value", ")", "{", "$",...
Set the widths of each column in the table. @param array $widths The widths of the columns. @param bool $fallback Whether to use these values as fallback only.
[ "Set", "the", "widths", "of", "each", "column", "in", "the", "table", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/table/Ascii.php#L38-L86
wp-cli/php-cli-tools
lib/cli/table/Ascii.php
Ascii.border
public function border() { if (!isset($this->_border)) { $this->_border = $this->_characters['corner']; foreach ($this->_widths as $width) { $this->_border .= str_repeat($this->_characters['line'], $width + 2); $this->_border .= $this->_characters['corner']; } } return $this->_border; }
php
public function border() { if (!isset($this->_border)) { $this->_border = $this->_characters['corner']; foreach ($this->_widths as $width) { $this->_border .= str_repeat($this->_characters['line'], $width + 2); $this->_border .= $this->_characters['corner']; } } return $this->_border; }
[ "public", "function", "border", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_border", ")", ")", "{", "$", "this", "->", "_border", "=", "$", "this", "->", "_characters", "[", "'corner'", "]", ";", "foreach", "(", "$", "this", ...
Render a border for the top and bottom and separating the headers from the table rows. @return string The table border.
[ "Render", "a", "border", "for", "the", "top", "and", "bottom", "and", "separating", "the", "headers", "from", "the", "table", "rows", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/table/Ascii.php#L114-L124
wp-cli/php-cli-tools
lib/cli/table/Ascii.php
Ascii.row
public function row( array $row ) { $extra_row_count = 0; if ( count( $row ) > 0 ) { $extra_rows = array_fill( 0, count( $row ), array() ); foreach( $row as $col => $value ) { $value = str_replace( array( "\r\n", "\n" ), ' ', $value ); $col_width = $this->_widths[ $col ]; $encoding = function_exists( 'mb_detect_encoding' ) ? mb_detect_encoding( $value, null, true /*strict*/ ) : false; $original_val_width = Colors::width( $value, self::isPreColorized( $col ), $encoding ); if ( $col_width && $original_val_width > $col_width ) { $row[ $col ] = \cli\safe_substr( $value, 0, $col_width, true /*is_width*/, $encoding ); $value = \cli\safe_substr( $value, \cli\safe_strlen( $row[ $col ], $encoding ), null /*length*/, false /*is_width*/, $encoding ); $i = 0; do { $extra_value = \cli\safe_substr( $value, 0, $col_width, true /*is_width*/, $encoding ); $val_width = Colors::width( $extra_value, self::isPreColorized( $col ), $encoding ); if ( $val_width ) { $extra_rows[ $col ][] = $extra_value; $value = \cli\safe_substr( $value, \cli\safe_strlen( $extra_value, $encoding ), null /*length*/, false /*is_width*/, $encoding ); $i++; if ( $i > $extra_row_count ) { $extra_row_count = $i; } } } while( $value ); } } } $row = array_map(array($this, 'padColumn'), $row, array_keys($row)); array_unshift($row, ''); // First border array_push($row, ''); // Last border $ret = join($this->_characters['border'], $row); if ( $extra_row_count ) { foreach( $extra_rows as $col => $col_values ) { while( count( $col_values ) < $extra_row_count ) { $col_values[] = ''; } } do { $row_values = array(); $has_more = false; foreach( $extra_rows as $col => &$col_values ) { $row_values[ $col ] = array_shift( $col_values ); if ( count( $col_values ) ) { $has_more = true; } } $row_values = array_map(array($this, 'padColumn'), $row_values, array_keys($row_values)); array_unshift($row_values, ''); // First border array_push($row_values, ''); // Last border $ret .= PHP_EOL . join($this->_characters['border'], $row_values); } while( $has_more ); } return $ret; }
php
public function row( array $row ) { $extra_row_count = 0; if ( count( $row ) > 0 ) { $extra_rows = array_fill( 0, count( $row ), array() ); foreach( $row as $col => $value ) { $value = str_replace( array( "\r\n", "\n" ), ' ', $value ); $col_width = $this->_widths[ $col ]; $encoding = function_exists( 'mb_detect_encoding' ) ? mb_detect_encoding( $value, null, true /*strict*/ ) : false; $original_val_width = Colors::width( $value, self::isPreColorized( $col ), $encoding ); if ( $col_width && $original_val_width > $col_width ) { $row[ $col ] = \cli\safe_substr( $value, 0, $col_width, true /*is_width*/, $encoding ); $value = \cli\safe_substr( $value, \cli\safe_strlen( $row[ $col ], $encoding ), null /*length*/, false /*is_width*/, $encoding ); $i = 0; do { $extra_value = \cli\safe_substr( $value, 0, $col_width, true /*is_width*/, $encoding ); $val_width = Colors::width( $extra_value, self::isPreColorized( $col ), $encoding ); if ( $val_width ) { $extra_rows[ $col ][] = $extra_value; $value = \cli\safe_substr( $value, \cli\safe_strlen( $extra_value, $encoding ), null /*length*/, false /*is_width*/, $encoding ); $i++; if ( $i > $extra_row_count ) { $extra_row_count = $i; } } } while( $value ); } } } $row = array_map(array($this, 'padColumn'), $row, array_keys($row)); array_unshift($row, ''); // First border array_push($row, ''); // Last border $ret = join($this->_characters['border'], $row); if ( $extra_row_count ) { foreach( $extra_rows as $col => $col_values ) { while( count( $col_values ) < $extra_row_count ) { $col_values[] = ''; } } do { $row_values = array(); $has_more = false; foreach( $extra_rows as $col => &$col_values ) { $row_values[ $col ] = array_shift( $col_values ); if ( count( $col_values ) ) { $has_more = true; } } $row_values = array_map(array($this, 'padColumn'), $row_values, array_keys($row_values)); array_unshift($row_values, ''); // First border array_push($row_values, ''); // Last border $ret .= PHP_EOL . join($this->_characters['border'], $row_values); } while( $has_more ); } return $ret; }
[ "public", "function", "row", "(", "array", "$", "row", ")", "{", "$", "extra_row_count", "=", "0", ";", "if", "(", "count", "(", "$", "row", ")", ">", "0", ")", "{", "$", "extra_rows", "=", "array_fill", "(", "0", ",", "count", "(", "$", "row", ...
Renders a row for output. @param array $row The table row. @return string The formatted table row.
[ "Renders", "a", "row", "for", "output", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/table/Ascii.php#L132-L197
wp-cli/php-cli-tools
lib/cli/table/Ascii.php
Ascii.isPreColorized
public function isPreColorized( $column ) { if ( is_bool( $this->_pre_colorized ) ) { return $this->_pre_colorized; } if ( is_array( $this->_pre_colorized ) && isset( $this->_pre_colorized[ $column ] ) ) { return $this->_pre_colorized[ $column ]; } return false; }
php
public function isPreColorized( $column ) { if ( is_bool( $this->_pre_colorized ) ) { return $this->_pre_colorized; } if ( is_array( $this->_pre_colorized ) && isset( $this->_pre_colorized[ $column ] ) ) { return $this->_pre_colorized[ $column ]; } return false; }
[ "public", "function", "isPreColorized", "(", "$", "column", ")", "{", "if", "(", "is_bool", "(", "$", "this", "->", "_pre_colorized", ")", ")", "{", "return", "$", "this", "->", "_pre_colorized", ";", "}", "if", "(", "is_array", "(", "$", "this", "->",...
Is a column pre-colorized? @param int $column Column index to check. @return bool True if whole table is marked as pre-colorized, or if the individual column is pre-colorized; else false.
[ "Is", "a", "column", "pre", "-", "colorized?" ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/table/Ascii.php#L218-L226
wp-cli/php-cli-tools
lib/cli/progress/Bar.php
Bar.display
public function display($finish = false) { $_percent = $this->percent(); $percent = str_pad(floor($_percent * 100), 3); $msg = $this->_message; $msg = Streams::render($this->_formatMessage, compact('msg', 'percent')); $estimated = $this->formatTime($this->estimated()); $elapsed = str_pad($this->formatTime($this->elapsed()), strlen($estimated)); $timing = Streams::render($this->_formatTiming, compact('elapsed', 'estimated')); $size = Shell::columns(); $size -= strlen($msg . $timing); if ( $size < 0 ) { $size = 0; } $bar = str_repeat($this->_bars[0], floor($_percent * $size)) . $this->_bars[1]; // substr is needed to trim off the bar cap at 100% $bar = substr(str_pad($bar, $size, ' '), 0, $size); Streams::out($this->_format, compact('msg', 'bar', 'timing')); }
php
public function display($finish = false) { $_percent = $this->percent(); $percent = str_pad(floor($_percent * 100), 3); $msg = $this->_message; $msg = Streams::render($this->_formatMessage, compact('msg', 'percent')); $estimated = $this->formatTime($this->estimated()); $elapsed = str_pad($this->formatTime($this->elapsed()), strlen($estimated)); $timing = Streams::render($this->_formatTiming, compact('elapsed', 'estimated')); $size = Shell::columns(); $size -= strlen($msg . $timing); if ( $size < 0 ) { $size = 0; } $bar = str_repeat($this->_bars[0], floor($_percent * $size)) . $this->_bars[1]; // substr is needed to trim off the bar cap at 100% $bar = substr(str_pad($bar, $size, ' '), 0, $size); Streams::out($this->_format, compact('msg', 'bar', 'timing')); }
[ "public", "function", "display", "(", "$", "finish", "=", "false", ")", "{", "$", "_percent", "=", "$", "this", "->", "percent", "(", ")", ";", "$", "percent", "=", "str_pad", "(", "floor", "(", "$", "_percent", "*", "100", ")", ",", "3", ")", ";...
Prints the progress bar to the screen with percent complete, elapsed time and estimated total time. @param boolean $finish `true` if this was called from `cli\Notify::finish()`, `false` otherwise. @see cli\out() @see cli\Notify::formatTime() @see cli\Notify::elapsed() @see cli\Progress::estimated(); @see cli\Progress::percent() @see cli\Shell::columns()
[ "Prints", "the", "progress", "bar", "to", "the", "screen", "with", "percent", "complete", "elapsed", "time", "and", "estimated", "total", "time", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/progress/Bar.php#L47-L69
wp-cli/php-cli-tools
lib/cli/progress/Bar.php
Bar.tick
public function tick($increment = 1, $msg = null) { if ($msg) { $this->_message = $msg; } Notify::tick($increment); }
php
public function tick($increment = 1, $msg = null) { if ($msg) { $this->_message = $msg; } Notify::tick($increment); }
[ "public", "function", "tick", "(", "$", "increment", "=", "1", ",", "$", "msg", "=", "null", ")", "{", "if", "(", "$", "msg", ")", "{", "$", "this", "->", "_message", "=", "$", "msg", ";", "}", "Notify", "::", "tick", "(", "$", "increment", ")"...
This method augments the base definition from cli\Notify to optionally allow passing a new message. @param int $increment The amount to increment by. @param string $msg The text to display next to the Notifier. (optional) @see cli\Notify::tick()
[ "This", "method", "augments", "the", "base", "definition", "from", "cli", "\\", "Notify", "to", "optionally", "allow", "passing", "a", "new", "message", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/progress/Bar.php#L79-L84
wp-cli/php-cli-tools
lib/cli/Shell.php
Shell.columns
static public function columns() { static $columns; if ( getenv( 'PHP_CLI_TOOLS_TEST_SHELL_COLUMNS_RESET' ) ) { $columns = null; } if ( null === $columns ) { if ( function_exists( 'exec' ) ) { if ( self::is_windows() ) { // Cater for shells such as Cygwin and Git bash where `mode CON` returns an incorrect value for columns. if ( ( $shell = getenv( 'SHELL' ) ) && preg_match( '/(?:bash|zsh)(?:\.exe)?$/', $shell ) && getenv( 'TERM' ) ) { $columns = (int) exec( 'tput cols' ); } if ( ! $columns ) { $return_var = -1; $output = array(); exec( 'mode CON', $output, $return_var ); if ( 0 === $return_var && $output ) { // Look for second line ending in ": <number>" (searching for "Columns:" will fail on non-English locales). if ( preg_match( '/:\s*[0-9]+\n[^:]+:\s*([0-9]+)\n/', implode( "\n", $output ), $matches ) ) { $columns = (int) $matches[1]; } } } } else { if ( ! ( $columns = (int) getenv( 'COLUMNS' ) ) ) { $size = exec( '/usr/bin/env stty size 2>/dev/null' ); if ( '' !== $size && preg_match( '/[0-9]+ ([0-9]+)/', $size, $matches ) ) { $columns = (int) $matches[1]; } if ( ! $columns ) { if ( getenv( 'TERM' ) ) { $columns = (int) exec( '/usr/bin/env tput cols 2>/dev/null' ); } } } } } if ( ! $columns ) { $columns = 80; // default width of cmd window on Windows OS } } return $columns; }
php
static public function columns() { static $columns; if ( getenv( 'PHP_CLI_TOOLS_TEST_SHELL_COLUMNS_RESET' ) ) { $columns = null; } if ( null === $columns ) { if ( function_exists( 'exec' ) ) { if ( self::is_windows() ) { // Cater for shells such as Cygwin and Git bash where `mode CON` returns an incorrect value for columns. if ( ( $shell = getenv( 'SHELL' ) ) && preg_match( '/(?:bash|zsh)(?:\.exe)?$/', $shell ) && getenv( 'TERM' ) ) { $columns = (int) exec( 'tput cols' ); } if ( ! $columns ) { $return_var = -1; $output = array(); exec( 'mode CON', $output, $return_var ); if ( 0 === $return_var && $output ) { // Look for second line ending in ": <number>" (searching for "Columns:" will fail on non-English locales). if ( preg_match( '/:\s*[0-9]+\n[^:]+:\s*([0-9]+)\n/', implode( "\n", $output ), $matches ) ) { $columns = (int) $matches[1]; } } } } else { if ( ! ( $columns = (int) getenv( 'COLUMNS' ) ) ) { $size = exec( '/usr/bin/env stty size 2>/dev/null' ); if ( '' !== $size && preg_match( '/[0-9]+ ([0-9]+)/', $size, $matches ) ) { $columns = (int) $matches[1]; } if ( ! $columns ) { if ( getenv( 'TERM' ) ) { $columns = (int) exec( '/usr/bin/env tput cols 2>/dev/null' ); } } } } } if ( ! $columns ) { $columns = 80; // default width of cmd window on Windows OS } } return $columns; }
[ "static", "public", "function", "columns", "(", ")", "{", "static", "$", "columns", ";", "if", "(", "getenv", "(", "'PHP_CLI_TOOLS_TEST_SHELL_COLUMNS_RESET'", ")", ")", "{", "$", "columns", "=", "null", ";", "}", "if", "(", "null", "===", "$", "columns", ...
Returns the number of columns the current shell has for display. @return int The number of columns. @todo Test on more systems.
[ "Returns", "the", "number", "of", "columns", "the", "current", "shell", "has", "for", "display", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Shell.php#L27-L72
wp-cli/php-cli-tools
lib/cli/Shell.php
Shell.isPiped
static public function isPiped() { $shellPipe = getenv('SHELL_PIPE'); if ($shellPipe !== false) { return filter_var($shellPipe, FILTER_VALIDATE_BOOLEAN); } else { return (function_exists('posix_isatty') && !posix_isatty(STDOUT)); } }
php
static public function isPiped() { $shellPipe = getenv('SHELL_PIPE'); if ($shellPipe !== false) { return filter_var($shellPipe, FILTER_VALIDATE_BOOLEAN); } else { return (function_exists('posix_isatty') && !posix_isatty(STDOUT)); } }
[ "static", "public", "function", "isPiped", "(", ")", "{", "$", "shellPipe", "=", "getenv", "(", "'SHELL_PIPE'", ")", ";", "if", "(", "$", "shellPipe", "!==", "false", ")", "{", "return", "filter_var", "(", "$", "shellPipe", ",", "FILTER_VALIDATE_BOOLEAN", ...
Checks whether the output of the current script is a TTY or a pipe / redirect Returns true if STDOUT output is being redirected to a pipe or a file; false is output is being sent directly to the terminal. If an env variable SHELL_PIPE exists, returned result depends it's value. Strings like 1, 0, yes, no, that validate to booleans are accepted. To enable ASCII formatting even when shell is piped, use the ENV variable SHELL_PIPE=0 @return bool
[ "Checks", "whether", "the", "output", "of", "the", "current", "script", "is", "a", "TTY", "or", "a", "pipe", "/", "redirect" ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Shell.php#L88-L96
wp-cli/php-cli-tools
lib/cli/Notify.php
Notify.reset
public function reset() { $this->_current = 0; $this->_first = true; $this->_start = null; $this->_timer = null; }
php
public function reset() { $this->_current = 0; $this->_first = true; $this->_start = null; $this->_timer = null; }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "_current", "=", "0", ";", "$", "this", "->", "_first", "=", "true", ";", "$", "this", "->", "_start", "=", "null", ";", "$", "this", "->", "_timer", "=", "null", ";", "}" ]
Reset the notifier state so the same instance can be used in multiple loops.
[ "Reset", "the", "notifier", "state", "so", "the", "same", "instance", "can", "be", "used", "in", "multiple", "loops", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Notify.php#L58-L63
wp-cli/php-cli-tools
lib/cli/Notify.php
Notify.speed
public function speed() { static $tick, $iteration = 0, $speed = 0; if (!$this->_start) { return 0; } else if (!$tick) { $tick = $this->_start; } $now = microtime(true); $span = $now - $tick; if ($span > 1) { $iteration++; $tick = $now; $speed = ($this->_current / $iteration) / $span; } return $speed; }
php
public function speed() { static $tick, $iteration = 0, $speed = 0; if (!$this->_start) { return 0; } else if (!$tick) { $tick = $this->_start; } $now = microtime(true); $span = $now - $tick; if ($span > 1) { $iteration++; $tick = $now; $speed = ($this->_current / $iteration) / $span; } return $speed; }
[ "public", "function", "speed", "(", ")", "{", "static", "$", "tick", ",", "$", "iteration", "=", "0", ",", "$", "speed", "=", "0", ";", "if", "(", "!", "$", "this", "->", "_start", ")", "{", "return", "0", ";", "}", "else", "if", "(", "!", "$...
Calculates the speed (number of ticks per second) at which the Notifier is being updated. @return int The number of ticks performed in 1 second.
[ "Calculates", "the", "speed", "(", "number", "of", "ticks", "per", "second", ")", "at", "which", "the", "Notifier", "is", "being", "updated", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Notify.php#L94-L112
wp-cli/php-cli-tools
lib/cli/Notify.php
Notify.shouldUpdate
public function shouldUpdate() { $now = microtime(true) * 1000; if (empty($this->_timer)) { $this->_start = (int)(($this->_timer = $now) / 1000); return true; } if (($now - $this->_timer) > $this->_interval) { $this->_timer = $now; return true; } return false; }
php
public function shouldUpdate() { $now = microtime(true) * 1000; if (empty($this->_timer)) { $this->_start = (int)(($this->_timer = $now) / 1000); return true; } if (($now - $this->_timer) > $this->_interval) { $this->_timer = $now; return true; } return false; }
[ "public", "function", "shouldUpdate", "(", ")", "{", "$", "now", "=", "microtime", "(", "true", ")", "*", "1000", ";", "if", "(", "empty", "(", "$", "this", "->", "_timer", ")", ")", "{", "$", "this", "->", "_start", "=", "(", "int", ")", "(", ...
Determines whether the display should be updated or not according to our interval setting. @return boolean `true` if the display should be updated, `false` otherwise.
[ "Determines", "whether", "the", "display", "should", "be", "updated", "or", "not", "according", "to", "our", "interval", "setting", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Notify.php#L153-L166
wp-cli/php-cli-tools
lib/cli/Notify.php
Notify.tick
public function tick($increment = 1) { $this->increment($increment); if ($this->shouldUpdate()) { Streams::out("\r"); $this->display(); } }
php
public function tick($increment = 1) { $this->increment($increment); if ($this->shouldUpdate()) { Streams::out("\r"); $this->display(); } }
[ "public", "function", "tick", "(", "$", "increment", "=", "1", ")", "{", "$", "this", "->", "increment", "(", "$", "increment", ")", ";", "if", "(", "$", "this", "->", "shouldUpdate", "(", ")", ")", "{", "Streams", "::", "out", "(", "\"\\r\"", ")",...
This method is the meat of all Notifiers. First we increment the ticker and then update the display if enough time has passed since our last tick. @param int $increment The amount to increment by. @see cli\Notify::increment() @see cli\Notify::shouldUpdate() @see cli\Notify::display()
[ "This", "method", "is", "the", "meat", "of", "all", "Notifiers", ".", "First", "we", "increment", "the", "ticker", "and", "then", "update", "the", "display", "if", "enough", "time", "has", "passed", "since", "our", "last", "tick", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Notify.php#L177-L184
wp-cli/php-cli-tools
lib/cli/notify/Dots.php
Dots.display
public function display($finish = false) { $repeat = $this->_dots; if (!$finish) { $repeat = $this->_iteration++ % $repeat; } $msg = $this->_message; $dots = str_pad(str_repeat('.', $repeat), $this->_dots); $speed = number_format(round($this->speed())); $elapsed = $this->formatTime($this->elapsed()); Streams::out_padded($this->_format, compact('msg', 'dots', 'speed', 'elapsed')); }
php
public function display($finish = false) { $repeat = $this->_dots; if (!$finish) { $repeat = $this->_iteration++ % $repeat; } $msg = $this->_message; $dots = str_pad(str_repeat('.', $repeat), $this->_dots); $speed = number_format(round($this->speed())); $elapsed = $this->formatTime($this->elapsed()); Streams::out_padded($this->_format, compact('msg', 'dots', 'speed', 'elapsed')); }
[ "public", "function", "display", "(", "$", "finish", "=", "false", ")", "{", "$", "repeat", "=", "$", "this", "->", "_dots", ";", "if", "(", "!", "$", "finish", ")", "{", "$", "repeat", "=", "$", "this", "->", "_iteration", "++", "%", "$", "repea...
Prints the correct number of dots to `STDOUT` with the time elapsed and tick speed. @param boolean $finish `true` if this was called from `cli\Notify::finish()`, `false` otherwise. @see cli\out_padded() @see cli\Notify::formatTime() @see cli\Notify::speed()
[ "Prints", "the", "correct", "number", "of", "dots", "to", "STDOUT", "with", "the", "time", "elapsed", "and", "tick", "speed", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/notify/Dots.php#L53-L65
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.render
public static function render( $msg ) { $args = func_get_args(); // No string replacement is needed if( count( $args ) == 1 || ( is_string( $args[1] ) && '' === $args[1] ) ) { return Colors::shouldColorize() ? Colors::colorize( $msg ) : $msg; } // If the first argument is not an array just pass to sprintf if( !is_array( $args[1] ) ) { // Colorize the message first so sprintf doesn't bitch at us if ( Colors::shouldColorize() ) { $args[0] = Colors::colorize( $args[0] ); } // Escape percent characters for sprintf $args[0] = preg_replace('/(%([^\w]|$))/', "%$1", $args[0]); return call_user_func_array( 'sprintf', $args ); } // Here we do named replacement so formatting strings are more understandable foreach( $args[1] as $key => $value ) { $msg = str_replace( '{:' . $key . '}', $value, $msg ); } return Colors::shouldColorize() ? Colors::colorize( $msg ) : $msg; }
php
public static function render( $msg ) { $args = func_get_args(); // No string replacement is needed if( count( $args ) == 1 || ( is_string( $args[1] ) && '' === $args[1] ) ) { return Colors::shouldColorize() ? Colors::colorize( $msg ) : $msg; } // If the first argument is not an array just pass to sprintf if( !is_array( $args[1] ) ) { // Colorize the message first so sprintf doesn't bitch at us if ( Colors::shouldColorize() ) { $args[0] = Colors::colorize( $args[0] ); } // Escape percent characters for sprintf $args[0] = preg_replace('/(%([^\w]|$))/', "%$1", $args[0]); return call_user_func_array( 'sprintf', $args ); } // Here we do named replacement so formatting strings are more understandable foreach( $args[1] as $key => $value ) { $msg = str_replace( '{:' . $key . '}', $value, $msg ); } return Colors::shouldColorize() ? Colors::colorize( $msg ) : $msg; }
[ "public", "static", "function", "render", "(", "$", "msg", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "// No string replacement is needed", "if", "(", "count", "(", "$", "args", ")", "==", "1", "||", "(", "is_string", "(", "$", "args", ...
Handles rendering strings. If extra scalar arguments are given after the `$msg` the string will be rendered with `sprintf`. If the second argument is an `array` then each key in the array will be the placeholder name. Placeholders are of the format {:key}. @param string $msg The message to render. @param mixed ... Either scalar arguments or a single array argument. @return string The rendered string.
[ "Handles", "rendering", "strings", ".", "If", "extra", "scalar", "arguments", "are", "given", "after", "the", "$msg", "the", "string", "will", "be", "rendered", "with", "sprintf", ".", "If", "the", "second", "argument", "is", "an", "array", "then", "each", ...
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L30-L56
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.out_padded
public static function out_padded( $msg ) { $msg = self::_call( 'render', func_get_args() ); self::out( str_pad( $msg, \cli\Shell::columns() ) ); }
php
public static function out_padded( $msg ) { $msg = self::_call( 'render', func_get_args() ); self::out( str_pad( $msg, \cli\Shell::columns() ) ); }
[ "public", "static", "function", "out_padded", "(", "$", "msg", ")", "{", "$", "msg", "=", "self", "::", "_call", "(", "'render'", ",", "func_get_args", "(", ")", ")", ";", "self", "::", "out", "(", "str_pad", "(", "$", "msg", ",", "\\", "cli", "\\"...
Pads `$msg` to the width of the shell before passing to `cli\out`. @param string $msg The message to pad and pass on. @param mixed ... Either scalar arguments or a single array argument. @return void @see cli\out()
[ "Pads", "$msg", "to", "the", "width", "of", "the", "shell", "before", "passing", "to", "cli", "\\", "out", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L79-L82
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.err
public static function err( $msg = '' ) { // func_get_args is empty if no args are passed even with the default above. $args = array_merge( func_get_args(), array( '' ) ); $args[0] .= "\n"; fwrite( static::$err, self::_call( 'render', $args ) ); }
php
public static function err( $msg = '' ) { // func_get_args is empty if no args are passed even with the default above. $args = array_merge( func_get_args(), array( '' ) ); $args[0] .= "\n"; fwrite( static::$err, self::_call( 'render', $args ) ); }
[ "public", "static", "function", "err", "(", "$", "msg", "=", "''", ")", "{", "// func_get_args is empty if no args are passed even with the default above.", "$", "args", "=", "array_merge", "(", "func_get_args", "(", ")", ",", "array", "(", "''", ")", ")", ";", ...
Shortcut for printing to `STDERR`. The message and parameters are passed through `sprintf` before output. @param string $msg The message to output in `printf` format. With no string, a newline is printed. @param mixed ... Either scalar arguments or a single array argument. @return void
[ "Shortcut", "for", "printing", "to", "STDERR", ".", "The", "message", "and", "parameters", "are", "passed", "through", "sprintf", "before", "output", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L107-L112
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.input
public static function input( $format = null, $hide = false ) { if ( $hide ) Shell::hide(); if( $format ) { fscanf( static::$in, $format . "\n", $line ); } else { $line = fgets( static::$in ); } if ( $hide ) { Shell::hide( false ); echo "\n"; } if( $line === false ) { throw new \Exception( 'Caught ^D during input' ); } return trim( $line ); }
php
public static function input( $format = null, $hide = false ) { if ( $hide ) Shell::hide(); if( $format ) { fscanf( static::$in, $format . "\n", $line ); } else { $line = fgets( static::$in ); } if ( $hide ) { Shell::hide( false ); echo "\n"; } if( $line === false ) { throw new \Exception( 'Caught ^D during input' ); } return trim( $line ); }
[ "public", "static", "function", "input", "(", "$", "format", "=", "null", ",", "$", "hide", "=", "false", ")", "{", "if", "(", "$", "hide", ")", "Shell", "::", "hide", "(", ")", ";", "if", "(", "$", "format", ")", "{", "fscanf", "(", "static", ...
Takes input from `STDIN` in the given format. If an end of transmission character is sent (^D), an exception is thrown. @param string $format A valid input format. See `fscanf` for documentation. If none is given, all input up to the first newline is accepted. @param boolean $hide If true will hide what the user types in. @return string The input with whitespace trimmed. @throws \Exception Thrown if ctrl-D (EOT) is sent as input.
[ "Takes", "input", "from", "STDIN", "in", "the", "given", "format", ".", "If", "an", "end", "of", "transmission", "character", "is", "sent", "(", "^D", ")", "an", "exception", "is", "thrown", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L125-L145
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.prompt
public static function prompt( $question, $default = null, $marker = ': ', $hide = false ) { if( $default && strpos( $question, '[' ) === false ) { $question .= ' [' . $default . ']'; } while( true ) { self::out( $question . $marker ); $line = self::input( null, $hide ); if ( trim( $line ) !== '' ) return $line; if( $default !== false ) return $default; } }
php
public static function prompt( $question, $default = null, $marker = ': ', $hide = false ) { if( $default && strpos( $question, '[' ) === false ) { $question .= ' [' . $default . ']'; } while( true ) { self::out( $question . $marker ); $line = self::input( null, $hide ); if ( trim( $line ) !== '' ) return $line; if( $default !== false ) return $default; } }
[ "public", "static", "function", "prompt", "(", "$", "question", ",", "$", "default", "=", "null", ",", "$", "marker", "=", "': '", ",", "$", "hide", "=", "false", ")", "{", "if", "(", "$", "default", "&&", "strpos", "(", "$", "question", ",", "'['"...
Displays an input prompt. If no default value is provided the prompt will continue displaying until input is received. @param string $question The question to ask the user. @param bool|string $default A default value if the user provides no input. @param string $marker A string to append to the question and default value on display. @param boolean $hide Optionally hides what the user types in. @return string The users input. @see cli\input()
[ "Displays", "an", "input", "prompt", ".", "If", "no", "default", "value", "is", "provided", "the", "prompt", "will", "continue", "displaying", "until", "input", "is", "received", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L159-L173
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.choose
public static function choose( $question, $choice = 'yn', $default = 'n' ) { if( !is_string( $choice ) ) { $choice = join( '', $choice ); } // Make every choice character lowercase except the default $choice = str_ireplace( $default, strtoupper( $default ), strtolower( $choice ) ); // Seperate each choice with a forward-slash $choices = trim( join( '/', preg_split( '//', $choice ) ), '/' ); while( true ) { $line = self::prompt( sprintf( '%s? [%s]', $question, $choices ), $default, '' ); if( stripos( $choice, $line ) !== false ) { return strtolower( $line ); } if( !empty( $default ) ) { return strtolower( $default ); } } }
php
public static function choose( $question, $choice = 'yn', $default = 'n' ) { if( !is_string( $choice ) ) { $choice = join( '', $choice ); } // Make every choice character lowercase except the default $choice = str_ireplace( $default, strtoupper( $default ), strtolower( $choice ) ); // Seperate each choice with a forward-slash $choices = trim( join( '/', preg_split( '//', $choice ) ), '/' ); while( true ) { $line = self::prompt( sprintf( '%s? [%s]', $question, $choices ), $default, '' ); if( stripos( $choice, $line ) !== false ) { return strtolower( $line ); } if( !empty( $default ) ) { return strtolower( $default ); } } }
[ "public", "static", "function", "choose", "(", "$", "question", ",", "$", "choice", "=", "'yn'", ",", "$", "default", "=", "'n'", ")", "{", "if", "(", "!", "is_string", "(", "$", "choice", ")", ")", "{", "$", "choice", "=", "join", "(", "''", ","...
Presents a user with a multiple choice question, useful for 'yes/no' type questions (which this public static function defaults too). @param string $question The question to ask the user. @param string $choice A string of characters allowed as a response. Case is ignored. @param string $default The default choice. NULL if a default is not allowed. @return string The users choice. @see cli\prompt()
[ "Presents", "a", "user", "with", "a", "multiple", "choice", "question", "useful", "for", "yes", "/", "no", "type", "questions", "(", "which", "this", "public", "static", "function", "defaults", "too", ")", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L185-L205
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.menu
public static function menu( $items, $default = null, $title = 'Choose an item' ) { $map = array_values( $items ); if( $default && strpos( $title, '[' ) === false && isset( $items[$default] ) ) { $title .= ' [' . $items[$default] . ']'; } foreach( $map as $idx => $item ) { self::line( ' %d. %s', $idx + 1, (string)$item ); } self::line(); while( true ) { fwrite( static::$out, sprintf( '%s: ', $title ) ); $line = self::input(); if( is_numeric( $line ) ) { $line--; if( isset( $map[$line] ) ) { return array_search( $map[$line], $items ); } if( $line < 0 || $line >= count( $map ) ) { self::err( 'Invalid menu selection: out of range' ); } } else if( isset( $default ) ) { return $default; } } }
php
public static function menu( $items, $default = null, $title = 'Choose an item' ) { $map = array_values( $items ); if( $default && strpos( $title, '[' ) === false && isset( $items[$default] ) ) { $title .= ' [' . $items[$default] . ']'; } foreach( $map as $idx => $item ) { self::line( ' %d. %s', $idx + 1, (string)$item ); } self::line(); while( true ) { fwrite( static::$out, sprintf( '%s: ', $title ) ); $line = self::input(); if( is_numeric( $line ) ) { $line--; if( isset( $map[$line] ) ) { return array_search( $map[$line], $items ); } if( $line < 0 || $line >= count( $map ) ) { self::err( 'Invalid menu selection: out of range' ); } } else if( isset( $default ) ) { return $default; } } }
[ "public", "static", "function", "menu", "(", "$", "items", ",", "$", "default", "=", "null", ",", "$", "title", "=", "'Choose an item'", ")", "{", "$", "map", "=", "array_values", "(", "$", "items", ")", ";", "if", "(", "$", "default", "&&", "strpos"...
Displays an array of strings as a menu where a user can enter a number to choose an option. The array must be a single dimension with either strings or objects with a `__toString()` method. @param array $items The list of items the user can choose from. @param string $default The index of the default item. @param string $title The message displayed to the user when prompted. @return string The index of the chosen item. @see cli\line() @see cli\input() @see cli\err()
[ "Displays", "an", "array", "of", "strings", "as", "a", "menu", "where", "a", "user", "can", "enter", "a", "number", "to", "choose", "an", "option", ".", "The", "array", "must", "be", "a", "single", "dimension", "with", "either", "strings", "or", "objects...
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L220-L249
wp-cli/php-cli-tools
lib/cli/Streams.php
Streams.setStream
public static function setStream( $whichStream, $stream ) { if( !is_resource( $stream ) || get_resource_type( $stream ) !== 'stream' ) { throw new \Exception( 'Invalid resource type!' ); } if( property_exists( __CLASS__, $whichStream ) ) { static::${$whichStream} = $stream; } register_shutdown_function( function() use ($stream) { fclose( $stream ); } ); }
php
public static function setStream( $whichStream, $stream ) { if( !is_resource( $stream ) || get_resource_type( $stream ) !== 'stream' ) { throw new \Exception( 'Invalid resource type!' ); } if( property_exists( __CLASS__, $whichStream ) ) { static::${$whichStream} = $stream; } register_shutdown_function( function() use ($stream) { fclose( $stream ); } ); }
[ "public", "static", "function", "setStream", "(", "$", "whichStream", ",", "$", "stream", ")", "{", "if", "(", "!", "is_resource", "(", "$", "stream", ")", "||", "get_resource_type", "(", "$", "stream", ")", "!==", "'stream'", ")", "{", "throw", "new", ...
Sets one of the streams (input, output, or error) to a `stream` type resource. Valid $whichStream values are: - 'in' (default: STDIN) - 'out' (default: STDOUT) - 'err' (default: STDERR) Any custom streams will be closed for you on shutdown, so please don't close stream resources used with this method. @param string $whichStream The stream property to update @param resource $stream The new stream resource to use @return void @throws \Exception Thrown if $stream is not a resource of the 'stream' type.
[ "Sets", "one", "of", "the", "streams", "(", "input", "output", "or", "error", ")", "to", "a", "stream", "type", "resource", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Streams.php#L267-L277
wp-cli/php-cli-tools
lib/cli/table/Renderer.php
Renderer.setWidths
public function setWidths(array $widths, $fallback = false) { if ($fallback) { foreach ( $this->_widths as $index => $value ) { $widths[$index] = $value; } } $this->_widths = $widths; }
php
public function setWidths(array $widths, $fallback = false) { if ($fallback) { foreach ( $this->_widths as $index => $value ) { $widths[$index] = $value; } } $this->_widths = $widths; }
[ "public", "function", "setWidths", "(", "array", "$", "widths", ",", "$", "fallback", "=", "false", ")", "{", "if", "(", "$", "fallback", ")", "{", "foreach", "(", "$", "this", "->", "_widths", "as", "$", "index", "=>", "$", "value", ")", "{", "$",...
Set the widths of each column in the table. @param array $widths The widths of the columns. @param bool $fallback Whether to use these values as fallback only.
[ "Set", "the", "widths", "of", "each", "column", "in", "the", "table", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/table/Renderer.php#L31-L38
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.offsetExists
public function offsetExists($offset) { if ($offset instanceOf Argument) { $offset = $offset->key; } return array_key_exists($offset, $this->_parsed); }
php
public function offsetExists($offset) { if ($offset instanceOf Argument) { $offset = $offset->key; } return array_key_exists($offset, $this->_parsed); }
[ "public", "function", "offsetExists", "(", "$", "offset", ")", "{", "if", "(", "$", "offset", "instanceOf", "Argument", ")", "{", "$", "offset", "=", "$", "offset", "->", "key", ";", "}", "return", "array_key_exists", "(", "$", "offset", ",", "$", "thi...
Returns true if a given argument was parsed. @param mixed $offset An Argument object or the name of the argument. @return bool
[ "Returns", "true", "if", "a", "given", "argument", "was", "parsed", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L89-L95
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.offsetGet
public function offsetGet($offset) { if ($offset instanceOf Argument) { $offset = $offset->key; } if (isset($this->_parsed[$offset])) { return $this->_parsed[$offset]; } }
php
public function offsetGet($offset) { if ($offset instanceOf Argument) { $offset = $offset->key; } if (isset($this->_parsed[$offset])) { return $this->_parsed[$offset]; } }
[ "public", "function", "offsetGet", "(", "$", "offset", ")", "{", "if", "(", "$", "offset", "instanceOf", "Argument", ")", "{", "$", "offset", "=", "$", "offset", "->", "key", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "_parsed", "[", "$"...
Get the parsed argument's value. @param mixed $offset An Argument object or the name of the argument. @return mixed
[ "Get", "the", "parsed", "argument", "s", "value", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L103-L111
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.offsetSet
public function offsetSet($offset, $value) { if ($offset instanceOf Argument) { $offset = $offset->key; } $this->_parsed[$offset] = $value; }
php
public function offsetSet($offset, $value) { if ($offset instanceOf Argument) { $offset = $offset->key; } $this->_parsed[$offset] = $value; }
[ "public", "function", "offsetSet", "(", "$", "offset", ",", "$", "value", ")", "{", "if", "(", "$", "offset", "instanceOf", "Argument", ")", "{", "$", "offset", "=", "$", "offset", "->", "key", ";", "}", "$", "this", "->", "_parsed", "[", "$", "off...
Sets the value of a parsed argument. @param mixed $offset An Argument object or the name of the argument. @param mixed $value The value to set
[ "Sets", "the", "value", "of", "a", "parsed", "argument", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L119-L125
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.offsetUnset
public function offsetUnset($offset) { if ($offset instanceOf Argument) { $offset = $offset->key; } unset($this->_parsed[$offset]); }
php
public function offsetUnset($offset) { if ($offset instanceOf Argument) { $offset = $offset->key; } unset($this->_parsed[$offset]); }
[ "public", "function", "offsetUnset", "(", "$", "offset", ")", "{", "if", "(", "$", "offset", "instanceOf", "Argument", ")", "{", "$", "offset", "=", "$", "offset", "->", "key", ";", "}", "unset", "(", "$", "this", "->", "_parsed", "[", "$", "offset",...
Unset a parsed argument. @param mixed $offset An Argument object or the name of the argument.
[ "Unset", "a", "parsed", "argument", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L132-L138
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.addFlag
public function addFlag($flag, $settings = array()) { if (is_string($settings)) { $settings = array('description' => $settings); } if (is_array($flag)) { $settings['aliases'] = $flag; $flag = array_shift($settings['aliases']); } if (isset($this->_flags[$flag])) { $this->_warn('flag already exists: ' . $flag); return $this; } $settings += array( 'default' => false, 'stackable' => false, 'description' => null, 'aliases' => array() ); $this->_flags[$flag] = $settings; return $this; }
php
public function addFlag($flag, $settings = array()) { if (is_string($settings)) { $settings = array('description' => $settings); } if (is_array($flag)) { $settings['aliases'] = $flag; $flag = array_shift($settings['aliases']); } if (isset($this->_flags[$flag])) { $this->_warn('flag already exists: ' . $flag); return $this; } $settings += array( 'default' => false, 'stackable' => false, 'description' => null, 'aliases' => array() ); $this->_flags[$flag] = $settings; return $this; }
[ "public", "function", "addFlag", "(", "$", "flag", ",", "$", "settings", "=", "array", "(", ")", ")", "{", "if", "(", "is_string", "(", "$", "settings", ")", ")", "{", "$", "settings", "=", "array", "(", "'description'", "=>", "$", "settings", ")", ...
Adds a flag (boolean argument) to the argument list. @param mixed $flag A string representing the flag, or an array of strings. @param array $settings An array of settings for this flag. @setting string description A description to be shown in --help. @setting bool default The default value for this flag. @setting bool stackable Whether the flag is repeatable to increase the value. @setting array aliases Other ways to trigger this flag. @return $this
[ "Adds", "a", "flag", "(", "boolean", "argument", ")", "to", "the", "argument", "list", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L151-L173
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.addFlags
public function addFlags($flags) { foreach ($flags as $flag => $settings) { if (is_numeric($flag)) { $this->_warn('No flag character given'); continue; } $this->addFlag($flag, $settings); } return $this; }
php
public function addFlags($flags) { foreach ($flags as $flag => $settings) { if (is_numeric($flag)) { $this->_warn('No flag character given'); continue; } $this->addFlag($flag, $settings); } return $this; }
[ "public", "function", "addFlags", "(", "$", "flags", ")", "{", "foreach", "(", "$", "flags", "as", "$", "flag", "=>", "$", "settings", ")", "{", "if", "(", "is_numeric", "(", "$", "flag", ")", ")", "{", "$", "this", "->", "_warn", "(", "'No flag ch...
Add multiple flags at once. The input array should be keyed with the primary flag character, and the values should be the settings array used by {addFlag}. @param array $flags An array of flags to add @return $this
[ "Add", "multiple", "flags", "at", "once", ".", "The", "input", "array", "should", "be", "keyed", "with", "the", "primary", "flag", "character", "and", "the", "values", "should", "be", "the", "settings", "array", "used", "by", "{", "addFlag", "}", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L183-L194
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.addOption
public function addOption($option, $settings = array()) { if (is_string($settings)) { $settings = array('description' => $settings); } if (is_array($option)) { $settings['aliases'] = $option; $option = array_shift($settings['aliases']); } if (isset($this->_options[$option])) { $this->_warn('option already exists: ' . $option); return $this; } $settings += array( 'default' => null, 'description' => null, 'aliases' => array() ); $this->_options[$option] = $settings; return $this; }
php
public function addOption($option, $settings = array()) { if (is_string($settings)) { $settings = array('description' => $settings); } if (is_array($option)) { $settings['aliases'] = $option; $option = array_shift($settings['aliases']); } if (isset($this->_options[$option])) { $this->_warn('option already exists: ' . $option); return $this; } $settings += array( 'default' => null, 'description' => null, 'aliases' => array() ); $this->_options[$option] = $settings; return $this; }
[ "public", "function", "addOption", "(", "$", "option", ",", "$", "settings", "=", "array", "(", ")", ")", "{", "if", "(", "is_string", "(", "$", "settings", ")", ")", "{", "$", "settings", "=", "array", "(", "'description'", "=>", "$", "settings", ")...
Adds an option (string argument) to the argument list. @param mixed $option A string representing the option, or an array of strings. @param array $settings An array of settings for this option. @setting string description A description to be shown in --help. @setting bool default The default value for this option. @setting array aliases Other ways to trigger this option. @return $this
[ "Adds", "an", "option", "(", "string", "argument", ")", "to", "the", "argument", "list", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L206-L227
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.addOptions
public function addOptions($options) { foreach ($options as $option => $settings) { if (is_numeric($option)) { $this->_warn('No option string given'); continue; } $this->addOption($option, $settings); } return $this; }
php
public function addOptions($options) { foreach ($options as $option => $settings) { if (is_numeric($option)) { $this->_warn('No option string given'); continue; } $this->addOption($option, $settings); } return $this; }
[ "public", "function", "addOptions", "(", "$", "options", ")", "{", "foreach", "(", "$", "options", "as", "$", "option", "=>", "$", "settings", ")", "{", "if", "(", "is_numeric", "(", "$", "option", ")", ")", "{", "$", "this", "->", "_warn", "(", "'...
Add multiple options at once. The input array should be keyed with the primary option string, and the values should be the settings array used by {addOption}. @param array $options An array of options to add @return $this
[ "Add", "multiple", "options", "at", "once", ".", "The", "input", "array", "should", "be", "keyed", "with", "the", "primary", "option", "string", "and", "the", "values", "should", "be", "the", "settings", "array", "used", "by", "{", "addOption", "}", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L237-L248
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.getFlag
public function getFlag($flag) { if ($flag instanceOf Argument) { $obj = $flag; $flag = $flag->value; } if (isset($this->_flags[$flag])) { return $this->_flags[$flag]; } foreach ($this->_flags as $master => $settings) { if (in_array($flag, (array)$settings['aliases'])) { if (isset($obj)) { $obj->key = $master; } $cache[$flag] =& $settings; return $settings; } } }
php
public function getFlag($flag) { if ($flag instanceOf Argument) { $obj = $flag; $flag = $flag->value; } if (isset($this->_flags[$flag])) { return $this->_flags[$flag]; } foreach ($this->_flags as $master => $settings) { if (in_array($flag, (array)$settings['aliases'])) { if (isset($obj)) { $obj->key = $master; } $cache[$flag] =& $settings; return $settings; } } }
[ "public", "function", "getFlag", "(", "$", "flag", ")", "{", "if", "(", "$", "flag", "instanceOf", "Argument", ")", "{", "$", "obj", "=", "$", "flag", ";", "$", "flag", "=", "$", "flag", "->", "value", ";", "}", "if", "(", "isset", "(", "$", "t...
Get a flag by primary matcher or any defined aliases. @param mixed $flag Either a string representing the flag or an cli\arguments\Argument object. @return array
[ "Get", "a", "flag", "by", "primary", "matcher", "or", "any", "defined", "aliases", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L281-L301
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.isStackable
public function isStackable($flag) { $settings = $this->getFlag($flag); return isset($settings) && (true === $settings['stackable']); }
php
public function isStackable($flag) { $settings = $this->getFlag($flag); return isset($settings) && (true === $settings['stackable']); }
[ "public", "function", "isStackable", "(", "$", "flag", ")", "{", "$", "settings", "=", "$", "this", "->", "getFlag", "(", "$", "flag", ")", ";", "return", "isset", "(", "$", "settings", ")", "&&", "(", "true", "===", "$", "settings", "[", "'stackable...
Returns true if the given flag is stackable. @param mixed $flag Either a string representing the flag or an cli\arguments\Argument object. @return bool
[ "Returns", "true", "if", "the", "given", "flag", "is", "stackable", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L329-L333
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.getOption
public function getOption($option) { if ($option instanceOf Argument) { $obj = $option; $option = $option->value; } if (isset($this->_options[$option])) { return $this->_options[$option]; } foreach ($this->_options as $master => $settings) { if (in_array($option, (array)$settings['aliases'])) { if (isset($obj)) { $obj->key = $master; } return $settings; } } }
php
public function getOption($option) { if ($option instanceOf Argument) { $obj = $option; $option = $option->value; } if (isset($this->_options[$option])) { return $this->_options[$option]; } foreach ($this->_options as $master => $settings) { if (in_array($option, (array)$settings['aliases'])) { if (isset($obj)) { $obj->key = $master; } return $settings; } } }
[ "public", "function", "getOption", "(", "$", "option", ")", "{", "if", "(", "$", "option", "instanceOf", "Argument", ")", "{", "$", "obj", "=", "$", "option", ";", "$", "option", "=", "$", "option", "->", "value", ";", "}", "if", "(", "isset", "(",...
Get an option by primary matcher or any defined aliases. @param mixed $option Either a string representing the option or an cli\arguments\Argument object. @return array
[ "Get", "an", "option", "by", "primary", "matcher", "or", "any", "defined", "aliases", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L342-L361
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments.parse
public function parse() { $this->_invalid = array(); $this->_parsed = array(); $this->_lexer = new Lexer($this->_input); $this->_applyDefaults(); foreach ($this->_lexer as $argument) { if ($this->_parseFlag($argument)) { continue; } if ($this->_parseOption($argument)) { continue; } array_push($this->_invalid, $argument->raw); } if ($this->_strict && !empty($this->_invalid)) { throw new InvalidArguments($this->_invalid); } }
php
public function parse() { $this->_invalid = array(); $this->_parsed = array(); $this->_lexer = new Lexer($this->_input); $this->_applyDefaults(); foreach ($this->_lexer as $argument) { if ($this->_parseFlag($argument)) { continue; } if ($this->_parseOption($argument)) { continue; } array_push($this->_invalid, $argument->raw); } if ($this->_strict && !empty($this->_invalid)) { throw new InvalidArguments($this->_invalid); } }
[ "public", "function", "parse", "(", ")", "{", "$", "this", "->", "_invalid", "=", "array", "(", ")", ";", "$", "this", "->", "_parsed", "=", "array", "(", ")", ";", "$", "this", "->", "_lexer", "=", "new", "Lexer", "(", "$", "this", "->", "_input...
Parses the argument list with the given options. The returned argument list will use either the first long name given or the first name in the list if a long name is not given. @return array @throws arguments\InvalidArguments
[ "Parses", "the", "argument", "list", "with", "the", "given", "options", ".", "The", "returned", "argument", "list", "will", "use", "either", "the", "first", "long", "name", "given", "or", "the", "first", "name", "in", "the", "list", "if", "a", "long", "n...
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L390-L411
wp-cli/php-cli-tools
lib/cli/Arguments.php
Arguments._applyDefaults
private function _applyDefaults() { foreach($this->_flags as $flag => $settings) { $this[$flag] = $settings['default']; } foreach($this->_options as $option => $settings) { // If the default is 0 we should still let it be set. if (!empty($settings['default']) || $settings['default'] === 0) { $this[$option] = $settings['default']; } } }
php
private function _applyDefaults() { foreach($this->_flags as $flag => $settings) { $this[$flag] = $settings['default']; } foreach($this->_options as $option => $settings) { // If the default is 0 we should still let it be set. if (!empty($settings['default']) || $settings['default'] === 0) { $this[$option] = $settings['default']; } } }
[ "private", "function", "_applyDefaults", "(", ")", "{", "foreach", "(", "$", "this", "->", "_flags", "as", "$", "flag", "=>", "$", "settings", ")", "{", "$", "this", "[", "$", "flag", "]", "=", "$", "settings", "[", "'default'", "]", ";", "}", "for...
This applies the default values, if any, of all of the flags and options, so that if there is a default value it will be available.
[ "This", "applies", "the", "default", "values", "if", "any", "of", "all", "of", "the", "flags", "and", "options", "so", "that", "if", "there", "is", "a", "default", "value", "it", "will", "be", "available", "." ]
train
https://github.com/wp-cli/php-cli-tools/blob/fe9c7c44a9e1bf2196ec51dc38da0593dbf2993f/lib/cli/Arguments.php#L418-L429
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/CSSmin.php
CSSmin.do_raise_php_limits
private function do_raise_php_limits() { $php_limits = array( 'memory_limit' => $this->memory_limit, 'max_execution_time' => $this->max_execution_time, 'pcre.backtrack_limit' => $this->pcre_backtrack_limit, 'pcre.recursion_limit' => $this->pcre_recursion_limit ); // If current settings are higher respect them. foreach ($php_limits as $name => $suggested) { $current = $this->normalize_int(ini_get($name)); // memory_limit exception: allow -1 for "no memory limit". if ($current > -1 && ($suggested == -1 || $current < $suggested)) { ini_set($name, $suggested); } } }
php
private function do_raise_php_limits() { $php_limits = array( 'memory_limit' => $this->memory_limit, 'max_execution_time' => $this->max_execution_time, 'pcre.backtrack_limit' => $this->pcre_backtrack_limit, 'pcre.recursion_limit' => $this->pcre_recursion_limit ); // If current settings are higher respect them. foreach ($php_limits as $name => $suggested) { $current = $this->normalize_int(ini_get($name)); // memory_limit exception: allow -1 for "no memory limit". if ($current > -1 && ($suggested == -1 || $current < $suggested)) { ini_set($name, $suggested); } } }
[ "private", "function", "do_raise_php_limits", "(", ")", "{", "$", "php_limits", "=", "array", "(", "'memory_limit'", "=>", "$", "this", "->", "memory_limit", ",", "'max_execution_time'", "=>", "$", "this", "->", "max_execution_time", ",", "'pcre.backtrack_limit'", ...
Try to configure PHP to use at least the suggested minimum settings
[ "Try", "to", "configure", "PHP", "to", "use", "at", "least", "the", "suggested", "minimum", "settings" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/CSSmin.php#L189-L206
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/CSSmin.php
CSSmin.replace_string
private function replace_string($matches) { $match = $matches[0]; $quote = substr($match, 0, 1); // Must use addcslashes in PHP to avoid parsing of backslashes $match = addcslashes($this->str_slice($match, 1, -1), '\\'); // maybe the string contains a comment-like substring? // one, maybe more? put'em back then if (($pos = $this->index_of($match, self::COMMENT)) >= 0) { for ($i = 0, $max = count($this->comments); $i < $max; $i++) { $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1); } } // minify alpha opacity in filter strings $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match); $this->preserved_tokens[] = $match; return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote; }
php
private function replace_string($matches) { $match = $matches[0]; $quote = substr($match, 0, 1); // Must use addcslashes in PHP to avoid parsing of backslashes $match = addcslashes($this->str_slice($match, 1, -1), '\\'); // maybe the string contains a comment-like substring? // one, maybe more? put'em back then if (($pos = $this->index_of($match, self::COMMENT)) >= 0) { for ($i = 0, $max = count($this->comments); $i < $max; $i++) { $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1); } } // minify alpha opacity in filter strings $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match); $this->preserved_tokens[] = $match; return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote; }
[ "private", "function", "replace_string", "(", "$", "matches", ")", "{", "$", "match", "=", "$", "matches", "[", "0", "]", ";", "$", "quote", "=", "substr", "(", "$", "match", ",", "0", ",", "1", ")", ";", "// Must use addcslashes in PHP to avoid parsing of...
/* CALLBACKS ---------------------------------------------------------------------------------------------
[ "/", "*", "CALLBACKS", "---------------------------------------------------------------------------------------------" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/CSSmin.php#L557-L578
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/CSSmin.php
CSSmin.hue_to_rgb
private function hue_to_rgb($v1, $v2, $vh) { $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh); if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh; if ($vh * 2 < 1) return $v2; if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6; return $v1; }
php
private function hue_to_rgb($v1, $v2, $vh) { $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh); if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh; if ($vh * 2 < 1) return $v2; if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6; return $v1; }
[ "private", "function", "hue_to_rgb", "(", "$", "v1", ",", "$", "v2", ",", "$", "vh", ")", "{", "$", "vh", "=", "$", "vh", "<", "0", "?", "$", "vh", "+", "1", ":", "(", "$", "vh", ">", "1", "?", "$", "vh", "-", "1", ":", "$", "vh", ")", ...
/* HELPERS ---------------------------------------------------------------------------------------------
[ "/", "*", "HELPERS", "---------------------------------------------------------------------------------------------" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/CSSmin.php#L689-L696
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/CSSmin.php
CSSmin.index_of
private function index_of($haystack, $needle, $offset = 0) { $index = strpos($haystack, $needle, $offset); return ($index !== FALSE) ? $index : -1; }
php
private function index_of($haystack, $needle, $offset = 0) { $index = strpos($haystack, $needle, $offset); return ($index !== FALSE) ? $index : -1; }
[ "private", "function", "index_of", "(", "$", "haystack", ",", "$", "needle", ",", "$", "offset", "=", "0", ")", "{", "$", "index", "=", "strpos", "(", "$", "haystack", ",", "$", "needle", ",", "$", "offset", ")", ";", "return", "(", "$", "index", ...
PHP port of Javascript's "indexOf" function for strings only Author: Tubal Martin http://blog.margenn.com @param string $haystack @param string $needle @param int $offset index (optional) @return int
[ "PHP", "port", "of", "Javascript", "s", "indexOf", "function", "for", "strings", "only", "Author", ":", "Tubal", "Martin", "http", ":", "//", "blog", ".", "margenn", ".", "com" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/CSSmin.php#L717-L722
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/CSSmin.php
CSSmin.str_slice
private function str_slice($str, $start = 0, $end = false) { if ($end !== FALSE && ($start < 0 || $end <= 0)) { $max = strlen($str); if ($start < 0) { if (($start = $max + $start) < 0) { return ''; } } if ($end < 0) { if (($end = $max + $end) < 0) { return ''; } } if ($end <= $start) { return ''; } } $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start); return ($slice === FALSE) ? '' : $slice; }
php
private function str_slice($str, $start = 0, $end = false) { if ($end !== FALSE && ($start < 0 || $end <= 0)) { $max = strlen($str); if ($start < 0) { if (($start = $max + $start) < 0) { return ''; } } if ($end < 0) { if (($end = $max + $end) < 0) { return ''; } } if ($end <= $start) { return ''; } } $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start); return ($slice === FALSE) ? '' : $slice; }
[ "private", "function", "str_slice", "(", "$", "str", ",", "$", "start", "=", "0", ",", "$", "end", "=", "false", ")", "{", "if", "(", "$", "end", "!==", "FALSE", "&&", "(", "$", "start", "<", "0", "||", "$", "end", "<=", "0", ")", ")", "{", ...
PHP port of Javascript's "slice" function for strings only Author: Tubal Martin http://blog.margenn.com Tests: http://margenn.com/tubal/str_slice/ @param string $str @param int $start index @param int|bool $end index (optional) @return string
[ "PHP", "port", "of", "Javascript", "s", "slice", "function", "for", "strings", "only", "Author", ":", "Tubal", "Martin", "http", ":", "//", "blog", ".", "margenn", ".", "com", "Tests", ":", "http", ":", "//", "margenn", ".", "com", "/", "tubal", "/", ...
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/CSSmin.php#L734-L759
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/CSSmin.php
CSSmin.normalize_int
private function normalize_int($size) { if (is_numeric($size)) { return (int)$size; } $letter = substr($size, -1); $size = (int)$size; switch ($letter) { case 'M': case 'm': return $size * 1048576; case 'K': case 'k': return $size * 1024; case 'G': case 'g': return $size * 1073741824; } }
php
private function normalize_int($size) { if (is_numeric($size)) { return (int)$size; } $letter = substr($size, -1); $size = (int)$size; switch ($letter) { case 'M': case 'm': return $size * 1048576; case 'K': case 'k': return $size * 1024; case 'G': case 'g': return $size * 1073741824; } }
[ "private", "function", "normalize_int", "(", "$", "size", ")", "{", "if", "(", "is_numeric", "(", "$", "size", ")", ")", "{", "return", "(", "int", ")", "$", "size", ";", "}", "$", "letter", "=", "substr", "(", "$", "size", ",", "-", "1", ")", ...
Convert strings like "64M" or "30" to int values @param mixed $size @return int
[ "Convert", "strings", "like", "64M", "or", "30", "to", "int", "values" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/CSSmin.php#L766-L780
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/PackerServiceProvider.php
PackerServiceProvider.config
public function config() { $config = config('packer'); if (empty($config['environment'])) { $config['environment'] = app()->environment(); } if (empty($config['public_path'])) { $config['public_path'] = public_path(); } if (empty($config['asset'])) { $config['asset'] = asset(''); } return $config; }
php
public function config() { $config = config('packer'); if (empty($config['environment'])) { $config['environment'] = app()->environment(); } if (empty($config['public_path'])) { $config['public_path'] = public_path(); } if (empty($config['asset'])) { $config['asset'] = asset(''); } return $config; }
[ "public", "function", "config", "(", ")", "{", "$", "config", "=", "config", "(", "'packer'", ")", ";", "if", "(", "empty", "(", "$", "config", "[", "'environment'", "]", ")", ")", "{", "$", "config", "[", "'environment'", "]", "=", "app", "(", ")"...
Get the base settings from config file @return array
[ "Get", "the", "base", "settings", "from", "config", "file" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/PackerServiceProvider.php#L54-L71
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/JSMin.php
JSMin.action
protected function action($command) { // make sure we don't compress "a + ++b" to "a+++b", etc. if ($command === self::ACTION_DELETE_A_B && $this->b === ' ' && ($this->a === '+' || $this->a === '-')) { // Note: we're at an addition/substraction operator; the inputIndex // will certainly be a valid index if ($this->input[$this->inputIndex] === $this->a) { // This is "+ +" or "- -". Don't delete the space. $command = self::ACTION_KEEP_A; } } switch ($command) { case self::ACTION_KEEP_A: // 1 $this->output .= $this->a; if ($this->keptComment) { $this->output = rtrim($this->output, "\n"); $this->output .= $this->keptComment; $this->keptComment = ''; } $this->lastByteOut = $this->a; // fallthrough intentional case self::ACTION_DELETE_A: // 2 $this->a = $this->b; if ($this->a === "'" || $this->a === '"') { // string literal $str = $this->a; // in case needed for exception for (;;) { $this->output .= $this->a; $this->lastByteOut = $this->a; $this->a = $this->get(); if ($this->a === $this->b) { // end quote break; } if ($this->isEOF($this->a)) { $byte = $this->inputIndex - 1; throw new JSMin_UnterminatedStringException( "JSMin: Unterminated String at byte {$byte}: {$str}"); } $str .= $this->a; if ($this->a === '\\') { $this->output .= $this->a; $this->lastByteOut = $this->a; $this->a = $this->get(); $str .= $this->a; } } } // fallthrough intentional case self::ACTION_DELETE_A_B: // 3 $this->b = $this->next(); if ($this->b === '/' && $this->isRegexpLiteral()) { $this->output .= $this->a . $this->b; $pattern = '/'; // keep entire pattern in case we need to report it in the exception for (;;) { $this->a = $this->get(); $pattern .= $this->a; if ($this->a === '[') { for (;;) { $this->output .= $this->a; $this->a = $this->get(); $pattern .= $this->a; if ($this->a === ']') { break; } if ($this->a === '\\') { $this->output .= $this->a; $this->a = $this->get(); $pattern .= $this->a; } if ($this->isEOF($this->a)) { throw new JSMin_UnterminatedRegExpException( "JSMin: Unterminated set in RegExp at byte " . $this->inputIndex .": {$pattern}"); } } } if ($this->a === '/') { // end pattern break; // while (true) } elseif ($this->a === '\\') { $this->output .= $this->a; $this->a = $this->get(); $pattern .= $this->a; } elseif ($this->isEOF($this->a)) { $byte = $this->inputIndex - 1; throw new JSMin_UnterminatedRegExpException( "JSMin: Unterminated RegExp at byte {$byte}: {$pattern}"); } $this->output .= $this->a; $this->lastByteOut = $this->a; } $this->b = $this->next(); } // end case ACTION_DELETE_A_B } }
php
protected function action($command) { // make sure we don't compress "a + ++b" to "a+++b", etc. if ($command === self::ACTION_DELETE_A_B && $this->b === ' ' && ($this->a === '+' || $this->a === '-')) { // Note: we're at an addition/substraction operator; the inputIndex // will certainly be a valid index if ($this->input[$this->inputIndex] === $this->a) { // This is "+ +" or "- -". Don't delete the space. $command = self::ACTION_KEEP_A; } } switch ($command) { case self::ACTION_KEEP_A: // 1 $this->output .= $this->a; if ($this->keptComment) { $this->output = rtrim($this->output, "\n"); $this->output .= $this->keptComment; $this->keptComment = ''; } $this->lastByteOut = $this->a; // fallthrough intentional case self::ACTION_DELETE_A: // 2 $this->a = $this->b; if ($this->a === "'" || $this->a === '"') { // string literal $str = $this->a; // in case needed for exception for (;;) { $this->output .= $this->a; $this->lastByteOut = $this->a; $this->a = $this->get(); if ($this->a === $this->b) { // end quote break; } if ($this->isEOF($this->a)) { $byte = $this->inputIndex - 1; throw new JSMin_UnterminatedStringException( "JSMin: Unterminated String at byte {$byte}: {$str}"); } $str .= $this->a; if ($this->a === '\\') { $this->output .= $this->a; $this->lastByteOut = $this->a; $this->a = $this->get(); $str .= $this->a; } } } // fallthrough intentional case self::ACTION_DELETE_A_B: // 3 $this->b = $this->next(); if ($this->b === '/' && $this->isRegexpLiteral()) { $this->output .= $this->a . $this->b; $pattern = '/'; // keep entire pattern in case we need to report it in the exception for (;;) { $this->a = $this->get(); $pattern .= $this->a; if ($this->a === '[') { for (;;) { $this->output .= $this->a; $this->a = $this->get(); $pattern .= $this->a; if ($this->a === ']') { break; } if ($this->a === '\\') { $this->output .= $this->a; $this->a = $this->get(); $pattern .= $this->a; } if ($this->isEOF($this->a)) { throw new JSMin_UnterminatedRegExpException( "JSMin: Unterminated set in RegExp at byte " . $this->inputIndex .": {$pattern}"); } } } if ($this->a === '/') { // end pattern break; // while (true) } elseif ($this->a === '\\') { $this->output .= $this->a; $this->a = $this->get(); $pattern .= $this->a; } elseif ($this->isEOF($this->a)) { $byte = $this->inputIndex - 1; throw new JSMin_UnterminatedRegExpException( "JSMin: Unterminated RegExp at byte {$byte}: {$pattern}"); } $this->output .= $this->a; $this->lastByteOut = $this->a; } $this->b = $this->next(); } // end case ACTION_DELETE_A_B } }
[ "protected", "function", "action", "(", "$", "command", ")", "{", "// make sure we don't compress \"a + ++b\" to \"a+++b\", etc.", "if", "(", "$", "command", "===", "self", "::", "ACTION_DELETE_A_B", "&&", "$", "this", "->", "b", "===", "' '", "&&", "(", "$", "t...
ACTION_KEEP_A = Output A. Copy B to A. Get the next B. ACTION_DELETE_A = Copy B to A. Get the next B. ACTION_DELETE_A_B = Get the next B. @param int $command @throws JSMin_UnterminatedRegExpException|JSMin_UnterminatedStringException
[ "ACTION_KEEP_A", "=", "Output", "A", ".", "Copy", "B", "to", "A", ".", "Get", "the", "next", "B", ".", "ACTION_DELETE_A", "=", "Copy", "B", "to", "A", ".", "Get", "the", "next", "B", ".", "ACTION_DELETE_A_B", "=", "Get", "the", "next", "B", "." ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/JSMin.php#L168-L271
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/JSMin.php
JSMin.consumeSingleLineComment
protected function consumeSingleLineComment() { $comment = ''; while (true) { $get = $this->get(); $comment .= $get; if (ord($get) <= self::ORD_LF) { // end of line reached // if IE conditional comment if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) { $this->keptComment .= "/{$comment}"; } return; } } }
php
protected function consumeSingleLineComment() { $comment = ''; while (true) { $get = $this->get(); $comment .= $get; if (ord($get) <= self::ORD_LF) { // end of line reached // if IE conditional comment if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) { $this->keptComment .= "/{$comment}"; } return; } } }
[ "protected", "function", "consumeSingleLineComment", "(", ")", "{", "$", "comment", "=", "''", ";", "while", "(", "true", ")", "{", "$", "get", "=", "$", "this", "->", "get", "(", ")", ";", "$", "comment", ".=", "$", "get", ";", "if", "(", "ord", ...
Consume a single line comment from input (possibly retaining it)
[ "Consume", "a", "single", "line", "comment", "from", "input", "(", "possibly", "retaining", "it", ")" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/JSMin.php#L379-L394
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/JSMin.php
JSMin.consumeMultipleLineComment
protected function consumeMultipleLineComment() { $this->get(); $comment = ''; for (;;) { $get = $this->get(); if ($get === '*') { if ($this->peek() === '/') { // end of comment reached $this->get(); if ($this->keptComments && (0 === strpos($comment, '!'))) { // preserved by YUI Compressor if (empty($this->keptComment)) { // don't prepend a newline if two comments right after one another $this->keptComment = "\n"; } $this->keptComment .= "/*!" . substr($comment, 1) . "*/\n"; } elseif (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) { // IE conditional $this->keptComment .= "/*{$comment}*/"; } return; } } elseif ($get === null) { throw new JSMin_UnterminatedCommentException( "JSMin: Unterminated comment at byte {$this->inputIndex}: /*{$comment}"); } $comment .= $get; } }
php
protected function consumeMultipleLineComment() { $this->get(); $comment = ''; for (;;) { $get = $this->get(); if ($get === '*') { if ($this->peek() === '/') { // end of comment reached $this->get(); if ($this->keptComments && (0 === strpos($comment, '!'))) { // preserved by YUI Compressor if (empty($this->keptComment)) { // don't prepend a newline if two comments right after one another $this->keptComment = "\n"; } $this->keptComment .= "/*!" . substr($comment, 1) . "*/\n"; } elseif (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) { // IE conditional $this->keptComment .= "/*{$comment}*/"; } return; } } elseif ($get === null) { throw new JSMin_UnterminatedCommentException( "JSMin: Unterminated comment at byte {$this->inputIndex}: /*{$comment}"); } $comment .= $get; } }
[ "protected", "function", "consumeMultipleLineComment", "(", ")", "{", "$", "this", "->", "get", "(", ")", ";", "$", "comment", "=", "''", ";", "for", "(", ";", ";", ")", "{", "$", "get", "=", "$", "this", "->", "get", "(", ")", ";", "if", "(", ...
Consume a multiple line comment from input (possibly retaining it) @throws JSMin_UnterminatedCommentException
[ "Consume", "a", "multiple", "line", "comment", "from", "input", "(", "possibly", "retaining", "it", ")" ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/JSMin.php#L401-L430
eusonlito/laravel-Packer
src/Eusonlito/LaravelPacker/Processors/JSMin.php
JSMin.next
protected function next() { $get = $this->get(); if ($get === '/') { switch ($this->peek()) { case '/': $this->consumeSingleLineComment(); $get = "\n"; break; case '*': $this->consumeMultipleLineComment(); $get = ' '; break; } } return $get; }
php
protected function next() { $get = $this->get(); if ($get === '/') { switch ($this->peek()) { case '/': $this->consumeSingleLineComment(); $get = "\n"; break; case '*': $this->consumeMultipleLineComment(); $get = ' '; break; } } return $get; }
[ "protected", "function", "next", "(", ")", "{", "$", "get", "=", "$", "this", "->", "get", "(", ")", ";", "if", "(", "$", "get", "===", "'/'", ")", "{", "switch", "(", "$", "this", "->", "peek", "(", ")", ")", "{", "case", "'/'", ":", "$", ...
Get the next character, skipping over comments. Some comments may be preserved. @return string
[ "Get", "the", "next", "character", "skipping", "over", "comments", ".", "Some", "comments", "may", "be", "preserved", "." ]
train
https://github.com/eusonlito/laravel-Packer/blob/81003e4835a5b06eeac00c2ac2cbc0284825bd2e/src/Eusonlito/LaravelPacker/Processors/JSMin.php#L437-L454
caffeinated/themes
src/ThemesServiceProvider.php
ThemesServiceProvider.register
public function register() { $this->mergeConfigFrom( __DIR__.'/../config/themes.php', 'themes' ); $this->registerServices(); $this->registerNamespaces(); $this->commands([ GenerateTheme::class ]); }
php
public function register() { $this->mergeConfigFrom( __DIR__.'/../config/themes.php', 'themes' ); $this->registerServices(); $this->registerNamespaces(); $this->commands([ GenerateTheme::class ]); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/../config/themes.php'", ",", "'themes'", ")", ";", "$", "this", "->", "registerServices", "(", ")", ";", "$", "this", "->", "registerNamespaces", "...
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/ThemesServiceProvider.php#L37-L49
caffeinated/themes
src/ThemesServiceProvider.php
ThemesServiceProvider.registerServices
protected function registerServices() { $this->app->singleton('caffeinated.themes', function($app) { $themes = []; $items = []; if ($path = base_path('themes')) { if (file_exists($path) && is_dir($path)) { $themes = $this->app['files']->directories($path); } } foreach ($themes as $theme) { $manifest = new Manifest($theme.'/theme.json'); $items[] = collect($manifest->all()); } return new Theme($items); }); $this->app->singleton('view.finder', function($app) { return new ThemeViewFinder($app['files'], $app['config']['view.paths'], null); }); }
php
protected function registerServices() { $this->app->singleton('caffeinated.themes', function($app) { $themes = []; $items = []; if ($path = base_path('themes')) { if (file_exists($path) && is_dir($path)) { $themes = $this->app['files']->directories($path); } } foreach ($themes as $theme) { $manifest = new Manifest($theme.'/theme.json'); $items[] = collect($manifest->all()); } return new Theme($items); }); $this->app->singleton('view.finder', function($app) { return new ThemeViewFinder($app['files'], $app['config']['view.paths'], null); }); }
[ "protected", "function", "registerServices", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'caffeinated.themes'", ",", "function", "(", "$", "app", ")", "{", "$", "themes", "=", "[", "]", ";", "$", "items", "=", "[", "]", ";", "if...
Register the package services.
[ "Register", "the", "package", "services", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/ThemesServiceProvider.php#L64-L87
caffeinated/themes
src/ThemesServiceProvider.php
ThemesServiceProvider.registerNamespaces
protected function registerNamespaces() { $themes = app('caffeinated.themes')->all(); foreach ($themes as $theme) { $namespace = $theme->get('slug'); $hint = app('caffeinated.themes')->path('resources/views', $theme->get('slug')); app('view')->addNamespace($namespace, $hint); } }
php
protected function registerNamespaces() { $themes = app('caffeinated.themes')->all(); foreach ($themes as $theme) { $namespace = $theme->get('slug'); $hint = app('caffeinated.themes')->path('resources/views', $theme->get('slug')); app('view')->addNamespace($namespace, $hint); } }
[ "protected", "function", "registerNamespaces", "(", ")", "{", "$", "themes", "=", "app", "(", "'caffeinated.themes'", ")", "->", "all", "(", ")", ";", "foreach", "(", "$", "themes", "as", "$", "theme", ")", "{", "$", "namespace", "=", "$", "theme", "->...
Register the theme namespaces.
[ "Register", "the", "theme", "namespaces", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/ThemesServiceProvider.php#L92-L102
caffeinated/themes
src/Console/GenerateTheme.php
GenerateTheme.handle
public function handle() { $options = $this->getOptions(); $root = base_path('themes'); $stubsPath = __DIR__ . '/../../resources/stubs/theme'; $slug = $options['slug']; $name = $this->format($slug); if (File::isDirectory($root . '/' . $name)) { return $this->error('Theme already exists!'); } if (! File::isDirectory($root)) { File::makeDirectory($root); } foreach (File::allFiles($stubsPath) as $file) { $contents = $this->replacePlaceholders($file->getContents(), $options); $subPath = $file->getRelativePathname(); $filePath = $root.'/'.$options['name'].'/'.$subPath; $dir = dirname($filePath); if (! File::isDirectory($dir)) { File::makeDirectory($dir, 0755, true); } File::put($filePath, $contents); } $this->info("Theme created successfully."); }
php
public function handle() { $options = $this->getOptions(); $root = base_path('themes'); $stubsPath = __DIR__ . '/../../resources/stubs/theme'; $slug = $options['slug']; $name = $this->format($slug); if (File::isDirectory($root . '/' . $name)) { return $this->error('Theme already exists!'); } if (! File::isDirectory($root)) { File::makeDirectory($root); } foreach (File::allFiles($stubsPath) as $file) { $contents = $this->replacePlaceholders($file->getContents(), $options); $subPath = $file->getRelativePathname(); $filePath = $root.'/'.$options['name'].'/'.$subPath; $dir = dirname($filePath); if (! File::isDirectory($dir)) { File::makeDirectory($dir, 0755, true); } File::put($filePath, $contents); } $this->info("Theme created successfully."); }
[ "public", "function", "handle", "(", ")", "{", "$", "options", "=", "$", "this", "->", "getOptions", "(", ")", ";", "$", "root", "=", "base_path", "(", "'themes'", ")", ";", "$", "stubsPath", "=", "__DIR__", ".", "'/../../resources/stubs/theme'", ";", "$...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Console/GenerateTheme.php#L39-L69
caffeinated/themes
src/Console/GenerateTheme.php
GenerateTheme.replacePlaceholders
protected function replacePlaceholders($contents, $options) { $find = [ 'DummyNamespace', 'DummyEscapedNamespace', 'DummyName', 'DummySlug', 'DummyVersion', 'DummyDescription', 'DummyPackageName', 'DummyAuthor', ]; $replace = [ $options['namespace'], $options['escaped_namespace'], $options['name'], $options['slug'], $options['version'], $options['description'], $options['package_name'], $options['author'], ]; return str_replace($find, $replace, $contents); }
php
protected function replacePlaceholders($contents, $options) { $find = [ 'DummyNamespace', 'DummyEscapedNamespace', 'DummyName', 'DummySlug', 'DummyVersion', 'DummyDescription', 'DummyPackageName', 'DummyAuthor', ]; $replace = [ $options['namespace'], $options['escaped_namespace'], $options['name'], $options['slug'], $options['version'], $options['description'], $options['package_name'], $options['author'], ]; return str_replace($find, $replace, $contents); }
[ "protected", "function", "replacePlaceholders", "(", "$", "contents", ",", "$", "options", ")", "{", "$", "find", "=", "[", "'DummyNamespace'", ",", "'DummyEscapedNamespace'", ",", "'DummyName'", ",", "'DummySlug'", ",", "'DummyVersion'", ",", "'DummyDescription'", ...
Replace placeholders with actual content. @param $contents @param $options @return mixed
[ "Replace", "placeholders", "with", "actual", "content", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Console/GenerateTheme.php#L101-L126
caffeinated/themes
src/Theme.php
Theme.set
public function set($theme) { list($theme, $parent) = $this->resolveTheme($theme); if (! $this->isCurrently($theme->get('slug')) and (! is_null($this->getCurrent()))) { $this->removeRegisteredLocation(); } $this->setCurrent($theme->get('slug')); $this->registerAutoload($this->format($theme->get('slug'))); $this->addRegisteredLocation($theme, $parent); $this->symlinkPublicDirectory(); $this->registerServiceProvider($this->format($theme->get('slug'))); }
php
public function set($theme) { list($theme, $parent) = $this->resolveTheme($theme); if (! $this->isCurrently($theme->get('slug')) and (! is_null($this->getCurrent()))) { $this->removeRegisteredLocation(); } $this->setCurrent($theme->get('slug')); $this->registerAutoload($this->format($theme->get('slug'))); $this->addRegisteredLocation($theme, $parent); $this->symlinkPublicDirectory(); $this->registerServiceProvider($this->format($theme->get('slug'))); }
[ "public", "function", "set", "(", "$", "theme", ")", "{", "list", "(", "$", "theme", ",", "$", "parent", ")", "=", "$", "this", "->", "resolveTheme", "(", "$", "theme", ")", ";", "if", "(", "!", "$", "this", "->", "isCurrently", "(", "$", "theme"...
Register and set the currently active theme. @param string $theme
[ "Register", "and", "set", "the", "currently", "active", "theme", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Theme.php#L27-L41
caffeinated/themes
src/Theme.php
Theme.path
public function path($file = '', $theme = null) { if (is_null($theme)) { $theme = $this->getCurrent(); } $theme = $this->format($theme); return base_path("themes/{$theme}/{$file}"); }
php
public function path($file = '', $theme = null) { if (is_null($theme)) { $theme = $this->getCurrent(); } $theme = $this->format($theme); return base_path("themes/{$theme}/{$file}"); }
[ "public", "function", "path", "(", "$", "file", "=", "''", ",", "$", "theme", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "theme", ")", ")", "{", "$", "theme", "=", "$", "this", "->", "getCurrent", "(", ")", ";", "}", "$", "theme", ...
Get the path of the given theme file. @param string $file @param string $theme @return string
[ "Get", "the", "path", "of", "the", "given", "theme", "file", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Theme.php#L50-L59
caffeinated/themes
src/Theme.php
Theme.symlinkPublicDirectory
protected function symlinkPublicDirectory() { if (! file_exists(public_path('themes/'.$this->getCurrent()))) { if (! file_exists(public_path('themes'))) { app()->make('files')->makeDirectory(public_path('themes')); } app()->make('files')->link( $this->path('public'), public_path('themes/'.$this->getCurrent()) ); } }
php
protected function symlinkPublicDirectory() { if (! file_exists(public_path('themes/'.$this->getCurrent()))) { if (! file_exists(public_path('themes'))) { app()->make('files')->makeDirectory(public_path('themes')); } app()->make('files')->link( $this->path('public'), public_path('themes/'.$this->getCurrent()) ); } }
[ "protected", "function", "symlinkPublicDirectory", "(", ")", "{", "if", "(", "!", "file_exists", "(", "public_path", "(", "'themes/'", ".", "$", "this", "->", "getCurrent", "(", ")", ")", ")", ")", "{", "if", "(", "!", "file_exists", "(", "public_path", ...
Symlink the themes public directory so its accesible by the web. @return void
[ "Symlink", "the", "themes", "public", "directory", "so", "its", "accesible", "by", "the", "web", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Theme.php#L128-L139
caffeinated/themes
src/Theme.php
Theme.registerAutoload
protected function registerAutoload($theme) { $composer = require(base_path('vendor/autoload.php')); $class = 'Themes\\'.$theme.'\\'; $path = $this->path('src/'); if (! array_key_exists($class, $composer->getClassMap())) { $composer->addPsr4($class, $path); } }
php
protected function registerAutoload($theme) { $composer = require(base_path('vendor/autoload.php')); $class = 'Themes\\'.$theme.'\\'; $path = $this->path('src/'); if (! array_key_exists($class, $composer->getClassMap())) { $composer->addPsr4($class, $path); } }
[ "protected", "function", "registerAutoload", "(", "$", "theme", ")", "{", "$", "composer", "=", "require", "(", "base_path", "(", "'vendor/autoload.php'", ")", ")", ";", "$", "class", "=", "'Themes\\\\'", ".", "$", "theme", ".", "'\\\\'", ";", "$", "path",...
Register the themes path as a PSR-4 reference. @param string $theme @return void
[ "Register", "the", "themes", "path", "as", "a", "PSR", "-", "4", "reference", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Theme.php#L158-L168
caffeinated/themes
src/Concerns/RegistersViewLocations.php
RegistersViewLocations.resolveTheme
protected function resolveTheme($theme) { $theme = $this->where('slug', $theme)->first(); $parent = null; if ($theme->has('parent')) { $parent = $this->where('slug', $theme->get('parent'))->first(); } return [$theme, $parent]; }
php
protected function resolveTheme($theme) { $theme = $this->where('slug', $theme)->first(); $parent = null; if ($theme->has('parent')) { $parent = $this->where('slug', $theme->get('parent'))->first(); } return [$theme, $parent]; }
[ "protected", "function", "resolveTheme", "(", "$", "theme", ")", "{", "$", "theme", "=", "$", "this", "->", "where", "(", "'slug'", ",", "$", "theme", ")", "->", "first", "(", ")", ";", "$", "parent", "=", "null", ";", "if", "(", "$", "theme", "-...
Resolve and return the primary and parent themes. @param string $theme @return array
[ "Resolve", "and", "return", "the", "primary", "and", "parent", "themes", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Concerns/RegistersViewLocations.php#L13-L23
caffeinated/themes
src/Concerns/RegistersViewLocations.php
RegistersViewLocations.removeRegisteredLocation
protected function removeRegisteredLocation() { $current = $this->where('slug', $this->getCurrent())->first(); $currentLocation = $this->path('resources/views'); app('view.finder')->removeLocation($currentLocation); if ($current->has('parent')) { $parent = $this->where('slug', $current->get('parent'))->first(); $parentLocation = $this->path('resources/views', $parent->slug); app('view.finder')->removeLocation($parentLocation); } }
php
protected function removeRegisteredLocation() { $current = $this->where('slug', $this->getCurrent())->first(); $currentLocation = $this->path('resources/views'); app('view.finder')->removeLocation($currentLocation); if ($current->has('parent')) { $parent = $this->where('slug', $current->get('parent'))->first(); $parentLocation = $this->path('resources/views', $parent->slug); app('view.finder')->removeLocation($parentLocation); } }
[ "protected", "function", "removeRegisteredLocation", "(", ")", "{", "$", "current", "=", "$", "this", "->", "where", "(", "'slug'", ",", "$", "this", "->", "getCurrent", "(", ")", ")", "->", "first", "(", ")", ";", "$", "currentLocation", "=", "$", "th...
Remove the primary and parent theme from the view finder. @param Manifest $theme
[ "Remove", "the", "primary", "and", "parent", "theme", "from", "the", "view", "finder", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Concerns/RegistersViewLocations.php#L30-L42
caffeinated/themes
src/Concerns/RegistersViewLocations.php
RegistersViewLocations.addRegisteredLocation
protected function addRegisteredLocation($theme, $parent) { if (! is_null($parent)) { $parentLocation = $this->path('resources/views'); app('view.finder')->prependLocation($parentLocation); } $themeLocation = $this->path('resources/views'); app('view.finder')->prependLocation($themeLocation); }
php
protected function addRegisteredLocation($theme, $parent) { if (! is_null($parent)) { $parentLocation = $this->path('resources/views'); app('view.finder')->prependLocation($parentLocation); } $themeLocation = $this->path('resources/views'); app('view.finder')->prependLocation($themeLocation); }
[ "protected", "function", "addRegisteredLocation", "(", "$", "theme", ",", "$", "parent", ")", "{", "if", "(", "!", "is_null", "(", "$", "parent", ")", ")", "{", "$", "parentLocation", "=", "$", "this", "->", "path", "(", "'resources/views'", ")", ";", ...
Register the primary and parent theme with the view finder. @param Manifest $theme @param Manifest $parent
[ "Register", "the", "primary", "and", "parent", "theme", "with", "the", "view", "finder", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Concerns/RegistersViewLocations.php#L50-L59
caffeinated/themes
src/Manifest.php
Manifest.save
public function save() { if (file_exists($this->getPath())) { $this->setContent($this->encode()); file_put_contents($this->getPath(), $this->getContent()); return; } }
php
public function save() { if (file_exists($this->getPath())) { $this->setContent($this->encode()); file_put_contents($this->getPath(), $this->getContent()); return; } }
[ "public", "function", "save", "(", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "getPath", "(", ")", ")", ")", "{", "$", "this", "->", "setContent", "(", "$", "this", "->", "encode", "(", ")", ")", ";", "file_put_contents", "(", "$",...
Save the manifest file content.
[ "Save", "the", "manifest", "file", "content", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/Manifest.php#L63-L72
caffeinated/themes
src/View/ThemeViewFinder.php
ThemeViewFinder.removeLocation
public function removeLocation(string $location) { $key = array_search($location, $this->paths); if ($key) { unset($this->paths[$key]); } }
php
public function removeLocation(string $location) { $key = array_search($location, $this->paths); if ($key) { unset($this->paths[$key]); } }
[ "public", "function", "removeLocation", "(", "string", "$", "location", ")", "{", "$", "key", "=", "array_search", "(", "$", "location", ",", "$", "this", "->", "paths", ")", ";", "if", "(", "$", "key", ")", "{", "unset", "(", "$", "this", "->", "p...
Remove a location from the finder. @param string $location
[ "Remove", "a", "location", "from", "the", "finder", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/View/ThemeViewFinder.php#L15-L22
caffeinated/themes
src/View/ThemeViewFinder.php
ThemeViewFinder.findNamespacedView
protected function findNamespacedView($name) { list($namespace, $view) = $this->parseNamespaceSegments($name); $this->addThemeNamespaceHints($namespace); return $this->findInPaths($view, $this->hints[$namespace]); }
php
protected function findNamespacedView($name) { list($namespace, $view) = $this->parseNamespaceSegments($name); $this->addThemeNamespaceHints($namespace); return $this->findInPaths($view, $this->hints[$namespace]); }
[ "protected", "function", "findNamespacedView", "(", "$", "name", ")", "{", "list", "(", "$", "namespace", ",", "$", "view", ")", "=", "$", "this", "->", "parseNamespaceSegments", "(", "$", "name", ")", ";", "$", "this", "->", "addThemeNamespaceHints", "(",...
Get the path to a template with a named path. @param string $name @return string
[ "Get", "the", "path", "to", "a", "template", "with", "a", "named", "path", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/View/ThemeViewFinder.php#L30-L37
caffeinated/themes
src/View/ThemeViewFinder.php
ThemeViewFinder.addThemeNamespaceHints
protected function addThemeNamespaceHints($namespace) { $theme = Theme::getCurrent(); $hints = array_reverse($this->hints[$namespace]); $hints[] = Theme::path('resources/views/vendor/'.$namespace); if (class_exists(\Caffeinated\Modules\ModulesServiceProvider::class)) { $hints[] = Theme::path('resources/views/modules/'.$namespace); } $this->hints[$namespace] = array_reverse($hints); }
php
protected function addThemeNamespaceHints($namespace) { $theme = Theme::getCurrent(); $hints = array_reverse($this->hints[$namespace]); $hints[] = Theme::path('resources/views/vendor/'.$namespace); if (class_exists(\Caffeinated\Modules\ModulesServiceProvider::class)) { $hints[] = Theme::path('resources/views/modules/'.$namespace); } $this->hints[$namespace] = array_reverse($hints); }
[ "protected", "function", "addThemeNamespaceHints", "(", "$", "namespace", ")", "{", "$", "theme", "=", "Theme", "::", "getCurrent", "(", ")", ";", "$", "hints", "=", "array_reverse", "(", "$", "this", "->", "hints", "[", "$", "namespace", "]", ")", ";", ...
Add namespace hints for the currently set theme. @param string $namespace @return array
[ "Add", "namespace", "hints", "for", "the", "currently", "set", "theme", "." ]
train
https://github.com/caffeinated/themes/blob/cdafcb86f718afb9584c329b60224a9b4233f700/src/View/ThemeViewFinder.php#L45-L57