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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
AydinHassan/cli-md-renderer
src/InlineRenderer/TextRenderer.php
TextRenderer.render
public function render(AbstractInline $inline, CliRenderer $renderer) { if (!($inline instanceof Text)) { throw new \InvalidArgumentException(sprintf('Incompatible inline type: "%s"', get_class($inline))); } return $inline->getContent(); }
php
public function render(AbstractInline $inline, CliRenderer $renderer) { if (!($inline instanceof Text)) { throw new \InvalidArgumentException(sprintf('Incompatible inline type: "%s"', get_class($inline))); } return $inline->getContent(); }
[ "public", "function", "render", "(", "AbstractInline", "$", "inline", ",", "CliRenderer", "$", "renderer", ")", "{", "if", "(", "!", "(", "$", "inline", "instanceof", "Text", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Incompatible inline type: \"%s\"'", ",", "get_class", "(", "$", "inline", ")", ")", ")", ";", "}", "return", "$", "inline", "->", "getContent", "(", ")", ";", "}" ]
@param AbstractInline $inline @param CliRenderer $renderer @return string
[ "@param", "AbstractInline", "$inline", "@param", "CliRenderer", "$renderer" ]
train
https://github.com/AydinHassan/cli-md-renderer/blob/521f9ace2aeadd58bf8a3910704be8360f5bd7b2/src/InlineRenderer/TextRenderer.php#L23-L30
webforge-labs/psc-cms
lib/Psc/Form/StandardValidatorRule.php
StandardValidatorRule.generateRule
public static function generateRule($ruleSpecification) { $rs = $ruleSpecification; if (is_string($rs)) { if ($rs == 'nes') { return new NesValidatorRule(); } if ($rs == 'id') { return new IdValidatorRule(); } if ($rs == 'pi' || $rs == 'pint') { return new PositiveIntValidatorRule(); } if ($rs == 'array') { return new ArrayValidatorRule(); } if ($rs == 'pi0' || $rs == 'pint0') { $rule = new PositiveIntValidatorRule(); $rule->setZeroAllowed(TRUE); return $rule; } if (S::startsWith($rs,'/') && S::endsWith($rs,'/')) return self::generateRegexpRule($rs); $c = '\\'.__NAMESPACE__.'\\'.ucfirst($rs).'ValidatorRule'; if (class_exists($c)) { return new $c; } throw new \Psc\Exception('Unbekannte Parameter für generateRule '.Code::varInfo($rs)); } if (is_array($rs)) { $num = count($rs); } throw new \Psc\Exception('Unbekannte Parameter für generateRule '.Code::varInfo($rs)); }
php
public static function generateRule($ruleSpecification) { $rs = $ruleSpecification; if (is_string($rs)) { if ($rs == 'nes') { return new NesValidatorRule(); } if ($rs == 'id') { return new IdValidatorRule(); } if ($rs == 'pi' || $rs == 'pint') { return new PositiveIntValidatorRule(); } if ($rs == 'array') { return new ArrayValidatorRule(); } if ($rs == 'pi0' || $rs == 'pint0') { $rule = new PositiveIntValidatorRule(); $rule->setZeroAllowed(TRUE); return $rule; } if (S::startsWith($rs,'/') && S::endsWith($rs,'/')) return self::generateRegexpRule($rs); $c = '\\'.__NAMESPACE__.'\\'.ucfirst($rs).'ValidatorRule'; if (class_exists($c)) { return new $c; } throw new \Psc\Exception('Unbekannte Parameter für generateRule '.Code::varInfo($rs)); } if (is_array($rs)) { $num = count($rs); } throw new \Psc\Exception('Unbekannte Parameter für generateRule '.Code::varInfo($rs)); }
[ "public", "static", "function", "generateRule", "(", "$", "ruleSpecification", ")", "{", "$", "rs", "=", "$", "ruleSpecification", ";", "if", "(", "is_string", "(", "$", "rs", ")", ")", "{", "if", "(", "$", "rs", "==", "'nes'", ")", "{", "return", "new", "NesValidatorRule", "(", ")", ";", "}", "if", "(", "$", "rs", "==", "'id'", ")", "{", "return", "new", "IdValidatorRule", "(", ")", ";", "}", "if", "(", "$", "rs", "==", "'pi'", "||", "$", "rs", "==", "'pint'", ")", "{", "return", "new", "PositiveIntValidatorRule", "(", ")", ";", "}", "if", "(", "$", "rs", "==", "'array'", ")", "{", "return", "new", "ArrayValidatorRule", "(", ")", ";", "}", "if", "(", "$", "rs", "==", "'pi0'", "||", "$", "rs", "==", "'pint0'", ")", "{", "$", "rule", "=", "new", "PositiveIntValidatorRule", "(", ")", ";", "$", "rule", "->", "setZeroAllowed", "(", "TRUE", ")", ";", "return", "$", "rule", ";", "}", "if", "(", "S", "::", "startsWith", "(", "$", "rs", ",", "'/'", ")", "&&", "S", "::", "endsWith", "(", "$", "rs", ",", "'/'", ")", ")", "return", "self", "::", "generateRegexpRule", "(", "$", "rs", ")", ";", "$", "c", "=", "'\\\\'", ".", "__NAMESPACE__", ".", "'\\\\'", ".", "ucfirst", "(", "$", "rs", ")", ".", "'ValidatorRule'", ";", "if", "(", "class_exists", "(", "$", "c", ")", ")", "{", "return", "new", "$", "c", ";", "}", "throw", "new", "\\", "Psc", "\\", "Exception", "(", "'Unbekannte Parameter für generateRule '.", "C", "ode:", ":v", "arInfo(", "$", "r", "s)", ")", ";", "", "}", "if", "(", "is_array", "(", "$", "rs", ")", ")", "{", "$", "num", "=", "count", "(", "$", "rs", ")", ";", "}", "throw", "new", "\\", "Psc", "\\", "Exception", "(", "'Unbekannte Parameter für generateRule '.", "C", "ode:", ":v", "arInfo(", "$", "r", "s)", ")", ";", "", "}" ]
Erstellt eine neue Rule durch eine Spezifikation (was so quasi alles sein kann) Die Parameter dieser Funktion sind sehr Variabel Möglicherweise ist es einfacher generate[A-Za-z+]Rule zu benutzen
[ "Erstellt", "eine", "neue", "Rule", "durch", "eine", "Spezifikation", "(", "was", "so", "quasi", "alles", "sein", "kann", ")" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/StandardValidatorRule.php#L25-L69
webforge-labs/psc-cms
lib/Psc/Form/StandardValidatorRule.php
StandardValidatorRule.validate
public function validate($data) { if (isset($this->callback)) { return $this->callback->call(array($data)); } throw new \Psc\Exception('empty rule!'); }
php
public function validate($data) { if (isset($this->callback)) { return $this->callback->call(array($data)); } throw new \Psc\Exception('empty rule!'); }
[ "public", "function", "validate", "(", "$", "data", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "callback", ")", ")", "{", "return", "$", "this", "->", "callback", "->", "call", "(", "array", "(", "$", "data", ")", ")", ";", "}", "throw", "new", "\\", "Psc", "\\", "Exception", "(", "'empty rule!'", ")", ";", "}" ]
Validiert die gespeicherte Rule Achtung! nicht bool zurückgeben, stattdessen irgendeine Exception schmeissen @return $data
[ "Validiert", "die", "gespeicherte", "Rule" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Form/StandardValidatorRule.php#L85-L91
Lansoweb/LosBase
src/LosBase/Controller/ORM/AbstractCrudController.php
AbstractCrudController.getEntityService
public function getEntityService() { if (null === $this->entityService) { $entityServiceClass = $this->getEntityServiceClass(); if (!class_exists($entityServiceClass)) { throw new \RuntimeException("Classe $entityServiceClass inexistente!"); } $this->entityService = new $entityServiceClass(); $this->entityService->setServiceLocator($this->getServiceLocator()); } return $this->entityService; }
php
public function getEntityService() { if (null === $this->entityService) { $entityServiceClass = $this->getEntityServiceClass(); if (!class_exists($entityServiceClass)) { throw new \RuntimeException("Classe $entityServiceClass inexistente!"); } $this->entityService = new $entityServiceClass(); $this->entityService->setServiceLocator($this->getServiceLocator()); } return $this->entityService; }
[ "public", "function", "getEntityService", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "entityService", ")", "{", "$", "entityServiceClass", "=", "$", "this", "->", "getEntityServiceClass", "(", ")", ";", "if", "(", "!", "class_exists", "(", "$", "entityServiceClass", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Classe $entityServiceClass inexistente!\"", ")", ";", "}", "$", "this", "->", "entityService", "=", "new", "$", "entityServiceClass", "(", ")", ";", "$", "this", "->", "entityService", "->", "setServiceLocator", "(", "$", "this", "->", "getServiceLocator", "(", ")", ")", ";", "}", "return", "$", "this", "->", "entityService", ";", "}" ]
Retorna o serviço da entidade. @throws \InvalidArgumentException @return mixed
[ "Retorna", "o", "serviço", "da", "entidade", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Controller/ORM/AbstractCrudController.php#L60-L72
Lansoweb/LosBase
src/LosBase/Controller/ORM/AbstractCrudController.php
AbstractCrudController.getForm
public function getForm($entityClass = null) { if (null === $entityClass) { $entityClass = $this->getEntityClass(); } $builder = new AnnotationBuilder(); $form = $builder->createForm($entityClass); $hasEntity = false; foreach ($form->getElements() as $element) { if (method_exists($element, 'setObjectManager')) { $element->setObjectManager($this->getEntityManager()); $hasEntity = true; } elseif (method_exists($element, 'getProxy')) { $proxy = $element->getProxy(); if (method_exists($proxy, 'setObjectManager')) { $proxy->setObjectManager($this->getEntityManager()); $hasEntity = true; } } } if ($hasEntity) { $hydrator = new DoctrineHydrator($this->getEntityManager(), $entityClass); $form->setHydrator($hydrator); } else { $form->setHydrator(new ClassMethods()); } $form->add([ 'type' => 'Zend\Form\Element\Csrf', 'name' => 'csrf', 'attributes' => [ 'id' => 'csrf', ], ]); $submitElement = new \Zend\Form\Element\Button('submit'); $submitElement->setAttributes([ 'type' => 'submit', 'class' => 'btn btn-primary', ]); $submitElement->setLabel('Salvar'); $form->add($submitElement, [ 'priority' => -100, ]); $cancelarElement = new \Zend\Form\Element\Button('cancelar'); $cancelarElement->setAttributes([ 'type' => 'button', 'class' => 'btn btn-default', 'onclick' => 'top.location=\''.$this->url() ->fromRoute($this->getActionRoute('list')).'\'', ]); $cancelarElement->setLabel('Cancelar'); $form->add($cancelarElement, [ 'priority' => -100, ]); return $form; }
php
public function getForm($entityClass = null) { if (null === $entityClass) { $entityClass = $this->getEntityClass(); } $builder = new AnnotationBuilder(); $form = $builder->createForm($entityClass); $hasEntity = false; foreach ($form->getElements() as $element) { if (method_exists($element, 'setObjectManager')) { $element->setObjectManager($this->getEntityManager()); $hasEntity = true; } elseif (method_exists($element, 'getProxy')) { $proxy = $element->getProxy(); if (method_exists($proxy, 'setObjectManager')) { $proxy->setObjectManager($this->getEntityManager()); $hasEntity = true; } } } if ($hasEntity) { $hydrator = new DoctrineHydrator($this->getEntityManager(), $entityClass); $form->setHydrator($hydrator); } else { $form->setHydrator(new ClassMethods()); } $form->add([ 'type' => 'Zend\Form\Element\Csrf', 'name' => 'csrf', 'attributes' => [ 'id' => 'csrf', ], ]); $submitElement = new \Zend\Form\Element\Button('submit'); $submitElement->setAttributes([ 'type' => 'submit', 'class' => 'btn btn-primary', ]); $submitElement->setLabel('Salvar'); $form->add($submitElement, [ 'priority' => -100, ]); $cancelarElement = new \Zend\Form\Element\Button('cancelar'); $cancelarElement->setAttributes([ 'type' => 'button', 'class' => 'btn btn-default', 'onclick' => 'top.location=\''.$this->url() ->fromRoute($this->getActionRoute('list')).'\'', ]); $cancelarElement->setLabel('Cancelar'); $form->add($cancelarElement, [ 'priority' => -100, ]); return $form; }
[ "public", "function", "getForm", "(", "$", "entityClass", "=", "null", ")", "{", "if", "(", "null", "===", "$", "entityClass", ")", "{", "$", "entityClass", "=", "$", "this", "->", "getEntityClass", "(", ")", ";", "}", "$", "builder", "=", "new", "AnnotationBuilder", "(", ")", ";", "$", "form", "=", "$", "builder", "->", "createForm", "(", "$", "entityClass", ")", ";", "$", "hasEntity", "=", "false", ";", "foreach", "(", "$", "form", "->", "getElements", "(", ")", "as", "$", "element", ")", "{", "if", "(", "method_exists", "(", "$", "element", ",", "'setObjectManager'", ")", ")", "{", "$", "element", "->", "setObjectManager", "(", "$", "this", "->", "getEntityManager", "(", ")", ")", ";", "$", "hasEntity", "=", "true", ";", "}", "elseif", "(", "method_exists", "(", "$", "element", ",", "'getProxy'", ")", ")", "{", "$", "proxy", "=", "$", "element", "->", "getProxy", "(", ")", ";", "if", "(", "method_exists", "(", "$", "proxy", ",", "'setObjectManager'", ")", ")", "{", "$", "proxy", "->", "setObjectManager", "(", "$", "this", "->", "getEntityManager", "(", ")", ")", ";", "$", "hasEntity", "=", "true", ";", "}", "}", "}", "if", "(", "$", "hasEntity", ")", "{", "$", "hydrator", "=", "new", "DoctrineHydrator", "(", "$", "this", "->", "getEntityManager", "(", ")", ",", "$", "entityClass", ")", ";", "$", "form", "->", "setHydrator", "(", "$", "hydrator", ")", ";", "}", "else", "{", "$", "form", "->", "setHydrator", "(", "new", "ClassMethods", "(", ")", ")", ";", "}", "$", "form", "->", "add", "(", "[", "'type'", "=>", "'Zend\\Form\\Element\\Csrf'", ",", "'name'", "=>", "'csrf'", ",", "'attributes'", "=>", "[", "'id'", "=>", "'csrf'", ",", "]", ",", "]", ")", ";", "$", "submitElement", "=", "new", "\\", "Zend", "\\", "Form", "\\", "Element", "\\", "Button", "(", "'submit'", ")", ";", "$", "submitElement", "->", "setAttributes", "(", "[", "'type'", "=>", "'submit'", ",", "'class'", "=>", "'btn btn-primary'", ",", "]", ")", ";", "$", "submitElement", "->", "setLabel", "(", "'Salvar'", ")", ";", "$", "form", "->", "add", "(", "$", "submitElement", ",", "[", "'priority'", "=>", "-", "100", ",", "]", ")", ";", "$", "cancelarElement", "=", "new", "\\", "Zend", "\\", "Form", "\\", "Element", "\\", "Button", "(", "'cancelar'", ")", ";", "$", "cancelarElement", "->", "setAttributes", "(", "[", "'type'", "=>", "'button'", ",", "'class'", "=>", "'btn btn-default'", ",", "'onclick'", "=>", "'top.location=\\''", ".", "$", "this", "->", "url", "(", ")", "->", "fromRoute", "(", "$", "this", "->", "getActionRoute", "(", "'list'", ")", ")", ".", "'\\''", ",", "]", ")", ";", "$", "cancelarElement", "->", "setLabel", "(", "'Cancelar'", ")", ";", "$", "form", "->", "add", "(", "$", "cancelarElement", ",", "[", "'priority'", "=>", "-", "100", ",", "]", ")", ";", "return", "$", "form", ";", "}" ]
Retorna a form para o cadastro da entidade.
[ "Retorna", "a", "form", "para", "o", "cadastro", "da", "entidade", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Controller/ORM/AbstractCrudController.php#L136-L197
Lansoweb/LosBase
src/LosBase/Controller/ORM/AbstractCrudController.php
AbstractCrudController.listAction
public function listAction() { $page = $this->getRequest()->getQuery('page', 0); $limit = $this->getRequest()->getQuery('limit', $this->defaultPageSize); $sort = $this->getRequest()->getQuery('sort', $this->defaultSort); $order = $this->getRequest()->getQuery('order', $this->defaultOrder); if (empty($sort)) { $sort = $this->defaultSort; } $offset = $limit * $page - $limit; if ($offset < 0) { $offset = 0; } /* @var $qb \Doctrine\ORM\QueryBuilder */ $qb = $this->getEntityManager()->createQueryBuilder(); $qb->add('select', 'e') ->add('from', $this->getEntityClass().' e') ->orderBy('e.'.$sort, $order) ->setFirstResult($offset) ->setMaxResults($limit); $this->handleSearch($qb); $paginator = new Paginator(new DoctrinePaginator(new LosPaginator($qb, false))); $paginator->setDefaultItemCountPerPage($limit); $paginator->setCurrentPageNumber($page); $paginator->setPageRange($this->paginatorRange); return [ 'paginator' => $paginator, 'sort' => $sort, 'order' => $order, 'page' => $page, 'query' => $this->params()->fromQuery(), ]; }
php
public function listAction() { $page = $this->getRequest()->getQuery('page', 0); $limit = $this->getRequest()->getQuery('limit', $this->defaultPageSize); $sort = $this->getRequest()->getQuery('sort', $this->defaultSort); $order = $this->getRequest()->getQuery('order', $this->defaultOrder); if (empty($sort)) { $sort = $this->defaultSort; } $offset = $limit * $page - $limit; if ($offset < 0) { $offset = 0; } /* @var $qb \Doctrine\ORM\QueryBuilder */ $qb = $this->getEntityManager()->createQueryBuilder(); $qb->add('select', 'e') ->add('from', $this->getEntityClass().' e') ->orderBy('e.'.$sort, $order) ->setFirstResult($offset) ->setMaxResults($limit); $this->handleSearch($qb); $paginator = new Paginator(new DoctrinePaginator(new LosPaginator($qb, false))); $paginator->setDefaultItemCountPerPage($limit); $paginator->setCurrentPageNumber($page); $paginator->setPageRange($this->paginatorRange); return [ 'paginator' => $paginator, 'sort' => $sort, 'order' => $order, 'page' => $page, 'query' => $this->params()->fromQuery(), ]; }
[ "public", "function", "listAction", "(", ")", "{", "$", "page", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getQuery", "(", "'page'", ",", "0", ")", ";", "$", "limit", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getQuery", "(", "'limit'", ",", "$", "this", "->", "defaultPageSize", ")", ";", "$", "sort", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getQuery", "(", "'sort'", ",", "$", "this", "->", "defaultSort", ")", ";", "$", "order", "=", "$", "this", "->", "getRequest", "(", ")", "->", "getQuery", "(", "'order'", ",", "$", "this", "->", "defaultOrder", ")", ";", "if", "(", "empty", "(", "$", "sort", ")", ")", "{", "$", "sort", "=", "$", "this", "->", "defaultSort", ";", "}", "$", "offset", "=", "$", "limit", "*", "$", "page", "-", "$", "limit", ";", "if", "(", "$", "offset", "<", "0", ")", "{", "$", "offset", "=", "0", ";", "}", "/* @var $qb \\Doctrine\\ORM\\QueryBuilder */", "$", "qb", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "$", "qb", "->", "add", "(", "'select'", ",", "'e'", ")", "->", "add", "(", "'from'", ",", "$", "this", "->", "getEntityClass", "(", ")", ".", "' e'", ")", "->", "orderBy", "(", "'e.'", ".", "$", "sort", ",", "$", "order", ")", "->", "setFirstResult", "(", "$", "offset", ")", "->", "setMaxResults", "(", "$", "limit", ")", ";", "$", "this", "->", "handleSearch", "(", "$", "qb", ")", ";", "$", "paginator", "=", "new", "Paginator", "(", "new", "DoctrinePaginator", "(", "new", "LosPaginator", "(", "$", "qb", ",", "false", ")", ")", ")", ";", "$", "paginator", "->", "setDefaultItemCountPerPage", "(", "$", "limit", ")", ";", "$", "paginator", "->", "setCurrentPageNumber", "(", "$", "page", ")", ";", "$", "paginator", "->", "setPageRange", "(", "$", "this", "->", "paginatorRange", ")", ";", "return", "[", "'paginator'", "=>", "$", "paginator", ",", "'sort'", "=>", "$", "sort", ",", "'order'", "=>", "$", "order", ",", "'page'", "=>", "$", "page", ",", "'query'", "=>", "$", "this", "->", "params", "(", ")", "->", "fromQuery", "(", ")", ",", "]", ";", "}" ]
Lista as entidades, suporte a paginação, ordenação e busca.
[ "Lista", "as", "entidades", "suporte", "a", "paginação", "ordenação", "e", "busca", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Controller/ORM/AbstractCrudController.php#L206-L244
aedart/laravel-helpers
src/Traits/Filesystem/FileTrait.php
FileTrait.getFile
public function getFile(): ?Filesystem { if (!$this->hasFile()) { $this->setFile($this->getDefaultFile()); } return $this->file; }
php
public function getFile(): ?Filesystem { if (!$this->hasFile()) { $this->setFile($this->getDefaultFile()); } return $this->file; }
[ "public", "function", "getFile", "(", ")", ":", "?", "Filesystem", "{", "if", "(", "!", "$", "this", "->", "hasFile", "(", ")", ")", "{", "$", "this", "->", "setFile", "(", "$", "this", "->", "getDefaultFile", "(", ")", ")", ";", "}", "return", "$", "this", "->", "file", ";", "}" ]
Get file If no file has been set, this method will set and return a default file, if any such value is available @see getDefaultFile() @return Filesystem|null file or null if none file has been set
[ "Get", "file" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Filesystem/FileTrait.php#L53-L59
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Datatable/Data/DatatableDataManager.php
DatatableDataManager.getQueryFrom
public function getQueryFrom(DatatableViewInterface $datatableView) { $twig = $datatableView->getTwig(); $type = $datatableView->getAjax()->getType(); $parameterBag = null; if ('GET' === strtoupper($type)) { $parameterBag = $this->request->query; } if ('POST' === strtoupper($type)) { $parameterBag = $this->request->request; } $params = $parameterBag->all(); $query = new DatatableQuery( $this->serializer, $params, $datatableView, $this->configs, $twig, $this->imagineBundle, $this->doctrineExtensions, $this->locale ); return $query; }
php
public function getQueryFrom(DatatableViewInterface $datatableView) { $twig = $datatableView->getTwig(); $type = $datatableView->getAjax()->getType(); $parameterBag = null; if ('GET' === strtoupper($type)) { $parameterBag = $this->request->query; } if ('POST' === strtoupper($type)) { $parameterBag = $this->request->request; } $params = $parameterBag->all(); $query = new DatatableQuery( $this->serializer, $params, $datatableView, $this->configs, $twig, $this->imagineBundle, $this->doctrineExtensions, $this->locale ); return $query; }
[ "public", "function", "getQueryFrom", "(", "DatatableViewInterface", "$", "datatableView", ")", "{", "$", "twig", "=", "$", "datatableView", "->", "getTwig", "(", ")", ";", "$", "type", "=", "$", "datatableView", "->", "getAjax", "(", ")", "->", "getType", "(", ")", ";", "$", "parameterBag", "=", "null", ";", "if", "(", "'GET'", "===", "strtoupper", "(", "$", "type", ")", ")", "{", "$", "parameterBag", "=", "$", "this", "->", "request", "->", "query", ";", "}", "if", "(", "'POST'", "===", "strtoupper", "(", "$", "type", ")", ")", "{", "$", "parameterBag", "=", "$", "this", "->", "request", "->", "request", ";", "}", "$", "params", "=", "$", "parameterBag", "->", "all", "(", ")", ";", "$", "query", "=", "new", "DatatableQuery", "(", "$", "this", "->", "serializer", ",", "$", "params", ",", "$", "datatableView", ",", "$", "this", "->", "configs", ",", "$", "twig", ",", "$", "this", "->", "imagineBundle", ",", "$", "this", "->", "doctrineExtensions", ",", "$", "this", "->", "locale", ")", ";", "return", "$", "query", ";", "}" ]
Get query. @param DatatableViewInterface $datatableView @return DatatableQuery
[ "Get", "query", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Datatable/Data/DatatableDataManager.php#L109-L137
webforge-labs/psc-cms
lib/Psc/Doctrine/Hydrator.php
Hydrator.byIdentifierList
public function byIdentifierList($list, $sep = ',', $idname = 'id', $checkCardinality = TRUE, &$parsed = NULL, &$found = NULL) { if ($list == NULL) { return array(); } if (is_array($list)) { $identifiers = $list; } else { $identifiers = explode($sep, trim($list)); } $identifiers = array_map('trim',$identifiers); $identifiers = array_filter($identifiers, function ($identifier) { return !empty($identifier); // schließt auch 0 aus }); $parsed = count($identifiers); if (count($identifiers) == 0) return array(); $result = $this->getRepository()->findAllByIds($identifiers, $idname); $found = count($result); if ($checkCardinality && ($parsed != $found)) { throw new \Psc\Exception('Es konnten nicht alle identifier aus der Liste hydriert werden! Gefunden aus '.$list.': '.Code::varInfo($identifiers).' in der DB gefunden #'.count($result)); } return $result; }
php
public function byIdentifierList($list, $sep = ',', $idname = 'id', $checkCardinality = TRUE, &$parsed = NULL, &$found = NULL) { if ($list == NULL) { return array(); } if (is_array($list)) { $identifiers = $list; } else { $identifiers = explode($sep, trim($list)); } $identifiers = array_map('trim',$identifiers); $identifiers = array_filter($identifiers, function ($identifier) { return !empty($identifier); // schließt auch 0 aus }); $parsed = count($identifiers); if (count($identifiers) == 0) return array(); $result = $this->getRepository()->findAllByIds($identifiers, $idname); $found = count($result); if ($checkCardinality && ($parsed != $found)) { throw new \Psc\Exception('Es konnten nicht alle identifier aus der Liste hydriert werden! Gefunden aus '.$list.': '.Code::varInfo($identifiers).' in der DB gefunden #'.count($result)); } return $result; }
[ "public", "function", "byIdentifierList", "(", "$", "list", ",", "$", "sep", "=", "','", ",", "$", "idname", "=", "'id'", ",", "$", "checkCardinality", "=", "TRUE", ",", "&", "$", "parsed", "=", "NULL", ",", "&", "$", "found", "=", "NULL", ")", "{", "if", "(", "$", "list", "==", "NULL", ")", "{", "return", "array", "(", ")", ";", "}", "if", "(", "is_array", "(", "$", "list", ")", ")", "{", "$", "identifiers", "=", "$", "list", ";", "}", "else", "{", "$", "identifiers", "=", "explode", "(", "$", "sep", ",", "trim", "(", "$", "list", ")", ")", ";", "}", "$", "identifiers", "=", "array_map", "(", "'trim'", ",", "$", "identifiers", ")", ";", "$", "identifiers", "=", "array_filter", "(", "$", "identifiers", ",", "function", "(", "$", "identifier", ")", "{", "return", "!", "empty", "(", "$", "identifier", ")", ";", "// schließt auch 0 aus", "}", ")", ";", "$", "parsed", "=", "count", "(", "$", "identifiers", ")", ";", "if", "(", "count", "(", "$", "identifiers", ")", "==", "0", ")", "return", "array", "(", ")", ";", "$", "result", "=", "$", "this", "->", "getRepository", "(", ")", "->", "findAllByIds", "(", "$", "identifiers", ",", "$", "idname", ")", ";", "$", "found", "=", "count", "(", "$", "result", ")", ";", "if", "(", "$", "checkCardinality", "&&", "(", "$", "parsed", "!=", "$", "found", ")", ")", "{", "throw", "new", "\\", "Psc", "\\", "Exception", "(", "'Es konnten nicht alle identifier aus der Liste hydriert werden! Gefunden aus '", ".", "$", "list", ".", "': '", ".", "Code", "::", "varInfo", "(", "$", "identifiers", ")", ".", "' in der DB gefunden #'", ".", "count", "(", "$", "result", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Hydratet einen String von Identifiern getrennt mit $sep @param string $idname wird im dql verwendet (also klein)
[ "Hydratet", "einen", "String", "von", "Identifiern", "getrennt", "mit", "$sep" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/Hydrator.php#L32-L58
periaptio/empress-generator
src/Generators/FactoryGenerator.php
FactoryGenerator.getTemplateData
public function getTemplateData($data = []) { // generate fields $fillableColumns = $this->schemaParser->getFillableFields($data['TABLE_NAME']); logger($fillableColumns); $faker = Factory::create(); $fieldStr = []; foreach ($fillableColumns as $column) { try { if ($column['field'] === 'password') { $func = 'bcrypt(str_random(10))'; } else { $faker->getFormatter($column['field']); $func = '$faker->'.$column['field']; } } catch (\Exception $e) { logger($column['type']); switch ($column['type']) { case 'tinyInteger': $func = '$faker->randomNumber(2)'; break; case 'smallInteger': $func = '$faker->randomNumber(2)'; break; case 'mediumInteger': $func = '$faker->randomNumber(4)'; break; case 'integer': $func = '$faker->randomNumber(8)'; break; case 'char': case 'string': logger($column['field']); if (isset($column['args']) && !empty($column['args'])) { $max = $column['args']; } else { $max = 100; } $func = "str_random($max)"; break; case 'text': case 'boolean': $func = '$faker->'.$column['type'].'()'; break; case 'date': $func = '$faker->'.'dateTimeBetween()'; break; default: $func = ''; } } if (!empty($func)) { $fieldStr[] = "'".$column['field']."' => ".$func; } } $data['FIELDS'] = implode(",\n\t\t", $fieldStr); return $data; }
php
public function getTemplateData($data = []) { // generate fields $fillableColumns = $this->schemaParser->getFillableFields($data['TABLE_NAME']); logger($fillableColumns); $faker = Factory::create(); $fieldStr = []; foreach ($fillableColumns as $column) { try { if ($column['field'] === 'password') { $func = 'bcrypt(str_random(10))'; } else { $faker->getFormatter($column['field']); $func = '$faker->'.$column['field']; } } catch (\Exception $e) { logger($column['type']); switch ($column['type']) { case 'tinyInteger': $func = '$faker->randomNumber(2)'; break; case 'smallInteger': $func = '$faker->randomNumber(2)'; break; case 'mediumInteger': $func = '$faker->randomNumber(4)'; break; case 'integer': $func = '$faker->randomNumber(8)'; break; case 'char': case 'string': logger($column['field']); if (isset($column['args']) && !empty($column['args'])) { $max = $column['args']; } else { $max = 100; } $func = "str_random($max)"; break; case 'text': case 'boolean': $func = '$faker->'.$column['type'].'()'; break; case 'date': $func = '$faker->'.'dateTimeBetween()'; break; default: $func = ''; } } if (!empty($func)) { $fieldStr[] = "'".$column['field']."' => ".$func; } } $data['FIELDS'] = implode(",\n\t\t", $fieldStr); return $data; }
[ "public", "function", "getTemplateData", "(", "$", "data", "=", "[", "]", ")", "{", "// generate fields", "$", "fillableColumns", "=", "$", "this", "->", "schemaParser", "->", "getFillableFields", "(", "$", "data", "[", "'TABLE_NAME'", "]", ")", ";", "logger", "(", "$", "fillableColumns", ")", ";", "$", "faker", "=", "Factory", "::", "create", "(", ")", ";", "$", "fieldStr", "=", "[", "]", ";", "foreach", "(", "$", "fillableColumns", "as", "$", "column", ")", "{", "try", "{", "if", "(", "$", "column", "[", "'field'", "]", "===", "'password'", ")", "{", "$", "func", "=", "'bcrypt(str_random(10))'", ";", "}", "else", "{", "$", "faker", "->", "getFormatter", "(", "$", "column", "[", "'field'", "]", ")", ";", "$", "func", "=", "'$faker->'", ".", "$", "column", "[", "'field'", "]", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "logger", "(", "$", "column", "[", "'type'", "]", ")", ";", "switch", "(", "$", "column", "[", "'type'", "]", ")", "{", "case", "'tinyInteger'", ":", "$", "func", "=", "'$faker->randomNumber(2)'", ";", "break", ";", "case", "'smallInteger'", ":", "$", "func", "=", "'$faker->randomNumber(2)'", ";", "break", ";", "case", "'mediumInteger'", ":", "$", "func", "=", "'$faker->randomNumber(4)'", ";", "break", ";", "case", "'integer'", ":", "$", "func", "=", "'$faker->randomNumber(8)'", ";", "break", ";", "case", "'char'", ":", "case", "'string'", ":", "logger", "(", "$", "column", "[", "'field'", "]", ")", ";", "if", "(", "isset", "(", "$", "column", "[", "'args'", "]", ")", "&&", "!", "empty", "(", "$", "column", "[", "'args'", "]", ")", ")", "{", "$", "max", "=", "$", "column", "[", "'args'", "]", ";", "}", "else", "{", "$", "max", "=", "100", ";", "}", "$", "func", "=", "\"str_random($max)\"", ";", "break", ";", "case", "'text'", ":", "case", "'boolean'", ":", "$", "func", "=", "'$faker->'", ".", "$", "column", "[", "'type'", "]", ".", "'()'", ";", "break", ";", "case", "'date'", ":", "$", "func", "=", "'$faker->'", ".", "'dateTimeBetween()'", ";", "break", ";", "default", ":", "$", "func", "=", "''", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "func", ")", ")", "{", "$", "fieldStr", "[", "]", "=", "\"'\"", ".", "$", "column", "[", "'field'", "]", ".", "\"' => \"", ".", "$", "func", ";", "}", "}", "$", "data", "[", "'FIELDS'", "]", "=", "implode", "(", "\",\\n\\t\\t\"", ",", "$", "fieldStr", ")", ";", "return", "$", "data", ";", "}" ]
Fetch the template data @return array
[ "Fetch", "the", "template", "data" ]
train
https://github.com/periaptio/empress-generator/blob/749fb4b12755819e9c97377ebfb446ee0822168a/src/Generators/FactoryGenerator.php#L59-L122
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php
BaseUserCustomerRelationQuery.create
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof UserCustomerRelationQuery) { return $criteria; } $query = new UserCustomerRelationQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
php
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof UserCustomerRelationQuery) { return $criteria; } $query = new UserCustomerRelationQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
[ "public", "static", "function", "create", "(", "$", "modelAlias", "=", "null", ",", "$", "criteria", "=", "null", ")", "{", "if", "(", "$", "criteria", "instanceof", "UserCustomerRelationQuery", ")", "{", "return", "$", "criteria", ";", "}", "$", "query", "=", "new", "UserCustomerRelationQuery", "(", "null", ",", "null", ",", "$", "modelAlias", ")", ";", "if", "(", "$", "criteria", "instanceof", "Criteria", ")", "{", "$", "query", "->", "mergeWith", "(", "$", "criteria", ")", ";", "}", "return", "$", "query", ";", "}" ]
Returns a new UserCustomerRelationQuery object. @param string $modelAlias The alias of a model in the query @param UserCustomerRelationQuery|Criteria $criteria Optional Criteria to build the query from @return UserCustomerRelationQuery
[ "Returns", "a", "new", "UserCustomerRelationQuery", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php#L80-L92
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php
BaseUserCustomerRelationQuery.filterByUserId
public function filterByUserId($userId = null, $comparison = null) { if (is_array($userId)) { $useMinMax = false; if (isset($userId['min'])) { $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($userId['max'])) { $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId, $comparison); }
php
public function filterByUserId($userId = null, $comparison = null) { if (is_array($userId)) { $useMinMax = false; if (isset($userId['min'])) { $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($userId['max'])) { $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId, $comparison); }
[ "public", "function", "filterByUserId", "(", "$", "userId", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "userId", ")", ")", "{", "$", "useMinMax", "=", "false", ";", "if", "(", "isset", "(", "$", "userId", "[", "'min'", "]", ")", ")", "{", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "USER_ID", ",", "$", "userId", "[", "'min'", "]", ",", "Criteria", "::", "GREATER_EQUAL", ")", ";", "$", "useMinMax", "=", "true", ";", "}", "if", "(", "isset", "(", "$", "userId", "[", "'max'", "]", ")", ")", "{", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "USER_ID", ",", "$", "userId", "[", "'max'", "]", ",", "Criteria", "::", "LESS_EQUAL", ")", ";", "$", "useMinMax", "=", "true", ";", "}", "if", "(", "$", "useMinMax", ")", "{", "return", "$", "this", ";", "}", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "USER_ID", ",", "$", "userId", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the user_id column Example usage: <code> $query->filterByUserId(1234); // WHERE user_id = 1234 $query->filterByUserId(array(12, 34)); // WHERE user_id IN (12, 34) $query->filterByUserId(array('min' => 12)); // WHERE user_id >= 12 $query->filterByUserId(array('max' => 12)); // WHERE user_id <= 12 </code> @see filterByUser() @param mixed $userId The value to use as filter. Use scalar values for equality. Use array values for in_array() equivalent. Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return UserCustomerRelationQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "user_id", "column" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php#L308-L329
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php
BaseUserCustomerRelationQuery.filterByUser
public function filterByUser($user, $comparison = null) { if ($user instanceof User) { return $this ->addUsingAlias(UserCustomerRelationPeer::USER_ID, $user->getId(), $comparison); } elseif ($user instanceof PropelObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(UserCustomerRelationPeer::USER_ID, $user->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByUser() only accepts arguments of type User or PropelCollection'); } }
php
public function filterByUser($user, $comparison = null) { if ($user instanceof User) { return $this ->addUsingAlias(UserCustomerRelationPeer::USER_ID, $user->getId(), $comparison); } elseif ($user instanceof PropelObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(UserCustomerRelationPeer::USER_ID, $user->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByUser() only accepts arguments of type User or PropelCollection'); } }
[ "public", "function", "filterByUser", "(", "$", "user", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "user", "instanceof", "User", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "USER_ID", ",", "$", "user", "->", "getId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "user", "instanceof", "PropelObjectCollection", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "return", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "USER_ID", ",", "$", "user", "->", "toKeyValue", "(", "'PrimaryKey'", ",", "'Id'", ")", ",", "$", "comparison", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByUser() only accepts arguments of type User or PropelCollection'", ")", ";", "}", "}" ]
Filter the query by a related User object @param User|PropelObjectCollection $user The related object(s) to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return UserCustomerRelationQuery The current query, for fluid interface @throws PropelException - if the provided filter is invalid.
[ "Filter", "the", "query", "by", "a", "related", "User", "object" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php#L384-L399
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php
BaseUserCustomerRelationQuery.filterByCustomer
public function filterByCustomer($customer, $comparison = null) { if ($customer instanceof Customer) { return $this ->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customer->getId(), $comparison); } elseif ($customer instanceof PropelObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByCustomer() only accepts arguments of type Customer or PropelCollection'); } }
php
public function filterByCustomer($customer, $comparison = null) { if ($customer instanceof Customer) { return $this ->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customer->getId(), $comparison); } elseif ($customer instanceof PropelObjectCollection) { if (null === $comparison) { $comparison = Criteria::IN; } return $this ->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison); } else { throw new PropelException('filterByCustomer() only accepts arguments of type Customer or PropelCollection'); } }
[ "public", "function", "filterByCustomer", "(", "$", "customer", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "customer", "instanceof", "Customer", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "CUSTOMER_ID", ",", "$", "customer", "->", "getId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "customer", "instanceof", "PropelObjectCollection", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "return", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "CUSTOMER_ID", ",", "$", "customer", "->", "toKeyValue", "(", "'PrimaryKey'", ",", "'Id'", ")", ",", "$", "comparison", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByCustomer() only accepts arguments of type Customer or PropelCollection'", ")", ";", "}", "}" ]
Filter the query by a related Customer object @param Customer|PropelObjectCollection $customer The related object(s) to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return UserCustomerRelationQuery The current query, for fluid interface @throws PropelException - if the provided filter is invalid.
[ "Filter", "the", "query", "by", "a", "related", "Customer", "object" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php#L460-L475
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php
BaseUserCustomerRelationQuery.prune
public function prune($userCustomerRelation = null) { if ($userCustomerRelation) { $this->addUsingAlias(UserCustomerRelationPeer::ID, $userCustomerRelation->getId(), Criteria::NOT_EQUAL); } return $this; }
php
public function prune($userCustomerRelation = null) { if ($userCustomerRelation) { $this->addUsingAlias(UserCustomerRelationPeer::ID, $userCustomerRelation->getId(), Criteria::NOT_EQUAL); } return $this; }
[ "public", "function", "prune", "(", "$", "userCustomerRelation", "=", "null", ")", "{", "if", "(", "$", "userCustomerRelation", ")", "{", "$", "this", "->", "addUsingAlias", "(", "UserCustomerRelationPeer", "::", "ID", ",", "$", "userCustomerRelation", "->", "getId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "}", "return", "$", "this", ";", "}" ]
Exclude object from result @param UserCustomerRelation $userCustomerRelation Object to remove from the list of results @return UserCustomerRelationQuery The current query, for fluid interface
[ "Exclude", "object", "from", "result" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseUserCustomerRelationQuery.php#L534-L541
ClanCats/Core
src/bundles/UI/Alert.php
Alert.prepare
private static function prepare( $type, $message ) { // to avoid typos and other mistakes we // validate the alert type $type = strtolower( $type ); if ( !in_array( $type, static::$_types ) ) { throw new Exception( "UI\Alert - Unknown alert type '{$type}'!" ); } // We always need to return an array if ( !is_array( $message ) ) { return array( $message ); } return $message; }
php
private static function prepare( $type, $message ) { // to avoid typos and other mistakes we // validate the alert type $type = strtolower( $type ); if ( !in_array( $type, static::$_types ) ) { throw new Exception( "UI\Alert - Unknown alert type '{$type}'!" ); } // We always need to return an array if ( !is_array( $message ) ) { return array( $message ); } return $message; }
[ "private", "static", "function", "prepare", "(", "$", "type", ",", "$", "message", ")", "{", "// to avoid typos and other mistakes we ", "// validate the alert type", "$", "type", "=", "strtolower", "(", "$", "type", ")", ";", "if", "(", "!", "in_array", "(", "$", "type", ",", "static", "::", "$", "_types", ")", ")", "{", "throw", "new", "Exception", "(", "\"UI\\Alert - Unknown alert type '{$type}'!\"", ")", ";", "}", "// We always need to return an array", "if", "(", "!", "is_array", "(", "$", "message", ")", ")", "{", "return", "array", "(", "$", "message", ")", ";", "}", "return", "$", "message", ";", "}" ]
Validate the alert type and format the message @param string $type @param string|array $message @return array
[ "Validate", "the", "alert", "type", "and", "format", "the", "message" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/bundles/UI/Alert.php#L53-L69
aedart/laravel-helpers
src/Traits/Filesystem/CloudStorageTrait.php
CloudStorageTrait.getCloudStorage
public function getCloudStorage(): ?Cloud { if (!$this->hasCloudStorage()) { $this->setCloudStorage($this->getDefaultCloudStorage()); } return $this->cloudStorage; }
php
public function getCloudStorage(): ?Cloud { if (!$this->hasCloudStorage()) { $this->setCloudStorage($this->getDefaultCloudStorage()); } return $this->cloudStorage; }
[ "public", "function", "getCloudStorage", "(", ")", ":", "?", "Cloud", "{", "if", "(", "!", "$", "this", "->", "hasCloudStorage", "(", ")", ")", "{", "$", "this", "->", "setCloudStorage", "(", "$", "this", "->", "getDefaultCloudStorage", "(", ")", ")", ";", "}", "return", "$", "this", "->", "cloudStorage", ";", "}" ]
Get cloud storage If no cloud storage has been set, this method will set and return a default cloud storage, if any such value is available @see getDefaultCloudStorage() @return Cloud|null cloud storage or null if none cloud storage has been set
[ "Get", "cloud", "storage" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Filesystem/CloudStorageTrait.php#L53-L59
aedart/laravel-helpers
src/Traits/Filesystem/CloudStorageTrait.php
CloudStorageTrait.getDefaultCloudStorage
public function getDefaultCloudStorage(): ?Cloud { // By default, the Storage Facade does not return the // any actual storage fisk, but rather an // instance of \Illuminate\Filesystem\FilesystemManager. // Therefore, we make sure only to obtain its // "disk", to make sure that its the correct // instance that we obtain. $manager = Storage::getFacadeRoot(); if (isset($manager)) { return $manager->disk(); } return $manager; }
php
public function getDefaultCloudStorage(): ?Cloud { // By default, the Storage Facade does not return the // any actual storage fisk, but rather an // instance of \Illuminate\Filesystem\FilesystemManager. // Therefore, we make sure only to obtain its // "disk", to make sure that its the correct // instance that we obtain. $manager = Storage::getFacadeRoot(); if (isset($manager)) { return $manager->disk(); } return $manager; }
[ "public", "function", "getDefaultCloudStorage", "(", ")", ":", "?", "Cloud", "{", "// By default, the Storage Facade does not return the", "// any actual storage fisk, but rather an", "// instance of \\Illuminate\\Filesystem\\FilesystemManager.", "// Therefore, we make sure only to obtain its", "// \"disk\", to make sure that its the correct", "// instance that we obtain.", "$", "manager", "=", "Storage", "::", "getFacadeRoot", "(", ")", ";", "if", "(", "isset", "(", "$", "manager", ")", ")", "{", "return", "$", "manager", "->", "disk", "(", ")", ";", "}", "return", "$", "manager", ";", "}" ]
Get a default cloud storage value, if any is available @return Cloud|null A default cloud storage value or Null if no default value is available
[ "Get", "a", "default", "cloud", "storage", "value", "if", "any", "is", "available" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Filesystem/CloudStorageTrait.php#L76-L89
drsdre/yii2-xmlsoccer
models/Match.php
Match.beforeSave
public function beforeSave($insert) { $this->date = strtotime($this->date); return parent::beforeSave($insert); }
php
public function beforeSave($insert) { $this->date = strtotime($this->date); return parent::beforeSave($insert); }
[ "public", "function", "beforeSave", "(", "$", "insert", ")", "{", "$", "this", "->", "date", "=", "strtotime", "(", "$", "this", "->", "date", ")", ";", "return", "parent", "::", "beforeSave", "(", "$", "insert", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drsdre/yii2-xmlsoccer/blob/a746edee6269ed0791bac6c6165a946adc30d994/models/Match.php#L92-L96
ruvents/ruwork-polyfill-form-dti-bundle
DependencyInjection/RuworkPolyfillFormDTIExtension.php
RuworkPolyfillFormDTIExtension.load
public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $public = !class_exists(FormPass::class); $container->findDefinition('ruwork_polyfill_form_dti.extension.date_time') ->setPublic($public); $container->findDefinition('ruwork_polyfill_form_dti.extension.date') ->setPublic($public); $container->findDefinition('ruwork_polyfill_form_dti.extension.time') ->setPublic($public); $container->findDefinition('ruwork_polyfill_form_dti.guesser.doctrine_orm') ->setPublic($public); }
php
public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $public = !class_exists(FormPass::class); $container->findDefinition('ruwork_polyfill_form_dti.extension.date_time') ->setPublic($public); $container->findDefinition('ruwork_polyfill_form_dti.extension.date') ->setPublic($public); $container->findDefinition('ruwork_polyfill_form_dti.extension.time') ->setPublic($public); $container->findDefinition('ruwork_polyfill_form_dti.guesser.doctrine_orm') ->setPublic($public); }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "loader", "=", "new", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "loader", "->", "load", "(", "'services.xml'", ")", ";", "$", "public", "=", "!", "class_exists", "(", "FormPass", "::", "class", ")", ";", "$", "container", "->", "findDefinition", "(", "'ruwork_polyfill_form_dti.extension.date_time'", ")", "->", "setPublic", "(", "$", "public", ")", ";", "$", "container", "->", "findDefinition", "(", "'ruwork_polyfill_form_dti.extension.date'", ")", "->", "setPublic", "(", "$", "public", ")", ";", "$", "container", "->", "findDefinition", "(", "'ruwork_polyfill_form_dti.extension.time'", ")", "->", "setPublic", "(", "$", "public", ")", ";", "$", "container", "->", "findDefinition", "(", "'ruwork_polyfill_form_dti.guesser.doctrine_orm'", ")", "->", "setPublic", "(", "$", "public", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/ruvents/ruwork-polyfill-form-dti-bundle/blob/3d5517d628a9982d17cb79b5991b88c6b79f5384/DependencyInjection/RuworkPolyfillFormDTIExtension.php#L16-L34
onigoetz/imagecache
src/Transfer.php
Transfer.stream
public function stream() { if (ob_get_level()) { ob_end_clean(); } // Transfer file in 1024 byte chunks to save memory usage. if ($fd = fopen($this->path, 'rb')) { while (!feof($fd)) { echo fread($fd, 1024); } fclose($fd); } }
php
public function stream() { if (ob_get_level()) { ob_end_clean(); } // Transfer file in 1024 byte chunks to save memory usage. if ($fd = fopen($this->path, 'rb')) { while (!feof($fd)) { echo fread($fd, 1024); } fclose($fd); } }
[ "public", "function", "stream", "(", ")", "{", "if", "(", "ob_get_level", "(", ")", ")", "{", "ob_end_clean", "(", ")", ";", "}", "// Transfer file in 1024 byte chunks to save memory usage.", "if", "(", "$", "fd", "=", "fopen", "(", "$", "this", "->", "path", ",", "'rb'", ")", ")", "{", "while", "(", "!", "feof", "(", "$", "fd", ")", ")", "{", "echo", "fread", "(", "$", "fd", ",", "1024", ")", ";", "}", "fclose", "(", "$", "fd", ")", ";", "}", "}" ]
Transfer an image to the browser
[ "Transfer", "an", "image", "to", "the", "browser" ]
train
https://github.com/onigoetz/imagecache/blob/8e22c11def1733819183e8296bab3c8a4ffc1d9c/src/Transfer.php#L67-L80
onigoetz/imagecache
src/Transfer.php
Transfer.getCachingHeaders
protected function getCachingHeaders($fileinfo) { // Set default values: $last_modified = gmdate('D, d M Y H:i:s', $fileinfo[9]) . ' GMT'; $etag = md5($last_modified); // See if the client has provided the required HTTP headers: $if_modified_since = $this->server_value('HTTP_IF_MODIFIED_SINCE', false); $if_none_match = $this->server_value('HTTP_IF_NONE_MATCH', false); if ($if_modified_since && $if_none_match && $if_none_match == $etag && $if_modified_since == $last_modified) { $this->status = 304; } // Send appropriate response: $this->headers['Last-Modified'] = $last_modified; $this->headers['ETag'] = $etag; }
php
protected function getCachingHeaders($fileinfo) { // Set default values: $last_modified = gmdate('D, d M Y H:i:s', $fileinfo[9]) . ' GMT'; $etag = md5($last_modified); // See if the client has provided the required HTTP headers: $if_modified_since = $this->server_value('HTTP_IF_MODIFIED_SINCE', false); $if_none_match = $this->server_value('HTTP_IF_NONE_MATCH', false); if ($if_modified_since && $if_none_match && $if_none_match == $etag && $if_modified_since == $last_modified) { $this->status = 304; } // Send appropriate response: $this->headers['Last-Modified'] = $last_modified; $this->headers['ETag'] = $etag; }
[ "protected", "function", "getCachingHeaders", "(", "$", "fileinfo", ")", "{", "// Set default values:", "$", "last_modified", "=", "gmdate", "(", "'D, d M Y H:i:s'", ",", "$", "fileinfo", "[", "9", "]", ")", ".", "' GMT'", ";", "$", "etag", "=", "md5", "(", "$", "last_modified", ")", ";", "// See if the client has provided the required HTTP headers:", "$", "if_modified_since", "=", "$", "this", "->", "server_value", "(", "'HTTP_IF_MODIFIED_SINCE'", ",", "false", ")", ";", "$", "if_none_match", "=", "$", "this", "->", "server_value", "(", "'HTTP_IF_NONE_MATCH'", ",", "false", ")", ";", "if", "(", "$", "if_modified_since", "&&", "$", "if_none_match", "&&", "$", "if_none_match", "==", "$", "etag", "&&", "$", "if_modified_since", "==", "$", "last_modified", ")", "{", "$", "this", "->", "status", "=", "304", ";", "}", "// Send appropriate response:", "$", "this", "->", "headers", "[", "'Last-Modified'", "]", "=", "$", "last_modified", ";", "$", "this", "->", "headers", "[", "'ETag'", "]", "=", "$", "etag", ";", "}" ]
Set file headers that handle "If-Modified-Since" correctly for the given fileinfo. @param array $fileinfo Array returned by stat().
[ "Set", "file", "headers", "that", "handle", "If", "-", "Modified", "-", "Since", "correctly", "for", "the", "given", "fileinfo", "." ]
train
https://github.com/onigoetz/imagecache/blob/8e22c11def1733819183e8296bab3c8a4ffc1d9c/src/Transfer.php#L88-L105
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addCode
public function addCode($tableName, $columnName = 'code') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->string(32)->comment('Code for this item, used identifying when needed. Another criteria to replace ID because ID is auto-increment')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addCode($tableName, $columnName = 'code') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->string(32)->comment('Code for this item, used identifying when needed. Another criteria to replace ID because ID is auto-increment')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addCode", "(", "$", "tableName", ",", "$", "columnName", "=", "'code'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "string", "(", "32", ")", "->", "comment", "(", "'Code for this item, used identifying when needed. Another criteria to replace ID because ID is auto-increment'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put index to `code` column Use if identity an item alternatively to ID @param $tableName
[ "Add", "and", "put", "index", "to", "code", "column", "Use", "if", "identity", "an", "item", "alternatively", "to", "ID" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L36-L41
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addCreatedDate
public function addCreatedDate($tableName, $columnName = 'created_date_gmt') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->dateTime()->comment('Date and time this record created (in GMT)')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addCreatedDate($tableName, $columnName = 'created_date_gmt') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->dateTime()->comment('Date and time this record created (in GMT)')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addCreatedDate", "(", "$", "tableName", ",", "$", "columnName", "=", "'created_date_gmt'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "dateTime", "(", ")", "->", "comment", "(", "'Date and time this record created (in GMT)'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put Index to created_at column Store the datetime the record has been created (should be stored in GMT 0) @param $tableName @param string $columnName Name of the column
[ "Add", "and", "put", "Index", "to", "created_at", "column", "Store", "the", "datetime", "the", "record", "has", "been", "created", "(", "should", "be", "stored", "in", "GMT", "0", ")" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L49-L54
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addUpdatedDate
public function addUpdatedDate($tableName, $columnName = 'updated_date_gmt') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->dateTime()->comment('Date and time this record updated (in GMT)')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addUpdatedDate($tableName, $columnName = 'updated_date_gmt') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->dateTime()->comment('Date and time this record updated (in GMT)')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addUpdatedDate", "(", "$", "tableName", ",", "$", "columnName", "=", "'updated_date_gmt'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "dateTime", "(", ")", "->", "comment", "(", "'Date and time this record updated (in GMT)'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put Index to updated_at column Store the datetime the record has been updated (should be stored in GMT 0) @param $tableName @param string $columnName Name of the column
[ "Add", "and", "put", "Index", "to", "updated_at", "column", "Store", "the", "datetime", "the", "record", "has", "been", "updated", "(", "should", "be", "stored", "in", "GMT", "0", ")" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L62-L67
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addPublishedDate
public function addPublishedDate($tableName, $columnName = 'published_at_gmt') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->dateTime()->comment('Date and time this record published (in GMT)')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addPublishedDate($tableName, $columnName = 'published_at_gmt') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->dateTime()->comment('Date and time this record published (in GMT)')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addPublishedDate", "(", "$", "tableName", ",", "$", "columnName", "=", "'published_at_gmt'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "dateTime", "(", ")", "->", "comment", "(", "'Date and time this record published (in GMT)'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put Index to published_at column Store the datetime the record has been published to public (should be stored in GMT 0, may be a scheduled time in the future) @param $tableName
[ "Add", "and", "put", "Index", "to", "published_at", "column", "Store", "the", "datetime", "the", "record", "has", "been", "published", "to", "public", "(", "should", "be", "stored", "in", "GMT", "0", "may", "be", "a", "scheduled", "time", "in", "the", "future", ")" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L75-L81
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addCreatorID
public function addCreatorID($tableName, $columnName = 'creator_id') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->bigInteger()->comment('ID of user who created this item')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addCreatorID($tableName, $columnName = 'creator_id') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->bigInteger()->comment('ID of user who created this item')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addCreatorID", "(", "$", "tableName", ",", "$", "columnName", "=", "'creator_id'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "bigInteger", "(", ")", "->", "comment", "(", "'ID of user who created this item'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put Index to creator_id column Store id of user who create this record @param $tableName
[ "Add", "and", "put", "Index", "to", "creator_id", "column", "Store", "id", "of", "user", "who", "create", "this", "record" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L88-L93
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addIsDeleted
public function addIsDeleted($tableName, $columnName = 'is_deleted') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->boolean()->defaultValue(0)->comment('Mark an item is deleted (in trash) or not')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addIsDeleted($tableName, $columnName = 'is_deleted') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->boolean()->defaultValue(0)->comment('Mark an item is deleted (in trash) or not')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addIsDeleted", "(", "$", "tableName", ",", "$", "columnName", "=", "'is_deleted'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "boolean", "(", ")", "->", "defaultValue", "(", "0", ")", "->", "comment", "(", "'Mark an item is deleted (in trash) or not'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put Index to is_deleted column This flag (0 or 1) for putting it to trash without completely delete it off the database @param $tableName
[ "Add", "and", "put", "Index", "to", "is_deleted", "column", "This", "flag", "(", "0", "or", "1", ")", "for", "putting", "it", "to", "trash", "without", "completely", "delete", "it", "off", "the", "database" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L100-L105
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addStatus
public function addStatus($tableName, $columnName = 'status') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->smallInteger()->notNull()->defaultValue(1)->comment('Status of this item, 0: draft, not publised, 1: published ')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
php
public function addStatus($tableName, $columnName = 'status') { $this->addColumn('{{%' . $tableName . '}}', $columnName, $this->smallInteger()->notNull()->defaultValue(1)->comment('Status of this item, 0: draft, not publised, 1: published ')); $this->createIndex($tableName . '_' . $columnName . '_idx', '{{%' . $tableName . '}}', $columnName); }
[ "public", "function", "addStatus", "(", "$", "tableName", ",", "$", "columnName", "=", "'status'", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ",", "$", "this", "->", "smallInteger", "(", ")", "->", "notNull", "(", ")", "->", "defaultValue", "(", "1", ")", "->", "comment", "(", "'Status of this item, 0: draft, not publised, 1: published '", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_'", ".", "$", "columnName", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "$", "columnName", ")", ";", "}" ]
Add and put Index to ordering_weight column For custom order in sorting to be displayed in the frontend @param $tableName
[ "Add", "and", "put", "Index", "to", "ordering_weight", "column", "For", "custom", "order", "in", "sorting", "to", "be", "displayed", "in", "the", "frontend" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L124-L129
npbtrac/yii2-enpii-cms
libs/override/db/NpMigration.php
NpMigration.addOrderingWeight
public function addOrderingWeight($tableName) { $this->addColumn('{{%' . $tableName . '}}', 'ordering_weight', $this->bigInteger()->defaultValue(0)->comment('An extra index for custom sorting')); $this->createIndex($tableName . '_ordering_weight' . '_idx', '{{%' . $tableName . '}}', 'ordering_weight'); }
php
public function addOrderingWeight($tableName) { $this->addColumn('{{%' . $tableName . '}}', 'ordering_weight', $this->bigInteger()->defaultValue(0)->comment('An extra index for custom sorting')); $this->createIndex($tableName . '_ordering_weight' . '_idx', '{{%' . $tableName . '}}', 'ordering_weight'); }
[ "public", "function", "addOrderingWeight", "(", "$", "tableName", ")", "{", "$", "this", "->", "addColumn", "(", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "'ordering_weight'", ",", "$", "this", "->", "bigInteger", "(", ")", "->", "defaultValue", "(", "0", ")", "->", "comment", "(", "'An extra index for custom sorting'", ")", ")", ";", "$", "this", "->", "createIndex", "(", "$", "tableName", ".", "'_ordering_weight'", ".", "'_idx'", ",", "'{{%'", ".", "$", "tableName", ".", "'}}'", ",", "'ordering_weight'", ")", ";", "}" ]
Add and put Index to ordering_weight column For custom order in sorting to be displayed in the frontend @param $tableName
[ "Add", "and", "put", "Index", "to", "ordering_weight", "column", "For", "custom", "order", "in", "sorting", "to", "be", "displayed", "in", "the", "frontend" ]
train
https://github.com/npbtrac/yii2-enpii-cms/blob/3495e697509a57a573983f552629ff9f707a63b9/libs/override/db/NpMigration.php#L136-L141
fyuze/framework
src/Fyuze/Http/Message/Message.php
Message.withProtocolVersion
public function withProtocolVersion($version) { if (in_array($version, ['1.0', '1.1', '2.0']) === false) { throw new InvalidArgumentException('You may only use a valid http protocol version, %d provided', $version); } return $this->_clone('protocol', $version); }
php
public function withProtocolVersion($version) { if (in_array($version, ['1.0', '1.1', '2.0']) === false) { throw new InvalidArgumentException('You may only use a valid http protocol version, %d provided', $version); } return $this->_clone('protocol', $version); }
[ "public", "function", "withProtocolVersion", "(", "$", "version", ")", "{", "if", "(", "in_array", "(", "$", "version", ",", "[", "'1.0'", ",", "'1.1'", ",", "'2.0'", "]", ")", "===", "false", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'You may only use a valid http protocol version, %d provided'", ",", "$", "version", ")", ";", "}", "return", "$", "this", "->", "_clone", "(", "'protocol'", ",", "$", "version", ")", ";", "}" ]
{@inheritdoc} @param string $version HTTP protocol version @return self @throws InvalidArgumentException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Message.php#L45-L52
fyuze/framework
src/Fyuze/Http/Message/Message.php
Message.getHeaders
public function getHeaders() { $headers = []; foreach($this->headers as $name => $values) { $headers[strtolower($name)] = $values; } return $headers; }
php
public function getHeaders() { $headers = []; foreach($this->headers as $name => $values) { $headers[strtolower($name)] = $values; } return $headers; }
[ "public", "function", "getHeaders", "(", ")", "{", "$", "headers", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "name", "=>", "$", "values", ")", "{", "$", "headers", "[", "strtolower", "(", "$", "name", ")", "]", "=", "$", "values", ";", "}", "return", "$", "headers", ";", "}" ]
{inheritdoc} @return array Returns an associative array of the message's headers. Each key MUST be a header name, and each value MUST be an array of strings for that header.
[ "{", "inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Message.php#L61-L70
fyuze/framework
src/Fyuze/Http/Message/Message.php
Message.getHeader
public function getHeader($name) { $name = strtolower($name); return $this->hasHeader($name) ? $this->headers[$name] : []; }
php
public function getHeader($name) { $name = strtolower($name); return $this->hasHeader($name) ? $this->headers[$name] : []; }
[ "public", "function", "getHeader", "(", "$", "name", ")", "{", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "return", "$", "this", "->", "hasHeader", "(", "$", "name", ")", "?", "$", "this", "->", "headers", "[", "$", "name", "]", ":", "[", "]", ";", "}" ]
{@inheritdoc} @param string $name Case-insensitive header field name. @return string[] An array of string values as provided for the given header. If the header does not appear in the message, this method MUST return an empty array.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Message.php#L96-L101
fyuze/framework
src/Fyuze/Http/Message/Message.php
Message.withHeader
public function withHeader($name, $value) { if (array_key_exists($name, $this->headers) && in_array($value, $this->headers[$name])) { return $this; } $instance = clone $this; $instance->headers[$name] = array_filter((array)$value); return $instance; }
php
public function withHeader($name, $value) { if (array_key_exists($name, $this->headers) && in_array($value, $this->headers[$name])) { return $this; } $instance = clone $this; $instance->headers[$name] = array_filter((array)$value); return $instance; }
[ "public", "function", "withHeader", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "headers", ")", "&&", "in_array", "(", "$", "value", ",", "$", "this", "->", "headers", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", ";", "}", "$", "instance", "=", "clone", "$", "this", ";", "$", "instance", "->", "headers", "[", "$", "name", "]", "=", "array_filter", "(", "(", "array", ")", "$", "value", ")", ";", "return", "$", "instance", ";", "}" ]
{@inheritdoc} @param string $name Case-insensitive header field name. @param string|string[] $value Header value(s). @return self @throws InvalidArgumentException for invalid header names or values.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Http/Message/Message.php#L124-L133
krzysztofmazur/php-object-mapper
src/KrzysztofMazur/ObjectMapper/Mapping/Field/ValueReader/MethodValueReader.php
MethodValueReader.readValue
protected function readValue($object) { return Reflection::getMethod(get_class($object), $this->methodName)->invokeArgs($object, $this->arguments); }
php
protected function readValue($object) { return Reflection::getMethod(get_class($object), $this->methodName)->invokeArgs($object, $this->arguments); }
[ "protected", "function", "readValue", "(", "$", "object", ")", "{", "return", "Reflection", "::", "getMethod", "(", "get_class", "(", "$", "object", ")", ",", "$", "this", "->", "methodName", ")", "->", "invokeArgs", "(", "$", "object", ",", "$", "this", "->", "arguments", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/krzysztofmazur/php-object-mapper/blob/2c22acad9634cfe8e9a75d72e665d450ada8d4e3/src/KrzysztofMazur/ObjectMapper/Mapping/Field/ValueReader/MethodValueReader.php#L43-L46
shinjin/freezer
src/Storage/DoctrineCache.php
DoctrineCache.doStore
protected function doStore(array $frozenObject) { foreach ($frozenObject['objects'] as $id => $object) { if ($object['isDirty'] === true) { $payload = array( 'class' => $object['class'], 'state' => $object['state'] ); $this->cache->save($id, $payload); } } }
php
protected function doStore(array $frozenObject) { foreach ($frozenObject['objects'] as $id => $object) { if ($object['isDirty'] === true) { $payload = array( 'class' => $object['class'], 'state' => $object['state'] ); $this->cache->save($id, $payload); } } }
[ "protected", "function", "doStore", "(", "array", "$", "frozenObject", ")", "{", "foreach", "(", "$", "frozenObject", "[", "'objects'", "]", "as", "$", "id", "=>", "$", "object", ")", "{", "if", "(", "$", "object", "[", "'isDirty'", "]", "===", "true", ")", "{", "$", "payload", "=", "array", "(", "'class'", "=>", "$", "object", "[", "'class'", "]", ",", "'state'", "=>", "$", "object", "[", "'state'", "]", ")", ";", "$", "this", "->", "cache", "->", "save", "(", "$", "id", ",", "$", "payload", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/shinjin/freezer/blob/f5955fb5476fa8ac456e27c0edafaae331d02cd3/src/Storage/DoctrineCache.php#L36-L48
shinjin/freezer
src/Storage/DoctrineCache.php
DoctrineCache.doFetch
protected function doFetch($id, array &$objects = array()) { $isRoot = empty($objects); if (!isset($objects[$id])) { if (($object = $this->cache->fetch($id)) === false) { return false; } $object['isDirty'] = false; $objects[$id] = $object; if (!$this->useLazyLoad) { $this->fetchArray($object['state'], $objects); } } if ($isRoot) { return array('root' => $id, 'objects' => $objects); } }
php
protected function doFetch($id, array &$objects = array()) { $isRoot = empty($objects); if (!isset($objects[$id])) { if (($object = $this->cache->fetch($id)) === false) { return false; } $object['isDirty'] = false; $objects[$id] = $object; if (!$this->useLazyLoad) { $this->fetchArray($object['state'], $objects); } } if ($isRoot) { return array('root' => $id, 'objects' => $objects); } }
[ "protected", "function", "doFetch", "(", "$", "id", ",", "array", "&", "$", "objects", "=", "array", "(", ")", ")", "{", "$", "isRoot", "=", "empty", "(", "$", "objects", ")", ";", "if", "(", "!", "isset", "(", "$", "objects", "[", "$", "id", "]", ")", ")", "{", "if", "(", "(", "$", "object", "=", "$", "this", "->", "cache", "->", "fetch", "(", "$", "id", ")", ")", "===", "false", ")", "{", "return", "false", ";", "}", "$", "object", "[", "'isDirty'", "]", "=", "false", ";", "$", "objects", "[", "$", "id", "]", "=", "$", "object", ";", "if", "(", "!", "$", "this", "->", "useLazyLoad", ")", "{", "$", "this", "->", "fetchArray", "(", "$", "object", "[", "'state'", "]", ",", "$", "objects", ")", ";", "}", "}", "if", "(", "$", "isRoot", ")", "{", "return", "array", "(", "'root'", "=>", "$", "id", ",", "'objects'", "=>", "$", "objects", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/shinjin/freezer/blob/f5955fb5476fa8ac456e27c0edafaae331d02cd3/src/Storage/DoctrineCache.php#L53-L73
webforge-labs/psc-cms
lib/Psc/UI/ComboBox2.php
ComboBox2.setAutoCompleteRequestMeta
public function setAutoCompleteRequestMeta(\Psc\CMS\AutoCompleteRequestMeta $autoCompleteRequestMeta) { $this->acRequestMeta = $autoCompleteRequestMeta; $this->avaibleItems = NULL; return $this; }
php
public function setAutoCompleteRequestMeta(\Psc\CMS\AutoCompleteRequestMeta $autoCompleteRequestMeta) { $this->acRequestMeta = $autoCompleteRequestMeta; $this->avaibleItems = NULL; return $this; }
[ "public", "function", "setAutoCompleteRequestMeta", "(", "\\", "Psc", "\\", "CMS", "\\", "AutoCompleteRequestMeta", "$", "autoCompleteRequestMeta", ")", "{", "$", "this", "->", "acRequestMeta", "=", "$", "autoCompleteRequestMeta", ";", "$", "this", "->", "avaibleItems", "=", "NULL", ";", "return", "$", "this", ";", "}" ]
Ist dies gesetzt wird avaibleItems ignoriert @param Psc\CMS\AutoCompleteRequestMeta $autoCompleteRequestMeta @chainable
[ "Ist", "dies", "gesetzt", "wird", "avaibleItems", "ignoriert" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/ComboBox2.php#L173-L177
webforge-labs/psc-cms
lib/Psc/UI/ComboBox2.php
ComboBox2.setSelected
public function setSelected($item) { if (!isset($this->entityMeta)) { throw new \Psc\Exception('EntityMeta muss übergeben werden wenn selected gesetzt wird'); } $ec = $this->entityMeta->getClass(); if (!($item instanceof $ec)) { throw new \InvalidArgumentException('Parameter Item für setSelected() muss vom Typ: '.$ec.' sein. '.Code::varInfo($item).' wurde übergeben'); } $this->selected = $item; return $this; }
php
public function setSelected($item) { if (!isset($this->entityMeta)) { throw new \Psc\Exception('EntityMeta muss übergeben werden wenn selected gesetzt wird'); } $ec = $this->entityMeta->getClass(); if (!($item instanceof $ec)) { throw new \InvalidArgumentException('Parameter Item für setSelected() muss vom Typ: '.$ec.' sein. '.Code::varInfo($item).' wurde übergeben'); } $this->selected = $item; return $this; }
[ "public", "function", "setSelected", "(", "$", "item", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "entityMeta", ")", ")", "{", "throw", "new", "\\", "Psc", "\\", "Exception", "(", "'EntityMeta muss übergeben werden wenn selected gesetzt wird')", ";", "", "}", "$", "ec", "=", "$", "this", "->", "entityMeta", "->", "getClass", "(", ")", ";", "if", "(", "!", "(", "$", "item", "instanceof", "$", "ec", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Parameter Item für setSelected() muss vom Typ: '.", "$", "e", "c.", "'", " sein. '.", "C", "ode:", ":v", "arInfo(", "$", "i", "tem)", ".", "'", " wurde übergeben');", "", "", "}", "$", "this", "->", "selected", "=", "$", "item", ";", "return", "$", "this", ";", "}" ]
Setzt das Element welches in der ComboBox ausgewählt ist
[ "Setzt", "das", "Element", "welches", "in", "der", "ComboBox", "ausgewählt", "ist" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/ComboBox2.php#L191-L203
yuncms/framework
src/oauth2/actions/Token.php
Token.run
public function run() { if (!$grantType = GrantType::getRequestValue('grant_type')) { throw new Exception(Yii::t('yuncms', 'The grant type was not specified in the request')); } if (isset($this->grantTypes[$grantType])) { $grantModel = Yii::createObject($this->grantTypes[$grantType]); } else { throw new Exception(Yii::t('yuncms', "An unsupported grant type was requested"), Exception::UNSUPPORTED_GRANT_TYPE); } $grantModel->validate(); Yii::$app->response->data = $grantModel->getResponseData(); }
php
public function run() { if (!$grantType = GrantType::getRequestValue('grant_type')) { throw new Exception(Yii::t('yuncms', 'The grant type was not specified in the request')); } if (isset($this->grantTypes[$grantType])) { $grantModel = Yii::createObject($this->grantTypes[$grantType]); } else { throw new Exception(Yii::t('yuncms', "An unsupported grant type was requested"), Exception::UNSUPPORTED_GRANT_TYPE); } $grantModel->validate(); Yii::$app->response->data = $grantModel->getResponseData(); }
[ "public", "function", "run", "(", ")", "{", "if", "(", "!", "$", "grantType", "=", "GrantType", "::", "getRequestValue", "(", "'grant_type'", ")", ")", "{", "throw", "new", "Exception", "(", "Yii", "::", "t", "(", "'yuncms'", ",", "'The grant type was not specified in the request'", ")", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "grantTypes", "[", "$", "grantType", "]", ")", ")", "{", "$", "grantModel", "=", "Yii", "::", "createObject", "(", "$", "this", "->", "grantTypes", "[", "$", "grantType", "]", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "Yii", "::", "t", "(", "'yuncms'", ",", "\"An unsupported grant type was requested\"", ")", ",", "Exception", "::", "UNSUPPORTED_GRANT_TYPE", ")", ";", "}", "$", "grantModel", "->", "validate", "(", ")", ";", "Yii", "::", "$", "app", "->", "response", "->", "data", "=", "$", "grantModel", "->", "getResponseData", "(", ")", ";", "}" ]
run @throws Exception @throws \yii\base\InvalidConfigException
[ "run" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/oauth2/actions/Token.php#L71-L83
webforge-labs/psc-cms
lib/Psc/UI/Form.php
Form.group
public static function group($legend, $content, $flags = 0x000000) { $group = UIHTML::Tag('fieldset', new \stdClass) ->addClass('ui-corner-all') ->addClass('ui-widget-content') ->addClass('\Psc\group') ; $group->contentTemplate = "%legend%\n %div%"; $group->content->legend = UIHTML::Tag('legend',$legend); $group->content->div = UIHTML::Tag('div',$content,array('class'=>'content')); if ($flags & self::GROUP_COLLAPSIBLE) { $group->content->legend->addClass('collapsible'); } return $group; }
php
public static function group($legend, $content, $flags = 0x000000) { $group = UIHTML::Tag('fieldset', new \stdClass) ->addClass('ui-corner-all') ->addClass('ui-widget-content') ->addClass('\Psc\group') ; $group->contentTemplate = "%legend%\n %div%"; $group->content->legend = UIHTML::Tag('legend',$legend); $group->content->div = UIHTML::Tag('div',$content,array('class'=>'content')); if ($flags & self::GROUP_COLLAPSIBLE) { $group->content->legend->addClass('collapsible'); } return $group; }
[ "public", "static", "function", "group", "(", "$", "legend", ",", "$", "content", ",", "$", "flags", "=", "0x000000", ")", "{", "$", "group", "=", "UIHTML", "::", "Tag", "(", "'fieldset'", ",", "new", "\\", "stdClass", ")", "->", "addClass", "(", "'ui-corner-all'", ")", "->", "addClass", "(", "'ui-widget-content'", ")", "->", "addClass", "(", "'\\Psc\\group'", ")", ";", "$", "group", "->", "contentTemplate", "=", "\"%legend%\\n %div%\"", ";", "$", "group", "->", "content", "->", "legend", "=", "UIHTML", "::", "Tag", "(", "'legend'", ",", "$", "legend", ")", ";", "$", "group", "->", "content", "->", "div", "=", "UIHTML", "::", "Tag", "(", "'div'", ",", "$", "content", ",", "array", "(", "'class'", "=>", "'content'", ")", ")", ";", "if", "(", "$", "flags", "&", "self", "::", "GROUP_COLLAPSIBLE", ")", "{", "$", "group", "->", "content", "->", "legend", "->", "addClass", "(", "'collapsible'", ")", ";", "}", "return", "$", "group", ";", "}" ]
Eine Gruppe von Element mit einer Überschrift der Inhalt ist eingerückt und es befindet sich ein Rahmen herum @param mixed $legend der inhalt der Überschrift @param mixed $content der Inhalt des Containers @return HTMLTag
[ "Eine", "Gruppe", "von", "Element", "mit", "einer", "Überschrift" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Form.php#L42-L59
webforge-labs/psc-cms
lib/Psc/UI/Form.php
Form.input
public static function input(HTMLTag $formInputItem, $hint = NULL, $flags = 0x000000) { return new FormInput($formInputItem, $hint, $flags); }
php
public static function input(HTMLTag $formInputItem, $hint = NULL, $flags = 0x000000) { return new FormInput($formInputItem, $hint, $flags); }
[ "public", "static", "function", "input", "(", "HTMLTag", "$", "formInputItem", ",", "$", "hint", "=", "NULL", ",", "$", "flags", "=", "0x000000", ")", "{", "return", "new", "FormInput", "(", "$", "formInputItem", ",", "$", "hint", ",", "$", "flags", ")", ";", "}" ]
UIForm::inputSet( UIForm::Input(UIForm::text(...), 'muss nicht unbedingt angegeben werden', UIForm::BR) ) @return FormInput
[ "UIForm", "::", "inputSet", "(", "UIForm", "::", "Input", "(", "UIForm", "::", "text", "(", "...", ")", "muss", "nicht", "unbedingt", "angegeben", "werden", "UIForm", "::", "BR", ")", ")" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Form.php#L179-L181
webforge-labs/psc-cms
lib/Psc/UI/Form.php
Form.attachLabel
public static function attachLabel($element, $label, $type = self::LABEL_TOP) { Code::value($type, self::LABEL_TOP, self::LABEL_CHECKBOX); if ($label != NULL) { $element->templateContent->label = fHTML::label($label, $element) ->addClass('\Psc\label') ; if ($type == self::LABEL_TOP) { $element->templatePrepend('%label%'); // nicht überschreiben sondern prependen } if ($type == self::LABEL_CHECKBOX) { $element->template = '%self% %label%'; $element->templateContent->label->addClass('checkbox-label'); } } return $element; }
php
public static function attachLabel($element, $label, $type = self::LABEL_TOP) { Code::value($type, self::LABEL_TOP, self::LABEL_CHECKBOX); if ($label != NULL) { $element->templateContent->label = fHTML::label($label, $element) ->addClass('\Psc\label') ; if ($type == self::LABEL_TOP) { $element->templatePrepend('%label%'); // nicht überschreiben sondern prependen } if ($type == self::LABEL_CHECKBOX) { $element->template = '%self% %label%'; $element->templateContent->label->addClass('checkbox-label'); } } return $element; }
[ "public", "static", "function", "attachLabel", "(", "$", "element", ",", "$", "label", ",", "$", "type", "=", "self", "::", "LABEL_TOP", ")", "{", "Code", "::", "value", "(", "$", "type", ",", "self", "::", "LABEL_TOP", ",", "self", "::", "LABEL_CHECKBOX", ")", ";", "if", "(", "$", "label", "!=", "NULL", ")", "{", "$", "element", "->", "templateContent", "->", "label", "=", "fHTML", "::", "label", "(", "$", "label", ",", "$", "element", ")", "->", "addClass", "(", "'\\Psc\\label'", ")", ";", "if", "(", "$", "type", "==", "self", "::", "LABEL_TOP", ")", "{", "$", "element", "->", "templatePrepend", "(", "'%label%'", ")", ";", "// nicht überschreiben sondern prependen", "}", "if", "(", "$", "type", "==", "self", "::", "LABEL_CHECKBOX", ")", "{", "$", "element", "->", "template", "=", "'%self% %label%'", ";", "$", "element", "->", "templateContent", "->", "label", "->", "addClass", "(", "'checkbox-label'", ")", ";", "}", "}", "return", "$", "element", ";", "}" ]
benutzt von dropBox2
[ "benutzt", "von", "dropBox2" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Form.php#L232-L251
EvanDotPro/EdpGithub
src/EdpGithub/Api/User.php
User.repos
public function repos($username, array $params = array()) { $httpClient = $this->getClient()->getHttpClient(); return new RepositoryCollection( $httpClient, 'users/' . urlencode($username) . '/repos', $params ); }
php
public function repos($username, array $params = array()) { $httpClient = $this->getClient()->getHttpClient(); return new RepositoryCollection( $httpClient, 'users/' . urlencode($username) . '/repos', $params ); }
[ "public", "function", "repos", "(", "$", "username", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "httpClient", "=", "$", "this", "->", "getClient", "(", ")", "->", "getHttpClient", "(", ")", ";", "return", "new", "RepositoryCollection", "(", "$", "httpClient", ",", "'users/'", ".", "urlencode", "(", "$", "username", ")", ".", "'/repos'", ",", "$", "params", ")", ";", "}" ]
Get Repositories @link http://developer.github.com/v3/repos/ @param string $username @param array $params @return RepositoryCollection
[ "Get", "Repositories" ]
train
https://github.com/EvanDotPro/EdpGithub/blob/51f3e33e02edbef011103e3c2c1629d46af011a3/src/EdpGithub/Api/User.php#L31-L40
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Sub/FieldDefinitionSubManager.php
FieldDefinitionSubManager.createOrUpdateFieldDefinitions
public function createOrUpdateFieldDefinitions(array $updatedFieldDefinitions, array $existingFieldDefinitions, ContentTypeDraft $contentTypeDraft) { foreach ($updatedFieldDefinitions as $updatedField) { // Updating existing field definitions foreach ($existingFieldDefinitions as $existingField) { if ($existingField->identifier == $updatedField->data['identifier']) { $this->contentTypeService->updateFieldDefinition( $contentTypeDraft, $existingField, $this->updateFieldDefinition($updatedField) ); continue 2; } } // Creating new field definitions $this->contentTypeService->addFieldDefinition( $contentTypeDraft, $this->createFieldDefinition($updatedField) ); } }
php
public function createOrUpdateFieldDefinitions(array $updatedFieldDefinitions, array $existingFieldDefinitions, ContentTypeDraft $contentTypeDraft) { foreach ($updatedFieldDefinitions as $updatedField) { // Updating existing field definitions foreach ($existingFieldDefinitions as $existingField) { if ($existingField->identifier == $updatedField->data['identifier']) { $this->contentTypeService->updateFieldDefinition( $contentTypeDraft, $existingField, $this->updateFieldDefinition($updatedField) ); continue 2; } } // Creating new field definitions $this->contentTypeService->addFieldDefinition( $contentTypeDraft, $this->createFieldDefinition($updatedField) ); } }
[ "public", "function", "createOrUpdateFieldDefinitions", "(", "array", "$", "updatedFieldDefinitions", ",", "array", "$", "existingFieldDefinitions", ",", "ContentTypeDraft", "$", "contentTypeDraft", ")", "{", "foreach", "(", "$", "updatedFieldDefinitions", "as", "$", "updatedField", ")", "{", "// Updating existing field definitions", "foreach", "(", "$", "existingFieldDefinitions", "as", "$", "existingField", ")", "{", "if", "(", "$", "existingField", "->", "identifier", "==", "$", "updatedField", "->", "data", "[", "'identifier'", "]", ")", "{", "$", "this", "->", "contentTypeService", "->", "updateFieldDefinition", "(", "$", "contentTypeDraft", ",", "$", "existingField", ",", "$", "this", "->", "updateFieldDefinition", "(", "$", "updatedField", ")", ")", ";", "continue", "2", ";", "}", "}", "// Creating new field definitions", "$", "this", "->", "contentTypeService", "->", "addFieldDefinition", "(", "$", "contentTypeDraft", ",", "$", "this", "->", "createFieldDefinition", "(", "$", "updatedField", ")", ")", ";", "}", "}" ]
Creating new and updates existing field definitions. NOTE: Will NOT delete field definitions which no longer exist. @param FieldDefinitionObject[] $updatedFieldDefinitions @param FieldDefinition[] $existingFieldDefinitions @param ContentTypeDraft $contentTypeDraft
[ "Creating", "new", "and", "updates", "existing", "field", "definitions", ".", "NOTE", ":", "Will", "NOT", "delete", "field", "definitions", "which", "no", "longer", "exist", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Sub/FieldDefinitionSubManager.php#L81-L103
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Sub/FieldDefinitionSubManager.php
FieldDefinitionSubManager.createFieldDefinition
private function createFieldDefinition(FieldDefinitionObject $field) { $definition = $this->contentTypeService->newFieldDefinitionCreateStruct($field->data['identifier'], $field->data['type']); $field->getMapper()->mapObjectToCreateStruct($definition); return $definition; }
php
private function createFieldDefinition(FieldDefinitionObject $field) { $definition = $this->contentTypeService->newFieldDefinitionCreateStruct($field->data['identifier'], $field->data['type']); $field->getMapper()->mapObjectToCreateStruct($definition); return $definition; }
[ "private", "function", "createFieldDefinition", "(", "FieldDefinitionObject", "$", "field", ")", "{", "$", "definition", "=", "$", "this", "->", "contentTypeService", "->", "newFieldDefinitionCreateStruct", "(", "$", "field", "->", "data", "[", "'identifier'", "]", ",", "$", "field", "->", "data", "[", "'type'", "]", ")", ";", "$", "field", "->", "getMapper", "(", ")", "->", "mapObjectToCreateStruct", "(", "$", "definition", ")", ";", "return", "$", "definition", ";", "}" ]
@param FieldDefinitionObject $field @return FieldDefinitionCreateStruct
[ "@param", "FieldDefinitionObject", "$field" ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Sub/FieldDefinitionSubManager.php#L110-L116
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Sub/FieldDefinitionSubManager.php
FieldDefinitionSubManager.updateFieldDefinition
private function updateFieldDefinition(FieldDefinitionObject $field) { $definition = $this->contentTypeService->newFieldDefinitionUpdateStruct(); $field->getMapper()->mapObjectToUpdateStruct($definition); return $definition; }
php
private function updateFieldDefinition(FieldDefinitionObject $field) { $definition = $this->contentTypeService->newFieldDefinitionUpdateStruct(); $field->getMapper()->mapObjectToUpdateStruct($definition); return $definition; }
[ "private", "function", "updateFieldDefinition", "(", "FieldDefinitionObject", "$", "field", ")", "{", "$", "definition", "=", "$", "this", "->", "contentTypeService", "->", "newFieldDefinitionUpdateStruct", "(", ")", ";", "$", "field", "->", "getMapper", "(", ")", "->", "mapObjectToUpdateStruct", "(", "$", "definition", ")", ";", "return", "$", "definition", ";", "}" ]
@param FieldDefinitionObject $field @return FieldDefinitionUpdateStruct
[ "@param", "FieldDefinitionObject", "$field" ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Sub/FieldDefinitionSubManager.php#L123-L129
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/ClassUtils.php
ClassUtils.hasTrait
public static function hasTrait($class, $traitName, $isRecursive = false) { if (is_string($class)) { $class = new \ReflectionClass($class); } if (in_array($traitName, $class->getTraitNames(), true)) { return true; } $parentClass = $class->getParentClass(); if ((false === $isRecursive) || (false === $parentClass) || (null === $parentClass)) { return false; } return static::hasTrait($parentClass, $traitName, $isRecursive); }
php
public static function hasTrait($class, $traitName, $isRecursive = false) { if (is_string($class)) { $class = new \ReflectionClass($class); } if (in_array($traitName, $class->getTraitNames(), true)) { return true; } $parentClass = $class->getParentClass(); if ((false === $isRecursive) || (false === $parentClass) || (null === $parentClass)) { return false; } return static::hasTrait($parentClass, $traitName, $isRecursive); }
[ "public", "static", "function", "hasTrait", "(", "$", "class", ",", "$", "traitName", ",", "$", "isRecursive", "=", "false", ")", "{", "if", "(", "is_string", "(", "$", "class", ")", ")", "{", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "}", "if", "(", "in_array", "(", "$", "traitName", ",", "$", "class", "->", "getTraitNames", "(", ")", ",", "true", ")", ")", "{", "return", "true", ";", "}", "$", "parentClass", "=", "$", "class", "->", "getParentClass", "(", ")", ";", "if", "(", "(", "false", "===", "$", "isRecursive", ")", "||", "(", "false", "===", "$", "parentClass", ")", "||", "(", "null", "===", "$", "parentClass", ")", ")", "{", "return", "false", ";", "}", "return", "static", "::", "hasTrait", "(", "$", "parentClass", ",", "$", "traitName", ",", "$", "isRecursive", ")", ";", "}" ]
Return true if the given object use the given trait, FALSE if not. @param \ReflectionClass|string $class @param string $traitName @param bool $isRecursive @return bool
[ "Return", "true", "if", "the", "given", "object", "use", "the", "given", "trait", "FALSE", "if", "not", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/ClassUtils.php#L28-L45
dreamfactorysoftware/df-file
src/Components/WebDAVFileSystem.php
WebDAVFileSystem.normalizeFolderInfo
protected function normalizeFolderInfo(array & $folder, $localizer) { parent::normalizeFolderInfo($folder, $localizer); $folder['last_modified'] = gmdate('D, d M Y H:i:s \G\M\T', array_get($folder, 'timestamp', 0)); unset($folder['timestamp']); }
php
protected function normalizeFolderInfo(array & $folder, $localizer) { parent::normalizeFolderInfo($folder, $localizer); $folder['last_modified'] = gmdate('D, d M Y H:i:s \G\M\T', array_get($folder, 'timestamp', 0)); unset($folder['timestamp']); }
[ "protected", "function", "normalizeFolderInfo", "(", "array", "&", "$", "folder", ",", "$", "localizer", ")", "{", "parent", "::", "normalizeFolderInfo", "(", "$", "folder", ",", "$", "localizer", ")", ";", "$", "folder", "[", "'last_modified'", "]", "=", "gmdate", "(", "'D, d M Y H:i:s \\G\\M\\T'", ",", "array_get", "(", "$", "folder", ",", "'timestamp'", ",", "0", ")", ")", ";", "unset", "(", "$", "folder", "[", "'timestamp'", "]", ")", ";", "}" ]
@param array $folder @param string $localizer @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
[ "@param", "array", "$folder", "@param", "string", "$localizer" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/WebDAVFileSystem.php#L47-L52
silvercommerce/catalogue-frontend
src/extensions/CatalogueExtension.php
CatalogueExtension.isCurrent
public function isCurrent() { $currentPage = Director::get_current_page(); if ($currentPage instanceof ContentController) { $currentPage = $currentPage->data(); } if ($currentPage instanceof CatalogueCategory || $currentPage instanceof CatalogueProduct) { return $currentPage === $this->owner || $currentPage->ID === $this->owner->ID; } return false; }
php
public function isCurrent() { $currentPage = Director::get_current_page(); if ($currentPage instanceof ContentController) { $currentPage = $currentPage->data(); } if ($currentPage instanceof CatalogueCategory || $currentPage instanceof CatalogueProduct) { return $currentPage === $this->owner || $currentPage->ID === $this->owner->ID; } return false; }
[ "public", "function", "isCurrent", "(", ")", "{", "$", "currentPage", "=", "Director", "::", "get_current_page", "(", ")", ";", "if", "(", "$", "currentPage", "instanceof", "ContentController", ")", "{", "$", "currentPage", "=", "$", "currentPage", "->", "data", "(", ")", ";", "}", "if", "(", "$", "currentPage", "instanceof", "CatalogueCategory", "||", "$", "currentPage", "instanceof", "CatalogueProduct", ")", "{", "return", "$", "currentPage", "===", "$", "this", "->", "owner", "||", "$", "currentPage", "->", "ID", "===", "$", "this", "->", "owner", "->", "ID", ";", "}", "return", "false", ";", "}" ]
Returns true if this is the currently active page being used to handle this request. @return bool
[ "Returns", "true", "if", "this", "is", "the", "currently", "active", "page", "being", "used", "to", "handle", "this", "request", "." ]
train
https://github.com/silvercommerce/catalogue-frontend/blob/671f1e32bf6bc6eb193c6608ae904cd055540cc4/src/extensions/CatalogueExtension.php#L61-L72
silvercommerce/catalogue-frontend
src/extensions/CatalogueExtension.php
CatalogueExtension.isSection
public function isSection() { $is_curr = $this->isCurrent(); $curr = Director::get_current_page(); return $is_curr || ( ($curr instanceof CatalogueCategory || $curr instanceof CatalogueProduct) && in_array($this->owner->ID, $curr->getAncestors()->column()) ); }
php
public function isSection() { $is_curr = $this->isCurrent(); $curr = Director::get_current_page(); return $is_curr || ( ($curr instanceof CatalogueCategory || $curr instanceof CatalogueProduct) && in_array($this->owner->ID, $curr->getAncestors()->column()) ); }
[ "public", "function", "isSection", "(", ")", "{", "$", "is_curr", "=", "$", "this", "->", "isCurrent", "(", ")", ";", "$", "curr", "=", "Director", "::", "get_current_page", "(", ")", ";", "return", "$", "is_curr", "||", "(", "(", "$", "curr", "instanceof", "CatalogueCategory", "||", "$", "curr", "instanceof", "CatalogueProduct", ")", "&&", "in_array", "(", "$", "this", "->", "owner", "->", "ID", ",", "$", "curr", "->", "getAncestors", "(", ")", "->", "column", "(", ")", ")", ")", ";", "}" ]
Check if this page is in the currently active section (e.g. it is either current or one of its children is currently being viewed). @return bool
[ "Check", "if", "this", "page", "is", "in", "the", "currently", "active", "section", "(", "e", ".", "g", ".", "it", "is", "either", "current", "or", "one", "of", "its", "children", "is", "currently", "being", "viewed", ")", "." ]
train
https://github.com/silvercommerce/catalogue-frontend/blob/671f1e32bf6bc6eb193c6608ae904cd055540cc4/src/extensions/CatalogueExtension.php#L80-L88
silvercommerce/catalogue-frontend
src/extensions/CatalogueExtension.php
CatalogueExtension.getControllerName
public function getControllerName() { //default controller for SiteTree objects $controller = CatalogueController::class; //go through the ancestry for this class looking for $ancestry = ClassInfo::ancestry($this->owner->ClassName); // loop over the array going from the deepest descendant (ie: the current class) to SiteTree while ($class = array_pop($ancestry)) { //we don't need to go any deeper than the SiteTree class if ($class == CatalogueProduct::class || $class == CatalogueCategory::class) { break; } // If we have a class of "{$ClassName}Controller" then we found our controller if (class_exists($candidate = sprintf('%sController', $class))) { $controller = $candidate; break; } elseif (class_exists($candidate = sprintf('%s_Controller', $class))) { // Support the legacy underscored filename, but raise a deprecation notice Deprecation::notice( '5.0', 'Underscored controller class names are deprecated. Use "MyController" instead of "My_Controller".', Deprecation::SCOPE_GLOBAL ); $controller = $candidate; break; } } return $controller; }
php
public function getControllerName() { //default controller for SiteTree objects $controller = CatalogueController::class; //go through the ancestry for this class looking for $ancestry = ClassInfo::ancestry($this->owner->ClassName); // loop over the array going from the deepest descendant (ie: the current class) to SiteTree while ($class = array_pop($ancestry)) { //we don't need to go any deeper than the SiteTree class if ($class == CatalogueProduct::class || $class == CatalogueCategory::class) { break; } // If we have a class of "{$ClassName}Controller" then we found our controller if (class_exists($candidate = sprintf('%sController', $class))) { $controller = $candidate; break; } elseif (class_exists($candidate = sprintf('%s_Controller', $class))) { // Support the legacy underscored filename, but raise a deprecation notice Deprecation::notice( '5.0', 'Underscored controller class names are deprecated. Use "MyController" instead of "My_Controller".', Deprecation::SCOPE_GLOBAL ); $controller = $candidate; break; } } return $controller; }
[ "public", "function", "getControllerName", "(", ")", "{", "//default controller for SiteTree objects", "$", "controller", "=", "CatalogueController", "::", "class", ";", "//go through the ancestry for this class looking for", "$", "ancestry", "=", "ClassInfo", "::", "ancestry", "(", "$", "this", "->", "owner", "->", "ClassName", ")", ";", "// loop over the array going from the deepest descendant (ie: the current class) to SiteTree", "while", "(", "$", "class", "=", "array_pop", "(", "$", "ancestry", ")", ")", "{", "//we don't need to go any deeper than the SiteTree class", "if", "(", "$", "class", "==", "CatalogueProduct", "::", "class", "||", "$", "class", "==", "CatalogueCategory", "::", "class", ")", "{", "break", ";", "}", "// If we have a class of \"{$ClassName}Controller\" then we found our controller", "if", "(", "class_exists", "(", "$", "candidate", "=", "sprintf", "(", "'%sController'", ",", "$", "class", ")", ")", ")", "{", "$", "controller", "=", "$", "candidate", ";", "break", ";", "}", "elseif", "(", "class_exists", "(", "$", "candidate", "=", "sprintf", "(", "'%s_Controller'", ",", "$", "class", ")", ")", ")", "{", "// Support the legacy underscored filename, but raise a deprecation notice", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Underscored controller class names are deprecated. Use \"MyController\" instead of \"My_Controller\".'", ",", "Deprecation", "::", "SCOPE_GLOBAL", ")", ";", "$", "controller", "=", "$", "candidate", ";", "break", ";", "}", "}", "return", "$", "controller", ";", "}" ]
Find the controller name by our convention of {$ModelClass}Controller @return string
[ "Find", "the", "controller", "name", "by", "our", "convention", "of", "{", "$ModelClass", "}", "Controller" ]
train
https://github.com/silvercommerce/catalogue-frontend/blob/671f1e32bf6bc6eb193c6608ae904cd055540cc4/src/extensions/CatalogueExtension.php#L213-L245
silvercommerce/catalogue-frontend
src/extensions/CatalogueExtension.php
CatalogueExtension.MetaTags
public function MetaTags($includeTitle = true) { $tags = []; $owner = $this->getOwner(); if ($includeTitle && strtolower($includeTitle) != 'false') { $tags[] = HTML::createTag( 'title', [], $owner->obj('Title')->forTemplate() ); } $generator = trim(Config::inst()->get(self::class, 'meta_generator')); if (!empty($generator)) { $tags[] = HTML::createTag('meta', array( 'name' => 'generator', 'content' => $generator, )); } $charset = ContentNegotiator::config()->uninherited('encoding'); $tags[] = HTML::createTag('meta', array( 'http-equiv' => 'Content-Type', 'content' => 'text/html; charset=' . $charset, )); if ($owner->MetaDescription) { $tags[] = HTML::createTag('meta', array( 'name' => 'description', 'content' => $owner->MetaDescription, )); } if (Permission::check('CMS_ACCESS_CMSMain') && $owner->exists()) { $tags[] = HTML::createTag( 'meta', [ 'name' => 'x-page-id', 'content' => $owner->obj('ID')->forTemplate() ] ); $tags[] = HTML::createTag( 'meta', [ 'name' => 'x-cms-edit-link', 'content' => $owner->obj('CMSEditLink')->forTemplate() ] ); } $tags = implode("\n", $tags); if ($owner->ExtraMeta) { $tags .= $owner->obj('ExtraMeta')->forTemplate(); } $owner->extend('updateMetaTags', $tags); return $tags; }
php
public function MetaTags($includeTitle = true) { $tags = []; $owner = $this->getOwner(); if ($includeTitle && strtolower($includeTitle) != 'false') { $tags[] = HTML::createTag( 'title', [], $owner->obj('Title')->forTemplate() ); } $generator = trim(Config::inst()->get(self::class, 'meta_generator')); if (!empty($generator)) { $tags[] = HTML::createTag('meta', array( 'name' => 'generator', 'content' => $generator, )); } $charset = ContentNegotiator::config()->uninherited('encoding'); $tags[] = HTML::createTag('meta', array( 'http-equiv' => 'Content-Type', 'content' => 'text/html; charset=' . $charset, )); if ($owner->MetaDescription) { $tags[] = HTML::createTag('meta', array( 'name' => 'description', 'content' => $owner->MetaDescription, )); } if (Permission::check('CMS_ACCESS_CMSMain') && $owner->exists()) { $tags[] = HTML::createTag( 'meta', [ 'name' => 'x-page-id', 'content' => $owner->obj('ID')->forTemplate() ] ); $tags[] = HTML::createTag( 'meta', [ 'name' => 'x-cms-edit-link', 'content' => $owner->obj('CMSEditLink')->forTemplate() ] ); } $tags = implode("\n", $tags); if ($owner->ExtraMeta) { $tags .= $owner->obj('ExtraMeta')->forTemplate(); } $owner->extend('updateMetaTags', $tags); return $tags; }
[ "public", "function", "MetaTags", "(", "$", "includeTitle", "=", "true", ")", "{", "$", "tags", "=", "[", "]", ";", "$", "owner", "=", "$", "this", "->", "getOwner", "(", ")", ";", "if", "(", "$", "includeTitle", "&&", "strtolower", "(", "$", "includeTitle", ")", "!=", "'false'", ")", "{", "$", "tags", "[", "]", "=", "HTML", "::", "createTag", "(", "'title'", ",", "[", "]", ",", "$", "owner", "->", "obj", "(", "'Title'", ")", "->", "forTemplate", "(", ")", ")", ";", "}", "$", "generator", "=", "trim", "(", "Config", "::", "inst", "(", ")", "->", "get", "(", "self", "::", "class", ",", "'meta_generator'", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "generator", ")", ")", "{", "$", "tags", "[", "]", "=", "HTML", "::", "createTag", "(", "'meta'", ",", "array", "(", "'name'", "=>", "'generator'", ",", "'content'", "=>", "$", "generator", ",", ")", ")", ";", "}", "$", "charset", "=", "ContentNegotiator", "::", "config", "(", ")", "->", "uninherited", "(", "'encoding'", ")", ";", "$", "tags", "[", "]", "=", "HTML", "::", "createTag", "(", "'meta'", ",", "array", "(", "'http-equiv'", "=>", "'Content-Type'", ",", "'content'", "=>", "'text/html; charset='", ".", "$", "charset", ",", ")", ")", ";", "if", "(", "$", "owner", "->", "MetaDescription", ")", "{", "$", "tags", "[", "]", "=", "HTML", "::", "createTag", "(", "'meta'", ",", "array", "(", "'name'", "=>", "'description'", ",", "'content'", "=>", "$", "owner", "->", "MetaDescription", ",", ")", ")", ";", "}", "if", "(", "Permission", "::", "check", "(", "'CMS_ACCESS_CMSMain'", ")", "&&", "$", "owner", "->", "exists", "(", ")", ")", "{", "$", "tags", "[", "]", "=", "HTML", "::", "createTag", "(", "'meta'", ",", "[", "'name'", "=>", "'x-page-id'", ",", "'content'", "=>", "$", "owner", "->", "obj", "(", "'ID'", ")", "->", "forTemplate", "(", ")", "]", ")", ";", "$", "tags", "[", "]", "=", "HTML", "::", "createTag", "(", "'meta'", ",", "[", "'name'", "=>", "'x-cms-edit-link'", ",", "'content'", "=>", "$", "owner", "->", "obj", "(", "'CMSEditLink'", ")", "->", "forTemplate", "(", ")", "]", ")", ";", "}", "$", "tags", "=", "implode", "(", "\"\\n\"", ",", "$", "tags", ")", ";", "if", "(", "$", "owner", "->", "ExtraMeta", ")", "{", "$", "tags", ".=", "$", "owner", "->", "obj", "(", "'ExtraMeta'", ")", "->", "forTemplate", "(", ")", ";", "}", "$", "owner", "->", "extend", "(", "'updateMetaTags'", ",", "$", "tags", ")", ";", "return", "$", "tags", ";", "}" ]
Return the title, description, keywords and language metatags. NOTE: Shamelessley taken from SiteTree @param bool $includeTitle Show default <title>-tag, set to false for custom templating @return string The XHTML metatags
[ "Return", "the", "title", "description", "keywords", "and", "language", "metatags", ".", "NOTE", ":", "Shamelessley", "taken", "from", "SiteTree" ]
train
https://github.com/silvercommerce/catalogue-frontend/blob/671f1e32bf6bc6eb193c6608ae904cd055540cc4/src/extensions/CatalogueExtension.php#L255-L313
xinix-technology/norm
src/Norm/Cursor.php
Cursor.sort
public function sort(array $sorts = array()) { if (func_num_args() === 0) { return $this->sorts; } $this->sorts = array(); foreach ($sorts as $key => $value) { if ($key[0] === '$') { $key[0] = '_'; } $this->sorts[$key] = $value; } return $this; }
php
public function sort(array $sorts = array()) { if (func_num_args() === 0) { return $this->sorts; } $this->sorts = array(); foreach ($sorts as $key => $value) { if ($key[0] === '$') { $key[0] = '_'; } $this->sorts[$key] = $value; } return $this; }
[ "public", "function", "sort", "(", "array", "$", "sorts", "=", "array", "(", ")", ")", "{", "if", "(", "func_num_args", "(", ")", "===", "0", ")", "{", "return", "$", "this", "->", "sorts", ";", "}", "$", "this", "->", "sorts", "=", "array", "(", ")", ";", "foreach", "(", "$", "sorts", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "key", "[", "0", "]", "===", "'$'", ")", "{", "$", "key", "[", "0", "]", "=", "'_'", ";", "}", "$", "this", "->", "sorts", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "this", ";", "}" ]
When argument specified will set new sorts otherwise will return existing sorts @param array $sorts @return mixed When argument specified will return sorts otherwise return chainable object
[ "When", "argument", "specified", "will", "set", "new", "sorts", "otherwise", "will", "return", "existing", "sorts" ]
train
https://github.com/xinix-technology/norm/blob/c357f7d3a75d05324dd84b8f6a968a094c53d603/src/Norm/Cursor.php#L167-L184
xinix-technology/norm
src/Norm/Cursor.php
Cursor.match
public function match($q) { if (is_null($q)) { return $this; } $orCriteria = array(); $schema = $this->collection->schema(); if (empty($schema)) { throw new \Exception('[Norm\Cursor] Cannot use match for schemaless collection'); } foreach ($schema as $key => $value) { $orCriteria[] = array($key.'!like' => $q); } $this->criteria = $this->translateCriteria(array('!or' => $orCriteria)); return $this; }
php
public function match($q) { if (is_null($q)) { return $this; } $orCriteria = array(); $schema = $this->collection->schema(); if (empty($schema)) { throw new \Exception('[Norm\Cursor] Cannot use match for schemaless collection'); } foreach ($schema as $key => $value) { $orCriteria[] = array($key.'!like' => $q); } $this->criteria = $this->translateCriteria(array('!or' => $orCriteria)); return $this; }
[ "public", "function", "match", "(", "$", "q", ")", "{", "if", "(", "is_null", "(", "$", "q", ")", ")", "{", "return", "$", "this", ";", "}", "$", "orCriteria", "=", "array", "(", ")", ";", "$", "schema", "=", "$", "this", "->", "collection", "->", "schema", "(", ")", ";", "if", "(", "empty", "(", "$", "schema", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'[Norm\\Cursor] Cannot use match for schemaless collection'", ")", ";", "}", "foreach", "(", "$", "schema", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "orCriteria", "[", "]", "=", "array", "(", "$", "key", ".", "'!like'", "=>", "$", "q", ")", ";", "}", "$", "this", "->", "criteria", "=", "$", "this", "->", "translateCriteria", "(", "array", "(", "'!or'", "=>", "$", "orCriteria", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set query to match on every field exists in schema. Beware this will override criteria @param string $q String to query @return \Norm\Cursor Chainable object
[ "Set", "query", "to", "match", "on", "every", "field", "exists", "in", "schema", ".", "Beware", "this", "will", "override", "criteria" ]
train
https://github.com/xinix-technology/norm/blob/c357f7d3a75d05324dd84b8f6a968a094c53d603/src/Norm/Cursor.php#L193-L214
xinix-technology/norm
src/Norm/Cursor.php
Cursor.toArray
public function toArray($plain = false) { $result = array(); foreach ($this as $key => $value) { if ($plain) { $result[] = $value->toArray(); } else { $result[] = $this->connection->unmarshall($value); } } return $result; }
php
public function toArray($plain = false) { $result = array(); foreach ($this as $key => $value) { if ($plain) { $result[] = $value->toArray(); } else { $result[] = $this->connection->unmarshall($value); } } return $result; }
[ "public", "function", "toArray", "(", "$", "plain", "=", "false", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "plain", ")", "{", "$", "result", "[", "]", "=", "$", "value", "->", "toArray", "(", ")", ";", "}", "else", "{", "$", "result", "[", "]", "=", "$", "this", "->", "connection", "->", "unmarshall", "(", "$", "value", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Extract data into array of models. @param boolean $plain When true will return array of associative array. @return array
[ "Extract", "data", "into", "array", "of", "models", "." ]
train
https://github.com/xinix-technology/norm/blob/c357f7d3a75d05324dd84b8f6a968a094c53d603/src/Norm/Cursor.php#L223-L236
matks/MarkdownBlogBundle
Blog/Factory/LibraryFactory.php
LibraryFactory.buildPost
private function buildPost($filename) { $filepath = $this->postsDirectory . $filename; $publishDate = $this->computeFilePublishDate($filepath); $name = basename($filename, '.md'); $post = new Post($filepath, $name, $publishDate); return $post; }
php
private function buildPost($filename) { $filepath = $this->postsDirectory . $filename; $publishDate = $this->computeFilePublishDate($filepath); $name = basename($filename, '.md'); $post = new Post($filepath, $name, $publishDate); return $post; }
[ "private", "function", "buildPost", "(", "$", "filename", ")", "{", "$", "filepath", "=", "$", "this", "->", "postsDirectory", ".", "$", "filename", ";", "$", "publishDate", "=", "$", "this", "->", "computeFilePublishDate", "(", "$", "filepath", ")", ";", "$", "name", "=", "basename", "(", "$", "filename", ",", "'.md'", ")", ";", "$", "post", "=", "new", "Post", "(", "$", "filepath", ",", "$", "name", ",", "$", "publishDate", ")", ";", "return", "$", "post", ";", "}" ]
@param string $filename @return Post
[ "@param", "string", "$filename" ]
train
https://github.com/matks/MarkdownBlogBundle/blob/b3438f143ece5e926b891d8f481dba35948b05fb/Blog/Factory/LibraryFactory.php#L71-L80
matks/MarkdownBlogBundle
Blog/Factory/LibraryFactory.php
LibraryFactory.buildPostFromRegisterEntry
private function buildPostFromRegisterEntry($filename, RegisterEntry $entry) { $filepath = $this->postsDirectory . $filename; if (null !== $entry->getPublishDate()) { $publishDate = $entry->getPublishDate(); } else { $publishDate = $this->computeFilePublishDate($filepath); } if (null !== $entry->getAlias()) { $name = $entry->getAlias(); } else { $name = basename($filename, '.md'); } if ($entry->getBlogType() === Post::TYPE_EXTERNAL) { $post = new ExternalPost( $filepath, $name, $publishDate, $entry->getCategory(), $entry->getTags(), $entry->getUrl() ); } else { $post = new Post( $filepath, $name, $publishDate, $entry->getCategory(), $entry->getTags() ); } return $post; }
php
private function buildPostFromRegisterEntry($filename, RegisterEntry $entry) { $filepath = $this->postsDirectory . $filename; if (null !== $entry->getPublishDate()) { $publishDate = $entry->getPublishDate(); } else { $publishDate = $this->computeFilePublishDate($filepath); } if (null !== $entry->getAlias()) { $name = $entry->getAlias(); } else { $name = basename($filename, '.md'); } if ($entry->getBlogType() === Post::TYPE_EXTERNAL) { $post = new ExternalPost( $filepath, $name, $publishDate, $entry->getCategory(), $entry->getTags(), $entry->getUrl() ); } else { $post = new Post( $filepath, $name, $publishDate, $entry->getCategory(), $entry->getTags() ); } return $post; }
[ "private", "function", "buildPostFromRegisterEntry", "(", "$", "filename", ",", "RegisterEntry", "$", "entry", ")", "{", "$", "filepath", "=", "$", "this", "->", "postsDirectory", ".", "$", "filename", ";", "if", "(", "null", "!==", "$", "entry", "->", "getPublishDate", "(", ")", ")", "{", "$", "publishDate", "=", "$", "entry", "->", "getPublishDate", "(", ")", ";", "}", "else", "{", "$", "publishDate", "=", "$", "this", "->", "computeFilePublishDate", "(", "$", "filepath", ")", ";", "}", "if", "(", "null", "!==", "$", "entry", "->", "getAlias", "(", ")", ")", "{", "$", "name", "=", "$", "entry", "->", "getAlias", "(", ")", ";", "}", "else", "{", "$", "name", "=", "basename", "(", "$", "filename", ",", "'.md'", ")", ";", "}", "if", "(", "$", "entry", "->", "getBlogType", "(", ")", "===", "Post", "::", "TYPE_EXTERNAL", ")", "{", "$", "post", "=", "new", "ExternalPost", "(", "$", "filepath", ",", "$", "name", ",", "$", "publishDate", ",", "$", "entry", "->", "getCategory", "(", ")", ",", "$", "entry", "->", "getTags", "(", ")", ",", "$", "entry", "->", "getUrl", "(", ")", ")", ";", "}", "else", "{", "$", "post", "=", "new", "Post", "(", "$", "filepath", ",", "$", "name", ",", "$", "publishDate", ",", "$", "entry", "->", "getCategory", "(", ")", ",", "$", "entry", "->", "getTags", "(", ")", ")", ";", "}", "return", "$", "post", ";", "}" ]
@param string $filename @param RegisterEntry $entry @return Post
[ "@param", "string", "$filename", "@param", "RegisterEntry", "$entry" ]
train
https://github.com/matks/MarkdownBlogBundle/blob/b3438f143ece5e926b891d8f481dba35948b05fb/Blog/Factory/LibraryFactory.php#L88-L124
matks/MarkdownBlogBundle
Blog/Factory/LibraryFactory.php
LibraryFactory.computeFilePublishDate
private function computeFilePublishDate($filepath) { $creationTimestamp = filectime($filepath); if (false === $creationTimestamp) { throw new \InvalidArgumentException("Could not get creation date of file $filepath"); } $creationDateTime = new \DateTime('@' . $creationTimestamp); return $creationDateTime->format('Y-m-d'); }
php
private function computeFilePublishDate($filepath) { $creationTimestamp = filectime($filepath); if (false === $creationTimestamp) { throw new \InvalidArgumentException("Could not get creation date of file $filepath"); } $creationDateTime = new \DateTime('@' . $creationTimestamp); return $creationDateTime->format('Y-m-d'); }
[ "private", "function", "computeFilePublishDate", "(", "$", "filepath", ")", "{", "$", "creationTimestamp", "=", "filectime", "(", "$", "filepath", ")", ";", "if", "(", "false", "===", "$", "creationTimestamp", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Could not get creation date of file $filepath\"", ")", ";", "}", "$", "creationDateTime", "=", "new", "\\", "DateTime", "(", "'@'", ".", "$", "creationTimestamp", ")", ";", "return", "$", "creationDateTime", "->", "format", "(", "'Y-m-d'", ")", ";", "}" ]
@param string $filepath @return string
[ "@param", "string", "$filepath" ]
train
https://github.com/matks/MarkdownBlogBundle/blob/b3438f143ece5e926b891d8f481dba35948b05fb/Blog/Factory/LibraryFactory.php#L167-L176
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/Sitemap/Priority.php
Zend_Validate_Sitemap_Priority.isValid
public function isValid($value) { $this->_setValue($value); if (!is_numeric($value)) { return false; } $value = (float)$value; return $value >= 0 && $value <= 1; }
php
public function isValid($value) { $this->_setValue($value); if (!is_numeric($value)) { return false; } $value = (float)$value; return $value >= 0 && $value <= 1; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "this", "->", "_setValue", "(", "$", "value", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "$", "value", "=", "(", "float", ")", "$", "value", ";", "return", "$", "value", ">=", "0", "&&", "$", "value", "<=", "1", ";", "}" ]
Validates if a string is valid as a sitemap priority @link http://www.sitemaps.org/protocol.php#prioritydef <priority> @param string $value value to validate @return boolean
[ "Validates", "if", "a", "string", "is", "valid", "as", "a", "sitemap", "priority" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/Sitemap/Priority.php#L63-L73
arsengoian/viper-framework
src/Viper/Core/Model/ModelConfig.php
ModelConfig.checkTableStructure
private function checkTableStructure() { $this -> runMigrations(); if ($this -> writeAllowed()) { $this -> createMissingColumns(); // TODO ADD foreign, primary keys and constraints } // Check column structure if ($this -> overwriteAllowed()) { $this -> checkColumnTypes(); // TODO edit column order so that it corresponds // TODO MODIFY keys and constraints } // Remove columns if ($this -> deleteAllowed()) { $this -> sanitizeColumns(); // TODO delete keys and constraints } }
php
private function checkTableStructure() { $this -> runMigrations(); if ($this -> writeAllowed()) { $this -> createMissingColumns(); // TODO ADD foreign, primary keys and constraints } // Check column structure if ($this -> overwriteAllowed()) { $this -> checkColumnTypes(); // TODO edit column order so that it corresponds // TODO MODIFY keys and constraints } // Remove columns if ($this -> deleteAllowed()) { $this -> sanitizeColumns(); // TODO delete keys and constraints } }
[ "private", "function", "checkTableStructure", "(", ")", "{", "$", "this", "->", "runMigrations", "(", ")", ";", "if", "(", "$", "this", "->", "writeAllowed", "(", ")", ")", "{", "$", "this", "->", "createMissingColumns", "(", ")", ";", "// TODO ADD foreign, primary keys and constraints", "}", "// Check column structure", "if", "(", "$", "this", "->", "overwriteAllowed", "(", ")", ")", "{", "$", "this", "->", "checkColumnTypes", "(", ")", ";", "// TODO edit column order so that it corresponds", "// TODO MODIFY keys and constraints", "}", "// Remove columns", "if", "(", "$", "this", "->", "deleteAllowed", "(", ")", ")", "{", "$", "this", "->", "sanitizeColumns", "(", ")", ";", "// TODO delete keys and constraints", "}", "}" ]
TODO if called upon error try various remedies in order to save time if the first one works
[ "TODO", "if", "called", "upon", "error", "try", "various", "remedies", "in", "order", "to", "save", "time", "if", "the", "first", "one", "works" ]
train
https://github.com/arsengoian/viper-framework/blob/22796c5cc219cae3ca0b4af370a347ba2acab0f2/src/Viper/Core/Model/ModelConfig.php#L254-L274
dafiti/datajet-client
src/Datajet/Resource/Product.php
Product.import
public function import(array $data) { $response = $this->client->post("{$this->uriImport}product/", [ 'json' => $data, 'query' => [ 'key' => $this->config['data']['key'], ], ]); $response = json_decode($response->getBody(), true); if (isset($response['affected']) && $response['affected'] > 0) { return true; } return false; }
php
public function import(array $data) { $response = $this->client->post("{$this->uriImport}product/", [ 'json' => $data, 'query' => [ 'key' => $this->config['data']['key'], ], ]); $response = json_decode($response->getBody(), true); if (isset($response['affected']) && $response['affected'] > 0) { return true; } return false; }
[ "public", "function", "import", "(", "array", "$", "data", ")", "{", "$", "response", "=", "$", "this", "->", "client", "->", "post", "(", "\"{$this->uriImport}product/\"", ",", "[", "'json'", "=>", "$", "data", ",", "'query'", "=>", "[", "'key'", "=>", "$", "this", "->", "config", "[", "'data'", "]", "[", "'key'", "]", ",", "]", ",", "]", ")", ";", "$", "response", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "if", "(", "isset", "(", "$", "response", "[", "'affected'", "]", ")", "&&", "$", "response", "[", "'affected'", "]", ">", "0", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Atomic product import. @param array $data A list of product to import @throws \GuzzleHttp\Exception\GuzzleException @return bool
[ "Atomic", "product", "import", "." ]
train
https://github.com/dafiti/datajet-client/blob/c8555362521690b95451d2006d891b30facd8a46/src/Datajet/Resource/Product.php#L65-L81
dafiti/datajet-client
src/Datajet/Resource/Product.php
Product.search
public function search(array $data) { if (!isset($data['size'])) { $data['size'] = 10; } $response = $this->client->post("{$this->uriSearch}search/", [ 'json' => $data, 'query' => [ 'key' => $this->config['search']['key'], ], ]); $response = json_decode($response->getBody(), true); return $response; }
php
public function search(array $data) { if (!isset($data['size'])) { $data['size'] = 10; } $response = $this->client->post("{$this->uriSearch}search/", [ 'json' => $data, 'query' => [ 'key' => $this->config['search']['key'], ], ]); $response = json_decode($response->getBody(), true); return $response; }
[ "public", "function", "search", "(", "array", "$", "data", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'size'", "]", ")", ")", "{", "$", "data", "[", "'size'", "]", "=", "10", ";", "}", "$", "response", "=", "$", "this", "->", "client", "->", "post", "(", "\"{$this->uriSearch}search/\"", ",", "[", "'json'", "=>", "$", "data", ",", "'query'", "=>", "[", "'key'", "=>", "$", "this", "->", "config", "[", "'search'", "]", "[", "'key'", "]", ",", "]", ",", "]", ")", ";", "$", "response", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "return", "$", "response", ";", "}" ]
Product Search. @param array $data Search parameters @throws \GuzzleHttp\Exception\GuzzleException @return array
[ "Product", "Search", "." ]
train
https://github.com/dafiti/datajet-client/blob/c8555362521690b95451d2006d891b30facd8a46/src/Datajet/Resource/Product.php#L92-L108
dafiti/datajet-client
src/Datajet/Resource/Product.php
Product.delete
public function delete($id) { $response = false; if (empty($id)) { throw new \InvalidArgumentException('ID Product cannot be empty'); } try { $apiResponse = $this->client->delete("{$this->uriImport}product/{$id}", [ 'query' => [ 'key' => $this->config['data']['key'], ], ]); $apiResponse = json_decode($apiResponse->getBody(), true); if (isset($apiResponse['affected']) && $apiResponse['affected'] > 0) { $response = true; } } catch (ClientException $e) { $response = false; } return $response; }
php
public function delete($id) { $response = false; if (empty($id)) { throw new \InvalidArgumentException('ID Product cannot be empty'); } try { $apiResponse = $this->client->delete("{$this->uriImport}product/{$id}", [ 'query' => [ 'key' => $this->config['data']['key'], ], ]); $apiResponse = json_decode($apiResponse->getBody(), true); if (isset($apiResponse['affected']) && $apiResponse['affected'] > 0) { $response = true; } } catch (ClientException $e) { $response = false; } return $response; }
[ "public", "function", "delete", "(", "$", "id", ")", "{", "$", "response", "=", "false", ";", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'ID Product cannot be empty'", ")", ";", "}", "try", "{", "$", "apiResponse", "=", "$", "this", "->", "client", "->", "delete", "(", "\"{$this->uriImport}product/{$id}\"", ",", "[", "'query'", "=>", "[", "'key'", "=>", "$", "this", "->", "config", "[", "'data'", "]", "[", "'key'", "]", ",", "]", ",", "]", ")", ";", "$", "apiResponse", "=", "json_decode", "(", "$", "apiResponse", "->", "getBody", "(", ")", ",", "true", ")", ";", "if", "(", "isset", "(", "$", "apiResponse", "[", "'affected'", "]", ")", "&&", "$", "apiResponse", "[", "'affected'", "]", ">", "0", ")", "{", "$", "response", "=", "true", ";", "}", "}", "catch", "(", "ClientException", "$", "e", ")", "{", "$", "response", "=", "false", ";", "}", "return", "$", "response", ";", "}" ]
Product Delete. @param string $id @return bool
[ "Product", "Delete", "." ]
train
https://github.com/dafiti/datajet-client/blob/c8555362521690b95451d2006d891b30facd8a46/src/Datajet/Resource/Product.php#L117-L141
OpenClassrooms/Akismet
src/Client/Impl/ApiClientImpl.php
ApiClientImpl.post
public function post($resource, array $params) { $params['blog'] = $this->blog; $response = $this->client->post($resource, ['form_params' => $params]); return $response->getBody()->getContents(); }
php
public function post($resource, array $params) { $params['blog'] = $this->blog; $response = $this->client->post($resource, ['form_params' => $params]); return $response->getBody()->getContents(); }
[ "public", "function", "post", "(", "$", "resource", ",", "array", "$", "params", ")", "{", "$", "params", "[", "'blog'", "]", "=", "$", "this", "->", "blog", ";", "$", "response", "=", "$", "this", "->", "client", "->", "post", "(", "$", "resource", ",", "[", "'form_params'", "=>", "$", "params", "]", ")", ";", "return", "$", "response", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/OpenClassrooms/Akismet/blob/b1bd35128f5dfe028481adf338d5eb752a09b90e/src/Client/Impl/ApiClientImpl.php#L42-L49
webforge-labs/psc-cms
lib/Psc/System/Deploy/ConfigureApacheTask.php
ConfigureApacheTask.addAlias
public function addAlias($location, $path) { $this->setVar('aliases', $this->getVar('aliases'). sprintf("\n Alias %s %s", $location , $this->replaceHelpers($path)) ); return $this; }
php
public function addAlias($location, $path) { $this->setVar('aliases', $this->getVar('aliases'). sprintf("\n Alias %s %s", $location , $this->replaceHelpers($path)) ); return $this; }
[ "public", "function", "addAlias", "(", "$", "location", ",", "$", "path", ")", "{", "$", "this", "->", "setVar", "(", "'aliases'", ",", "$", "this", "->", "getVar", "(", "'aliases'", ")", ".", "sprintf", "(", "\"\\n Alias %s %s\"", ",", "$", "location", ",", "$", "this", "->", "replaceHelpers", "(", "$", "path", ")", ")", ")", ";", "return", "$", "this", ";", "}" ]
Adds an Location alias $this->addAlias('/images /var/local/banane');
[ "Adds", "an", "Location", "alias" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/System/Deploy/ConfigureApacheTask.php#L157-L163
yuncms/framework
src/helpers/HtmlPurifier.php
HtmlPurifier.convertToUtf8
public static function convertToUtf8(string $string, HTMLPurifier_Config $config): string { return \HTMLPurifier_Encoder::convertToUTF8($string, $config, null); }
php
public static function convertToUtf8(string $string, HTMLPurifier_Config $config): string { return \HTMLPurifier_Encoder::convertToUTF8($string, $config, null); }
[ "public", "static", "function", "convertToUtf8", "(", "string", "$", "string", ",", "HTMLPurifier_Config", "$", "config", ")", ":", "string", "{", "return", "\\", "HTMLPurifier_Encoder", "::", "convertToUTF8", "(", "$", "string", ",", "$", "config", ",", "null", ")", ";", "}" ]
@param string $string @param HTMLPurifier_Config $config @return string
[ "@param", "string", "$string", "@param", "HTMLPurifier_Config", "$config" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/HtmlPurifier.php#L36-L39
yuncms/framework
src/helpers/HtmlPurifier.php
HtmlPurifier.configure
public static function configure($config) { // Don't set alt attributes to filenames by default $config->set('Attr.DefaultImageAlt', ''); $config->set('Attr.DefaultInvalidImageAlt', ''); // Add support for some HTML5 elements // see http://htmlpurifier.org/phorum/read.php?3,6731,6731 $config->set('HTML.DefinitionID', '1'); // see https://github.com/mewebstudio/Purifier/issues/32#issuecomment-182502361 // see https://gist.github.com/lluchs/3303693 if ($def = $config->maybeGetRawHTMLDefinition()) { // Content model actually excludes several tags, not modelled here $def->addElement('address', 'Block', 'Flow', 'Common'); $def->addElement('hgroup', 'Block', 'Required: h1 | h2 | h3 | h4 | h5 | h6', 'Common'); // http://developers.whatwg.org/grouping-content.html $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common'); $def->addElement('figcaption', 'Inline', 'Flow', 'Common'); // http://developers.whatwg.org/text-level-semantics.html $def->addElement('s', 'Inline', 'Inline', 'Common'); $def->addElement('var', 'Inline', 'Inline', 'Common'); $def->addElement('sub', 'Inline', 'Inline', 'Common'); $def->addElement('sup', 'Inline', 'Inline', 'Common'); $def->addElement('mark', 'Inline', 'Inline', 'Common'); $def->addElement('wbr', 'Inline', 'Empty', 'Core'); // http://developers.whatwg.org/edits.html $def->addElement('ins', 'Block', 'Flow', 'Common', ['cite' => 'URI', 'datetime' => 'CDATA']); $def->addElement('del', 'Block', 'Flow', 'Common', ['cite' => 'URI', 'datetime' => 'CDATA']); } }
php
public static function configure($config) { // Don't set alt attributes to filenames by default $config->set('Attr.DefaultImageAlt', ''); $config->set('Attr.DefaultInvalidImageAlt', ''); // Add support for some HTML5 elements // see http://htmlpurifier.org/phorum/read.php?3,6731,6731 $config->set('HTML.DefinitionID', '1'); // see https://github.com/mewebstudio/Purifier/issues/32#issuecomment-182502361 // see https://gist.github.com/lluchs/3303693 if ($def = $config->maybeGetRawHTMLDefinition()) { // Content model actually excludes several tags, not modelled here $def->addElement('address', 'Block', 'Flow', 'Common'); $def->addElement('hgroup', 'Block', 'Required: h1 | h2 | h3 | h4 | h5 | h6', 'Common'); // http://developers.whatwg.org/grouping-content.html $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common'); $def->addElement('figcaption', 'Inline', 'Flow', 'Common'); // http://developers.whatwg.org/text-level-semantics.html $def->addElement('s', 'Inline', 'Inline', 'Common'); $def->addElement('var', 'Inline', 'Inline', 'Common'); $def->addElement('sub', 'Inline', 'Inline', 'Common'); $def->addElement('sup', 'Inline', 'Inline', 'Common'); $def->addElement('mark', 'Inline', 'Inline', 'Common'); $def->addElement('wbr', 'Inline', 'Empty', 'Core'); // http://developers.whatwg.org/edits.html $def->addElement('ins', 'Block', 'Flow', 'Common', ['cite' => 'URI', 'datetime' => 'CDATA']); $def->addElement('del', 'Block', 'Flow', 'Common', ['cite' => 'URI', 'datetime' => 'CDATA']); } }
[ "public", "static", "function", "configure", "(", "$", "config", ")", "{", "// Don't set alt attributes to filenames by default", "$", "config", "->", "set", "(", "'Attr.DefaultImageAlt'", ",", "''", ")", ";", "$", "config", "->", "set", "(", "'Attr.DefaultInvalidImageAlt'", ",", "''", ")", ";", "// Add support for some HTML5 elements", "// see http://htmlpurifier.org/phorum/read.php?3,6731,6731", "$", "config", "->", "set", "(", "'HTML.DefinitionID'", ",", "'1'", ")", ";", "// see https://github.com/mewebstudio/Purifier/issues/32#issuecomment-182502361", "// see https://gist.github.com/lluchs/3303693", "if", "(", "$", "def", "=", "$", "config", "->", "maybeGetRawHTMLDefinition", "(", ")", ")", "{", "// Content model actually excludes several tags, not modelled here", "$", "def", "->", "addElement", "(", "'address'", ",", "'Block'", ",", "'Flow'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'hgroup'", ",", "'Block'", ",", "'Required: h1 | h2 | h3 | h4 | h5 | h6'", ",", "'Common'", ")", ";", "// http://developers.whatwg.org/grouping-content.html", "$", "def", "->", "addElement", "(", "'figure'", ",", "'Block'", ",", "'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'figcaption'", ",", "'Inline'", ",", "'Flow'", ",", "'Common'", ")", ";", "// http://developers.whatwg.org/text-level-semantics.html", "$", "def", "->", "addElement", "(", "'s'", ",", "'Inline'", ",", "'Inline'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'var'", ",", "'Inline'", ",", "'Inline'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'sub'", ",", "'Inline'", ",", "'Inline'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'sup'", ",", "'Inline'", ",", "'Inline'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'mark'", ",", "'Inline'", ",", "'Inline'", ",", "'Common'", ")", ";", "$", "def", "->", "addElement", "(", "'wbr'", ",", "'Inline'", ",", "'Empty'", ",", "'Core'", ")", ";", "// http://developers.whatwg.org/edits.html", "$", "def", "->", "addElement", "(", "'ins'", ",", "'Block'", ",", "'Flow'", ",", "'Common'", ",", "[", "'cite'", "=>", "'URI'", ",", "'datetime'", "=>", "'CDATA'", "]", ")", ";", "$", "def", "->", "addElement", "(", "'del'", ",", "'Block'", ",", "'Flow'", ",", "'Common'", ",", "[", "'cite'", "=>", "'URI'", ",", "'datetime'", "=>", "'CDATA'", "]", ")", ";", "}", "}" ]
configure @param HTMLPurifier_Config $config The config to use for HtmlPurifier. @return void
[ "configure" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/HtmlPurifier.php#L47-L79
claroline/ForumBundle
Repository/ForumRepository.php
ForumRepository.findSubjects
public function findSubjects(Category $category, $getQuery = false) { $dql = " SELECT s.id as id, COUNT(m_count.id) AS count_messages, MAX(m.creationDate) AS last_message_created, s.id as subjectId, s.title as title, s.isSticked as isSticked, s.author as subject_author, subjectCreator.lastName as subject_creator_lastname, subjectCreator.firstName as subject_creator_firstname, subjectCreator.id as subject_creator_id, lastUser.lastName as last_message_creator_lastname, lastUser.firstName as last_message_creator_firstname, s.creationDate as subject_created, s.isClosed as is_closed FROM Claroline\ForumBundle\Entity\Subject s JOIN s.messages m_count JOIN s.creator subjectCreator JOIN s.category category JOIN s.messages m JOIN m.creator lastUser WITH lastUser.id = ( SELECT lcu.id FROM Claroline\ForumBundle\Entity\Message m2 JOIN m2.subject s2 JOIN m2.creator lcu JOIN s2.category c2 WHERE NOT EXISTS ( SELECT m3 FROM Claroline\ForumBundle\Entity\Message m3 JOIN m3.subject s3 WHERE s2.id = s3.id AND m2.id < m3.id ) and c2.id = :categoryId and m2.id = m.id ) WHERE category.id = :categoryId GROUP BY s.id, subjectCreator.lastName, subjectCreator.firstName, lastUser.lastName, lastUser.firstName ORDER BY isSticked DESC, last_message_created DESC "; $query = $this->_em->createQuery($dql); $query->setParameter('categoryId', $category->getId()); return ($getQuery) ? $query: $query->getResult(); }
php
public function findSubjects(Category $category, $getQuery = false) { $dql = " SELECT s.id as id, COUNT(m_count.id) AS count_messages, MAX(m.creationDate) AS last_message_created, s.id as subjectId, s.title as title, s.isSticked as isSticked, s.author as subject_author, subjectCreator.lastName as subject_creator_lastname, subjectCreator.firstName as subject_creator_firstname, subjectCreator.id as subject_creator_id, lastUser.lastName as last_message_creator_lastname, lastUser.firstName as last_message_creator_firstname, s.creationDate as subject_created, s.isClosed as is_closed FROM Claroline\ForumBundle\Entity\Subject s JOIN s.messages m_count JOIN s.creator subjectCreator JOIN s.category category JOIN s.messages m JOIN m.creator lastUser WITH lastUser.id = ( SELECT lcu.id FROM Claroline\ForumBundle\Entity\Message m2 JOIN m2.subject s2 JOIN m2.creator lcu JOIN s2.category c2 WHERE NOT EXISTS ( SELECT m3 FROM Claroline\ForumBundle\Entity\Message m3 JOIN m3.subject s3 WHERE s2.id = s3.id AND m2.id < m3.id ) and c2.id = :categoryId and m2.id = m.id ) WHERE category.id = :categoryId GROUP BY s.id, subjectCreator.lastName, subjectCreator.firstName, lastUser.lastName, lastUser.firstName ORDER BY isSticked DESC, last_message_created DESC "; $query = $this->_em->createQuery($dql); $query->setParameter('categoryId', $category->getId()); return ($getQuery) ? $query: $query->getResult(); }
[ "public", "function", "findSubjects", "(", "Category", "$", "category", ",", "$", "getQuery", "=", "false", ")", "{", "$", "dql", "=", "\"\n SELECT s.id as id,\n COUNT(m_count.id) AS count_messages,\n MAX(m.creationDate) AS last_message_created,\n s.id as subjectId,\n s.title as title,\n s.isSticked as isSticked,\n s.author as subject_author,\n subjectCreator.lastName as subject_creator_lastname,\n subjectCreator.firstName as subject_creator_firstname,\n subjectCreator.id as subject_creator_id,\n lastUser.lastName as last_message_creator_lastname,\n lastUser.firstName as last_message_creator_firstname,\n s.creationDate as subject_created,\n s.isClosed as is_closed\n FROM Claroline\\ForumBundle\\Entity\\Subject s\n JOIN s.messages m_count\n JOIN s.creator subjectCreator\n JOIN s.category category\n JOIN s.messages m\n JOIN m.creator lastUser WITH lastUser.id =\n (\n SELECT lcu.id FROM Claroline\\ForumBundle\\Entity\\Message m2\n JOIN m2.subject s2\n JOIN m2.creator lcu\n JOIN s2.category c2\n WHERE NOT EXISTS\n (\n SELECT m3 FROM Claroline\\ForumBundle\\Entity\\Message m3\n JOIN m3.subject s3\n WHERE s2.id = s3.id\n AND m2.id < m3.id\n )\n and c2.id = :categoryId\n and m2.id = m.id\n )\n WHERE category.id = :categoryId\n GROUP BY s.id, subjectCreator.lastName, subjectCreator.firstName, lastUser.lastName, lastUser.firstName\n ORDER BY isSticked DESC, last_message_created DESC\n \"", ";", "$", "query", "=", "$", "this", "->", "_em", "->", "createQuery", "(", "$", "dql", ")", ";", "$", "query", "->", "setParameter", "(", "'categoryId'", ",", "$", "category", "->", "getId", "(", ")", ")", ";", "return", "(", "$", "getQuery", ")", "?", "$", "query", ":", "$", "query", "->", "getResult", "(", ")", ";", "}" ]
Deep magic goes here. Gets a subject with some of its last messages datas. @param ResourceInstance $forum @return type
[ "Deep", "magic", "goes", "here", ".", "Gets", "a", "subject", "with", "some", "of", "its", "last", "messages", "datas", "." ]
train
https://github.com/claroline/ForumBundle/blob/bd85dfd870cacee541ea94fec8e59744bf90eaf4/Repository/ForumRepository.php#L30-L76
webforge-labs/psc-cms
lib/Psc/CMS/Module.php
Module.dispatchBootstrapped
public function dispatchBootstrapped() { PSC::getEventManager()->dispatchEvent('Psc.ModuleBootstrapped', NULL, $this); PSC::getEventManager()->dispatchEvent('Psc.'.$this->getName().'.ModuleBootstrapped', NULL, $this); }
php
public function dispatchBootstrapped() { PSC::getEventManager()->dispatchEvent('Psc.ModuleBootstrapped', NULL, $this); PSC::getEventManager()->dispatchEvent('Psc.'.$this->getName().'.ModuleBootstrapped', NULL, $this); }
[ "public", "function", "dispatchBootstrapped", "(", ")", "{", "PSC", "::", "getEventManager", "(", ")", "->", "dispatchEvent", "(", "'Psc.ModuleBootstrapped'", ",", "NULL", ",", "$", "this", ")", ";", "PSC", "::", "getEventManager", "(", ")", "->", "dispatchEvent", "(", "'Psc.'", ".", "$", "this", "->", "getName", "(", ")", ".", "'.ModuleBootstrapped'", ",", "NULL", ",", "$", "this", ")", ";", "}" ]
Sollte unbedingt nach bootstrap() aufgerufen werden
[ "Sollte", "unbedingt", "nach", "bootstrap", "()", "aufgerufen", "werden" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Module.php#L134-L137
webforge-labs/psc-cms
lib/Psc/Code/AST/LParameters.php
LParameters.addParameter
public function addParameter(LParameter $parameter) { $this->parameters->set($parameter->getName(), $parameter); return $this; }
php
public function addParameter(LParameter $parameter) { $this->parameters->set($parameter->getName(), $parameter); return $this; }
[ "public", "function", "addParameter", "(", "LParameter", "$", "parameter", ")", "{", "$", "this", "->", "parameters", "->", "set", "(", "$", "parameter", "->", "getName", "(", ")", ",", "$", "parameter", ")", ";", "return", "$", "this", ";", "}" ]
Fügt einen Parameter hinzu @param LParamter $parameter @chainable
[ "Fügt", "einen", "Parameter", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/AST/LParameters.php#L51-L54
djgadd/themosis-illuminate
src/Mail/MailServiceProvider.php
MailServiceProvider.registerMarkdownRenderer
protected function registerMarkdownRenderer() { $this->app->singleton(Markdown::class, function ($app) { $config = $app->make('config'); return new Markdown($app->make('view'), [ 'theme' => $config->get('mail.markdown.theme', 'default'), 'paths' => $config->get('mail.markdown.paths', []), ]); }); }
php
protected function registerMarkdownRenderer() { $this->app->singleton(Markdown::class, function ($app) { $config = $app->make('config'); return new Markdown($app->make('view'), [ 'theme' => $config->get('mail.markdown.theme', 'default'), 'paths' => $config->get('mail.markdown.paths', []), ]); }); }
[ "protected", "function", "registerMarkdownRenderer", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "Markdown", "::", "class", ",", "function", "(", "$", "app", ")", "{", "$", "config", "=", "$", "app", "->", "make", "(", "'config'", ")", ";", "return", "new", "Markdown", "(", "$", "app", "->", "make", "(", "'view'", ")", ",", "[", "'theme'", "=>", "$", "config", "->", "get", "(", "'mail.markdown.theme'", ",", "'default'", ")", ",", "'paths'", "=>", "$", "config", "->", "get", "(", "'mail.markdown.paths'", ",", "[", "]", ")", ",", "]", ")", ";", "}", ")", ";", "}" ]
Register the Markdown renderer instance. @return void
[ "Register", "the", "Markdown", "renderer", "instance", "." ]
train
https://github.com/djgadd/themosis-illuminate/blob/13ee4c3413cddd85a2f262ac361f35c81da0c53c/src/Mail/MailServiceProvider.php#L130-L140
forxer/tao
src/Tao/Utilities.php
Utilities.getMemoryUsageData
public function getMemoryUsageData() { if (null === $this->memoryUsageData) { $memoryUsage = memory_get_usage(); $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; $this->memoryUsageData = [ round($memoryUsage/pow(1024, ($i=floor(log($memoryUsage, 1024))) ), 2), $unit[$i] ]; } return $this->memoryUsageData; }
php
public function getMemoryUsageData() { if (null === $this->memoryUsageData) { $memoryUsage = memory_get_usage(); $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; $this->memoryUsageData = [ round($memoryUsage/pow(1024, ($i=floor(log($memoryUsage, 1024))) ), 2), $unit[$i] ]; } return $this->memoryUsageData; }
[ "public", "function", "getMemoryUsageData", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "memoryUsageData", ")", "{", "$", "memoryUsage", "=", "memory_get_usage", "(", ")", ";", "$", "unit", "=", "[", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", "]", ";", "$", "this", "->", "memoryUsageData", "=", "[", "round", "(", "$", "memoryUsage", "/", "pow", "(", "1024", ",", "(", "$", "i", "=", "floor", "(", "log", "(", "$", "memoryUsage", ",", "1024", ")", ")", ")", ")", ",", "2", ")", ",", "$", "unit", "[", "$", "i", "]", "]", ";", "}", "return", "$", "this", "->", "memoryUsageData", ";", "}" ]
Return the application memory usage data. @return array
[ "Return", "the", "application", "memory", "usage", "data", "." ]
train
https://github.com/forxer/tao/blob/b5e9109c244a29a72403ae6a58633ab96a67c660/src/Tao/Utilities.php#L68-L83
forxer/tao
src/Tao/Utilities.php
Utilities.setConfiguration
public function setConfiguration(array $config = []) { # Merge config with default values $config = $config + $this->getDefaultConfiguration(); # If debug mode, store config data for debug purpose if (!empty($config['debug'])) { $this->config = $config; } return $config; }
php
public function setConfiguration(array $config = []) { # Merge config with default values $config = $config + $this->getDefaultConfiguration(); # If debug mode, store config data for debug purpose if (!empty($config['debug'])) { $this->config = $config; } return $config; }
[ "public", "function", "setConfiguration", "(", "array", "$", "config", "=", "[", "]", ")", "{", "# Merge config with default values", "$", "config", "=", "$", "config", "+", "$", "this", "->", "getDefaultConfiguration", "(", ")", ";", "# If debug mode, store config data for debug purpose", "if", "(", "!", "empty", "(", "$", "config", "[", "'debug'", "]", ")", ")", "{", "$", "this", "->", "config", "=", "$", "config", ";", "}", "return", "$", "config", ";", "}" ]
Return application configuration values. @param array $config @return array
[ "Return", "application", "configuration", "values", "." ]
train
https://github.com/forxer/tao/blob/b5e9109c244a29a72403ae6a58633ab96a67c660/src/Tao/Utilities.php#L156-L167
dreamfactorysoftware/df-file
src/Components/DfFtpAdapter.php
DfFtpAdapter.listDirectoryContentsRecursive
protected function listDirectoryContentsRecursive($directory) { $listing = $this->normalizeListing($this->ftpRawlist('-aln', $directory) ?: [], $directory); $output = []; foreach ($listing as $directory) { $output[] = $directory; if ($directory['type'] !== 'dir') { continue; } $output = array_merge($output, $this->listDirectoryContentsRecursive($directory['path'])); } return $output; }
php
protected function listDirectoryContentsRecursive($directory) { $listing = $this->normalizeListing($this->ftpRawlist('-aln', $directory) ?: [], $directory); $output = []; foreach ($listing as $directory) { $output[] = $directory; if ($directory['type'] !== 'dir') { continue; } $output = array_merge($output, $this->listDirectoryContentsRecursive($directory['path'])); } return $output; }
[ "protected", "function", "listDirectoryContentsRecursive", "(", "$", "directory", ")", "{", "$", "listing", "=", "$", "this", "->", "normalizeListing", "(", "$", "this", "->", "ftpRawlist", "(", "'-aln'", ",", "$", "directory", ")", "?", ":", "[", "]", ",", "$", "directory", ")", ";", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "listing", "as", "$", "directory", ")", "{", "$", "output", "[", "]", "=", "$", "directory", ";", "if", "(", "$", "directory", "[", "'type'", "]", "!==", "'dir'", ")", "{", "continue", ";", "}", "$", "output", "=", "array_merge", "(", "$", "output", ",", "$", "this", "->", "listDirectoryContentsRecursive", "(", "$", "directory", "[", "'path'", "]", ")", ")", ";", "}", "return", "$", "output", ";", "}" ]
@inheritdoc @param string $directory
[ "@inheritdoc" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/DfFtpAdapter.php#L14-L29
dreamfactorysoftware/df-file
src/Components/DfFtpAdapter.php
DfFtpAdapter.getMetadata
public function getMetadata($path) { $connection = $this->getConnection(); if ($path === '') { return ['type' => 'dir', 'path' => '']; } if (@ftp_chdir($connection, $path) === true) { $this->setConnectionRoot(); return ['type' => 'dir', 'path' => $path]; } $listing = $this->ftpRawlist('-A', str_replace('*', '\\*', $path)); if (empty($listing) || in_array('total 0', $listing, true)) { return false; } if (preg_match('/.* not found/', $listing[0])) { return false; } if (preg_match('/^total [0-9]*$/', $listing[0])) { array_shift($listing); } $filename = basename($path); $basePath = str_replace($filename, null, $path); $basePath = rtrim($basePath, '/'); return $this->normalizeObject($listing[0], $basePath); }
php
public function getMetadata($path) { $connection = $this->getConnection(); if ($path === '') { return ['type' => 'dir', 'path' => '']; } if (@ftp_chdir($connection, $path) === true) { $this->setConnectionRoot(); return ['type' => 'dir', 'path' => $path]; } $listing = $this->ftpRawlist('-A', str_replace('*', '\\*', $path)); if (empty($listing) || in_array('total 0', $listing, true)) { return false; } if (preg_match('/.* not found/', $listing[0])) { return false; } if (preg_match('/^total [0-9]*$/', $listing[0])) { array_shift($listing); } $filename = basename($path); $basePath = str_replace($filename, null, $path); $basePath = rtrim($basePath, '/'); return $this->normalizeObject($listing[0], $basePath); }
[ "public", "function", "getMetadata", "(", "$", "path", ")", "{", "$", "connection", "=", "$", "this", "->", "getConnection", "(", ")", ";", "if", "(", "$", "path", "===", "''", ")", "{", "return", "[", "'type'", "=>", "'dir'", ",", "'path'", "=>", "''", "]", ";", "}", "if", "(", "@", "ftp_chdir", "(", "$", "connection", ",", "$", "path", ")", "===", "true", ")", "{", "$", "this", "->", "setConnectionRoot", "(", ")", ";", "return", "[", "'type'", "=>", "'dir'", ",", "'path'", "=>", "$", "path", "]", ";", "}", "$", "listing", "=", "$", "this", "->", "ftpRawlist", "(", "'-A'", ",", "str_replace", "(", "'*'", ",", "'\\\\*'", ",", "$", "path", ")", ")", ";", "if", "(", "empty", "(", "$", "listing", ")", "||", "in_array", "(", "'total 0'", ",", "$", "listing", ",", "true", ")", ")", "{", "return", "false", ";", "}", "if", "(", "preg_match", "(", "'/.* not found/'", ",", "$", "listing", "[", "0", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "preg_match", "(", "'/^total [0-9]*$/'", ",", "$", "listing", "[", "0", "]", ")", ")", "{", "array_shift", "(", "$", "listing", ")", ";", "}", "$", "filename", "=", "basename", "(", "$", "path", ")", ";", "$", "basePath", "=", "str_replace", "(", "$", "filename", ",", "null", ",", "$", "path", ")", ";", "$", "basePath", "=", "rtrim", "(", "$", "basePath", ",", "'/'", ")", ";", "return", "$", "this", "->", "normalizeObject", "(", "$", "listing", "[", "0", "]", ",", "$", "basePath", ")", ";", "}" ]
@param string $path @return array|bool
[ "@param", "string", "$path" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/DfFtpAdapter.php#L36-L69
webforge-labs/psc-cms
lib/Psc/Doctrine/FlushSQLLogger.php
FlushSQLLogger.startQuery
public function startQuery($sql, array $params = null, array $types = null) { if ($params != NULL) { foreach ($params as $p) { try { if (is_array($p)) $p = Helper::implodeIdentifiers($p); } catch (\Exception $e) { $p = '[unconvertible array]'; } if (is_string($p)) $p = "'".\Webforge\Common\String::cut($p,50,'...')."'"; if ($p instanceof \DateTime) $p = $p->format('YDM-H:I'); $sql = preg_replace('/\?/',(string) $p, $sql, 1); // ersetze das erste ? mit dem parameter } } print $sql . PHP_EOL; flush(); }
php
public function startQuery($sql, array $params = null, array $types = null) { if ($params != NULL) { foreach ($params as $p) { try { if (is_array($p)) $p = Helper::implodeIdentifiers($p); } catch (\Exception $e) { $p = '[unconvertible array]'; } if (is_string($p)) $p = "'".\Webforge\Common\String::cut($p,50,'...')."'"; if ($p instanceof \DateTime) $p = $p->format('YDM-H:I'); $sql = preg_replace('/\?/',(string) $p, $sql, 1); // ersetze das erste ? mit dem parameter } } print $sql . PHP_EOL; flush(); }
[ "public", "function", "startQuery", "(", "$", "sql", ",", "array", "$", "params", "=", "null", ",", "array", "$", "types", "=", "null", ")", "{", "if", "(", "$", "params", "!=", "NULL", ")", "{", "foreach", "(", "$", "params", "as", "$", "p", ")", "{", "try", "{", "if", "(", "is_array", "(", "$", "p", ")", ")", "$", "p", "=", "Helper", "::", "implodeIdentifiers", "(", "$", "p", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "p", "=", "'[unconvertible array]'", ";", "}", "if", "(", "is_string", "(", "$", "p", ")", ")", "$", "p", "=", "\"'\"", ".", "\\", "Webforge", "\\", "Common", "\\", "String", "::", "cut", "(", "$", "p", ",", "50", ",", "'...'", ")", ".", "\"'\"", ";", "if", "(", "$", "p", "instanceof", "\\", "DateTime", ")", "$", "p", "=", "$", "p", "->", "format", "(", "'YDM-H:I'", ")", ";", "$", "sql", "=", "preg_replace", "(", "'/\\?/'", ",", "(", "string", ")", "$", "p", ",", "$", "sql", ",", "1", ")", ";", "// ersetze das erste ? mit dem parameter", "}", "}", "print", "$", "sql", ".", "PHP_EOL", ";", "flush", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/FlushSQLLogger.php#L10-L25
ixocreate/application
src/Http/ErrorHandling/Response/NotFoundHandler.php
NotFoundHandler.generateNotFoundPlainResponse
private function generateNotFoundPlainResponse(ServerRequestInterface $request) : ResponseInterface { $response = ($this->responseFactory)()->withStatus(StatusCodeInterface::STATUS_NOT_FOUND); $response->getBody() ->write(\sprintf( "Encountered a 404 Error, %s doesn't exist", (string) $request->getUri() )); return $response; }
php
private function generateNotFoundPlainResponse(ServerRequestInterface $request) : ResponseInterface { $response = ($this->responseFactory)()->withStatus(StatusCodeInterface::STATUS_NOT_FOUND); $response->getBody() ->write(\sprintf( "Encountered a 404 Error, %s doesn't exist", (string) $request->getUri() )); return $response; }
[ "private", "function", "generateNotFoundPlainResponse", "(", "ServerRequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "$", "response", "=", "(", "$", "this", "->", "responseFactory", ")", "(", ")", "->", "withStatus", "(", "StatusCodeInterface", "::", "STATUS_NOT_FOUND", ")", ";", "$", "response", "->", "getBody", "(", ")", "->", "write", "(", "\\", "sprintf", "(", "\"Encountered a 404 Error, %s doesn't exist\"", ",", "(", "string", ")", "$", "request", "->", "getUri", "(", ")", ")", ")", ";", "return", "$", "response", ";", "}" ]
Generates a plain text response indicating the request method and URI. @param ServerRequestInterface $request @return ResponseInterface
[ "Generates", "a", "plain", "text", "response", "indicating", "the", "request", "method", "and", "URI", "." ]
train
https://github.com/ixocreate/application/blob/6b0ef355ecf96af63d0dd5b901b4c9a5a69daf05/src/Http/ErrorHandling/Response/NotFoundHandler.php#L73-L83
ixocreate/application
src/Http/ErrorHandling/Response/NotFoundHandler.php
NotFoundHandler.generateTemplateResponse
private function generateTemplateResponse( Renderer $renderer, ServerRequestInterface $request ) : ResponseInterface { $response = ($this->responseFactory)()->withStatus(StatusCodeInterface::STATUS_NOT_FOUND); $response->getBody()->write( $renderer->render($this->template, ['request' => $request]) ); return $response; }
php
private function generateTemplateResponse( Renderer $renderer, ServerRequestInterface $request ) : ResponseInterface { $response = ($this->responseFactory)()->withStatus(StatusCodeInterface::STATUS_NOT_FOUND); $response->getBody()->write( $renderer->render($this->template, ['request' => $request]) ); return $response; }
[ "private", "function", "generateTemplateResponse", "(", "Renderer", "$", "renderer", ",", "ServerRequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "$", "response", "=", "(", "$", "this", "->", "responseFactory", ")", "(", ")", "->", "withStatus", "(", "StatusCodeInterface", "::", "STATUS_NOT_FOUND", ")", ";", "$", "response", "->", "getBody", "(", ")", "->", "write", "(", "$", "renderer", "->", "render", "(", "$", "this", "->", "template", ",", "[", "'request'", "=>", "$", "request", "]", ")", ")", ";", "return", "$", "response", ";", "}" ]
Generates a response using a template. Template will receive the current request via the "request" variable. @param Renderer $renderer @param ServerRequestInterface $request @return ResponseInterface
[ "Generates", "a", "response", "using", "a", "template", "." ]
train
https://github.com/ixocreate/application/blob/6b0ef355ecf96af63d0dd5b901b4c9a5a69daf05/src/Http/ErrorHandling/Response/NotFoundHandler.php#L93-L103
yuncms/framework
src/admin/behaviors/LoginAttemptBehavior.php
LoginAttemptBehavior.beforeValidate
public function beforeValidate() { if ($this->_attempt = AdminLoginAttempt::findByKey($this->getKey())) { if ($this->_attempt->amount >= $this->attempts) { $this->owner->addError($this->usernameAttribute, $this->message); } } }
php
public function beforeValidate() { if ($this->_attempt = AdminLoginAttempt::findByKey($this->getKey())) { if ($this->_attempt->amount >= $this->attempts) { $this->owner->addError($this->usernameAttribute, $this->message); } } }
[ "public", "function", "beforeValidate", "(", ")", "{", "if", "(", "$", "this", "->", "_attempt", "=", "AdminLoginAttempt", "::", "findByKey", "(", "$", "this", "->", "getKey", "(", ")", ")", ")", "{", "if", "(", "$", "this", "->", "_attempt", "->", "amount", ">=", "$", "this", "->", "attempts", ")", "{", "$", "this", "->", "owner", "->", "addError", "(", "$", "this", "->", "usernameAttribute", ",", "$", "this", "->", "message", ")", ";", "}", "}", "}" ]
验证前检查拦截
[ "验证前检查拦截" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/admin/behaviors/LoginAttemptBehavior.php#L118-L125
yuncms/framework
src/admin/behaviors/LoginAttemptBehavior.php
LoginAttemptBehavior.getUserLoginAttempt
public function getUserLoginAttempt() { if (!$this->_attempt) { $this->_attempt = new AdminLoginAttempt; $this->_attempt->key = $this->getKey(); } return $this->_attempt; }
php
public function getUserLoginAttempt() { if (!$this->_attempt) { $this->_attempt = new AdminLoginAttempt; $this->_attempt->key = $this->getKey(); } return $this->_attempt; }
[ "public", "function", "getUserLoginAttempt", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_attempt", ")", "{", "$", "this", "->", "_attempt", "=", "new", "AdminLoginAttempt", ";", "$", "this", "->", "_attempt", "->", "key", "=", "$", "this", "->", "getKey", "(", ")", ";", "}", "return", "$", "this", "->", "_attempt", ";", "}" ]
获取拦截历史 @return AdminLoginAttempt
[ "获取拦截历史" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/admin/behaviors/LoginAttemptBehavior.php#L157-L164
PortaText/php-sdk
src/PortaText/Command/Api/Summary.php
Summary.getEndpoint
protected function getEndpoint($method) { $endpoint = "summary"; $queryString = array(); $dateFrom = $this->getArgument("date_from"); if (!is_null($dateFrom)) { $queryString['date_from'] = $dateFrom; $this->delArgument("date_from"); } $dateTo = $this->getArgument("date_to"); if (!is_null($dateTo)) { $queryString['date_to'] = $dateTo; $this->delArgument("date_to"); } $granularity = $this->getArgument("granularity"); if (!is_null($granularity)) { $queryString['granularity'] = $granularity; $this->delArgument("granularity"); } if (!empty($queryString)) { $queryString = http_build_query($queryString); $endpoint .= "?$queryString"; } return $endpoint; }
php
protected function getEndpoint($method) { $endpoint = "summary"; $queryString = array(); $dateFrom = $this->getArgument("date_from"); if (!is_null($dateFrom)) { $queryString['date_from'] = $dateFrom; $this->delArgument("date_from"); } $dateTo = $this->getArgument("date_to"); if (!is_null($dateTo)) { $queryString['date_to'] = $dateTo; $this->delArgument("date_to"); } $granularity = $this->getArgument("granularity"); if (!is_null($granularity)) { $queryString['granularity'] = $granularity; $this->delArgument("granularity"); } if (!empty($queryString)) { $queryString = http_build_query($queryString); $endpoint .= "?$queryString"; } return $endpoint; }
[ "protected", "function", "getEndpoint", "(", "$", "method", ")", "{", "$", "endpoint", "=", "\"summary\"", ";", "$", "queryString", "=", "array", "(", ")", ";", "$", "dateFrom", "=", "$", "this", "->", "getArgument", "(", "\"date_from\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "dateFrom", ")", ")", "{", "$", "queryString", "[", "'date_from'", "]", "=", "$", "dateFrom", ";", "$", "this", "->", "delArgument", "(", "\"date_from\"", ")", ";", "}", "$", "dateTo", "=", "$", "this", "->", "getArgument", "(", "\"date_to\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "dateTo", ")", ")", "{", "$", "queryString", "[", "'date_to'", "]", "=", "$", "dateTo", ";", "$", "this", "->", "delArgument", "(", "\"date_to\"", ")", ";", "}", "$", "granularity", "=", "$", "this", "->", "getArgument", "(", "\"granularity\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "granularity", ")", ")", "{", "$", "queryString", "[", "'granularity'", "]", "=", "$", "granularity", ";", "$", "this", "->", "delArgument", "(", "\"granularity\"", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "queryString", ")", ")", "{", "$", "queryString", "=", "http_build_query", "(", "$", "queryString", ")", ";", "$", "endpoint", ".=", "\"?$queryString\"", ";", "}", "return", "$", "endpoint", ";", "}" ]
Returns a string with the endpoint for the given command. @param string $method Method for this command. @return string
[ "Returns", "a", "string", "with", "the", "endpoint", "for", "the", "given", "command", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Command/Api/Summary.php#L93-L117
ClanCats/Core
src/console/orbit.php
orbit.action_install
public function action_install( $params ) { $path = $params[0]; // get target directory $target_dir = \CCArr::get( 'target', $params, ORBITPATH ); if ( empty( $path ) ) { CCCli::line( 'no ship path given.', 'red' ); return; } /* * direct install if starting with / */ if ( substr( $path, 0, 1 ) == '/' ) { // fix path if ( substr( $path, -1 ) != '/' ) { $path .= '/'; } // is directory if ( !is_dir( $path ) ) { CCCli::line( 'could not find a ship at path: '.$path, 'red' ); return; } // define the target $target = $target_dir.basename( $path ).'/'; // check if we already have an directory with the same name if ( $target != $path && is_dir( $target ) ) { if ( !CCCli::confirm( "there is already a ship with this name. do you want to overwrite?", true ) ) { return; } } // are ya serius.. if ( !CCCli::confirm( "are you sure you want to install this ship?", true ) ) { return; } // move the directory if ( $target != $path ) { rename( $path, $target ); } // run the installer try { \CCOrbit::install( $target ); } catch ( \Exception $e ) { CCCli::line( $e->getMessage(), 'red' ); CCCli::line( 'ship installation failure.', 'red' ); return; } // we are done CCCli::line( 'ship installation succeeded', 'green' ); return; } // check if the module is in our orbit path if ( is_dir( ORBITPATH.$path ) ) { // there is a ship yay CCCli::line( 'found ship at path: '.ORBITPATH.$path, 'green' ); return static::action_install( array( ORBITPATH.$path, 'target' => \CCArr::get( 'target', $params ) ) ); } // check if the module is in CCF dir if ( is_dir( CCROOT.$path ) ) { // there is a ship yay CCCli::line( 'found ship at path: '.CCROOT.$path, 'green' ); return static::action_install( array( CCROOT.$path, 'target' => \CCArr::get( 'target', $params ) ) ); } // search the repository for this ship CCCli::line( 'searching the repositories for: '.$path.' ...', 'cyan' ); }
php
public function action_install( $params ) { $path = $params[0]; // get target directory $target_dir = \CCArr::get( 'target', $params, ORBITPATH ); if ( empty( $path ) ) { CCCli::line( 'no ship path given.', 'red' ); return; } /* * direct install if starting with / */ if ( substr( $path, 0, 1 ) == '/' ) { // fix path if ( substr( $path, -1 ) != '/' ) { $path .= '/'; } // is directory if ( !is_dir( $path ) ) { CCCli::line( 'could not find a ship at path: '.$path, 'red' ); return; } // define the target $target = $target_dir.basename( $path ).'/'; // check if we already have an directory with the same name if ( $target != $path && is_dir( $target ) ) { if ( !CCCli::confirm( "there is already a ship with this name. do you want to overwrite?", true ) ) { return; } } // are ya serius.. if ( !CCCli::confirm( "are you sure you want to install this ship?", true ) ) { return; } // move the directory if ( $target != $path ) { rename( $path, $target ); } // run the installer try { \CCOrbit::install( $target ); } catch ( \Exception $e ) { CCCli::line( $e->getMessage(), 'red' ); CCCli::line( 'ship installation failure.', 'red' ); return; } // we are done CCCli::line( 'ship installation succeeded', 'green' ); return; } // check if the module is in our orbit path if ( is_dir( ORBITPATH.$path ) ) { // there is a ship yay CCCli::line( 'found ship at path: '.ORBITPATH.$path, 'green' ); return static::action_install( array( ORBITPATH.$path, 'target' => \CCArr::get( 'target', $params ) ) ); } // check if the module is in CCF dir if ( is_dir( CCROOT.$path ) ) { // there is a ship yay CCCli::line( 'found ship at path: '.CCROOT.$path, 'green' ); return static::action_install( array( CCROOT.$path, 'target' => \CCArr::get( 'target', $params ) ) ); } // search the repository for this ship CCCli::line( 'searching the repositories for: '.$path.' ...', 'cyan' ); }
[ "public", "function", "action_install", "(", "$", "params", ")", "{", "$", "path", "=", "$", "params", "[", "0", "]", ";", "// get target directory", "$", "target_dir", "=", "\\", "CCArr", "::", "get", "(", "'target'", ",", "$", "params", ",", "ORBITPATH", ")", ";", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "CCCli", "::", "line", "(", "'no ship path given.'", ",", "'red'", ")", ";", "return", ";", "}", "/*\n\t\t * direct install if starting with /\n\t\t */", "if", "(", "substr", "(", "$", "path", ",", "0", ",", "1", ")", "==", "'/'", ")", "{", "// fix path", "if", "(", "substr", "(", "$", "path", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "path", ".=", "'/'", ";", "}", "// is directory", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "CCCli", "::", "line", "(", "'could not find a ship at path: '", ".", "$", "path", ",", "'red'", ")", ";", "return", ";", "}", "// define the target", "$", "target", "=", "$", "target_dir", ".", "basename", "(", "$", "path", ")", ".", "'/'", ";", "// check if we already have an directory with the same name", "if", "(", "$", "target", "!=", "$", "path", "&&", "is_dir", "(", "$", "target", ")", ")", "{", "if", "(", "!", "CCCli", "::", "confirm", "(", "\"there is already a ship with this name. do you want to overwrite?\"", ",", "true", ")", ")", "{", "return", ";", "}", "}", "// are ya serius..", "if", "(", "!", "CCCli", "::", "confirm", "(", "\"are you sure you want to install this ship?\"", ",", "true", ")", ")", "{", "return", ";", "}", "// move the directory", "if", "(", "$", "target", "!=", "$", "path", ")", "{", "rename", "(", "$", "path", ",", "$", "target", ")", ";", "}", "// run the installer", "try", "{", "\\", "CCOrbit", "::", "install", "(", "$", "target", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "CCCli", "::", "line", "(", "$", "e", "->", "getMessage", "(", ")", ",", "'red'", ")", ";", "CCCli", "::", "line", "(", "'ship installation failure.'", ",", "'red'", ")", ";", "return", ";", "}", "// we are done", "CCCli", "::", "line", "(", "'ship installation succeeded'", ",", "'green'", ")", ";", "return", ";", "}", "// check if the module is in our orbit path", "if", "(", "is_dir", "(", "ORBITPATH", ".", "$", "path", ")", ")", "{", "// there is a ship yay", "CCCli", "::", "line", "(", "'found ship at path: '", ".", "ORBITPATH", ".", "$", "path", ",", "'green'", ")", ";", "return", "static", "::", "action_install", "(", "array", "(", "ORBITPATH", ".", "$", "path", ",", "'target'", "=>", "\\", "CCArr", "::", "get", "(", "'target'", ",", "$", "params", ")", ")", ")", ";", "}", "// check if the module is in CCF dir", "if", "(", "is_dir", "(", "CCROOT", ".", "$", "path", ")", ")", "{", "// there is a ship yay", "CCCli", "::", "line", "(", "'found ship at path: '", ".", "CCROOT", ".", "$", "path", ",", "'green'", ")", ";", "return", "static", "::", "action_install", "(", "array", "(", "CCROOT", ".", "$", "path", ",", "'target'", "=>", "\\", "CCArr", "::", "get", "(", "'target'", ",", "$", "params", ")", ")", ")", ";", "}", "// search the repository for this ship", "CCCli", "::", "line", "(", "'searching the repositories for: '", ".", "$", "path", ".", "' ...'", ",", "'cyan'", ")", ";", "}" ]
install an orbit module @param array $params
[ "install", "an", "orbit", "module" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/console/orbit.php#L35-L116
ClanCats/Core
src/console/orbit.php
orbit.action_uninstall
public function action_uninstall( $params ) { $path = $params[0]; if ( empty( $path ) ) { CCCli::line( 'no ship path given.', 'red' ); return; } /* * direct install if starting with / */ if ( substr( $path, 0, 1 ) == '/' ) { // fix path if ( substr( $path, -1 ) != '/' ) { $path .= '/'; } // is directory if ( !is_dir( $path ) ) { CCCli::line( 'could not find a ship at path: '.$path, 'red' ); return; } // are ya serius.. if ( !CCCli::confirm( "are you sure you want to uninstall this ship?", true ) ) { return; } // run the uninstaller try { \CCOrbit::uninstall( $path ); } catch ( \Exception $e ) { CCCli::line( $e->getMessage(), 'red' ); CCCli::line( 'ship destroying failure.', 'red' ); return; } // also remove the direcoty? if ( CCCli::confirm( "do you also wish to remove the ship files?", true ) ) { \CCFile::delete( $path ); } // we are done CCCli::line( 'ship destroyed!', 'green' ); return; } // check if the module is in our orbit path if ( is_dir( ORBITPATH.$path ) ) { // there is a ship yay CCCli::line( 'found ship at path: '.ORBITPATH.$path, 'green' ); return static::action_uninstall( array( ORBITPATH.$path ) ); } // nothing to do here CCCli::line( 'could not find a ship at this path or name.', 'red' ); return; }
php
public function action_uninstall( $params ) { $path = $params[0]; if ( empty( $path ) ) { CCCli::line( 'no ship path given.', 'red' ); return; } /* * direct install if starting with / */ if ( substr( $path, 0, 1 ) == '/' ) { // fix path if ( substr( $path, -1 ) != '/' ) { $path .= '/'; } // is directory if ( !is_dir( $path ) ) { CCCli::line( 'could not find a ship at path: '.$path, 'red' ); return; } // are ya serius.. if ( !CCCli::confirm( "are you sure you want to uninstall this ship?", true ) ) { return; } // run the uninstaller try { \CCOrbit::uninstall( $path ); } catch ( \Exception $e ) { CCCli::line( $e->getMessage(), 'red' ); CCCli::line( 'ship destroying failure.', 'red' ); return; } // also remove the direcoty? if ( CCCli::confirm( "do you also wish to remove the ship files?", true ) ) { \CCFile::delete( $path ); } // we are done CCCli::line( 'ship destroyed!', 'green' ); return; } // check if the module is in our orbit path if ( is_dir( ORBITPATH.$path ) ) { // there is a ship yay CCCli::line( 'found ship at path: '.ORBITPATH.$path, 'green' ); return static::action_uninstall( array( ORBITPATH.$path ) ); } // nothing to do here CCCli::line( 'could not find a ship at this path or name.', 'red' ); return; }
[ "public", "function", "action_uninstall", "(", "$", "params", ")", "{", "$", "path", "=", "$", "params", "[", "0", "]", ";", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "CCCli", "::", "line", "(", "'no ship path given.'", ",", "'red'", ")", ";", "return", ";", "}", "/*\n\t\t * direct install if starting with /\n\t\t */", "if", "(", "substr", "(", "$", "path", ",", "0", ",", "1", ")", "==", "'/'", ")", "{", "// fix path", "if", "(", "substr", "(", "$", "path", ",", "-", "1", ")", "!=", "'/'", ")", "{", "$", "path", ".=", "'/'", ";", "}", "// is directory", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "CCCli", "::", "line", "(", "'could not find a ship at path: '", ".", "$", "path", ",", "'red'", ")", ";", "return", ";", "}", "// are ya serius..", "if", "(", "!", "CCCli", "::", "confirm", "(", "\"are you sure you want to uninstall this ship?\"", ",", "true", ")", ")", "{", "return", ";", "}", "// run the uninstaller", "try", "{", "\\", "CCOrbit", "::", "uninstall", "(", "$", "path", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "CCCli", "::", "line", "(", "$", "e", "->", "getMessage", "(", ")", ",", "'red'", ")", ";", "CCCli", "::", "line", "(", "'ship destroying failure.'", ",", "'red'", ")", ";", "return", ";", "}", "// also remove the direcoty?", "if", "(", "CCCli", "::", "confirm", "(", "\"do you also wish to remove the ship files?\"", ",", "true", ")", ")", "{", "\\", "CCFile", "::", "delete", "(", "$", "path", ")", ";", "}", "// we are done", "CCCli", "::", "line", "(", "'ship destroyed!'", ",", "'green'", ")", ";", "return", ";", "}", "// check if the module is in our orbit path", "if", "(", "is_dir", "(", "ORBITPATH", ".", "$", "path", ")", ")", "{", "// there is a ship yay", "CCCli", "::", "line", "(", "'found ship at path: '", ".", "ORBITPATH", ".", "$", "path", ",", "'green'", ")", ";", "return", "static", "::", "action_uninstall", "(", "array", "(", "ORBITPATH", ".", "$", "path", ")", ")", ";", "}", "// nothing to do here", "CCCli", "::", "line", "(", "'could not find a ship at this path or name.'", ",", "'red'", ")", ";", "return", ";", "}" ]
uninstall an orbit module @param array $params
[ "uninstall", "an", "orbit", "module" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/console/orbit.php#L123-L182
egeloen/IvorySerializerBundle
FOS/Type/ExceptionType.php
ExceptionType.convert
public function convert($exception, TypeMetadataInterface $type, ContextInterface $context) { if ($context->getDirection() === Direction::DESERIALIZATION) { throw new \RuntimeException('Deserializing an "Exception" is not supported.'); } $result = ['code' => 500]; if ($context->hasOption('template_data')) { $templateData = $context->getOption('template_data'); if (isset($templateData['status_code'])) { $result['code'] = $templateData['status_code']; } } $result['message'] = $this->getExceptionMessage($exception, $result['code']); if ($this->debug) { $result['exception'] = $this->serializeException($exception); } return $context->getVisitor()->visitArray($result, $type, $context); }
php
public function convert($exception, TypeMetadataInterface $type, ContextInterface $context) { if ($context->getDirection() === Direction::DESERIALIZATION) { throw new \RuntimeException('Deserializing an "Exception" is not supported.'); } $result = ['code' => 500]; if ($context->hasOption('template_data')) { $templateData = $context->getOption('template_data'); if (isset($templateData['status_code'])) { $result['code'] = $templateData['status_code']; } } $result['message'] = $this->getExceptionMessage($exception, $result['code']); if ($this->debug) { $result['exception'] = $this->serializeException($exception); } return $context->getVisitor()->visitArray($result, $type, $context); }
[ "public", "function", "convert", "(", "$", "exception", ",", "TypeMetadataInterface", "$", "type", ",", "ContextInterface", "$", "context", ")", "{", "if", "(", "$", "context", "->", "getDirection", "(", ")", "===", "Direction", "::", "DESERIALIZATION", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Deserializing an \"Exception\" is not supported.'", ")", ";", "}", "$", "result", "=", "[", "'code'", "=>", "500", "]", ";", "if", "(", "$", "context", "->", "hasOption", "(", "'template_data'", ")", ")", "{", "$", "templateData", "=", "$", "context", "->", "getOption", "(", "'template_data'", ")", ";", "if", "(", "isset", "(", "$", "templateData", "[", "'status_code'", "]", ")", ")", "{", "$", "result", "[", "'code'", "]", "=", "$", "templateData", "[", "'status_code'", "]", ";", "}", "}", "$", "result", "[", "'message'", "]", "=", "$", "this", "->", "getExceptionMessage", "(", "$", "exception", ",", "$", "result", "[", "'code'", "]", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "$", "result", "[", "'exception'", "]", "=", "$", "this", "->", "serializeException", "(", "$", "exception", ")", ";", "}", "return", "$", "context", "->", "getVisitor", "(", ")", "->", "visitArray", "(", "$", "result", ",", "$", "type", ",", "$", "context", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/egeloen/IvorySerializerBundle/blob/a2bdd912bf715c61b823cf7257ee232d5c823dd3/FOS/Type/ExceptionType.php#L45-L68
left-right/center
src/CenterServiceProvider.php
CenterServiceProvider.config
private function config() { $this->loadViewsFrom(__DIR__ . '/views', 'center'); $this->loadTranslationsFrom(__DIR__ . '/translations', 'center'); $this->publishes([ __DIR__ . '/../assets/public' => public_path('vendor/center'), ], 'public'); $this->publishes([ __DIR__ . '/config' => config_path('center'), ], 'config'); $this->publishes([ __DIR__ . '/translations/en/site.php' => app_path('../resources/lang/vendor/center/en/site.php'), __DIR__ . '/translations/en/users.php' => app_path('../resources/lang/vendor/center/en/users.php'), ], 'lang'); //include __DIR__ . '/macros.php'; include __DIR__ . '/routes.php'; }
php
private function config() { $this->loadViewsFrom(__DIR__ . '/views', 'center'); $this->loadTranslationsFrom(__DIR__ . '/translations', 'center'); $this->publishes([ __DIR__ . '/../assets/public' => public_path('vendor/center'), ], 'public'); $this->publishes([ __DIR__ . '/config' => config_path('center'), ], 'config'); $this->publishes([ __DIR__ . '/translations/en/site.php' => app_path('../resources/lang/vendor/center/en/site.php'), __DIR__ . '/translations/en/users.php' => app_path('../resources/lang/vendor/center/en/users.php'), ], 'lang'); //include __DIR__ . '/macros.php'; include __DIR__ . '/routes.php'; }
[ "private", "function", "config", "(", ")", "{", "$", "this", "->", "loadViewsFrom", "(", "__DIR__", ".", "'/views'", ",", "'center'", ")", ";", "$", "this", "->", "loadTranslationsFrom", "(", "__DIR__", ".", "'/translations'", ",", "'center'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../assets/public'", "=>", "public_path", "(", "'vendor/center'", ")", ",", "]", ",", "'public'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/config'", "=>", "config_path", "(", "'center'", ")", ",", "]", ",", "'config'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/translations/en/site.php'", "=>", "app_path", "(", "'../resources/lang/vendor/center/en/site.php'", ")", ",", "__DIR__", ".", "'/translations/en/users.php'", "=>", "app_path", "(", "'../resources/lang/vendor/center/en/users.php'", ")", ",", "]", ",", "'lang'", ")", ";", "//include __DIR__ . '/macros.php';", "include", "__DIR__", ".", "'/routes.php'", ";", "}" ]
set up publishes paths and define config locations
[ "set", "up", "publishes", "paths", "and", "define", "config", "locations" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/CenterServiceProvider.php#L49-L64
left-right/center
src/CenterServiceProvider.php
CenterServiceProvider.schema
private function schema() { //todo: consider caching this $expanded_tables = []; $tables = config('center.tables', []); foreach ($tables as $table=>$table_properties) { //sanitize for use in db names and php functions $table = str_slug($table, '_'); //parse table definition $table_properties = self::associateNumericKeys($table_properties); $table_properties['name'] = $table; $table_properties['title'] = trans('center::' . $table . '.title'); if (!isset($table_properties['keep_clean'])) $table_properties['keep_clean'] = false; if (!isset($table_properties['creatable'])) $table_properties['creatable'] = true; if (!isset($table_properties['editable'])) $table_properties['editable'] = true; if (!isset($table_properties['deletable'])) $table_properties['deletable'] = true; if (!isset($table_properties['list'])) $table_properties['list'] = []; if (!isset($table_properties['export'])) $table_properties['export'] = []; if (!isset($table_properties['search'])) $table_properties['search'] = []; if (!isset($table_properties['filters'])) $table_properties['filters'] = []; if (!isset($table_properties['timestamps'])) $table_properties['timestamps'] = true; //temp, soon to look up from permissions table $table_properties['dates'] = []; //loop through fields if (!isset($table_properties['fields'])) $table_properties['fields'] = []; $expanded_fields = []; foreach ($table_properties['fields'] as $field=>$field_properties) { //resolve shorthand, eg 'updated_at' if (is_int($field)) $field = $field_properties; if (is_string($field_properties)) { if (strpos($field_properties, ' ') !== false) { $parts = explode(' ', $field_properties); $field_properties = [ 'required' => in_array('required', $parts), 'hidden' => in_array('hidden', $parts), 'type' => implode(array_diff($parts, ['required', 'hidden'])), ]; } else { $field_properties = ['type' => $field_properties]; } } $field_properties = self::associateNumericKeys($field_properties); //set types on reserved system fields if ($field == 'permissions') $field_properties['type'] = 'permissions'; if (in_array($field, ['created_at', 'updated_at', 'deleted_at'])) $field_properties['type'] = 'datetime'; if (in_array($field, ['id', 'created_by', 'updated_by', 'deleted_by', 'precedence'])) $field_properties['type'] = 'integer'; //check field type is supported if (!in_array($field_properties['type'], self::$field_types)) { trigger_error('field ' . $table . '.' . $field . ' is of type ' . $field_properties['type'] . ' which is not supported.'); } //relationship columns always end in _id, eg image_id //this is so that $model->image_id and $model->image->src can work if (in_array($field_properties['type'], ['image', 'select', 'user'])) { if (!ends_with($field, '_id')) $field .= '_id'; } //set other field attributes $field_properties['name'] = $field; $field_properties['title'] = trans('center::' . $table . '.fields.' . $field); if (!isset($field_properties['required'])) { if (in_array($field, ['id', 'created_at', 'updated_at'])) { $field_properties['required'] = true; } elseif (in_array($field_properties['type'], ['checkbox'])) { $field_properties['required'] = true; } else { $field_properties['required'] = false; } } //in general, the name of a checkboxes field should be the name of its joining table //however your are allowed to name the source, and let the system set the joining table for you if (($field_properties['type'] == 'checkboxes') && empty($field_properties['source'])) { $field_properties['source'] = $field; $field = $field_properties['name'] = RowController::formatJoiningTable($table, $field); } if ($field_properties['type'] == 'user') $field_properties['source'] = config('center.db.users'); //field max lengths if ($field_properties['type'] == 'phone') $field_properties['maxlength'] = 10; if ($field_properties['type'] == 'zip') $field_properties['maxlength'] = 5; if ($field_properties['type'] == 'us_state') $field_properties['maxlength'] = 2; if ($field_properties['type'] == 'country') $field_properties['maxlength'] = 2; if (!isset($field_properties['hidden'])) $field_properties['hidden'] = in_array($field, ['id', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by', 'deleted_by', 'password', 'precedence']); if (in_array($field_properties['type'], ['image' ,'images'])) { if (empty($field_properties['width'])) $field_properties['width'] = null; if (empty($field_properties['height'])) $field_properties['height'] = null; } //empty source on if (in_array($field_properties['type'], ['latitude', 'longitude', 'slug'])) { if (empty($field_properties['source'])) $field_properties['source'] = null; } //forced overrides if ($field_properties['type'] == 'password') $field_properties['hidden'] = true; if ($field_properties['hidden']) $field_properties['required'] = false; //save $expanded_fields[$field] = (object) $field_properties; } //save fields to table as an object $table_properties['fields'] = (object) $expanded_fields; //default table properties if (!isset($table_properties['list_grouping'])) $table_properties['list_grouping'] = ''; if (!isset($table_properties['model'])) $table_properties['model'] = studly_case(str_singular($table)); if (!isset($table_properties['hidden'])) $table_properties['hidden'] = false; if (!isset($table_properties['links'])) $table_properties['links'] = []; if (!isset($table_properties['order_by'])) { $table_properties['order_by'] = [$table . '.id'=>'asc']; } else { $table_properties['order_by'] = self::associateNumericKeys($table_properties['order_by'], 'asc'); foreach ($table_properties['order_by'] as $column => $direction) { //add table name to disambiguate if (!strstr($column, '.')) { unset($table_properties['order_by'][$column]); $table_properties['order_by'][$table . '.' . $column] = $direction; } } } //save table to $tables array as an object $expanded_tables[$table] = (object) $table_properties; } //sort alpha by title uksort($expanded_tables, function($a, $b) use ($expanded_tables) { return $expanded_tables[$a]->title > $expanded_tables[$b]->title; }); //dd($expanded_tables); Config::set('center.tables', $expanded_tables); }
php
private function schema() { //todo: consider caching this $expanded_tables = []; $tables = config('center.tables', []); foreach ($tables as $table=>$table_properties) { //sanitize for use in db names and php functions $table = str_slug($table, '_'); //parse table definition $table_properties = self::associateNumericKeys($table_properties); $table_properties['name'] = $table; $table_properties['title'] = trans('center::' . $table . '.title'); if (!isset($table_properties['keep_clean'])) $table_properties['keep_clean'] = false; if (!isset($table_properties['creatable'])) $table_properties['creatable'] = true; if (!isset($table_properties['editable'])) $table_properties['editable'] = true; if (!isset($table_properties['deletable'])) $table_properties['deletable'] = true; if (!isset($table_properties['list'])) $table_properties['list'] = []; if (!isset($table_properties['export'])) $table_properties['export'] = []; if (!isset($table_properties['search'])) $table_properties['search'] = []; if (!isset($table_properties['filters'])) $table_properties['filters'] = []; if (!isset($table_properties['timestamps'])) $table_properties['timestamps'] = true; //temp, soon to look up from permissions table $table_properties['dates'] = []; //loop through fields if (!isset($table_properties['fields'])) $table_properties['fields'] = []; $expanded_fields = []; foreach ($table_properties['fields'] as $field=>$field_properties) { //resolve shorthand, eg 'updated_at' if (is_int($field)) $field = $field_properties; if (is_string($field_properties)) { if (strpos($field_properties, ' ') !== false) { $parts = explode(' ', $field_properties); $field_properties = [ 'required' => in_array('required', $parts), 'hidden' => in_array('hidden', $parts), 'type' => implode(array_diff($parts, ['required', 'hidden'])), ]; } else { $field_properties = ['type' => $field_properties]; } } $field_properties = self::associateNumericKeys($field_properties); //set types on reserved system fields if ($field == 'permissions') $field_properties['type'] = 'permissions'; if (in_array($field, ['created_at', 'updated_at', 'deleted_at'])) $field_properties['type'] = 'datetime'; if (in_array($field, ['id', 'created_by', 'updated_by', 'deleted_by', 'precedence'])) $field_properties['type'] = 'integer'; //check field type is supported if (!in_array($field_properties['type'], self::$field_types)) { trigger_error('field ' . $table . '.' . $field . ' is of type ' . $field_properties['type'] . ' which is not supported.'); } //relationship columns always end in _id, eg image_id //this is so that $model->image_id and $model->image->src can work if (in_array($field_properties['type'], ['image', 'select', 'user'])) { if (!ends_with($field, '_id')) $field .= '_id'; } //set other field attributes $field_properties['name'] = $field; $field_properties['title'] = trans('center::' . $table . '.fields.' . $field); if (!isset($field_properties['required'])) { if (in_array($field, ['id', 'created_at', 'updated_at'])) { $field_properties['required'] = true; } elseif (in_array($field_properties['type'], ['checkbox'])) { $field_properties['required'] = true; } else { $field_properties['required'] = false; } } //in general, the name of a checkboxes field should be the name of its joining table //however your are allowed to name the source, and let the system set the joining table for you if (($field_properties['type'] == 'checkboxes') && empty($field_properties['source'])) { $field_properties['source'] = $field; $field = $field_properties['name'] = RowController::formatJoiningTable($table, $field); } if ($field_properties['type'] == 'user') $field_properties['source'] = config('center.db.users'); //field max lengths if ($field_properties['type'] == 'phone') $field_properties['maxlength'] = 10; if ($field_properties['type'] == 'zip') $field_properties['maxlength'] = 5; if ($field_properties['type'] == 'us_state') $field_properties['maxlength'] = 2; if ($field_properties['type'] == 'country') $field_properties['maxlength'] = 2; if (!isset($field_properties['hidden'])) $field_properties['hidden'] = in_array($field, ['id', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by', 'deleted_by', 'password', 'precedence']); if (in_array($field_properties['type'], ['image' ,'images'])) { if (empty($field_properties['width'])) $field_properties['width'] = null; if (empty($field_properties['height'])) $field_properties['height'] = null; } //empty source on if (in_array($field_properties['type'], ['latitude', 'longitude', 'slug'])) { if (empty($field_properties['source'])) $field_properties['source'] = null; } //forced overrides if ($field_properties['type'] == 'password') $field_properties['hidden'] = true; if ($field_properties['hidden']) $field_properties['required'] = false; //save $expanded_fields[$field] = (object) $field_properties; } //save fields to table as an object $table_properties['fields'] = (object) $expanded_fields; //default table properties if (!isset($table_properties['list_grouping'])) $table_properties['list_grouping'] = ''; if (!isset($table_properties['model'])) $table_properties['model'] = studly_case(str_singular($table)); if (!isset($table_properties['hidden'])) $table_properties['hidden'] = false; if (!isset($table_properties['links'])) $table_properties['links'] = []; if (!isset($table_properties['order_by'])) { $table_properties['order_by'] = [$table . '.id'=>'asc']; } else { $table_properties['order_by'] = self::associateNumericKeys($table_properties['order_by'], 'asc'); foreach ($table_properties['order_by'] as $column => $direction) { //add table name to disambiguate if (!strstr($column, '.')) { unset($table_properties['order_by'][$column]); $table_properties['order_by'][$table . '.' . $column] = $direction; } } } //save table to $tables array as an object $expanded_tables[$table] = (object) $table_properties; } //sort alpha by title uksort($expanded_tables, function($a, $b) use ($expanded_tables) { return $expanded_tables[$a]->title > $expanded_tables[$b]->title; }); //dd($expanded_tables); Config::set('center.tables', $expanded_tables); }
[ "private", "function", "schema", "(", ")", "{", "//todo: consider caching this", "$", "expanded_tables", "=", "[", "]", ";", "$", "tables", "=", "config", "(", "'center.tables'", ",", "[", "]", ")", ";", "foreach", "(", "$", "tables", "as", "$", "table", "=>", "$", "table_properties", ")", "{", "//sanitize for use in db names and php functions", "$", "table", "=", "str_slug", "(", "$", "table", ",", "'_'", ")", ";", "//parse table definition", "$", "table_properties", "=", "self", "::", "associateNumericKeys", "(", "$", "table_properties", ")", ";", "$", "table_properties", "[", "'name'", "]", "=", "$", "table", ";", "$", "table_properties", "[", "'title'", "]", "=", "trans", "(", "'center::'", ".", "$", "table", ".", "'.title'", ")", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'keep_clean'", "]", ")", ")", "$", "table_properties", "[", "'keep_clean'", "]", "=", "false", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'creatable'", "]", ")", ")", "$", "table_properties", "[", "'creatable'", "]", "=", "true", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'editable'", "]", ")", ")", "$", "table_properties", "[", "'editable'", "]", "=", "true", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'deletable'", "]", ")", ")", "$", "table_properties", "[", "'deletable'", "]", "=", "true", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'list'", "]", ")", ")", "$", "table_properties", "[", "'list'", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'export'", "]", ")", ")", "$", "table_properties", "[", "'export'", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'search'", "]", ")", ")", "$", "table_properties", "[", "'search'", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'filters'", "]", ")", ")", "$", "table_properties", "[", "'filters'", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'timestamps'", "]", ")", ")", "$", "table_properties", "[", "'timestamps'", "]", "=", "true", ";", "//temp, soon to look up from permissions table", "$", "table_properties", "[", "'dates'", "]", "=", "[", "]", ";", "//loop through fields", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'fields'", "]", ")", ")", "$", "table_properties", "[", "'fields'", "]", "=", "[", "]", ";", "$", "expanded_fields", "=", "[", "]", ";", "foreach", "(", "$", "table_properties", "[", "'fields'", "]", "as", "$", "field", "=>", "$", "field_properties", ")", "{", "//resolve shorthand, eg 'updated_at'", "if", "(", "is_int", "(", "$", "field", ")", ")", "$", "field", "=", "$", "field_properties", ";", "if", "(", "is_string", "(", "$", "field_properties", ")", ")", "{", "if", "(", "strpos", "(", "$", "field_properties", ",", "' '", ")", "!==", "false", ")", "{", "$", "parts", "=", "explode", "(", "' '", ",", "$", "field_properties", ")", ";", "$", "field_properties", "=", "[", "'required'", "=>", "in_array", "(", "'required'", ",", "$", "parts", ")", ",", "'hidden'", "=>", "in_array", "(", "'hidden'", ",", "$", "parts", ")", ",", "'type'", "=>", "implode", "(", "array_diff", "(", "$", "parts", ",", "[", "'required'", ",", "'hidden'", "]", ")", ")", ",", "]", ";", "}", "else", "{", "$", "field_properties", "=", "[", "'type'", "=>", "$", "field_properties", "]", ";", "}", "}", "$", "field_properties", "=", "self", "::", "associateNumericKeys", "(", "$", "field_properties", ")", ";", "//set types on reserved system fields", "if", "(", "$", "field", "==", "'permissions'", ")", "$", "field_properties", "[", "'type'", "]", "=", "'permissions'", ";", "if", "(", "in_array", "(", "$", "field", ",", "[", "'created_at'", ",", "'updated_at'", ",", "'deleted_at'", "]", ")", ")", "$", "field_properties", "[", "'type'", "]", "=", "'datetime'", ";", "if", "(", "in_array", "(", "$", "field", ",", "[", "'id'", ",", "'created_by'", ",", "'updated_by'", ",", "'deleted_by'", ",", "'precedence'", "]", ")", ")", "$", "field_properties", "[", "'type'", "]", "=", "'integer'", ";", "//check field type is supported", "if", "(", "!", "in_array", "(", "$", "field_properties", "[", "'type'", "]", ",", "self", "::", "$", "field_types", ")", ")", "{", "trigger_error", "(", "'field '", ".", "$", "table", ".", "'.'", ".", "$", "field", ".", "' is of type '", ".", "$", "field_properties", "[", "'type'", "]", ".", "' which is not supported.'", ")", ";", "}", "//relationship columns always end in _id, eg image_id", "//this is so that $model->image_id and $model->image->src can work", "if", "(", "in_array", "(", "$", "field_properties", "[", "'type'", "]", ",", "[", "'image'", ",", "'select'", ",", "'user'", "]", ")", ")", "{", "if", "(", "!", "ends_with", "(", "$", "field", ",", "'_id'", ")", ")", "$", "field", ".=", "'_id'", ";", "}", "//set other field attributes", "$", "field_properties", "[", "'name'", "]", "=", "$", "field", ";", "$", "field_properties", "[", "'title'", "]", "=", "trans", "(", "'center::'", ".", "$", "table", ".", "'.fields.'", ".", "$", "field", ")", ";", "if", "(", "!", "isset", "(", "$", "field_properties", "[", "'required'", "]", ")", ")", "{", "if", "(", "in_array", "(", "$", "field", ",", "[", "'id'", ",", "'created_at'", ",", "'updated_at'", "]", ")", ")", "{", "$", "field_properties", "[", "'required'", "]", "=", "true", ";", "}", "elseif", "(", "in_array", "(", "$", "field_properties", "[", "'type'", "]", ",", "[", "'checkbox'", "]", ")", ")", "{", "$", "field_properties", "[", "'required'", "]", "=", "true", ";", "}", "else", "{", "$", "field_properties", "[", "'required'", "]", "=", "false", ";", "}", "}", "//in general, the name of a checkboxes field should be the name of its joining table", "//however your are allowed to name the source, and let the system set the joining table for you", "if", "(", "(", "$", "field_properties", "[", "'type'", "]", "==", "'checkboxes'", ")", "&&", "empty", "(", "$", "field_properties", "[", "'source'", "]", ")", ")", "{", "$", "field_properties", "[", "'source'", "]", "=", "$", "field", ";", "$", "field", "=", "$", "field_properties", "[", "'name'", "]", "=", "RowController", "::", "formatJoiningTable", "(", "$", "table", ",", "$", "field", ")", ";", "}", "if", "(", "$", "field_properties", "[", "'type'", "]", "==", "'user'", ")", "$", "field_properties", "[", "'source'", "]", "=", "config", "(", "'center.db.users'", ")", ";", "//field max lengths", "if", "(", "$", "field_properties", "[", "'type'", "]", "==", "'phone'", ")", "$", "field_properties", "[", "'maxlength'", "]", "=", "10", ";", "if", "(", "$", "field_properties", "[", "'type'", "]", "==", "'zip'", ")", "$", "field_properties", "[", "'maxlength'", "]", "=", "5", ";", "if", "(", "$", "field_properties", "[", "'type'", "]", "==", "'us_state'", ")", "$", "field_properties", "[", "'maxlength'", "]", "=", "2", ";", "if", "(", "$", "field_properties", "[", "'type'", "]", "==", "'country'", ")", "$", "field_properties", "[", "'maxlength'", "]", "=", "2", ";", "if", "(", "!", "isset", "(", "$", "field_properties", "[", "'hidden'", "]", ")", ")", "$", "field_properties", "[", "'hidden'", "]", "=", "in_array", "(", "$", "field", ",", "[", "'id'", ",", "'created_at'", ",", "'updated_at'", ",", "'deleted_at'", ",", "'created_by'", ",", "'updated_by'", ",", "'deleted_by'", ",", "'password'", ",", "'precedence'", "]", ")", ";", "if", "(", "in_array", "(", "$", "field_properties", "[", "'type'", "]", ",", "[", "'image'", ",", "'images'", "]", ")", ")", "{", "if", "(", "empty", "(", "$", "field_properties", "[", "'width'", "]", ")", ")", "$", "field_properties", "[", "'width'", "]", "=", "null", ";", "if", "(", "empty", "(", "$", "field_properties", "[", "'height'", "]", ")", ")", "$", "field_properties", "[", "'height'", "]", "=", "null", ";", "}", "//empty source on ", "if", "(", "in_array", "(", "$", "field_properties", "[", "'type'", "]", ",", "[", "'latitude'", ",", "'longitude'", ",", "'slug'", "]", ")", ")", "{", "if", "(", "empty", "(", "$", "field_properties", "[", "'source'", "]", ")", ")", "$", "field_properties", "[", "'source'", "]", "=", "null", ";", "}", "//forced overrides", "if", "(", "$", "field_properties", "[", "'type'", "]", "==", "'password'", ")", "$", "field_properties", "[", "'hidden'", "]", "=", "true", ";", "if", "(", "$", "field_properties", "[", "'hidden'", "]", ")", "$", "field_properties", "[", "'required'", "]", "=", "false", ";", "//save", "$", "expanded_fields", "[", "$", "field", "]", "=", "(", "object", ")", "$", "field_properties", ";", "}", "//save fields to table as an object", "$", "table_properties", "[", "'fields'", "]", "=", "(", "object", ")", "$", "expanded_fields", ";", "//default table properties", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'list_grouping'", "]", ")", ")", "$", "table_properties", "[", "'list_grouping'", "]", "=", "''", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'model'", "]", ")", ")", "$", "table_properties", "[", "'model'", "]", "=", "studly_case", "(", "str_singular", "(", "$", "table", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'hidden'", "]", ")", ")", "$", "table_properties", "[", "'hidden'", "]", "=", "false", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'links'", "]", ")", ")", "$", "table_properties", "[", "'links'", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "table_properties", "[", "'order_by'", "]", ")", ")", "{", "$", "table_properties", "[", "'order_by'", "]", "=", "[", "$", "table", ".", "'.id'", "=>", "'asc'", "]", ";", "}", "else", "{", "$", "table_properties", "[", "'order_by'", "]", "=", "self", "::", "associateNumericKeys", "(", "$", "table_properties", "[", "'order_by'", "]", ",", "'asc'", ")", ";", "foreach", "(", "$", "table_properties", "[", "'order_by'", "]", "as", "$", "column", "=>", "$", "direction", ")", "{", "//add table name to disambiguate", "if", "(", "!", "strstr", "(", "$", "column", ",", "'.'", ")", ")", "{", "unset", "(", "$", "table_properties", "[", "'order_by'", "]", "[", "$", "column", "]", ")", ";", "$", "table_properties", "[", "'order_by'", "]", "[", "$", "table", ".", "'.'", ".", "$", "column", "]", "=", "$", "direction", ";", "}", "}", "}", "//save table to $tables array as an object", "$", "expanded_tables", "[", "$", "table", "]", "=", "(", "object", ")", "$", "table_properties", ";", "}", "//sort alpha by title", "uksort", "(", "$", "expanded_tables", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "expanded_tables", ")", "{", "return", "$", "expanded_tables", "[", "$", "a", "]", "->", "title", ">", "$", "expanded_tables", "[", "$", "b", "]", "->", "title", ";", "}", ")", ";", "//dd($expanded_tables);", "Config", "::", "set", "(", "'center.tables'", ",", "$", "expanded_tables", ")", ";", "}" ]
parse through config, expand it by applying default values and permissions
[ "parse", "through", "config", "expand", "it", "by", "applying", "default", "values", "and", "permissions" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/CenterServiceProvider.php#L67-L213
left-right/center
src/CenterServiceProvider.php
CenterServiceProvider.models
private function models() { $relationships = $dates = []; $tables = config('center.tables'); //loop through once to create relationships between tables foreach ($tables as $table) { $dates[$table->name] = []; if (!isset($relationships[$table->name])) $relationships[$table->name] = []; foreach ($table->fields as $field) { //define relationships if ($field->type == 'checkboxes') { //out from this object $order_by = []; foreach ($tables[$field->source]->order_by as $column=>$direction) { $order_by[] = '->orderBy("' . $column . '", "' . $direction . '")'; } $relationships[$table->name][] = ' public function ' . $tables[$field->source]->name . '() { return $this->belongsToMany("LeftRight\Center\Models\\' . $tables[$field->source]->model . '", "' . $field->name . '", "' . RowController::formatKeyColumn($table->name) . '", "' . RowController::formatKeyColumn($tables[$field->source]->name) . '")' . implode($order_by) . '; } '; //back from the related object $order_by = []; foreach ($table->order_by as $column=>$direction) { $order_by[] = '->orderBy("' . $column . '", "' . $direction . '")'; } $relationships[$tables[$field->source]->name][] = ' public function ' . $table->name . '() { return $this->belongsToMany("LeftRight\Center\Models\\' . $table->model . '", "' . $field->name . '", "' . RowController::formatKeyColumn($tables[$field->source]->name) . '", "' . RowController::formatKeyColumn($table->name) . '")' . implode($order_by) . '; } '; } elseif (in_array($field->type, ['date', 'datetime'])) { $dates[$table->name][] = '\'' . $field->name . '\''; } elseif ($field->type == 'image') { //cannot overwrite property $relationships[$table->name][] = ' public function ' . substr($field->name, 0, -3) . '() { return $this->hasOne("LeftRight\Center\Models\File", "id", "' . $field->name . '"); } '; } elseif (in_array($field->type, ['select', 'user'])) { //public function ' . $tables[$field->source]->name . '() { //out from this object $relationships[$table->name][] = ' public function ' . substr($field->name, 0, -3) . '() { return $this->belongsTo("LeftRight\Center\Models\\' . $tables[$field->source]->model . '", "' . $field->name . '"); } '; //back from the related object $relationships[$tables[$field->source]->name][] = ' public function ' . $table->name . '() { return $this->hasMany("LeftRight\Center\Models\\' . $table->model . '", "' . $field->name . '"); } '; } } } //debug //dd($relationships); //now we must loop through again; the first loop set relationships on other tables foreach ($tables as $table) { eval('namespace LeftRight\Center\Models; use Illuminate\Database\Eloquent\SoftDeletes; use Auth; use DateTime; use DB; use Eloquent; class ' . $table->model . ' extends Eloquent { ' . (isset($table->fields->deleted_at) ? 'use SoftDeletes;' : '') . ' public $table = \'' . $table->name . '\'; //public intentionally public $timestamps = false; //going to override if present protected $guarded = []; protected $dates = [' . implode(',', $dates[$table->name]) . ']; public static function boot() { parent::boot(); static::creating(function($object) {' . (isset($table->fields->precedence) ? ' $object->precedence = DB::table(\'' . $table->name . '\')->max(\'precedence\') + 1; ' : '') . (isset($table->fields->created_by) ? ' $object->created_by = Auth::id(); ' : '') . ($table->timestamps && isset($table->fields->created_at) ? ' $object->created_at = new DateTime(); ' : '') . (isset($table->fields->updated_by) ? ' $object->updated_by = Auth::id(); ' : '') . ($table->timestamps && isset($table->fields->updated_at) ? ' $object->updated_at = new DateTime(); ' : '') . '}); static::updating(function($object) {' . (isset($table->fields->updated_by) ? ' $object->updated_by = Auth::id(); ' : '') . ($table->timestamps && isset($table->fields->updated_at) ? ' $object->updated_at = new DateTime(); ' : '') . '}); } public function creator() { return $this->belongsTo(\'User\', \'created_by\'); } public function updater() { return $this->belongsTo(\'User\', \'updated_by\'); } ' . implode(' ', $relationships[$table->name]) . ' }'); } }
php
private function models() { $relationships = $dates = []; $tables = config('center.tables'); //loop through once to create relationships between tables foreach ($tables as $table) { $dates[$table->name] = []; if (!isset($relationships[$table->name])) $relationships[$table->name] = []; foreach ($table->fields as $field) { //define relationships if ($field->type == 'checkboxes') { //out from this object $order_by = []; foreach ($tables[$field->source]->order_by as $column=>$direction) { $order_by[] = '->orderBy("' . $column . '", "' . $direction . '")'; } $relationships[$table->name][] = ' public function ' . $tables[$field->source]->name . '() { return $this->belongsToMany("LeftRight\Center\Models\\' . $tables[$field->source]->model . '", "' . $field->name . '", "' . RowController::formatKeyColumn($table->name) . '", "' . RowController::formatKeyColumn($tables[$field->source]->name) . '")' . implode($order_by) . '; } '; //back from the related object $order_by = []; foreach ($table->order_by as $column=>$direction) { $order_by[] = '->orderBy("' . $column . '", "' . $direction . '")'; } $relationships[$tables[$field->source]->name][] = ' public function ' . $table->name . '() { return $this->belongsToMany("LeftRight\Center\Models\\' . $table->model . '", "' . $field->name . '", "' . RowController::formatKeyColumn($tables[$field->source]->name) . '", "' . RowController::formatKeyColumn($table->name) . '")' . implode($order_by) . '; } '; } elseif (in_array($field->type, ['date', 'datetime'])) { $dates[$table->name][] = '\'' . $field->name . '\''; } elseif ($field->type == 'image') { //cannot overwrite property $relationships[$table->name][] = ' public function ' . substr($field->name, 0, -3) . '() { return $this->hasOne("LeftRight\Center\Models\File", "id", "' . $field->name . '"); } '; } elseif (in_array($field->type, ['select', 'user'])) { //public function ' . $tables[$field->source]->name . '() { //out from this object $relationships[$table->name][] = ' public function ' . substr($field->name, 0, -3) . '() { return $this->belongsTo("LeftRight\Center\Models\\' . $tables[$field->source]->model . '", "' . $field->name . '"); } '; //back from the related object $relationships[$tables[$field->source]->name][] = ' public function ' . $table->name . '() { return $this->hasMany("LeftRight\Center\Models\\' . $table->model . '", "' . $field->name . '"); } '; } } } //debug //dd($relationships); //now we must loop through again; the first loop set relationships on other tables foreach ($tables as $table) { eval('namespace LeftRight\Center\Models; use Illuminate\Database\Eloquent\SoftDeletes; use Auth; use DateTime; use DB; use Eloquent; class ' . $table->model . ' extends Eloquent { ' . (isset($table->fields->deleted_at) ? 'use SoftDeletes;' : '') . ' public $table = \'' . $table->name . '\'; //public intentionally public $timestamps = false; //going to override if present protected $guarded = []; protected $dates = [' . implode(',', $dates[$table->name]) . ']; public static function boot() { parent::boot(); static::creating(function($object) {' . (isset($table->fields->precedence) ? ' $object->precedence = DB::table(\'' . $table->name . '\')->max(\'precedence\') + 1; ' : '') . (isset($table->fields->created_by) ? ' $object->created_by = Auth::id(); ' : '') . ($table->timestamps && isset($table->fields->created_at) ? ' $object->created_at = new DateTime(); ' : '') . (isset($table->fields->updated_by) ? ' $object->updated_by = Auth::id(); ' : '') . ($table->timestamps && isset($table->fields->updated_at) ? ' $object->updated_at = new DateTime(); ' : '') . '}); static::updating(function($object) {' . (isset($table->fields->updated_by) ? ' $object->updated_by = Auth::id(); ' : '') . ($table->timestamps && isset($table->fields->updated_at) ? ' $object->updated_at = new DateTime(); ' : '') . '}); } public function creator() { return $this->belongsTo(\'User\', \'created_by\'); } public function updater() { return $this->belongsTo(\'User\', \'updated_by\'); } ' . implode(' ', $relationships[$table->name]) . ' }'); } }
[ "private", "function", "models", "(", ")", "{", "$", "relationships", "=", "$", "dates", "=", "[", "]", ";", "$", "tables", "=", "config", "(", "'center.tables'", ")", ";", "//loop through once to create relationships between tables", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "$", "dates", "[", "$", "table", "->", "name", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "relationships", "[", "$", "table", "->", "name", "]", ")", ")", "$", "relationships", "[", "$", "table", "->", "name", "]", "=", "[", "]", ";", "foreach", "(", "$", "table", "->", "fields", "as", "$", "field", ")", "{", "//define relationships", "if", "(", "$", "field", "->", "type", "==", "'checkboxes'", ")", "{", "//out from this object", "$", "order_by", "=", "[", "]", ";", "foreach", "(", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "order_by", "as", "$", "column", "=>", "$", "direction", ")", "{", "$", "order_by", "[", "]", "=", "'->orderBy(\"'", ".", "$", "column", ".", "'\", \"'", ".", "$", "direction", ".", "'\")'", ";", "}", "$", "relationships", "[", "$", "table", "->", "name", "]", "[", "]", "=", "'\n\t\t\t\t\tpublic function '", ".", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "name", ".", "'() {\n\t\t\t\t\t\treturn $this->belongsToMany(\"LeftRight\\Center\\Models\\\\'", ".", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "model", ".", "'\", \"'", ".", "$", "field", "->", "name", ".", "'\", \"'", ".", "RowController", "::", "formatKeyColumn", "(", "$", "table", "->", "name", ")", ".", "'\", \"'", ".", "RowController", "::", "formatKeyColumn", "(", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "name", ")", ".", "'\")'", ".", "implode", "(", "$", "order_by", ")", ".", "';\n\t\t\t\t\t}\n\t\t\t\t\t'", ";", "//back from the related object", "$", "order_by", "=", "[", "]", ";", "foreach", "(", "$", "table", "->", "order_by", "as", "$", "column", "=>", "$", "direction", ")", "{", "$", "order_by", "[", "]", "=", "'->orderBy(\"'", ".", "$", "column", ".", "'\", \"'", ".", "$", "direction", ".", "'\")'", ";", "}", "$", "relationships", "[", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "name", "]", "[", "]", "=", "'\n\t\t\t\t\tpublic function '", ".", "$", "table", "->", "name", ".", "'() {\n\t\t\t\t\t\treturn $this->belongsToMany(\"LeftRight\\Center\\Models\\\\'", ".", "$", "table", "->", "model", ".", "'\", \"'", ".", "$", "field", "->", "name", ".", "'\", \"'", ".", "RowController", "::", "formatKeyColumn", "(", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "name", ")", ".", "'\", \"'", ".", "RowController", "::", "formatKeyColumn", "(", "$", "table", "->", "name", ")", ".", "'\")'", ".", "implode", "(", "$", "order_by", ")", ".", "';\n\t\t\t\t\t}\n\t\t\t\t\t'", ";", "}", "elseif", "(", "in_array", "(", "$", "field", "->", "type", ",", "[", "'date'", ",", "'datetime'", "]", ")", ")", "{", "$", "dates", "[", "$", "table", "->", "name", "]", "[", "]", "=", "'\\''", ".", "$", "field", "->", "name", ".", "'\\''", ";", "}", "elseif", "(", "$", "field", "->", "type", "==", "'image'", ")", "{", "//cannot overwrite property", "$", "relationships", "[", "$", "table", "->", "name", "]", "[", "]", "=", "'\n\t\t\t\t\tpublic function '", ".", "substr", "(", "$", "field", "->", "name", ",", "0", ",", "-", "3", ")", ".", "'() {\n\t\t\t\t\t\treturn $this->hasOne(\"LeftRight\\Center\\Models\\File\", \"id\", \"'", ".", "$", "field", "->", "name", ".", "'\");\n\t\t\t\t\t}\n\t\t\t\t\t'", ";", "}", "elseif", "(", "in_array", "(", "$", "field", "->", "type", ",", "[", "'select'", ",", "'user'", "]", ")", ")", "{", "//public function ' . $tables[$field->source]->name . '() {", "//out from this object", "$", "relationships", "[", "$", "table", "->", "name", "]", "[", "]", "=", "'\n\t\t\t\t\tpublic function '", ".", "substr", "(", "$", "field", "->", "name", ",", "0", ",", "-", "3", ")", ".", "'() {\n\t\t\t\t\t\treturn $this->belongsTo(\"LeftRight\\Center\\Models\\\\'", ".", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "model", ".", "'\", \"'", ".", "$", "field", "->", "name", ".", "'\");\n\t\t\t\t\t}\n\t\t\t\t\t'", ";", "//back from the related object", "$", "relationships", "[", "$", "tables", "[", "$", "field", "->", "source", "]", "->", "name", "]", "[", "]", "=", "'\n\t\t\t\t\tpublic function '", ".", "$", "table", "->", "name", ".", "'() {\n\t\t\t\t\t\treturn $this->hasMany(\"LeftRight\\Center\\Models\\\\'", ".", "$", "table", "->", "model", ".", "'\", \"'", ".", "$", "field", "->", "name", ".", "'\");\n\t\t\t\t\t}\n\t\t\t\t\t'", ";", "}", "}", "}", "//debug", "//dd($relationships);", "//now we must loop through again; the first loop set relationships on other tables", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "eval", "(", "'namespace LeftRight\\Center\\Models;\n\t\t\tuse Illuminate\\Database\\Eloquent\\SoftDeletes;\n\t\t\tuse Auth;\n\t\t\tuse DateTime;\n\t\t\tuse DB;\n\t\t\tuse Eloquent;\n\n\t\t\tclass '", ".", "$", "table", "->", "model", ".", "' extends Eloquent {\n\t\t\t '", ".", "(", "isset", "(", "$", "table", "->", "fields", "->", "deleted_at", ")", "?", "'use SoftDeletes;'", ":", "''", ")", ".", "'\n\t\t\t\tpublic $table = \\''", ".", "$", "table", "->", "name", ".", "'\\'; //public intentionally\n\t\t\t\tpublic $timestamps = false; //going to override if present\n\t\t\t\tprotected $guarded = [];\n\t\t\t\tprotected $dates = ['", ".", "implode", "(", "','", ",", "$", "dates", "[", "$", "table", "->", "name", "]", ")", ".", "'];\n\n\t\t\t\tpublic static function boot() {\n\t\t\t\t\tparent::boot();\n\t\t\t static::creating(function($object) {'", ".", "(", "isset", "(", "$", "table", "->", "fields", "->", "precedence", ")", "?", "'\n\t\t\t\t\t\t$object->precedence = DB::table(\\''", ".", "$", "table", "->", "name", ".", "'\\')->max(\\'precedence\\') + 1;\n\t\t\t\t\t\t'", ":", "''", ")", ".", "(", "isset", "(", "$", "table", "->", "fields", "->", "created_by", ")", "?", "'\n\t\t\t\t\t\t$object->created_by = Auth::id();\n\t\t\t\t\t\t'", ":", "''", ")", ".", "(", "$", "table", "->", "timestamps", "&&", "isset", "(", "$", "table", "->", "fields", "->", "created_at", ")", "?", "'\n\t\t\t\t\t\t$object->created_at = new DateTime();\n\t\t\t\t\t\t'", ":", "''", ")", ".", "(", "isset", "(", "$", "table", "->", "fields", "->", "updated_by", ")", "?", "'\n\t\t\t\t\t\t$object->updated_by = Auth::id();\n\t\t\t\t\t\t'", ":", "''", ")", ".", "(", "$", "table", "->", "timestamps", "&&", "isset", "(", "$", "table", "->", "fields", "->", "updated_at", ")", "?", "'\n\t\t\t\t\t\t$object->updated_at = new DateTime();\n\t\t\t\t\t\t'", ":", "''", ")", ".", "'});\n\t\t\t static::updating(function($object) {'", ".", "(", "isset", "(", "$", "table", "->", "fields", "->", "updated_by", ")", "?", "'\n\t\t\t\t\t\t$object->updated_by = Auth::id();\n\t\t\t\t\t\t'", ":", "''", ")", ".", "(", "$", "table", "->", "timestamps", "&&", "isset", "(", "$", "table", "->", "fields", "->", "updated_at", ")", "?", "'\n\t\t\t\t\t\t$object->updated_at = new DateTime();\n\t\t\t\t\t\t'", ":", "''", ")", ".", "'});\n\t\t\t\t}\n\n\t\t\t\tpublic function creator() {\n\t\t\t\t\treturn $this->belongsTo(\\'User\\', \\'created_by\\');\n\t\t\t\t}\n\n\t\t\t\tpublic function updater() {\n\t\t\t\t\treturn $this->belongsTo(\\'User\\', \\'updated_by\\');\n\t\t\t\t}\n\n\t\t\t\t'", ".", "implode", "(", "' '", ",", "$", "relationships", "[", "$", "table", "->", "name", "]", ")", ".", "'\n\t\t\t}'", ")", ";", "}", "}" ]
loop through and process the $fields into $objects for model methods below
[ "loop", "through", "and", "process", "the", "$fields", "into", "$objects", "for", "model", "methods", "below" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/CenterServiceProvider.php#L217-L350
left-right/center
src/CenterServiceProvider.php
CenterServiceProvider.associateNumericKeys
private static function associateNumericKeys($array, $default=true) { if (is_string($array)) { $array = [$array => $default]; } else { foreach ($array as $key=>$value) { if (is_int($key)) { $array[$value] = $default; unset($array[$key]); } } } return $array; }
php
private static function associateNumericKeys($array, $default=true) { if (is_string($array)) { $array = [$array => $default]; } else { foreach ($array as $key=>$value) { if (is_int($key)) { $array[$value] = $default; unset($array[$key]); } } } return $array; }
[ "private", "static", "function", "associateNumericKeys", "(", "$", "array", ",", "$", "default", "=", "true", ")", "{", "if", "(", "is_string", "(", "$", "array", ")", ")", "{", "$", "array", "=", "[", "$", "array", "=>", "$", "default", "]", ";", "}", "else", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "array", "[", "$", "value", "]", "=", "$", "default", ";", "unset", "(", "$", "array", "[", "$", "key", "]", ")", ";", "}", "}", "}", "return", "$", "array", ";", "}" ]
helper for config()
[ "helper", "for", "config", "()" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/CenterServiceProvider.php#L353-L365
left-right/center
src/CenterServiceProvider.php
CenterServiceProvider.saveImage
public static function saveImage($table_name, $field_name, $file_name, $row_id=null, $extension=null) { return FileController::saveImage($table_name, $field_name, $file_name, $row_id, $extension); }
php
public static function saveImage($table_name, $field_name, $file_name, $row_id=null, $extension=null) { return FileController::saveImage($table_name, $field_name, $file_name, $row_id, $extension); }
[ "public", "static", "function", "saveImage", "(", "$", "table_name", ",", "$", "field_name", ",", "$", "file_name", ",", "$", "row_id", "=", "null", ",", "$", "extension", "=", "null", ")", "{", "return", "FileController", "::", "saveImage", "(", "$", "table_name", ",", "$", "field_name", ",", "$", "file_name", ",", "$", "row_id", ",", "$", "extension", ")", ";", "}" ]
save image interface (todo move to facade)
[ "save", "image", "interface", "(", "todo", "move", "to", "facade", ")" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/CenterServiceProvider.php#L368-L370
wikimedia/CLDRPluralRuleParser
src/Range.php
Range.isNumberIn
function isNumberIn( $number, $integerConstraint = true ) { foreach ( $this->parts as $part ) { if ( is_array( $part ) ) { if ( ( !$integerConstraint || floor( $number ) === (float)$number ) && $number >= $part[0] && $number <= $part[1] ) { return true; } } else { if ( $number == $part ) { return true; } } } return false; }
php
function isNumberIn( $number, $integerConstraint = true ) { foreach ( $this->parts as $part ) { if ( is_array( $part ) ) { if ( ( !$integerConstraint || floor( $number ) === (float)$number ) && $number >= $part[0] && $number <= $part[1] ) { return true; } } else { if ( $number == $part ) { return true; } } } return false; }
[ "function", "isNumberIn", "(", "$", "number", ",", "$", "integerConstraint", "=", "true", ")", "{", "foreach", "(", "$", "this", "->", "parts", "as", "$", "part", ")", "{", "if", "(", "is_array", "(", "$", "part", ")", ")", "{", "if", "(", "(", "!", "$", "integerConstraint", "||", "floor", "(", "$", "number", ")", "===", "(", "float", ")", "$", "number", ")", "&&", "$", "number", ">=", "$", "part", "[", "0", "]", "&&", "$", "number", "<=", "$", "part", "[", "1", "]", ")", "{", "return", "true", ";", "}", "}", "else", "{", "if", "(", "$", "number", "==", "$", "part", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Determine if the given number is inside the range. @param int $number The number to check @param bool $integerConstraint If true, also asserts the number is an integer; otherwise, number simply has to be inside the range. @return bool True if the number is inside the range; otherwise, false.
[ "Determine", "if", "the", "given", "number", "is", "inside", "the", "range", "." ]
train
https://github.com/wikimedia/CLDRPluralRuleParser/blob/4c5d71a3fd62a75871da8562310ca2258647ee6d/src/Range.php#L44-L60
wikimedia/CLDRPluralRuleParser
src/Range.php
Range.add
function add( $other ) { if ( $other instanceof self ) { $this->parts = array_merge( $this->parts, $other->parts ); } else { $this->parts[] = $other; } }
php
function add( $other ) { if ( $other instanceof self ) { $this->parts = array_merge( $this->parts, $other->parts ); } else { $this->parts[] = $other; } }
[ "function", "add", "(", "$", "other", ")", "{", "if", "(", "$", "other", "instanceof", "self", ")", "{", "$", "this", "->", "parts", "=", "array_merge", "(", "$", "this", "->", "parts", ",", "$", "other", "->", "parts", ")", ";", "}", "else", "{", "$", "this", "->", "parts", "[", "]", "=", "$", "other", ";", "}", "}" ]
Add another part to this range. @param Range|int $other The part to add, either a range object itself or a single number.
[ "Add", "another", "part", "to", "this", "range", "." ]
train
https://github.com/wikimedia/CLDRPluralRuleParser/blob/4c5d71a3fd62a75871da8562310ca2258647ee6d/src/Range.php#L79-L85
Ocramius/OcraDiCompiler
src/OcraDiCompiler/Mvc/Service/DiStrictAbstractServiceFactory.php
DiStrictAbstractServiceFactory.createServiceWithName
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $serviceName, $requestedName) { if (!isset($this->allowedServiceNames[$requestedName])) { throw new Exception\InvalidServiceNameException('Service "' . $requestedName . '" is not whitelisted'); } if ($serviceLocator instanceof AbstractPluginManager) { /* @var $serviceLocator AbstractPluginManager */ $this->serviceLocator = $serviceLocator->getServiceLocator(); } else { $this->serviceLocator = $serviceLocator; } return parent::get($requestedName); }
php
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $serviceName, $requestedName) { if (!isset($this->allowedServiceNames[$requestedName])) { throw new Exception\InvalidServiceNameException('Service "' . $requestedName . '" is not whitelisted'); } if ($serviceLocator instanceof AbstractPluginManager) { /* @var $serviceLocator AbstractPluginManager */ $this->serviceLocator = $serviceLocator->getServiceLocator(); } else { $this->serviceLocator = $serviceLocator; } return parent::get($requestedName); }
[ "public", "function", "createServiceWithName", "(", "ServiceLocatorInterface", "$", "serviceLocator", ",", "$", "serviceName", ",", "$", "requestedName", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "allowedServiceNames", "[", "$", "requestedName", "]", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidServiceNameException", "(", "'Service \"'", ".", "$", "requestedName", ".", "'\" is not whitelisted'", ")", ";", "}", "if", "(", "$", "serviceLocator", "instanceof", "AbstractPluginManager", ")", "{", "/* @var $serviceLocator AbstractPluginManager */", "$", "this", "->", "serviceLocator", "=", "$", "serviceLocator", "->", "getServiceLocator", "(", ")", ";", "}", "else", "{", "$", "this", "->", "serviceLocator", "=", "$", "serviceLocator", ";", "}", "return", "parent", "::", "get", "(", "$", "requestedName", ")", ";", "}" ]
{@inheritDoc} Allows creation of services only when in a whitelist
[ "{", "@inheritDoc", "}" ]
train
https://github.com/Ocramius/OcraDiCompiler/blob/667f4b24771f27fb9c8d6c38ffaf72d9cd55ca4a/src/OcraDiCompiler/Mvc/Service/DiStrictAbstractServiceFactory.php#L102-L117
VincentChalnot/SidusAdminBundle
Routing/AdminRouter.php
AdminRouter.generateAdminPath
public function generateAdminPath( $admin, $actionCode, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH ): string { $admin = $this->getAdmin($admin); $action = $admin->getAction($actionCode); $missingParams = $this->computeMissingRouteParameters($action->getRoute(), $parameters); foreach ($missingParams as $missingParam) { if ($this->router->getContext()->hasParameter($missingParam)) { $parameters[$missingParam] = $this->router->getContext()->getParameter($missingParam); } } return $this->router->generate($action->getRouteName(), $parameters, $referenceType); }
php
public function generateAdminPath( $admin, $actionCode, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH ): string { $admin = $this->getAdmin($admin); $action = $admin->getAction($actionCode); $missingParams = $this->computeMissingRouteParameters($action->getRoute(), $parameters); foreach ($missingParams as $missingParam) { if ($this->router->getContext()->hasParameter($missingParam)) { $parameters[$missingParam] = $this->router->getContext()->getParameter($missingParam); } } return $this->router->generate($action->getRouteName(), $parameters, $referenceType); }
[ "public", "function", "generateAdminPath", "(", "$", "admin", ",", "$", "actionCode", ",", "array", "$", "parameters", "=", "[", "]", ",", "$", "referenceType", "=", "UrlGeneratorInterface", "::", "ABSOLUTE_PATH", ")", ":", "string", "{", "$", "admin", "=", "$", "this", "->", "getAdmin", "(", "$", "admin", ")", ";", "$", "action", "=", "$", "admin", "->", "getAction", "(", "$", "actionCode", ")", ";", "$", "missingParams", "=", "$", "this", "->", "computeMissingRouteParameters", "(", "$", "action", "->", "getRoute", "(", ")", ",", "$", "parameters", ")", ";", "foreach", "(", "$", "missingParams", "as", "$", "missingParam", ")", "{", "if", "(", "$", "this", "->", "router", "->", "getContext", "(", ")", "->", "hasParameter", "(", "$", "missingParam", ")", ")", "{", "$", "parameters", "[", "$", "missingParam", "]", "=", "$", "this", "->", "router", "->", "getContext", "(", ")", "->", "getParameter", "(", "$", "missingParam", ")", ";", "}", "}", "return", "$", "this", "->", "router", "->", "generate", "(", "$", "action", "->", "getRouteName", "(", ")", ",", "$", "parameters", ",", "$", "referenceType", ")", ";", "}" ]
@param string|Admin $admin @param string $actionCode @param array $parameters @param int $referenceType @return string
[ "@param", "string|Admin", "$admin", "@param", "string", "$actionCode", "@param", "array", "$parameters", "@param", "int", "$referenceType" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Routing/AdminRouter.php#L66-L83
VincentChalnot/SidusAdminBundle
Routing/AdminRouter.php
AdminRouter.generateEntityPath
public function generateEntityPath( $entity, $actionCode, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH ): string { $admin = $this->adminEntityMatcher->getAdminForEntity($entity); return $this->generateAdminEntityPath($admin, $entity, $actionCode, $parameters, $referenceType); }
php
public function generateEntityPath( $entity, $actionCode, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH ): string { $admin = $this->adminEntityMatcher->getAdminForEntity($entity); return $this->generateAdminEntityPath($admin, $entity, $actionCode, $parameters, $referenceType); }
[ "public", "function", "generateEntityPath", "(", "$", "entity", ",", "$", "actionCode", ",", "array", "$", "parameters", "=", "[", "]", ",", "$", "referenceType", "=", "UrlGeneratorInterface", "::", "ABSOLUTE_PATH", ")", ":", "string", "{", "$", "admin", "=", "$", "this", "->", "adminEntityMatcher", "->", "getAdminForEntity", "(", "$", "entity", ")", ";", "return", "$", "this", "->", "generateAdminEntityPath", "(", "$", "admin", ",", "$", "entity", ",", "$", "actionCode", ",", "$", "parameters", ",", "$", "referenceType", ")", ";", "}" ]
@param mixed $entity @param string $actionCode @param array $parameters @param int $referenceType @throws \Exception @return string
[ "@param", "mixed", "$entity", "@param", "string", "$actionCode", "@param", "array", "$parameters", "@param", "int", "$referenceType" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Routing/AdminRouter.php#L95-L104
VincentChalnot/SidusAdminBundle
Routing/AdminRouter.php
AdminRouter.generateAdminEntityPath
public function generateAdminEntityPath( $admin, $entity, $actionCode, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH ): string { $admin = $this->getAdmin($admin); $action = $admin->getAction($actionCode); $missingParams = $this->computeMissingRouteParameters($action->getRoute(), $parameters); foreach ($missingParams as $missingParam) { try { $parameters[$missingParam] = $this->accessor->getValue($entity, $missingParam); } catch (\Exception $e) { try { // Fallback to array syntax $parameters[$missingParam] = $this->accessor->getValue($entity, "[{$missingParam}]"); } catch (\Exception $e) { $contextParam = $this->router->getContext()->getParameter($missingParam); if (null !== $contextParam) { $parameters[$missingParam] = $contextParam; } } } } return $this->router->generate($action->getRouteName(), $parameters, $referenceType); }
php
public function generateAdminEntityPath( $admin, $entity, $actionCode, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH ): string { $admin = $this->getAdmin($admin); $action = $admin->getAction($actionCode); $missingParams = $this->computeMissingRouteParameters($action->getRoute(), $parameters); foreach ($missingParams as $missingParam) { try { $parameters[$missingParam] = $this->accessor->getValue($entity, $missingParam); } catch (\Exception $e) { try { // Fallback to array syntax $parameters[$missingParam] = $this->accessor->getValue($entity, "[{$missingParam}]"); } catch (\Exception $e) { $contextParam = $this->router->getContext()->getParameter($missingParam); if (null !== $contextParam) { $parameters[$missingParam] = $contextParam; } } } } return $this->router->generate($action->getRouteName(), $parameters, $referenceType); }
[ "public", "function", "generateAdminEntityPath", "(", "$", "admin", ",", "$", "entity", ",", "$", "actionCode", ",", "array", "$", "parameters", "=", "[", "]", ",", "$", "referenceType", "=", "UrlGeneratorInterface", "::", "ABSOLUTE_PATH", ")", ":", "string", "{", "$", "admin", "=", "$", "this", "->", "getAdmin", "(", "$", "admin", ")", ";", "$", "action", "=", "$", "admin", "->", "getAction", "(", "$", "actionCode", ")", ";", "$", "missingParams", "=", "$", "this", "->", "computeMissingRouteParameters", "(", "$", "action", "->", "getRoute", "(", ")", ",", "$", "parameters", ")", ";", "foreach", "(", "$", "missingParams", "as", "$", "missingParam", ")", "{", "try", "{", "$", "parameters", "[", "$", "missingParam", "]", "=", "$", "this", "->", "accessor", "->", "getValue", "(", "$", "entity", ",", "$", "missingParam", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "try", "{", "// Fallback to array syntax", "$", "parameters", "[", "$", "missingParam", "]", "=", "$", "this", "->", "accessor", "->", "getValue", "(", "$", "entity", ",", "\"[{$missingParam}]\"", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "contextParam", "=", "$", "this", "->", "router", "->", "getContext", "(", ")", "->", "getParameter", "(", "$", "missingParam", ")", ";", "if", "(", "null", "!==", "$", "contextParam", ")", "{", "$", "parameters", "[", "$", "missingParam", "]", "=", "$", "contextParam", ";", "}", "}", "}", "}", "return", "$", "this", "->", "router", "->", "generate", "(", "$", "action", "->", "getRouteName", "(", ")", ",", "$", "parameters", ",", "$", "referenceType", ")", ";", "}" ]
@param string|Admin $admin @param mixed $entity @param string $actionCode @param array $parameters @param int $referenceType @throws \Exception @return string
[ "@param", "string|Admin", "$admin", "@param", "mixed", "$entity", "@param", "string", "$actionCode", "@param", "array", "$parameters", "@param", "int", "$referenceType" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Routing/AdminRouter.php#L117-L145
VincentChalnot/SidusAdminBundle
Routing/AdminRouter.php
AdminRouter.getAdmin
protected function getAdmin($admin): Admin { if (null === $admin) { return $this->adminRegistry->getCurrentAdmin(); } if ($admin instanceof Admin) { return $admin; } return $this->adminRegistry->getAdmin($admin); }
php
protected function getAdmin($admin): Admin { if (null === $admin) { return $this->adminRegistry->getCurrentAdmin(); } if ($admin instanceof Admin) { return $admin; } return $this->adminRegistry->getAdmin($admin); }
[ "protected", "function", "getAdmin", "(", "$", "admin", ")", ":", "Admin", "{", "if", "(", "null", "===", "$", "admin", ")", "{", "return", "$", "this", "->", "adminRegistry", "->", "getCurrentAdmin", "(", ")", ";", "}", "if", "(", "$", "admin", "instanceof", "Admin", ")", "{", "return", "$", "admin", ";", "}", "return", "$", "this", "->", "adminRegistry", "->", "getAdmin", "(", "$", "admin", ")", ";", "}" ]
@param string|Admin $admin @throws \UnexpectedValueException @return Admin
[ "@param", "string|Admin", "$admin" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Routing/AdminRouter.php#L154-L164
VincentChalnot/SidusAdminBundle
Routing/AdminRouter.php
AdminRouter.computeMissingRouteParameters
protected function computeMissingRouteParameters(Route $route, array $parameters): array { $compiledRoute = $route->compile(); $variables = array_flip($compiledRoute->getVariables()); $mergedParams = array_replace($route->getDefaults(), $this->router->getContext()->getParameters(), $parameters); return array_flip(array_diff_key($variables, $mergedParams)); }
php
protected function computeMissingRouteParameters(Route $route, array $parameters): array { $compiledRoute = $route->compile(); $variables = array_flip($compiledRoute->getVariables()); $mergedParams = array_replace($route->getDefaults(), $this->router->getContext()->getParameters(), $parameters); return array_flip(array_diff_key($variables, $mergedParams)); }
[ "protected", "function", "computeMissingRouteParameters", "(", "Route", "$", "route", ",", "array", "$", "parameters", ")", ":", "array", "{", "$", "compiledRoute", "=", "$", "route", "->", "compile", "(", ")", ";", "$", "variables", "=", "array_flip", "(", "$", "compiledRoute", "->", "getVariables", "(", ")", ")", ";", "$", "mergedParams", "=", "array_replace", "(", "$", "route", "->", "getDefaults", "(", ")", ",", "$", "this", "->", "router", "->", "getContext", "(", ")", "->", "getParameters", "(", ")", ",", "$", "parameters", ")", ";", "return", "array_flip", "(", "array_diff_key", "(", "$", "variables", ",", "$", "mergedParams", ")", ")", ";", "}" ]
@param Route $route @param array $parameters @throws \LogicException @return array
[ "@param", "Route", "$route", "@param", "array", "$parameters" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Routing/AdminRouter.php#L174-L181
php-rise/rise
src/Translation.php
Translation.translate
public function translate($key, $defaultValue = '', $locale = null) { if ($locale === null) { $locale = $this->getlocale(); } if (isset($this->translations[$locale][$key])) { return $this->translations[$locale][$key]; } return $defaultValue; }
php
public function translate($key, $defaultValue = '', $locale = null) { if ($locale === null) { $locale = $this->getlocale(); } if (isset($this->translations[$locale][$key])) { return $this->translations[$locale][$key]; } return $defaultValue; }
[ "public", "function", "translate", "(", "$", "key", ",", "$", "defaultValue", "=", "''", ",", "$", "locale", "=", "null", ")", "{", "if", "(", "$", "locale", "===", "null", ")", "{", "$", "locale", "=", "$", "this", "->", "getlocale", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "translations", "[", "$", "locale", "]", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "translations", "[", "$", "locale", "]", "[", "$", "key", "]", ";", "}", "return", "$", "defaultValue", ";", "}" ]
Translate an identifier to specific value. @param string $key Translation identifier. @param string $defaultValue Optional. @param string $locale Optional. Specify the locale of translation result. @return string
[ "Translate", "an", "identifier", "to", "specific", "value", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Translation.php#L101-L111
php-rise/rise
src/Translation.php
Translation.readConfig
protected function readConfig() { $file = $this->path->getConfigPath() . '/translation.php'; if (file_exists($file)) { $config = require($file); if (isset($config['translations'])) { $this->translations = $config['translations']; } if (isset($config['defaultLocale'])) { $this->setDefaultLocale($config['defaultLocale']); } } return $this; }
php
protected function readConfig() { $file = $this->path->getConfigPath() . '/translation.php'; if (file_exists($file)) { $config = require($file); if (isset($config['translations'])) { $this->translations = $config['translations']; } if (isset($config['defaultLocale'])) { $this->setDefaultLocale($config['defaultLocale']); } } return $this; }
[ "protected", "function", "readConfig", "(", ")", "{", "$", "file", "=", "$", "this", "->", "path", "->", "getConfigPath", "(", ")", ".", "'/translation.php'", ";", "if", "(", "file_exists", "(", "$", "file", ")", ")", "{", "$", "config", "=", "require", "(", "$", "file", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'translations'", "]", ")", ")", "{", "$", "this", "->", "translations", "=", "$", "config", "[", "'translations'", "]", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'defaultLocale'", "]", ")", ")", "{", "$", "this", "->", "setDefaultLocale", "(", "$", "config", "[", "'defaultLocale'", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Read configurations. @return self
[ "Read", "configurations", "." ]
train
https://github.com/php-rise/rise/blob/cd14ef9956f1b6875b7bcd642545dcef6a9152b7/src/Translation.php#L118-L130