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
VincentChalnot/SidusAdminBundle
DependencyInjection/SidusAdminExtension.php
SidusAdminExtension.createAdminServiceDefinition
protected function createAdminServiceDefinition($code, array $adminConfiguration, ContainerBuilder $container): void { $adminConfiguration = array_merge(['action_class' => $this->globalConfig['action_class']], $adminConfiguration); $definition = new Definition( $this->globalConfig['admin_class'], [ $code, $adminConfiguration, ] ); $definition->addTag('sidus.admin'); $definition->setPublic(false); $container->setDefinition('sidus_admin.admin.'.$code, $definition); }
php
protected function createAdminServiceDefinition($code, array $adminConfiguration, ContainerBuilder $container): void { $adminConfiguration = array_merge(['action_class' => $this->globalConfig['action_class']], $adminConfiguration); $definition = new Definition( $this->globalConfig['admin_class'], [ $code, $adminConfiguration, ] ); $definition->addTag('sidus.admin'); $definition->setPublic(false); $container->setDefinition('sidus_admin.admin.'.$code, $definition); }
[ "protected", "function", "createAdminServiceDefinition", "(", "$", "code", ",", "array", "$", "adminConfiguration", ",", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "adminConfiguration", "=", "array_merge", "(", "[", "'action_class'", "=>", "$", "this", "->", "globalConfig", "[", "'action_class'", "]", "]", ",", "$", "adminConfiguration", ")", ";", "$", "definition", "=", "new", "Definition", "(", "$", "this", "->", "globalConfig", "[", "'admin_class'", "]", ",", "[", "$", "code", ",", "$", "adminConfiguration", ",", "]", ")", ";", "$", "definition", "->", "addTag", "(", "'sidus.admin'", ")", ";", "$", "definition", "->", "setPublic", "(", "false", ")", ";", "$", "container", "->", "setDefinition", "(", "'sidus_admin.admin.'", ".", "$", "code", ",", "$", "definition", ")", ";", "}" ]
@param string $code @param array $adminConfiguration @param ContainerBuilder $container @throws BadMethodCallException
[ "@param", "string", "$code", "@param", "array", "$adminConfiguration", "@param", "ContainerBuilder", "$container" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/DependencyInjection/SidusAdminExtension.php#L67-L81
tigris-php/telegram-bot-api
src/Types/ReplyKeyboardMarkup.php
ReplyKeyboardMarkup.create
public static function create( $keyboard, $resize_keyboard = false, $one_time_keyboard = false, $selective = false ) { return static::build(compact( 'keyboard', 'resize_keyboard', 'one_time_keyboard', 'selective' )); }
php
public static function create( $keyboard, $resize_keyboard = false, $one_time_keyboard = false, $selective = false ) { return static::build(compact( 'keyboard', 'resize_keyboard', 'one_time_keyboard', 'selective' )); }
[ "public", "static", "function", "create", "(", "$", "keyboard", ",", "$", "resize_keyboard", "=", "false", ",", "$", "one_time_keyboard", "=", "false", ",", "$", "selective", "=", "false", ")", "{", "return", "static", "::", "build", "(", "compact", "(", "'keyboard'", ",", "'resize_keyboard'", ",", "'one_time_keyboard'", ",", "'selective'", ")", ")", ";", "}" ]
Constructor @param KeyboardButton[][] $keyboard @param bool $resize_keyboard @param bool $one_time_keyboard @param bool $selective @return static
[ "Constructor" ]
train
https://github.com/tigris-php/telegram-bot-api/blob/7350c81d571387005d58079d8c654ee44504cdcf/src/Types/ReplyKeyboardMarkup.php#L33-L45
SachaMorard/phalcon-console
Library/Phalcon/Builder/Path.php
Path.getConfig
public function getConfig($type = null) { $types = ['php' => true, 'ini' => true]; $type = isset($types[$type]) ? $type : 'ini'; foreach (['app/config/', 'config/', 'apps/config/', 'apps/frontend/config/'] as $configPath) { if ('ini' == $type && file_exists($this->rootPath . $configPath . 'config.ini')) { return new ConfigIni($this->rootPath . $configPath . 'config.ini'); } else { if (file_exists($this->rootPath . $configPath. 'config.php')) { $config = include($this->rootPath . $configPath . 'config.php'); if (is_array($config)) { $config = new Config($config); } return $config; } } } $directory = new RecursiveDirectoryIterator('.'); $iterator = new RecursiveIteratorIterator($directory); foreach ($iterator as $f) { if (preg_match('/config\.php$/i', $f->getPathName())) { $config = include $f->getPathName(); if (is_array($config)) { $config = new Config($config); } return $config; } else { if (preg_match('/config\.ini$/i', $f->getPathName())) { return new ConfigIni($f->getPathName()); } } } throw new BuilderException("Builder can't locate the configuration file"); }
php
public function getConfig($type = null) { $types = ['php' => true, 'ini' => true]; $type = isset($types[$type]) ? $type : 'ini'; foreach (['app/config/', 'config/', 'apps/config/', 'apps/frontend/config/'] as $configPath) { if ('ini' == $type && file_exists($this->rootPath . $configPath . 'config.ini')) { return new ConfigIni($this->rootPath . $configPath . 'config.ini'); } else { if (file_exists($this->rootPath . $configPath. 'config.php')) { $config = include($this->rootPath . $configPath . 'config.php'); if (is_array($config)) { $config = new Config($config); } return $config; } } } $directory = new RecursiveDirectoryIterator('.'); $iterator = new RecursiveIteratorIterator($directory); foreach ($iterator as $f) { if (preg_match('/config\.php$/i', $f->getPathName())) { $config = include $f->getPathName(); if (is_array($config)) { $config = new Config($config); } return $config; } else { if (preg_match('/config\.ini$/i', $f->getPathName())) { return new ConfigIni($f->getPathName()); } } } throw new BuilderException("Builder can't locate the configuration file"); }
[ "public", "function", "getConfig", "(", "$", "type", "=", "null", ")", "{", "$", "types", "=", "[", "'php'", "=>", "true", ",", "'ini'", "=>", "true", "]", ";", "$", "type", "=", "isset", "(", "$", "types", "[", "$", "type", "]", ")", "?", "$", "type", ":", "'ini'", ";", "foreach", "(", "[", "'app/config/'", ",", "'config/'", ",", "'apps/config/'", ",", "'apps/frontend/config/'", "]", "as", "$", "configPath", ")", "{", "if", "(", "'ini'", "==", "$", "type", "&&", "file_exists", "(", "$", "this", "->", "rootPath", ".", "$", "configPath", ".", "'config.ini'", ")", ")", "{", "return", "new", "ConfigIni", "(", "$", "this", "->", "rootPath", ".", "$", "configPath", ".", "'config.ini'", ")", ";", "}", "else", "{", "if", "(", "file_exists", "(", "$", "this", "->", "rootPath", ".", "$", "configPath", ".", "'config.php'", ")", ")", "{", "$", "config", "=", "include", "(", "$", "this", "->", "rootPath", ".", "$", "configPath", ".", "'config.php'", ")", ";", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "$", "config", "=", "new", "Config", "(", "$", "config", ")", ";", "}", "return", "$", "config", ";", "}", "}", "}", "$", "directory", "=", "new", "RecursiveDirectoryIterator", "(", "'.'", ")", ";", "$", "iterator", "=", "new", "RecursiveIteratorIterator", "(", "$", "directory", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "f", ")", "{", "if", "(", "preg_match", "(", "'/config\\.php$/i'", ",", "$", "f", "->", "getPathName", "(", ")", ")", ")", "{", "$", "config", "=", "include", "$", "f", "->", "getPathName", "(", ")", ";", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "$", "config", "=", "new", "Config", "(", "$", "config", ")", ";", "}", "return", "$", "config", ";", "}", "else", "{", "if", "(", "preg_match", "(", "'/config\\.ini$/i'", ",", "$", "f", "->", "getPathName", "(", ")", ")", ")", "{", "return", "new", "ConfigIni", "(", "$", "f", "->", "getPathName", "(", ")", ")", ";", "}", "}", "}", "throw", "new", "BuilderException", "(", "\"Builder can't locate the configuration file\"", ")", ";", "}" ]
Tries to find the current configuration in the application @param string $type Config type: ini | php @return \Phalcon\Config @throws BuilderException
[ "Tries", "to", "find", "the", "current", "configuration", "in", "the", "application" ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Builder/Path.php#L50-L88
SachaMorard/phalcon-console
Library/Phalcon/Builder/Path.php
Path.isAbsolutePath
public function isAbsolutePath($path) { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { if (preg_match('/^[A-Z]:\\\\/', $path)) { return true; } } else { if (substr($path, 0, 1) == DIRECTORY_SEPARATOR) { return true; } } return false; }
php
public function isAbsolutePath($path) { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { if (preg_match('/^[A-Z]:\\\\/', $path)) { return true; } } else { if (substr($path, 0, 1) == DIRECTORY_SEPARATOR) { return true; } } return false; }
[ "public", "function", "isAbsolutePath", "(", "$", "path", ")", "{", "if", "(", "strtoupper", "(", "substr", "(", "PHP_OS", ",", "0", ",", "3", ")", ")", "===", "'WIN'", ")", "{", "if", "(", "preg_match", "(", "'/^[A-Z]:\\\\\\\\/'", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "}", "else", "{", "if", "(", "substr", "(", "$", "path", ",", "0", ",", "1", ")", "==", "DIRECTORY_SEPARATOR", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if a path is absolute @param string $path Path to check @return bool
[ "Check", "if", "a", "path", "is", "absolute" ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Builder/Path.php#L115-L128
ClanCats/Core
src/classes/CCAsset/Holder.php
CCAsset_Holder.add
public function add( $item ) { // when the first character is a "smaller than" we simply assume // that a custom tag has been passed and not a filepath if ( strpos( $item, "<" ) !== false ) { $macro = '_'; } else { $macro = CCStr::extension( $item ); } if ( !isset( $this->assets[$macro] ) ) { $this->assets[$macro] = array(); } $this->assets[$macro][] = $item; }
php
public function add( $item ) { // when the first character is a "smaller than" we simply assume // that a custom tag has been passed and not a filepath if ( strpos( $item, "<" ) !== false ) { $macro = '_'; } else { $macro = CCStr::extension( $item ); } if ( !isset( $this->assets[$macro] ) ) { $this->assets[$macro] = array(); } $this->assets[$macro][] = $item; }
[ "public", "function", "add", "(", "$", "item", ")", "{", "// when the first character is a \"smaller than\" we simply assume", "// that a custom tag has been passed and not a filepath", "if", "(", "strpos", "(", "$", "item", ",", "\"<\"", ")", "!==", "false", ")", "{", "$", "macro", "=", "'_'", ";", "}", "else", "{", "$", "macro", "=", "CCStr", "::", "extension", "(", "$", "item", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "assets", "[", "$", "macro", "]", ")", ")", "{", "$", "this", "->", "assets", "[", "$", "macro", "]", "=", "array", "(", ")", ";", "}", "$", "this", "->", "assets", "[", "$", "macro", "]", "[", "]", "=", "$", "item", ";", "}" ]
Add an asset to the holder. Basically this method checks the file extension to sort them and generate the correct code using the macros. $holder->add( 'jquery.js' ); $holder->add( 'style.css' ); $holder->add( '<script>document.write( "Hello World" );</script>' ); @param string $item @return void
[ "Add", "an", "asset", "to", "the", "holder", ".", "Basically", "this", "method", "checks", "the", "file", "extension", "to", "sort", "them", "and", "generate", "the", "correct", "code", "using", "the", "macros", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCAsset/Holder.php#L39-L56
ClanCats/Core
src/classes/CCAsset/Holder.php
CCAsset_Holder.get
public function get( $type = null ) { if ( is_null( $type ) ) { return $this->assets; } if ( !isset( $this->assets[$type] ) ) { return array(); } return $this->assets[$type]; }
php
public function get( $type = null ) { if ( is_null( $type ) ) { return $this->assets; } if ( !isset( $this->assets[$type] ) ) { return array(); } return $this->assets[$type]; }
[ "public", "function", "get", "(", "$", "type", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "type", ")", ")", "{", "return", "$", "this", "->", "assets", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "assets", "[", "$", "type", "]", ")", ")", "{", "return", "array", "(", ")", ";", "}", "return", "$", "this", "->", "assets", "[", "$", "type", "]", ";", "}" ]
Get all assets by a specific macro / type $holder->get(); $holder->get( 'css' ); @param string $type By passing null all items from all types are returned @return array
[ "Get", "all", "assets", "by", "a", "specific", "macro", "/", "type" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCAsset/Holder.php#L67-L80
ClanCats/Core
src/classes/CCAsset/Holder.php
CCAsset_Holder.clear
public function clear( $type = null ) { if ( is_null( $type ) ) { $this->assets = array(); } else { if ( isset( $this->assets[$type] ) ) { $this->assets[$type] = array(); } } }
php
public function clear( $type = null ) { if ( is_null( $type ) ) { $this->assets = array(); } else { if ( isset( $this->assets[$type] ) ) { $this->assets[$type] = array(); } } }
[ "public", "function", "clear", "(", "$", "type", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "type", ")", ")", "{", "$", "this", "->", "assets", "=", "array", "(", ")", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "this", "->", "assets", "[", "$", "type", "]", ")", ")", "{", "$", "this", "->", "assets", "[", "$", "type", "]", "=", "array", "(", ")", ";", "}", "}", "}" ]
Clear the asset holder, deletes all contained assets of a special type or if $type is null everything. $holder->clear(); $holder->clear( 'js' ); @param string $type @return void
[ "Clear", "the", "asset", "holder", "deletes", "all", "contained", "assets", "of", "a", "special", "type", "or", "if", "$type", "is", "null", "everything", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCAsset/Holder.php#L92-L105
Lansoweb/LosBase
src/LosBase/Controller/ODM/AbstractCrudController.php
AbstractCrudController.getDocumentService
public function getDocumentService() { if (null === $this->documentService) { $documentServiceClass = $this->getDocumentServiceClass(); if (!class_exists($documentServiceClass)) { throw new \RuntimeException("Classe $documentServiceClass inexistente!"); } $this->documentService = new $documentServiceClass(); $this->documentService->setServiceLocator($this->getServiceLocator()); } return $this->documentService; }
php
public function getDocumentService() { if (null === $this->documentService) { $documentServiceClass = $this->getDocumentServiceClass(); if (!class_exists($documentServiceClass)) { throw new \RuntimeException("Classe $documentServiceClass inexistente!"); } $this->documentService = new $documentServiceClass(); $this->documentService->setServiceLocator($this->getServiceLocator()); } return $this->documentService; }
[ "public", "function", "getDocumentService", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "documentService", ")", "{", "$", "documentServiceClass", "=", "$", "this", "->", "getDocumentServiceClass", "(", ")", ";", "if", "(", "!", "class_exists", "(", "$", "documentServiceClass", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Classe $documentServiceClass inexistente!\"", ")", ";", "}", "$", "this", "->", "documentService", "=", "new", "$", "documentServiceClass", "(", ")", ";", "$", "this", "->", "documentService", "->", "setServiceLocator", "(", "$", "this", "->", "getServiceLocator", "(", ")", ")", ";", "}", "return", "$", "this", "->", "documentService", ";", "}" ]
Retorna o serviço do documento. @throws \InvalidArgumentException @return mixed
[ "Retorna", "o", "serviço", "do", "documento", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Controller/ODM/AbstractCrudController.php#L59-L71
Lansoweb/LosBase
src/LosBase/Controller/ODM/AbstractCrudController.php
AbstractCrudController.getForm
public function getForm($documentClass = null) { if (null === $documentClass) { $documentClass = $this->getDocumentClass(); } $builder = new AnnotationBuilder(); $form = $builder->createForm($documentClass); $hasDocument = false; foreach ($form->getElements() as $element) { if (method_exists($element, 'setObjectManager')) { $element->setObjectManager($this->getDocumentManager()); $hasDocument = true; } elseif (method_exists($element, 'getProxy')) { $proxy = $element->getProxy(); if (method_exists($proxy, 'setObjectManager')) { $proxy->setObjectManager($this->getDocumentManager()); $hasDocument = true; } } } if ($hasDocument) { $hydrator = new DoctrineObjectHydrator($this->getDocumentManager(), $documentClass); $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($documentClass = null) { if (null === $documentClass) { $documentClass = $this->getDocumentClass(); } $builder = new AnnotationBuilder(); $form = $builder->createForm($documentClass); $hasDocument = false; foreach ($form->getElements() as $element) { if (method_exists($element, 'setObjectManager')) { $element->setObjectManager($this->getDocumentManager()); $hasDocument = true; } elseif (method_exists($element, 'getProxy')) { $proxy = $element->getProxy(); if (method_exists($proxy, 'setObjectManager')) { $proxy->setObjectManager($this->getDocumentManager()); $hasDocument = true; } } } if ($hasDocument) { $hydrator = new DoctrineObjectHydrator($this->getDocumentManager(), $documentClass); $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", "(", "$", "documentClass", "=", "null", ")", "{", "if", "(", "null", "===", "$", "documentClass", ")", "{", "$", "documentClass", "=", "$", "this", "->", "getDocumentClass", "(", ")", ";", "}", "$", "builder", "=", "new", "AnnotationBuilder", "(", ")", ";", "$", "form", "=", "$", "builder", "->", "createForm", "(", "$", "documentClass", ")", ";", "$", "hasDocument", "=", "false", ";", "foreach", "(", "$", "form", "->", "getElements", "(", ")", "as", "$", "element", ")", "{", "if", "(", "method_exists", "(", "$", "element", ",", "'setObjectManager'", ")", ")", "{", "$", "element", "->", "setObjectManager", "(", "$", "this", "->", "getDocumentManager", "(", ")", ")", ";", "$", "hasDocument", "=", "true", ";", "}", "elseif", "(", "method_exists", "(", "$", "element", ",", "'getProxy'", ")", ")", "{", "$", "proxy", "=", "$", "element", "->", "getProxy", "(", ")", ";", "if", "(", "method_exists", "(", "$", "proxy", ",", "'setObjectManager'", ")", ")", "{", "$", "proxy", "->", "setObjectManager", "(", "$", "this", "->", "getDocumentManager", "(", ")", ")", ";", "$", "hasDocument", "=", "true", ";", "}", "}", "}", "if", "(", "$", "hasDocument", ")", "{", "$", "hydrator", "=", "new", "DoctrineObjectHydrator", "(", "$", "this", "->", "getDocumentManager", "(", ")", ",", "$", "documentClass", ")", ";", "$", "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 do documento.
[ "Retorna", "a", "form", "para", "o", "cadastro", "do", "documento", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Controller/ODM/AbstractCrudController.php#L135-L196
Lansoweb/LosBase
src/LosBase/Controller/ODM/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\ODM\MongoDB\Query\Builder */ $qb = $this->getDocumentManager()->createQueryBuilder($this->getDocumentClass()); $qb->select() ->sort($sort, $order) ->limit($limit) ->skip($offset); $this->handleSearch($qb); $paginator = new Paginator(new DoctrinePaginator($qb->getQuery()->execute())); $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\ODM\MongoDB\Query\Builder */ $qb = $this->getDocumentManager()->createQueryBuilder($this->getDocumentClass()); $qb->select() ->sort($sort, $order) ->limit($limit) ->skip($offset); $this->handleSearch($qb); $paginator = new Paginator(new DoctrinePaginator($qb->getQuery()->execute())); $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\\ODM\\MongoDB\\Query\\Builder */", "$", "qb", "=", "$", "this", "->", "getDocumentManager", "(", ")", "->", "createQueryBuilder", "(", "$", "this", "->", "getDocumentClass", "(", ")", ")", ";", "$", "qb", "->", "select", "(", ")", "->", "sort", "(", "$", "sort", ",", "$", "order", ")", "->", "limit", "(", "$", "limit", ")", "->", "skip", "(", "$", "offset", ")", ";", "$", "this", "->", "handleSearch", "(", "$", "qb", ")", ";", "$", "paginator", "=", "new", "Paginator", "(", "new", "DoctrinePaginator", "(", "$", "qb", "->", "getQuery", "(", ")", "->", "execute", "(", ")", ")", ")", ";", "$", "paginator", "->", "setDefaultItemCountPerPage", "(", "$", "limit", ")", ";", "$", "paginator", "->", "setCurrentPageNumber", "(", "$", "page", ")", ";", "$", "paginator", "->", "setPageRange", "(", "$", "this", "->", "paginatorRange", ")", ";", "return", "[", "'paginator'", "=>", "$", "paginator", ",", "'sort'", "=>", "$", "sort", ",", "'order'", "=>", "$", "order", ",", "'page'", "=>", "$", "page", ",", "'query'", "=>", "$", "this", "->", "params", "(", ")", "->", "fromQuery", "(", ")", ",", "]", ";", "}" ]
Lista os documentos, suporte a paginação, ordenação e busca.
[ "Lista", "os", "documentos", "suporte", "a", "paginação", "ordenação", "e", "busca", "." ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/Controller/ODM/AbstractCrudController.php#L205-L242
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.getFieldNames
public static function getFieldNames($type = BasePeer::TYPE_PHPNAME) { if (!array_key_exists($type, CustomerPeer::$fieldNames)) { throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); } return CustomerPeer::$fieldNames[$type]; }
php
public static function getFieldNames($type = BasePeer::TYPE_PHPNAME) { if (!array_key_exists($type, CustomerPeer::$fieldNames)) { throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); } return CustomerPeer::$fieldNames[$type]; }
[ "public", "static", "function", "getFieldNames", "(", "$", "type", "=", "BasePeer", "::", "TYPE_PHPNAME", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "type", ",", "CustomerPeer", "::", "$", "fieldNames", ")", ")", "{", "throw", "new", "PropelException", "(", "'Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. '", ".", "$", "type", ".", "' was given.'", ")", ";", "}", "return", "CustomerPeer", "::", "$", "fieldNames", "[", "$", "type", "]", ";", "}" ]
Returns an array of field names. @param string $type The type of fieldnames to return: One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM @return array A list of field names @throws PropelException - if the type is not valid.
[ "Returns", "an", "array", "of", "field", "names", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L154-L161
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.addSelectColumns
public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { $criteria->addSelectColumn(CustomerPeer::ID); $criteria->addSelectColumn(CustomerPeer::NAME); $criteria->addSelectColumn(CustomerPeer::STREET); $criteria->addSelectColumn(CustomerPeer::ZIP); $criteria->addSelectColumn(CustomerPeer::CITY); $criteria->addSelectColumn(CustomerPeer::COUNTRY_ID); $criteria->addSelectColumn(CustomerPeer::PHONE); $criteria->addSelectColumn(CustomerPeer::FAX); $criteria->addSelectColumn(CustomerPeer::EMAIL); $criteria->addSelectColumn(CustomerPeer::LEGALFORM); $criteria->addSelectColumn(CustomerPeer::LOGO); $criteria->addSelectColumn(CustomerPeer::CREATED); $criteria->addSelectColumn(CustomerPeer::NOTES); } else { $criteria->addSelectColumn($alias . '.id'); $criteria->addSelectColumn($alias . '.name'); $criteria->addSelectColumn($alias . '.street'); $criteria->addSelectColumn($alias . '.zip'); $criteria->addSelectColumn($alias . '.city'); $criteria->addSelectColumn($alias . '.country_id'); $criteria->addSelectColumn($alias . '.phone'); $criteria->addSelectColumn($alias . '.fax'); $criteria->addSelectColumn($alias . '.email'); $criteria->addSelectColumn($alias . '.legalform'); $criteria->addSelectColumn($alias . '.logo'); $criteria->addSelectColumn($alias . '.created'); $criteria->addSelectColumn($alias . '.notes'); } }
php
public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { $criteria->addSelectColumn(CustomerPeer::ID); $criteria->addSelectColumn(CustomerPeer::NAME); $criteria->addSelectColumn(CustomerPeer::STREET); $criteria->addSelectColumn(CustomerPeer::ZIP); $criteria->addSelectColumn(CustomerPeer::CITY); $criteria->addSelectColumn(CustomerPeer::COUNTRY_ID); $criteria->addSelectColumn(CustomerPeer::PHONE); $criteria->addSelectColumn(CustomerPeer::FAX); $criteria->addSelectColumn(CustomerPeer::EMAIL); $criteria->addSelectColumn(CustomerPeer::LEGALFORM); $criteria->addSelectColumn(CustomerPeer::LOGO); $criteria->addSelectColumn(CustomerPeer::CREATED); $criteria->addSelectColumn(CustomerPeer::NOTES); } else { $criteria->addSelectColumn($alias . '.id'); $criteria->addSelectColumn($alias . '.name'); $criteria->addSelectColumn($alias . '.street'); $criteria->addSelectColumn($alias . '.zip'); $criteria->addSelectColumn($alias . '.city'); $criteria->addSelectColumn($alias . '.country_id'); $criteria->addSelectColumn($alias . '.phone'); $criteria->addSelectColumn($alias . '.fax'); $criteria->addSelectColumn($alias . '.email'); $criteria->addSelectColumn($alias . '.legalform'); $criteria->addSelectColumn($alias . '.logo'); $criteria->addSelectColumn($alias . '.created'); $criteria->addSelectColumn($alias . '.notes'); } }
[ "public", "static", "function", "addSelectColumns", "(", "Criteria", "$", "criteria", ",", "$", "alias", "=", "null", ")", "{", "if", "(", "null", "===", "$", "alias", ")", "{", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "ID", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "NAME", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "STREET", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "ZIP", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "CITY", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "COUNTRY_ID", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "PHONE", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "FAX", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "EMAIL", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "LEGALFORM", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "LOGO", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "CREATED", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "CustomerPeer", "::", "NOTES", ")", ";", "}", "else", "{", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.id'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.name'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.street'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.zip'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.city'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.country_id'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.phone'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.fax'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.email'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.legalform'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.logo'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.created'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.notes'", ")", ";", "}", "}" ]
Add all the columns needed to create a new object. Note: any columns that were marked with lazyLoad="true" in the XML schema will not be added to the select list and only loaded on demand. @param Criteria $criteria object containing the columns to add. @param string $alias optional table alias @throws PropelException Any exceptions caught during processing will be rethrown wrapped into a PropelException.
[ "Add", "all", "the", "columns", "needed", "to", "create", "a", "new", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L192-L223
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.getInstanceFromPool
public static function getInstanceFromPool($key) { if (Propel::isInstancePoolingEnabled()) { if (isset(CustomerPeer::$instances[$key])) { return CustomerPeer::$instances[$key]; } } return null; // just to be explicit }
php
public static function getInstanceFromPool($key) { if (Propel::isInstancePoolingEnabled()) { if (isset(CustomerPeer::$instances[$key])) { return CustomerPeer::$instances[$key]; } } return null; // just to be explicit }
[ "public", "static", "function", "getInstanceFromPool", "(", "$", "key", ")", "{", "if", "(", "Propel", "::", "isInstancePoolingEnabled", "(", ")", ")", "{", "if", "(", "isset", "(", "CustomerPeer", "::", "$", "instances", "[", "$", "key", "]", ")", ")", "{", "return", "CustomerPeer", "::", "$", "instances", "[", "$", "key", "]", ";", "}", "}", "return", "null", ";", "// just to be explicit", "}" ]
Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. For tables with a single-column primary key, that simple pkey value will be returned. For tables with a multi-column primary key, a serialize()d version of the primary key will be returned. @param string $key The key (@see getPrimaryKeyHash()) for this instance. @return Customer Found object or null if 1) no instance exists for specified key or 2) instance pooling has been disabled. @see getPrimaryKeyHash()
[ "Retrieves", "a", "string", "version", "of", "the", "primary", "key", "from", "the", "DB", "resultset", "row", "that", "can", "be", "used", "to", "uniquely", "identify", "a", "row", "in", "this", "table", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L394-L403
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.populateObjects
public static function populateObjects(PDOStatement $stmt) { $results = array(); // set the class once to avoid overhead in the loop $cls = CustomerPeer::getOMClass(); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { $key = CustomerPeer::getPrimaryKeyHashFromRow($row, 0); if (null !== ($obj = CustomerPeer::getInstanceFromPool($key))) { // We no longer rehydrate the object, since this can cause data loss. // See http://www.propelorm.org/ticket/509 // $obj->hydrate($row, 0, true); // rehydrate $results[] = $obj; } else { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; CustomerPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); return $results; }
php
public static function populateObjects(PDOStatement $stmt) { $results = array(); // set the class once to avoid overhead in the loop $cls = CustomerPeer::getOMClass(); // populate the object(s) while ($row = $stmt->fetch(PDO::FETCH_NUM)) { $key = CustomerPeer::getPrimaryKeyHashFromRow($row, 0); if (null !== ($obj = CustomerPeer::getInstanceFromPool($key))) { // We no longer rehydrate the object, since this can cause data loss. // See http://www.propelorm.org/ticket/509 // $obj->hydrate($row, 0, true); // rehydrate $results[] = $obj; } else { $obj = new $cls(); $obj->hydrate($row); $results[] = $obj; CustomerPeer::addInstanceToPool($obj, $key); } // if key exists } $stmt->closeCursor(); return $results; }
[ "public", "static", "function", "populateObjects", "(", "PDOStatement", "$", "stmt", ")", "{", "$", "results", "=", "array", "(", ")", ";", "// set the class once to avoid overhead in the loop", "$", "cls", "=", "CustomerPeer", "::", "getOMClass", "(", ")", ";", "// populate the object(s)", "while", "(", "$", "row", "=", "$", "stmt", "->", "fetch", "(", "PDO", "::", "FETCH_NUM", ")", ")", "{", "$", "key", "=", "CustomerPeer", "::", "getPrimaryKeyHashFromRow", "(", "$", "row", ",", "0", ")", ";", "if", "(", "null", "!==", "(", "$", "obj", "=", "CustomerPeer", "::", "getInstanceFromPool", "(", "$", "key", ")", ")", ")", "{", "// We no longer rehydrate the object, since this can cause data loss.", "// See http://www.propelorm.org/ticket/509", "// $obj->hydrate($row, 0, true); // rehydrate", "$", "results", "[", "]", "=", "$", "obj", ";", "}", "else", "{", "$", "obj", "=", "new", "$", "cls", "(", ")", ";", "$", "obj", "->", "hydrate", "(", "$", "row", ")", ";", "$", "results", "[", "]", "=", "$", "obj", ";", "CustomerPeer", "::", "addInstanceToPool", "(", "$", "obj", ",", "$", "key", ")", ";", "}", "// if key exists", "}", "$", "stmt", "->", "closeCursor", "(", ")", ";", "return", "$", "results", ";", "}" ]
The returned array will contain objects of the default type or objects that inherit from the default. @throws PropelException Any exceptions caught during processing will be rethrown wrapped into a PropelException.
[ "The", "returned", "array", "will", "contain", "objects", "of", "the", "default", "type", "or", "objects", "that", "inherit", "from", "the", "default", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L476-L500
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.doSelectJoinCountry
public static function doSelectJoinCountry(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; // Set the correct dbName if it has not been overridden if ($criteria->getDbName() == Propel::getDefaultDB()) { $criteria->setDbName(CustomerPeer::DATABASE_NAME); } CustomerPeer::addSelectColumns($criteria); $startcol = CustomerPeer::NUM_HYDRATE_COLUMNS; CountryPeer::addSelectColumns($criteria); $criteria->addJoin(CustomerPeer::COUNTRY_ID, CountryPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { $key1 = CustomerPeer::getPrimaryKeyHashFromRow($row, 0); if (null !== ($obj1 = CustomerPeer::getInstanceFromPool($key1))) { // We no longer rehydrate the object, since this can cause data loss. // See http://www.propelorm.org/ticket/509 // $obj1->hydrate($row, 0, true); // rehydrate } else { $cls = CustomerPeer::getOMClass(); $obj1 = new $cls(); $obj1->hydrate($row); CustomerPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded $key2 = CountryPeer::getPrimaryKeyHashFromRow($row, $startcol); if ($key2 !== null) { $obj2 = CountryPeer::getInstanceFromPool($key2); if (!$obj2) { $cls = CountryPeer::getOMClass(); $obj2 = new $cls(); $obj2->hydrate($row, $startcol); CountryPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded // Add the $obj1 (Customer) to $obj2 (Country) $obj2->addCustomer($obj1); } // if joined row was not null $results[] = $obj1; } $stmt->closeCursor(); return $results; }
php
public static function doSelectJoinCountry(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; // Set the correct dbName if it has not been overridden if ($criteria->getDbName() == Propel::getDefaultDB()) { $criteria->setDbName(CustomerPeer::DATABASE_NAME); } CustomerPeer::addSelectColumns($criteria); $startcol = CustomerPeer::NUM_HYDRATE_COLUMNS; CountryPeer::addSelectColumns($criteria); $criteria->addJoin(CustomerPeer::COUNTRY_ID, CountryPeer::ID, $join_behavior); $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { $key1 = CustomerPeer::getPrimaryKeyHashFromRow($row, 0); if (null !== ($obj1 = CustomerPeer::getInstanceFromPool($key1))) { // We no longer rehydrate the object, since this can cause data loss. // See http://www.propelorm.org/ticket/509 // $obj1->hydrate($row, 0, true); // rehydrate } else { $cls = CustomerPeer::getOMClass(); $obj1 = new $cls(); $obj1->hydrate($row); CustomerPeer::addInstanceToPool($obj1, $key1); } // if $obj1 already loaded $key2 = CountryPeer::getPrimaryKeyHashFromRow($row, $startcol); if ($key2 !== null) { $obj2 = CountryPeer::getInstanceFromPool($key2); if (!$obj2) { $cls = CountryPeer::getOMClass(); $obj2 = new $cls(); $obj2->hydrate($row, $startcol); CountryPeer::addInstanceToPool($obj2, $key2); } // if obj2 already loaded // Add the $obj1 (Customer) to $obj2 (Country) $obj2->addCustomer($obj1); } // if joined row was not null $results[] = $obj1; } $stmt->closeCursor(); return $results; }
[ "public", "static", "function", "doSelectJoinCountry", "(", "Criteria", "$", "criteria", ",", "$", "con", "=", "null", ",", "$", "join_behavior", "=", "Criteria", "::", "LEFT_JOIN", ")", "{", "$", "criteria", "=", "clone", "$", "criteria", ";", "// Set the correct dbName if it has not been overridden", "if", "(", "$", "criteria", "->", "getDbName", "(", ")", "==", "Propel", "::", "getDefaultDB", "(", ")", ")", "{", "$", "criteria", "->", "setDbName", "(", "CustomerPeer", "::", "DATABASE_NAME", ")", ";", "}", "CustomerPeer", "::", "addSelectColumns", "(", "$", "criteria", ")", ";", "$", "startcol", "=", "CustomerPeer", "::", "NUM_HYDRATE_COLUMNS", ";", "CountryPeer", "::", "addSelectColumns", "(", "$", "criteria", ")", ";", "$", "criteria", "->", "addJoin", "(", "CustomerPeer", "::", "COUNTRY_ID", ",", "CountryPeer", "::", "ID", ",", "$", "join_behavior", ")", ";", "$", "stmt", "=", "BasePeer", "::", "doSelect", "(", "$", "criteria", ",", "$", "con", ")", ";", "$", "results", "=", "array", "(", ")", ";", "while", "(", "$", "row", "=", "$", "stmt", "->", "fetch", "(", "PDO", "::", "FETCH_NUM", ")", ")", "{", "$", "key1", "=", "CustomerPeer", "::", "getPrimaryKeyHashFromRow", "(", "$", "row", ",", "0", ")", ";", "if", "(", "null", "!==", "(", "$", "obj1", "=", "CustomerPeer", "::", "getInstanceFromPool", "(", "$", "key1", ")", ")", ")", "{", "// We no longer rehydrate the object, since this can cause data loss.", "// See http://www.propelorm.org/ticket/509", "// $obj1->hydrate($row, 0, true); // rehydrate", "}", "else", "{", "$", "cls", "=", "CustomerPeer", "::", "getOMClass", "(", ")", ";", "$", "obj1", "=", "new", "$", "cls", "(", ")", ";", "$", "obj1", "->", "hydrate", "(", "$", "row", ")", ";", "CustomerPeer", "::", "addInstanceToPool", "(", "$", "obj1", ",", "$", "key1", ")", ";", "}", "// if $obj1 already loaded", "$", "key2", "=", "CountryPeer", "::", "getPrimaryKeyHashFromRow", "(", "$", "row", ",", "$", "startcol", ")", ";", "if", "(", "$", "key2", "!==", "null", ")", "{", "$", "obj2", "=", "CountryPeer", "::", "getInstanceFromPool", "(", "$", "key2", ")", ";", "if", "(", "!", "$", "obj2", ")", "{", "$", "cls", "=", "CountryPeer", "::", "getOMClass", "(", ")", ";", "$", "obj2", "=", "new", "$", "cls", "(", ")", ";", "$", "obj2", "->", "hydrate", "(", "$", "row", ",", "$", "startcol", ")", ";", "CountryPeer", "::", "addInstanceToPool", "(", "$", "obj2", ",", "$", "key2", ")", ";", "}", "// if obj2 already loaded", "// Add the $obj1 (Customer) to $obj2 (Country)", "$", "obj2", "->", "addCustomer", "(", "$", "obj1", ")", ";", "}", "// if joined row was not null", "$", "results", "[", "]", "=", "$", "obj1", ";", "}", "$", "stmt", "->", "closeCursor", "(", ")", ";", "return", "$", "results", ";", "}" ]
Selects a collection of Customer objects pre-filled with their Country objects. @param Criteria $criteria @param PropelPDO $con @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN @return array Array of Customer objects. @throws PropelException Any exceptions caught during processing will be rethrown wrapped into a PropelException.
[ "Selects", "a", "collection", "of", "Customer", "objects", "pre", "-", "filled", "with", "their", "Country", "objects", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L589-L644
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.buildTableMap
public static function buildTableMap() { $dbMap = Propel::getDatabaseMap(BaseCustomerPeer::DATABASE_NAME); if (!$dbMap->hasTable(BaseCustomerPeer::TABLE_NAME)) { $dbMap->addTableObject(new \Slashworks\AppBundle\Model\map\CustomerTableMap()); } }
php
public static function buildTableMap() { $dbMap = Propel::getDatabaseMap(BaseCustomerPeer::DATABASE_NAME); if (!$dbMap->hasTable(BaseCustomerPeer::TABLE_NAME)) { $dbMap->addTableObject(new \Slashworks\AppBundle\Model\map\CustomerTableMap()); } }
[ "public", "static", "function", "buildTableMap", "(", ")", "{", "$", "dbMap", "=", "Propel", "::", "getDatabaseMap", "(", "BaseCustomerPeer", "::", "DATABASE_NAME", ")", ";", "if", "(", "!", "$", "dbMap", "->", "hasTable", "(", "BaseCustomerPeer", "::", "TABLE_NAME", ")", ")", "{", "$", "dbMap", "->", "addTableObject", "(", "new", "\\", "Slashworks", "\\", "AppBundle", "\\", "Model", "\\", "map", "\\", "CustomerTableMap", "(", ")", ")", ";", "}", "}" ]
Add a TableMap instance to the database for this peer class.
[ "Add", "a", "TableMap", "instance", "to", "the", "database", "for", "this", "peer", "class", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L781-L787
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.doDeleteAll
public static function doDeleteAll(PropelPDO $con = null) { if ($con === null) { $con = Propel::getConnection(CustomerPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); $affectedRows += CustomerPeer::doOnDeleteCascade(new Criteria(CustomerPeer::DATABASE_NAME), $con); CustomerPeer::doOnDeleteSetNull(new Criteria(CustomerPeer::DATABASE_NAME), $con); $affectedRows += BasePeer::doDeleteAll(CustomerPeer::TABLE_NAME, $con, CustomerPeer::DATABASE_NAME); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). CustomerPeer::clearInstancePool(); CustomerPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } }
php
public static function doDeleteAll(PropelPDO $con = null) { if ($con === null) { $con = Propel::getConnection(CustomerPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); $affectedRows += CustomerPeer::doOnDeleteCascade(new Criteria(CustomerPeer::DATABASE_NAME), $con); CustomerPeer::doOnDeleteSetNull(new Criteria(CustomerPeer::DATABASE_NAME), $con); $affectedRows += BasePeer::doDeleteAll(CustomerPeer::TABLE_NAME, $con, CustomerPeer::DATABASE_NAME); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). CustomerPeer::clearInstancePool(); CustomerPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } }
[ "public", "static", "function", "doDeleteAll", "(", "PropelPDO", "$", "con", "=", "null", ")", "{", "if", "(", "$", "con", "===", "null", ")", "{", "$", "con", "=", "Propel", "::", "getConnection", "(", "CustomerPeer", "::", "DATABASE_NAME", ",", "Propel", "::", "CONNECTION_WRITE", ")", ";", "}", "$", "affectedRows", "=", "0", ";", "// initialize var to track total num of affected rows", "try", "{", "// use transaction because $criteria could contain info", "// for more than one table or we could emulating ON DELETE CASCADE, etc.", "$", "con", "->", "beginTransaction", "(", ")", ";", "$", "affectedRows", "+=", "CustomerPeer", "::", "doOnDeleteCascade", "(", "new", "Criteria", "(", "CustomerPeer", "::", "DATABASE_NAME", ")", ",", "$", "con", ")", ";", "CustomerPeer", "::", "doOnDeleteSetNull", "(", "new", "Criteria", "(", "CustomerPeer", "::", "DATABASE_NAME", ")", ",", "$", "con", ")", ";", "$", "affectedRows", "+=", "BasePeer", "::", "doDeleteAll", "(", "CustomerPeer", "::", "TABLE_NAME", ",", "$", "con", ",", "CustomerPeer", "::", "DATABASE_NAME", ")", ";", "// Because this db requires some delete cascade/set null emulation, we have to", "// clear the cached instance *after* the emulation has happened (since", "// instances get re-added by the select statement contained therein).", "CustomerPeer", "::", "clearInstancePool", "(", ")", ";", "CustomerPeer", "::", "clearRelatedInstancePool", "(", ")", ";", "$", "con", "->", "commit", "(", ")", ";", "return", "$", "affectedRows", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "con", "->", "rollBack", "(", ")", ";", "throw", "$", "e", ";", "}", "}" ]
Deletes all rows from the customer table. @param PropelPDO $con the connection to use @return int The number of affected rows (if supported by underlying database driver). @throws PropelException
[ "Deletes", "all", "rows", "from", "the", "customer", "table", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L889-L914
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.doOnDeleteCascade
protected static function doOnDeleteCascade(Criteria $criteria, PropelPDO $con) { // initialize var to track total num of affected rows $affectedRows = 0; // first find the objects that are implicated by the $criteria $objects = CustomerPeer::doSelect($criteria, $con); foreach ($objects as $obj) { // delete related UserCustomerRelation objects $criteria = new Criteria(UserCustomerRelationPeer::DATABASE_NAME); $criteria->add(UserCustomerRelationPeer::CUSTOMER_ID, $obj->getId()); $affectedRows += UserCustomerRelationPeer::doDelete($criteria, $con); } return $affectedRows; }
php
protected static function doOnDeleteCascade(Criteria $criteria, PropelPDO $con) { // initialize var to track total num of affected rows $affectedRows = 0; // first find the objects that are implicated by the $criteria $objects = CustomerPeer::doSelect($criteria, $con); foreach ($objects as $obj) { // delete related UserCustomerRelation objects $criteria = new Criteria(UserCustomerRelationPeer::DATABASE_NAME); $criteria->add(UserCustomerRelationPeer::CUSTOMER_ID, $obj->getId()); $affectedRows += UserCustomerRelationPeer::doDelete($criteria, $con); } return $affectedRows; }
[ "protected", "static", "function", "doOnDeleteCascade", "(", "Criteria", "$", "criteria", ",", "PropelPDO", "$", "con", ")", "{", "// initialize var to track total num of affected rows", "$", "affectedRows", "=", "0", ";", "// first find the objects that are implicated by the $criteria", "$", "objects", "=", "CustomerPeer", "::", "doSelect", "(", "$", "criteria", ",", "$", "con", ")", ";", "foreach", "(", "$", "objects", "as", "$", "obj", ")", "{", "// delete related UserCustomerRelation objects", "$", "criteria", "=", "new", "Criteria", "(", "UserCustomerRelationPeer", "::", "DATABASE_NAME", ")", ";", "$", "criteria", "->", "add", "(", "UserCustomerRelationPeer", "::", "CUSTOMER_ID", ",", "$", "obj", "->", "getId", "(", ")", ")", ";", "$", "affectedRows", "+=", "UserCustomerRelationPeer", "::", "doDelete", "(", "$", "criteria", ",", "$", "con", ")", ";", "}", "return", "$", "affectedRows", ";", "}" ]
This is a method for emulating ON DELETE CASCADE for DBs that don't support this feature (like MySQL or SQLite). This method is not very speedy because it must perform a query first to get the implicated records and then perform the deletes by calling those Peer classes. This method should be used within a transaction if possible. @param Criteria $criteria @param PropelPDO $con @return int The number of affected rows (if supported by underlying database driver).
[ "This", "is", "a", "method", "for", "emulating", "ON", "DELETE", "CASCADE", "for", "DBs", "that", "don", "t", "support", "this", "feature", "(", "like", "MySQL", "or", "SQLite", ")", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L999-L1017
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php
BaseCustomerPeer.doOnDeleteSetNull
protected static function doOnDeleteSetNull(Criteria $criteria, PropelPDO $con) { // first find the objects that are implicated by the $criteria $objects = CustomerPeer::doSelect($criteria, $con); foreach ($objects as $obj) { // set fkey col in related RemoteApp rows to null $selectCriteria = new Criteria(CustomerPeer::DATABASE_NAME); $updateValues = new Criteria(CustomerPeer::DATABASE_NAME); $selectCriteria->add(RemoteAppPeer::CUSTOMER_ID, $obj->getId()); $updateValues->add(RemoteAppPeer::CUSTOMER_ID, null); BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey } }
php
protected static function doOnDeleteSetNull(Criteria $criteria, PropelPDO $con) { // first find the objects that are implicated by the $criteria $objects = CustomerPeer::doSelect($criteria, $con); foreach ($objects as $obj) { // set fkey col in related RemoteApp rows to null $selectCriteria = new Criteria(CustomerPeer::DATABASE_NAME); $updateValues = new Criteria(CustomerPeer::DATABASE_NAME); $selectCriteria->add(RemoteAppPeer::CUSTOMER_ID, $obj->getId()); $updateValues->add(RemoteAppPeer::CUSTOMER_ID, null); BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey } }
[ "protected", "static", "function", "doOnDeleteSetNull", "(", "Criteria", "$", "criteria", ",", "PropelPDO", "$", "con", ")", "{", "// first find the objects that are implicated by the $criteria", "$", "objects", "=", "CustomerPeer", "::", "doSelect", "(", "$", "criteria", ",", "$", "con", ")", ";", "foreach", "(", "$", "objects", "as", "$", "obj", ")", "{", "// set fkey col in related RemoteApp rows to null", "$", "selectCriteria", "=", "new", "Criteria", "(", "CustomerPeer", "::", "DATABASE_NAME", ")", ";", "$", "updateValues", "=", "new", "Criteria", "(", "CustomerPeer", "::", "DATABASE_NAME", ")", ";", "$", "selectCriteria", "->", "add", "(", "RemoteAppPeer", "::", "CUSTOMER_ID", ",", "$", "obj", "->", "getId", "(", ")", ")", ";", "$", "updateValues", "->", "add", "(", "RemoteAppPeer", "::", "CUSTOMER_ID", ",", "null", ")", ";", "BasePeer", "::", "doUpdate", "(", "$", "selectCriteria", ",", "$", "updateValues", ",", "$", "con", ")", ";", "// use BasePeer because generated Peer doUpdate() methods only update using pkey", "}", "}" ]
This is a method for emulating ON DELETE SET NULL DBs that don't support this feature (like MySQL or SQLite). This method is not very speedy because it must perform a query first to get the implicated records and then perform the deletes by calling those Peer classes. This method should be used within a transaction if possible. @param Criteria $criteria @param PropelPDO $con @return void
[ "This", "is", "a", "method", "for", "emulating", "ON", "DELETE", "SET", "NULL", "DBs", "that", "don", "t", "support", "this", "feature", "(", "like", "MySQL", "or", "SQLite", ")", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCustomerPeer.php#L1032-L1048
rayrutjes/domain-foundation
src/Audit/AuditUnitOfWorkListener.php
AuditUnitOfWorkListener.onEventRegistration
public function onEventRegistration(UnitOfWork $unitOfWork, Event $event) { $auditData = $this->auditDataProvider->provideAuditDataFor($this->command); if (!empty($auditData)) { $event = $event->enrichMetadata($auditData); } $this->recordedEvents[] = $event; return $event; }
php
public function onEventRegistration(UnitOfWork $unitOfWork, Event $event) { $auditData = $this->auditDataProvider->provideAuditDataFor($this->command); if (!empty($auditData)) { $event = $event->enrichMetadata($auditData); } $this->recordedEvents[] = $event; return $event; }
[ "public", "function", "onEventRegistration", "(", "UnitOfWork", "$", "unitOfWork", ",", "Event", "$", "event", ")", "{", "$", "auditData", "=", "$", "this", "->", "auditDataProvider", "->", "provideAuditDataFor", "(", "$", "this", "->", "command", ")", ";", "if", "(", "!", "empty", "(", "$", "auditData", ")", ")", "{", "$", "event", "=", "$", "event", "->", "enrichMetadata", "(", "$", "auditData", ")", ";", "}", "$", "this", "->", "recordedEvents", "[", "]", "=", "$", "event", ";", "return", "$", "event", ";", "}" ]
@param UnitOfWork $unitOfWork @param Event $event @return Event
[ "@param", "UnitOfWork", "$unitOfWork", "@param", "Event", "$event" ]
train
https://github.com/rayrutjes/domain-foundation/blob/2bce7cd6a6612f718e70e3176589c1abf39d1a3e/src/Audit/AuditUnitOfWorkListener.php#L75-L86
joomlatools/joomlatools-platform-legacy
code/form/field/modulelayout.php
JFormFieldModulelayout.getInput
protected function getInput() { // Get the client id. $clientId = $this->element['client_id']; if (is_null($clientId) && $this->form instanceof JForm) { $clientId = $this->form->getValue('client_id'); } $clientId = (int) $clientId; $client = JApplicationHelper::getClientInfo($clientId); // Get the module. $module = (string) $this->element['module']; if (empty($module) && ($this->form instanceof JForm)) { $module = $this->form->getValue('module'); } $module = preg_replace('#\W#', '', $module); // Get the template. $template = (string) $this->element['template']; $template = preg_replace('#\W#', '', $template); // Get the style. $template_style_id = ''; if ($this->form instanceof JForm) { $template_style_id = $this->form->getValue('template_style_id'); $template_style_id = preg_replace('#\W#', '', $template_style_id); } // If an extension and view are present build the options. if ($module && $client) { // Load language file $lang = JFactory::getLanguage(); $lang->load($module . '.sys', $client->path, null, false, true) || $lang->load($module . '.sys', $client->path . '/modules/' . $module, null, false, true); // Get the database object and a new query object. $db = JFactory::getDbo(); $query = $db->getQuery(true); // Build the query. $query->select('element, name') ->from('#__extensions as e') ->where('e.client_id = ' . (int) $clientId) ->where('e.type = ' . $db->quote('template')) ->where('e.enabled = 1'); if ($template) { $query->where('e.element = ' . $db->quote($template)); } if ($template_style_id) { $query->join('LEFT', '#__templates as s on s.template=e.element') ->where('s.id=' . (int) $template_style_id); } // Set the query and load the templates. $db->setQuery($query); $templates = $db->loadObjectList('element'); // Build the search paths for module layouts. $module_path = JPath::clean($client->path . '/modules/' . $module . '/tmpl'); // Prepare array of component layouts $module_layouts = array(); // Prepare the grouped list $groups = array(); // Add the layout options from the module path. if (is_dir($module_path) && ($module_layouts = JFolder::files($module_path, '^[^_]*\.php$'))) { // Create the group for the module $groups['_'] = array(); $groups['_']['id'] = $this->id . '__'; $groups['_']['text'] = JText::sprintf('JOPTION_FROM_MODULE'); $groups['_']['items'] = array(); foreach ($module_layouts as $file) { // Add an option to the module group $value = basename($file, '.php'); $text = $lang->hasKey($key = strtoupper($module . '_LAYOUT_' . $value)) ? JText::_($key) : $value; $groups['_']['items'][] = JHtml::_('select.option', '_:' . $value, $text); } } // Loop on all templates if ($templates) { foreach ($templates as $template) { // Load language file $lang->load('tpl_' . $template->element . '.sys', $client->path, null, false, true) || $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element, null, false, true); $template_path = JPath::clean($client->path . '/templates/' . $template->element . '/html/' . $module); // Add the layout options from the template path. if (is_dir($template_path) && ($files = JFolder::files($template_path, '^[^_]*\.php$'))) { foreach ($files as $i => $file) { // Remove layout that already exist in component ones if (in_array($file, $module_layouts)) { unset($files[$i]); } } if (count($files)) { // Create the group for the template $groups[$template->element] = array(); $groups[$template->element]['id'] = $this->id . '_' . $template->element; $groups[$template->element]['text'] = JText::sprintf('JOPTION_FROM_TEMPLATE', $template->name); $groups[$template->element]['items'] = array(); foreach ($files as $file) { // Add an option to the template group $value = basename($file, '.php'); $text = $lang->hasKey($key = strtoupper('TPL_' . $template->element . '_' . $module . '_LAYOUT_' . $value)) ? JText::_($key) : $value; $groups[$template->element]['items'][] = JHtml::_('select.option', $template->element . ':' . $value, $text); } } } } } // Compute attributes for the grouped list $attr = $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; // Prepare HTML code $html = array(); // Compute the current selected values $selected = array($this->value); // Add a grouped list $html[] = JHtml::_( 'select.groupedlist', $groups, $this->name, array('id' => $this->id, 'group.id' => 'id', 'list.attr' => $attr, 'list.select' => $selected) ); return implode($html); } else { return ''; } }
php
protected function getInput() { // Get the client id. $clientId = $this->element['client_id']; if (is_null($clientId) && $this->form instanceof JForm) { $clientId = $this->form->getValue('client_id'); } $clientId = (int) $clientId; $client = JApplicationHelper::getClientInfo($clientId); // Get the module. $module = (string) $this->element['module']; if (empty($module) && ($this->form instanceof JForm)) { $module = $this->form->getValue('module'); } $module = preg_replace('#\W#', '', $module); // Get the template. $template = (string) $this->element['template']; $template = preg_replace('#\W#', '', $template); // Get the style. $template_style_id = ''; if ($this->form instanceof JForm) { $template_style_id = $this->form->getValue('template_style_id'); $template_style_id = preg_replace('#\W#', '', $template_style_id); } // If an extension and view are present build the options. if ($module && $client) { // Load language file $lang = JFactory::getLanguage(); $lang->load($module . '.sys', $client->path, null, false, true) || $lang->load($module . '.sys', $client->path . '/modules/' . $module, null, false, true); // Get the database object and a new query object. $db = JFactory::getDbo(); $query = $db->getQuery(true); // Build the query. $query->select('element, name') ->from('#__extensions as e') ->where('e.client_id = ' . (int) $clientId) ->where('e.type = ' . $db->quote('template')) ->where('e.enabled = 1'); if ($template) { $query->where('e.element = ' . $db->quote($template)); } if ($template_style_id) { $query->join('LEFT', '#__templates as s on s.template=e.element') ->where('s.id=' . (int) $template_style_id); } // Set the query and load the templates. $db->setQuery($query); $templates = $db->loadObjectList('element'); // Build the search paths for module layouts. $module_path = JPath::clean($client->path . '/modules/' . $module . '/tmpl'); // Prepare array of component layouts $module_layouts = array(); // Prepare the grouped list $groups = array(); // Add the layout options from the module path. if (is_dir($module_path) && ($module_layouts = JFolder::files($module_path, '^[^_]*\.php$'))) { // Create the group for the module $groups['_'] = array(); $groups['_']['id'] = $this->id . '__'; $groups['_']['text'] = JText::sprintf('JOPTION_FROM_MODULE'); $groups['_']['items'] = array(); foreach ($module_layouts as $file) { // Add an option to the module group $value = basename($file, '.php'); $text = $lang->hasKey($key = strtoupper($module . '_LAYOUT_' . $value)) ? JText::_($key) : $value; $groups['_']['items'][] = JHtml::_('select.option', '_:' . $value, $text); } } // Loop on all templates if ($templates) { foreach ($templates as $template) { // Load language file $lang->load('tpl_' . $template->element . '.sys', $client->path, null, false, true) || $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element, null, false, true); $template_path = JPath::clean($client->path . '/templates/' . $template->element . '/html/' . $module); // Add the layout options from the template path. if (is_dir($template_path) && ($files = JFolder::files($template_path, '^[^_]*\.php$'))) { foreach ($files as $i => $file) { // Remove layout that already exist in component ones if (in_array($file, $module_layouts)) { unset($files[$i]); } } if (count($files)) { // Create the group for the template $groups[$template->element] = array(); $groups[$template->element]['id'] = $this->id . '_' . $template->element; $groups[$template->element]['text'] = JText::sprintf('JOPTION_FROM_TEMPLATE', $template->name); $groups[$template->element]['items'] = array(); foreach ($files as $file) { // Add an option to the template group $value = basename($file, '.php'); $text = $lang->hasKey($key = strtoupper('TPL_' . $template->element . '_' . $module . '_LAYOUT_' . $value)) ? JText::_($key) : $value; $groups[$template->element]['items'][] = JHtml::_('select.option', $template->element . ':' . $value, $text); } } } } } // Compute attributes for the grouped list $attr = $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; $attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; // Prepare HTML code $html = array(); // Compute the current selected values $selected = array($this->value); // Add a grouped list $html[] = JHtml::_( 'select.groupedlist', $groups, $this->name, array('id' => $this->id, 'group.id' => 'id', 'list.attr' => $attr, 'list.select' => $selected) ); return implode($html); } else { return ''; } }
[ "protected", "function", "getInput", "(", ")", "{", "// Get the client id.", "$", "clientId", "=", "$", "this", "->", "element", "[", "'client_id'", "]", ";", "if", "(", "is_null", "(", "$", "clientId", ")", "&&", "$", "this", "->", "form", "instanceof", "JForm", ")", "{", "$", "clientId", "=", "$", "this", "->", "form", "->", "getValue", "(", "'client_id'", ")", ";", "}", "$", "clientId", "=", "(", "int", ")", "$", "clientId", ";", "$", "client", "=", "JApplicationHelper", "::", "getClientInfo", "(", "$", "clientId", ")", ";", "// Get the module.", "$", "module", "=", "(", "string", ")", "$", "this", "->", "element", "[", "'module'", "]", ";", "if", "(", "empty", "(", "$", "module", ")", "&&", "(", "$", "this", "->", "form", "instanceof", "JForm", ")", ")", "{", "$", "module", "=", "$", "this", "->", "form", "->", "getValue", "(", "'module'", ")", ";", "}", "$", "module", "=", "preg_replace", "(", "'#\\W#'", ",", "''", ",", "$", "module", ")", ";", "// Get the template.", "$", "template", "=", "(", "string", ")", "$", "this", "->", "element", "[", "'template'", "]", ";", "$", "template", "=", "preg_replace", "(", "'#\\W#'", ",", "''", ",", "$", "template", ")", ";", "// Get the style.", "$", "template_style_id", "=", "''", ";", "if", "(", "$", "this", "->", "form", "instanceof", "JForm", ")", "{", "$", "template_style_id", "=", "$", "this", "->", "form", "->", "getValue", "(", "'template_style_id'", ")", ";", "$", "template_style_id", "=", "preg_replace", "(", "'#\\W#'", ",", "''", ",", "$", "template_style_id", ")", ";", "}", "// If an extension and view are present build the options.", "if", "(", "$", "module", "&&", "$", "client", ")", "{", "// Load language file", "$", "lang", "=", "JFactory", "::", "getLanguage", "(", ")", ";", "$", "lang", "->", "load", "(", "$", "module", ".", "'.sys'", ",", "$", "client", "->", "path", ",", "null", ",", "false", ",", "true", ")", "||", "$", "lang", "->", "load", "(", "$", "module", ".", "'.sys'", ",", "$", "client", "->", "path", ".", "'/modules/'", ".", "$", "module", ",", "null", ",", "false", ",", "true", ")", ";", "// Get the database object and a new query object.", "$", "db", "=", "JFactory", "::", "getDbo", "(", ")", ";", "$", "query", "=", "$", "db", "->", "getQuery", "(", "true", ")", ";", "// Build the query.", "$", "query", "->", "select", "(", "'element, name'", ")", "->", "from", "(", "'#__extensions as e'", ")", "->", "where", "(", "'e.client_id = '", ".", "(", "int", ")", "$", "clientId", ")", "->", "where", "(", "'e.type = '", ".", "$", "db", "->", "quote", "(", "'template'", ")", ")", "->", "where", "(", "'e.enabled = 1'", ")", ";", "if", "(", "$", "template", ")", "{", "$", "query", "->", "where", "(", "'e.element = '", ".", "$", "db", "->", "quote", "(", "$", "template", ")", ")", ";", "}", "if", "(", "$", "template_style_id", ")", "{", "$", "query", "->", "join", "(", "'LEFT'", ",", "'#__templates as s on s.template=e.element'", ")", "->", "where", "(", "'s.id='", ".", "(", "int", ")", "$", "template_style_id", ")", ";", "}", "// Set the query and load the templates.", "$", "db", "->", "setQuery", "(", "$", "query", ")", ";", "$", "templates", "=", "$", "db", "->", "loadObjectList", "(", "'element'", ")", ";", "// Build the search paths for module layouts.", "$", "module_path", "=", "JPath", "::", "clean", "(", "$", "client", "->", "path", ".", "'/modules/'", ".", "$", "module", ".", "'/tmpl'", ")", ";", "// Prepare array of component layouts", "$", "module_layouts", "=", "array", "(", ")", ";", "// Prepare the grouped list", "$", "groups", "=", "array", "(", ")", ";", "// Add the layout options from the module path.", "if", "(", "is_dir", "(", "$", "module_path", ")", "&&", "(", "$", "module_layouts", "=", "JFolder", "::", "files", "(", "$", "module_path", ",", "'^[^_]*\\.php$'", ")", ")", ")", "{", "// Create the group for the module", "$", "groups", "[", "'_'", "]", "=", "array", "(", ")", ";", "$", "groups", "[", "'_'", "]", "[", "'id'", "]", "=", "$", "this", "->", "id", ".", "'__'", ";", "$", "groups", "[", "'_'", "]", "[", "'text'", "]", "=", "JText", "::", "sprintf", "(", "'JOPTION_FROM_MODULE'", ")", ";", "$", "groups", "[", "'_'", "]", "[", "'items'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "module_layouts", "as", "$", "file", ")", "{", "// Add an option to the module group", "$", "value", "=", "basename", "(", "$", "file", ",", "'.php'", ")", ";", "$", "text", "=", "$", "lang", "->", "hasKey", "(", "$", "key", "=", "strtoupper", "(", "$", "module", ".", "'_LAYOUT_'", ".", "$", "value", ")", ")", "?", "JText", "::", "_", "(", "$", "key", ")", ":", "$", "value", ";", "$", "groups", "[", "'_'", "]", "[", "'items'", "]", "[", "]", "=", "JHtml", "::", "_", "(", "'select.option'", ",", "'_:'", ".", "$", "value", ",", "$", "text", ")", ";", "}", "}", "// Loop on all templates", "if", "(", "$", "templates", ")", "{", "foreach", "(", "$", "templates", "as", "$", "template", ")", "{", "// Load language file", "$", "lang", "->", "load", "(", "'tpl_'", ".", "$", "template", "->", "element", ".", "'.sys'", ",", "$", "client", "->", "path", ",", "null", ",", "false", ",", "true", ")", "||", "$", "lang", "->", "load", "(", "'tpl_'", ".", "$", "template", "->", "element", ".", "'.sys'", ",", "$", "client", "->", "path", ".", "'/templates/'", ".", "$", "template", "->", "element", ",", "null", ",", "false", ",", "true", ")", ";", "$", "template_path", "=", "JPath", "::", "clean", "(", "$", "client", "->", "path", ".", "'/templates/'", ".", "$", "template", "->", "element", ".", "'/html/'", ".", "$", "module", ")", ";", "// Add the layout options from the template path.", "if", "(", "is_dir", "(", "$", "template_path", ")", "&&", "(", "$", "files", "=", "JFolder", "::", "files", "(", "$", "template_path", ",", "'^[^_]*\\.php$'", ")", ")", ")", "{", "foreach", "(", "$", "files", "as", "$", "i", "=>", "$", "file", ")", "{", "// Remove layout that already exist in component ones", "if", "(", "in_array", "(", "$", "file", ",", "$", "module_layouts", ")", ")", "{", "unset", "(", "$", "files", "[", "$", "i", "]", ")", ";", "}", "}", "if", "(", "count", "(", "$", "files", ")", ")", "{", "// Create the group for the template", "$", "groups", "[", "$", "template", "->", "element", "]", "=", "array", "(", ")", ";", "$", "groups", "[", "$", "template", "->", "element", "]", "[", "'id'", "]", "=", "$", "this", "->", "id", ".", "'_'", ".", "$", "template", "->", "element", ";", "$", "groups", "[", "$", "template", "->", "element", "]", "[", "'text'", "]", "=", "JText", "::", "sprintf", "(", "'JOPTION_FROM_TEMPLATE'", ",", "$", "template", "->", "name", ")", ";", "$", "groups", "[", "$", "template", "->", "element", "]", "[", "'items'", "]", "=", "array", "(", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "// Add an option to the template group", "$", "value", "=", "basename", "(", "$", "file", ",", "'.php'", ")", ";", "$", "text", "=", "$", "lang", "->", "hasKey", "(", "$", "key", "=", "strtoupper", "(", "'TPL_'", ".", "$", "template", "->", "element", ".", "'_'", ".", "$", "module", ".", "'_LAYOUT_'", ".", "$", "value", ")", ")", "?", "JText", "::", "_", "(", "$", "key", ")", ":", "$", "value", ";", "$", "groups", "[", "$", "template", "->", "element", "]", "[", "'items'", "]", "[", "]", "=", "JHtml", "::", "_", "(", "'select.option'", ",", "$", "template", "->", "element", ".", "':'", ".", "$", "value", ",", "$", "text", ")", ";", "}", "}", "}", "}", "}", "// Compute attributes for the grouped list", "$", "attr", "=", "$", "this", "->", "element", "[", "'size'", "]", "?", "' size=\"'", ".", "(", "int", ")", "$", "this", "->", "element", "[", "'size'", "]", ".", "'\"'", ":", "''", ";", "$", "attr", ".=", "$", "this", "->", "element", "[", "'class'", "]", "?", "' class=\"'", ".", "(", "string", ")", "$", "this", "->", "element", "[", "'class'", "]", ".", "'\"'", ":", "''", ";", "// Prepare HTML code", "$", "html", "=", "array", "(", ")", ";", "// Compute the current selected values", "$", "selected", "=", "array", "(", "$", "this", "->", "value", ")", ";", "// Add a grouped list", "$", "html", "[", "]", "=", "JHtml", "::", "_", "(", "'select.groupedlist'", ",", "$", "groups", ",", "$", "this", "->", "name", ",", "array", "(", "'id'", "=>", "$", "this", "->", "id", ",", "'group.id'", "=>", "'id'", ",", "'list.attr'", "=>", "$", "attr", ",", "'list.select'", "=>", "$", "selected", ")", ")", ";", "return", "implode", "(", "$", "html", ")", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Method to get the field input for module layouts. @return string The field input. @since 11.1
[ "Method", "to", "get", "the", "field", "input", "for", "module", "layouts", "." ]
train
https://github.com/joomlatools/joomlatools-platform-legacy/blob/3a76944e2f2c415faa6504754c75321a3b478c06/code/form/field/modulelayout.php#L36-L198
whisller/IrcBotBundle
EventListener/Irc/ServerRequestListener.php
ServerRequestListener.processStringData
private function processStringData(DataFromServerEvent $event) { $regex = "/^(?:[:@]([^\\s]+) )?([^\\s]+)(?: ((?:[^:\\s][^\\s]* ?)*))?(?: ?:(.*))?$/"; // @author Joshua Lückers (http://joshualuckers.nl/2010/01/10/regular-expression-to-match-raw-irc-messages/) preg_match($regex, $event->getData(), $matches); if (isset($matches[2]) && ('' !== trim($matches[2]))) { $this->dispatcher->dispatch('whisnet_irc_bot.irc_command_'.$matches[2], new IrcCommandFoundEvent($matches)); } }
php
private function processStringData(DataFromServerEvent $event) { $regex = "/^(?:[:@]([^\\s]+) )?([^\\s]+)(?: ((?:[^:\\s][^\\s]* ?)*))?(?: ?:(.*))?$/"; // @author Joshua Lückers (http://joshualuckers.nl/2010/01/10/regular-expression-to-match-raw-irc-messages/) preg_match($regex, $event->getData(), $matches); if (isset($matches[2]) && ('' !== trim($matches[2]))) { $this->dispatcher->dispatch('whisnet_irc_bot.irc_command_'.$matches[2], new IrcCommandFoundEvent($matches)); } }
[ "private", "function", "processStringData", "(", "DataFromServerEvent", "$", "event", ")", "{", "$", "regex", "=", "\"/^(?:[:@]([^\\\\s]+) )?([^\\\\s]+)(?: ((?:[^:\\\\s][^\\\\s]* ?)*))?(?: ?:(.*))?$/\"", ";", "// @author Joshua Lückers (http://joshualuckers.nl/2010/01/10/regular-expression-to-match-raw-irc-messages/)", "preg_match", "(", "$", "regex", ",", "$", "event", "->", "getData", "(", ")", ",", "$", "matches", ")", ";", "if", "(", "isset", "(", "$", "matches", "[", "2", "]", ")", "&&", "(", "''", "!==", "trim", "(", "$", "matches", "[", "2", "]", ")", ")", ")", "{", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "'whisnet_irc_bot.irc_command_'", ".", "$", "matches", "[", "2", "]", ",", "new", "IrcCommandFoundEvent", "(", "$", "matches", ")", ")", ";", "}", "}" ]
Process string response from server. @param DataFromServerEvent $event
[ "Process", "string", "response", "from", "server", "." ]
train
https://github.com/whisller/IrcBotBundle/blob/d8bcafc1599cbbc7756b0a59f51ee988a2de0f2e/EventListener/Irc/ServerRequestListener.php#L45-L53
ufocoder/yii2-SyncSocial
src/components/SyncServicesValidator.php
SyncServicesValidator.validateAttribute
public function validateAttribute( $model, $attribute ) { $serviceList = $this->getSynchonizer()->getServiceList(); if ( $model->hasProperty( $attribute ) ) { if ( ! is_array( $model->$attribute ) ) { $this->addError( $model, $attribute, Yii::t( 'SyncSocial', 'Attribute "{attribute}" must be array', [ 'attribute' => $attribute ] ) ); } else { foreach ( $model->$attribute as $service ) { if ( ! in_array( $service, $serviceList ) ) { $this->addError( $model, $attribute, Yii::t( 'SyncSocial', 'Service list has wrong value' ) ); } } } } }
php
public function validateAttribute( $model, $attribute ) { $serviceList = $this->getSynchonizer()->getServiceList(); if ( $model->hasProperty( $attribute ) ) { if ( ! is_array( $model->$attribute ) ) { $this->addError( $model, $attribute, Yii::t( 'SyncSocial', 'Attribute "{attribute}" must be array', [ 'attribute' => $attribute ] ) ); } else { foreach ( $model->$attribute as $service ) { if ( ! in_array( $service, $serviceList ) ) { $this->addError( $model, $attribute, Yii::t( 'SyncSocial', 'Service list has wrong value' ) ); } } } } }
[ "public", "function", "validateAttribute", "(", "$", "model", ",", "$", "attribute", ")", "{", "$", "serviceList", "=", "$", "this", "->", "getSynchonizer", "(", ")", "->", "getServiceList", "(", ")", ";", "if", "(", "$", "model", "->", "hasProperty", "(", "$", "attribute", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "model", "->", "$", "attribute", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "model", ",", "$", "attribute", ",", "Yii", "::", "t", "(", "'SyncSocial'", ",", "'Attribute \"{attribute}\" must be array'", ",", "[", "'attribute'", "=>", "$", "attribute", "]", ")", ")", ";", "}", "else", "{", "foreach", "(", "$", "model", "->", "$", "attribute", "as", "$", "service", ")", "{", "if", "(", "!", "in_array", "(", "$", "service", ",", "$", "serviceList", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "model", ",", "$", "attribute", ",", "Yii", "::", "t", "(", "'SyncSocial'", ",", "'Service list has wrong value'", ")", ")", ";", "}", "}", "}", "}", "}" ]
@param \yii\base\Model $model @param string $attribute
[ "@param", "\\", "yii", "\\", "base", "\\", "Model", "$model" ]
train
https://github.com/ufocoder/yii2-SyncSocial/blob/2dbaaec2dad782c52fdd5b648a31ba7fe2a75e1b/src/components/SyncServicesValidator.php#L23-L41
EvanDotPro/EdpGithub
src/EdpGithub/Listener/Auth/HttpToken.php
HttpToken.preSend
public function preSend(Event $e) { $validator = new NotEmpty(); if (!isset($this->options['tokenOrLogin']) || !$validator->isValid($this->options['tokenOrLogin']) ) { throw new Exception\InvalidArgumentException('You need to set OAuth token!'); } /* @var Http\Request $request */ $request = $e->getTarget(); $headers = $request->getHeaders(); $params = array( 'Authorization' => 'token ' . $this->options['tokenOrLogin'], ); $headers->addHeaders($params); }
php
public function preSend(Event $e) { $validator = new NotEmpty(); if (!isset($this->options['tokenOrLogin']) || !$validator->isValid($this->options['tokenOrLogin']) ) { throw new Exception\InvalidArgumentException('You need to set OAuth token!'); } /* @var Http\Request $request */ $request = $e->getTarget(); $headers = $request->getHeaders(); $params = array( 'Authorization' => 'token ' . $this->options['tokenOrLogin'], ); $headers->addHeaders($params); }
[ "public", "function", "preSend", "(", "Event", "$", "e", ")", "{", "$", "validator", "=", "new", "NotEmpty", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'tokenOrLogin'", "]", ")", "||", "!", "$", "validator", "->", "isValid", "(", "$", "this", "->", "options", "[", "'tokenOrLogin'", "]", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "'You need to set OAuth token!'", ")", ";", "}", "/* @var Http\\Request $request */", "$", "request", "=", "$", "e", "->", "getTarget", "(", ")", ";", "$", "headers", "=", "$", "request", "->", "getHeaders", "(", ")", ";", "$", "params", "=", "array", "(", "'Authorization'", "=>", "'token '", ".", "$", "this", "->", "options", "[", "'tokenOrLogin'", "]", ",", ")", ";", "$", "headers", "->", "addHeaders", "(", "$", "params", ")", ";", "}" ]
Add Authorization Token to Header @throws Exception\InvalidArgumentException
[ "Add", "Authorization", "Token", "to", "Header" ]
train
https://github.com/EvanDotPro/EdpGithub/blob/51f3e33e02edbef011103e3c2c1629d46af011a3/src/EdpGithub/Listener/Auth/HttpToken.php#L17-L35
anime-db/app-bundle
src/Controller/MediaController.php
MediaController.faviconAction
public function faviconAction($host) { $response = new Response(); $response->headers->set('Content-Type', Downloader::FAVICON_MIME); $filename = $this->get('anime_db.downloader')->favicon($host); return $response->setContent(file_get_contents($filename)); }
php
public function faviconAction($host) { $response = new Response(); $response->headers->set('Content-Type', Downloader::FAVICON_MIME); $filename = $this->get('anime_db.downloader')->favicon($host); return $response->setContent(file_get_contents($filename)); }
[ "public", "function", "faviconAction", "(", "$", "host", ")", "{", "$", "response", "=", "new", "Response", "(", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "Downloader", "::", "FAVICON_MIME", ")", ";", "$", "filename", "=", "$", "this", "->", "get", "(", "'anime_db.downloader'", ")", "->", "favicon", "(", "$", "host", ")", ";", "return", "$", "response", "->", "setContent", "(", "file_get_contents", "(", "$", "filename", ")", ")", ";", "}" ]
@param string $host @return Response
[ "@param", "string", "$host" ]
train
https://github.com/anime-db/app-bundle/blob/ca3b342081719d41ba018792a75970cbb1f1fe22/src/Controller/MediaController.php#L22-L30
yuncms/framework
src/user/Bootstrap.php
Bootstrap.bootstrap
public function bootstrap($app) { if ($app->hasModule('user') && ($module = $app->getModule('user')) instanceof Module) { //监听用户活动时间 /** @var \yii\web\UserEvent $event */ $app->on(Application::EVENT_AFTER_REQUEST, function ($event) use ($app) { if (!$app->user->isGuest && Yii::$app->has('queue')) { $user = UserExtra::findOne(['user_id' => $app->user->id]); $user->updateAttributesAsync(['last_visit' => time()]); } }); //监听用户登录事件 /** @var \yii\web\UserEvent $event */ $app->user->on(User::EVENT_AFTER_LOGIN, function ($event) use ($app) { //记录最后登录时间记录最后登录IP记录登录次数 $user = UserExtra::findOne(['user_id' => $app->user->id]); $user->updateAttributesAsync(['login_at' => time(), 'login_ip' => Yii::$app->request->userIP]); $user->updateCountersAsync(['login_num' => 1]); }); } }
php
public function bootstrap($app) { if ($app->hasModule('user') && ($module = $app->getModule('user')) instanceof Module) { //监听用户活动时间 /** @var \yii\web\UserEvent $event */ $app->on(Application::EVENT_AFTER_REQUEST, function ($event) use ($app) { if (!$app->user->isGuest && Yii::$app->has('queue')) { $user = UserExtra::findOne(['user_id' => $app->user->id]); $user->updateAttributesAsync(['last_visit' => time()]); } }); //监听用户登录事件 /** @var \yii\web\UserEvent $event */ $app->user->on(User::EVENT_AFTER_LOGIN, function ($event) use ($app) { //记录最后登录时间记录最后登录IP记录登录次数 $user = UserExtra::findOne(['user_id' => $app->user->id]); $user->updateAttributesAsync(['login_at' => time(), 'login_ip' => Yii::$app->request->userIP]); $user->updateCountersAsync(['login_num' => 1]); }); } }
[ "public", "function", "bootstrap", "(", "$", "app", ")", "{", "if", "(", "$", "app", "->", "hasModule", "(", "'user'", ")", "&&", "(", "$", "module", "=", "$", "app", "->", "getModule", "(", "'user'", ")", ")", "instanceof", "Module", ")", "{", "//监听用户活动时间", "/** @var \\yii\\web\\UserEvent $event */", "$", "app", "->", "on", "(", "Application", "::", "EVENT_AFTER_REQUEST", ",", "function", "(", "$", "event", ")", "use", "(", "$", "app", ")", "{", "if", "(", "!", "$", "app", "->", "user", "->", "isGuest", "&&", "Yii", "::", "$", "app", "->", "has", "(", "'queue'", ")", ")", "{", "$", "user", "=", "UserExtra", "::", "findOne", "(", "[", "'user_id'", "=>", "$", "app", "->", "user", "->", "id", "]", ")", ";", "$", "user", "->", "updateAttributesAsync", "(", "[", "'last_visit'", "=>", "time", "(", ")", "]", ")", ";", "}", "}", ")", ";", "//监听用户登录事件", "/** @var \\yii\\web\\UserEvent $event */", "$", "app", "->", "user", "->", "on", "(", "User", "::", "EVENT_AFTER_LOGIN", ",", "function", "(", "$", "event", ")", "use", "(", "$", "app", ")", "{", "//记录最后登录时间记录最后登录IP记录登录次数", "$", "user", "=", "UserExtra", "::", "findOne", "(", "[", "'user_id'", "=>", "$", "app", "->", "user", "->", "id", "]", ")", ";", "$", "user", "->", "updateAttributesAsync", "(", "[", "'login_at'", "=>", "time", "(", ")", ",", "'login_ip'", "=>", "Yii", "::", "$", "app", "->", "request", "->", "userIP", "]", ")", ";", "$", "user", "->", "updateCountersAsync", "(", "[", "'login_num'", "=>", "1", "]", ")", ";", "}", ")", ";", "}", "}" ]
初始化 @param \yii\base\Application|\yuncms\web\Application $app
[ "初始化" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/Bootstrap.php#L28-L49
ClanCats/Core
src/console/migrator.php
migrator.action_create
public function action_create( $params ) { $name = array_shift( $params ); $file = \DB\Migrator::path( $name ); \CCFile::write( $file, "# ---> up\n\n\n\n# ---> down\n\n" ); }
php
public function action_create( $params ) { $name = array_shift( $params ); $file = \DB\Migrator::path( $name ); \CCFile::write( $file, "# ---> up\n\n\n\n# ---> down\n\n" ); }
[ "public", "function", "action_create", "(", "$", "params", ")", "{", "$", "name", "=", "array_shift", "(", "$", "params", ")", ";", "$", "file", "=", "\\", "DB", "\\", "Migrator", "::", "path", "(", "$", "name", ")", ";", "\\", "CCFile", "::", "write", "(", "$", "file", ",", "\"# ---> up\\n\\n\\n\\n# ---> down\\n\\n\"", ")", ";", "}" ]
Create new migration @param array $params @return void
[ "Create", "new", "migration" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/console/migrator.php#L66-L73
PortaText/php-sdk
src/PortaText/Command/Api/Sms.php
Sms.schedule
public function schedule($type, $details) { $schedule = array(); $schedule[$type] = $details; return $this->setArgument("schedule", $schedule); }
php
public function schedule($type, $details) { $schedule = array(); $schedule[$type] = $details; return $this->setArgument("schedule", $schedule); }
[ "public", "function", "schedule", "(", "$", "type", ",", "$", "details", ")", "{", "$", "schedule", "=", "array", "(", ")", ";", "$", "schedule", "[", "$", "type", "]", "=", "$", "details", ";", "return", "$", "this", "->", "setArgument", "(", "\"schedule\"", ",", "$", "schedule", ")", ";", "}" ]
Schedule this message @param integer $type Schedule type. @param array $details Schedule configuration. @return PortaText\Command\ICommand @see https://github.com/PortaText/docs/wiki/REST-API#schedules
[ "Schedule", "this", "message" ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Command/Api/Sms.php#L140-L145
PortaText/php-sdk
src/PortaText/Command/Api/Sms.php
Sms.getEndpoint
protected function getEndpoint($method) { $endpoint = "sms"; $searchParams = $this->getArgument("search_params"); if (!is_null($searchParams)) { $queryString = http_build_query($searchParams); $this->delArgument("search_params"); return "$endpoint?$queryString"; } $operationId = $this->getArgument("id"); if (!is_null($operationId)) { $endpoint .= "/$operationId"; $this->delArgument("id"); } return $endpoint; }
php
protected function getEndpoint($method) { $endpoint = "sms"; $searchParams = $this->getArgument("search_params"); if (!is_null($searchParams)) { $queryString = http_build_query($searchParams); $this->delArgument("search_params"); return "$endpoint?$queryString"; } $operationId = $this->getArgument("id"); if (!is_null($operationId)) { $endpoint .= "/$operationId"; $this->delArgument("id"); } return $endpoint; }
[ "protected", "function", "getEndpoint", "(", "$", "method", ")", "{", "$", "endpoint", "=", "\"sms\"", ";", "$", "searchParams", "=", "$", "this", "->", "getArgument", "(", "\"search_params\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "searchParams", ")", ")", "{", "$", "queryString", "=", "http_build_query", "(", "$", "searchParams", ")", ";", "$", "this", "->", "delArgument", "(", "\"search_params\"", ")", ";", "return", "\"$endpoint?$queryString\"", ";", "}", "$", "operationId", "=", "$", "this", "->", "getArgument", "(", "\"id\"", ")", ";", "if", "(", "!", "is_null", "(", "$", "operationId", ")", ")", "{", "$", "endpoint", ".=", "\"/$operationId\"", ";", "$", "this", "->", "delArgument", "(", "\"id\"", ")", ";", "}", "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/Sms.php#L154-L169
iocaste/microservice-foundation
src/Data/Repositories/Parameterizable.php
Parameterizable.findChoices
public function findChoices(Parameter $parameter): Collection { return $parameter->choices() ->where('parameter_id', $parameter->id) ->get(); }
php
public function findChoices(Parameter $parameter): Collection { return $parameter->choices() ->where('parameter_id', $parameter->id) ->get(); }
[ "public", "function", "findChoices", "(", "Parameter", "$", "parameter", ")", ":", "Collection", "{", "return", "$", "parameter", "->", "choices", "(", ")", "->", "where", "(", "'parameter_id'", ",", "$", "parameter", "->", "id", ")", "->", "get", "(", ")", ";", "}" ]
@param Parameter $parameter @return Collection
[ "@param", "Parameter", "$parameter" ]
train
https://github.com/iocaste/microservice-foundation/blob/274a154de4299e8a57314bab972e09f6d8cdae9e/src/Data/Repositories/Parameterizable.php#L19-L24
iocaste/microservice-foundation
src/Data/Repositories/Parameterizable.php
Parameterizable.getValue
public function getValue(Parameter $parameter, Model $model) { $modelParameter = $this->getModelParameter($model, $parameter->id); if (! $modelParameter) { if ($parameter->type === 'boolean') { return false; } return null; } if ($parameter->type === 'choice') { return $this->getParameterSelectedChoice($parameter, $modelParameter); } if ($parameter->type === 'boolean') { return (boolean) $modelParameter->value; } if ($parameter->type === 'integer') { return (int) $modelParameter->value; } if ($parameter->type === 'decimal') { return (float) $modelParameter->value; } // Return as string by default return $modelParameter->value; }
php
public function getValue(Parameter $parameter, Model $model) { $modelParameter = $this->getModelParameter($model, $parameter->id); if (! $modelParameter) { if ($parameter->type === 'boolean') { return false; } return null; } if ($parameter->type === 'choice') { return $this->getParameterSelectedChoice($parameter, $modelParameter); } if ($parameter->type === 'boolean') { return (boolean) $modelParameter->value; } if ($parameter->type === 'integer') { return (int) $modelParameter->value; } if ($parameter->type === 'decimal') { return (float) $modelParameter->value; } // Return as string by default return $modelParameter->value; }
[ "public", "function", "getValue", "(", "Parameter", "$", "parameter", ",", "Model", "$", "model", ")", "{", "$", "modelParameter", "=", "$", "this", "->", "getModelParameter", "(", "$", "model", ",", "$", "parameter", "->", "id", ")", ";", "if", "(", "!", "$", "modelParameter", ")", "{", "if", "(", "$", "parameter", "->", "type", "===", "'boolean'", ")", "{", "return", "false", ";", "}", "return", "null", ";", "}", "if", "(", "$", "parameter", "->", "type", "===", "'choice'", ")", "{", "return", "$", "this", "->", "getParameterSelectedChoice", "(", "$", "parameter", ",", "$", "modelParameter", ")", ";", "}", "if", "(", "$", "parameter", "->", "type", "===", "'boolean'", ")", "{", "return", "(", "boolean", ")", "$", "modelParameter", "->", "value", ";", "}", "if", "(", "$", "parameter", "->", "type", "===", "'integer'", ")", "{", "return", "(", "int", ")", "$", "modelParameter", "->", "value", ";", "}", "if", "(", "$", "parameter", "->", "type", "===", "'decimal'", ")", "{", "return", "(", "float", ")", "$", "modelParameter", "->", "value", ";", "}", "// Return as string by default", "return", "$", "modelParameter", "->", "value", ";", "}" ]
@param Parameter $parameter @param Model $model @return array|bool|float|int|mixed|null
[ "@param", "Parameter", "$parameter", "@param", "Model", "$model" ]
train
https://github.com/iocaste/microservice-foundation/blob/274a154de4299e8a57314bab972e09f6d8cdae9e/src/Data/Repositories/Parameterizable.php#L41-L71
iocaste/microservice-foundation
src/Data/Repositories/Parameterizable.php
Parameterizable.getParameterSelectedChoice
protected function getParameterSelectedChoice(Parameter $parameter, $modelParameter = null): ?array { $modelParameterValue = $modelParameter->value; $value = $parameter->choices() ->where('id', $modelParameterValue) ->where('parameter_id', $parameter->id) ->first(); if (! $value) { return null; } return [ 'id' => $value->id, 'slug' => $value->slug, 'name' => $value->translated_name, ]; }
php
protected function getParameterSelectedChoice(Parameter $parameter, $modelParameter = null): ?array { $modelParameterValue = $modelParameter->value; $value = $parameter->choices() ->where('id', $modelParameterValue) ->where('parameter_id', $parameter->id) ->first(); if (! $value) { return null; } return [ 'id' => $value->id, 'slug' => $value->slug, 'name' => $value->translated_name, ]; }
[ "protected", "function", "getParameterSelectedChoice", "(", "Parameter", "$", "parameter", ",", "$", "modelParameter", "=", "null", ")", ":", "?", "array", "{", "$", "modelParameterValue", "=", "$", "modelParameter", "->", "value", ";", "$", "value", "=", "$", "parameter", "->", "choices", "(", ")", "->", "where", "(", "'id'", ",", "$", "modelParameterValue", ")", "->", "where", "(", "'parameter_id'", ",", "$", "parameter", "->", "id", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "value", ")", "{", "return", "null", ";", "}", "return", "[", "'id'", "=>", "$", "value", "->", "id", ",", "'slug'", "=>", "$", "value", "->", "slug", ",", "'name'", "=>", "$", "value", "->", "translated_name", ",", "]", ";", "}" ]
@param Parameter $parameter @param null $modelParameter @return array|null
[ "@param", "Parameter", "$parameter", "@param", "null", "$modelParameter" ]
train
https://github.com/iocaste/microservice-foundation/blob/274a154de4299e8a57314bab972e09f6d8cdae9e/src/Data/Repositories/Parameterizable.php#L79-L97
yuncms/framework
src/helpers/SearchHelper.php
SearchHelper.normalizeKeywords
public static function normalizeKeywords($str, array $ignore = [], bool $processCharMap = true): string { // Flatten if (is_array($str)) { $str = StringHelper::toString($str, ' '); } // Get rid of tags $str = strip_tags($str); // Convert non-breaking spaces entities to regular ones $str = str_replace(['&nbsp;', '&#160;', '&#xa0;'], ' ', $str); // Get rid of entities $str = preg_replace('/&#?[a-z0-9]{2,8};/i', '', $str); // Normalize to lowercase $str = StringHelper::toLowerCase($str); if ($processCharMap) { // Remove punctuation and diacritics $str = strtr($str, self::_getCharMap()); } // Remove ignore-words? if (is_array($ignore) && !empty($ignore)) { foreach ($ignore as $word) { $word = preg_quote(static::normalizeKeywords($word), '/'); $str = preg_replace("/\b{$word}\b/u", '', $str); } } // Strip out new lines and superfluous spaces $str = preg_replace('/[\n\r]+/u', ' ', $str); $str = preg_replace('/\s{2,}/u', ' ', $str); // Trim white space $str = trim($str); return $str; }
php
public static function normalizeKeywords($str, array $ignore = [], bool $processCharMap = true): string { // Flatten if (is_array($str)) { $str = StringHelper::toString($str, ' '); } // Get rid of tags $str = strip_tags($str); // Convert non-breaking spaces entities to regular ones $str = str_replace(['&nbsp;', '&#160;', '&#xa0;'], ' ', $str); // Get rid of entities $str = preg_replace('/&#?[a-z0-9]{2,8};/i', '', $str); // Normalize to lowercase $str = StringHelper::toLowerCase($str); if ($processCharMap) { // Remove punctuation and diacritics $str = strtr($str, self::_getCharMap()); } // Remove ignore-words? if (is_array($ignore) && !empty($ignore)) { foreach ($ignore as $word) { $word = preg_quote(static::normalizeKeywords($word), '/'); $str = preg_replace("/\b{$word}\b/u", '', $str); } } // Strip out new lines and superfluous spaces $str = preg_replace('/[\n\r]+/u', ' ', $str); $str = preg_replace('/\s{2,}/u', ' ', $str); // Trim white space $str = trim($str); return $str; }
[ "public", "static", "function", "normalizeKeywords", "(", "$", "str", ",", "array", "$", "ignore", "=", "[", "]", ",", "bool", "$", "processCharMap", "=", "true", ")", ":", "string", "{", "// Flatten", "if", "(", "is_array", "(", "$", "str", ")", ")", "{", "$", "str", "=", "StringHelper", "::", "toString", "(", "$", "str", ",", "' '", ")", ";", "}", "// Get rid of tags", "$", "str", "=", "strip_tags", "(", "$", "str", ")", ";", "// Convert non-breaking spaces entities to regular ones", "$", "str", "=", "str_replace", "(", "[", "'&nbsp;'", ",", "'&#160;'", ",", "'&#xa0;'", "]", ",", "' '", ",", "$", "str", ")", ";", "// Get rid of entities", "$", "str", "=", "preg_replace", "(", "'/&#?[a-z0-9]{2,8};/i'", ",", "''", ",", "$", "str", ")", ";", "// Normalize to lowercase", "$", "str", "=", "StringHelper", "::", "toLowerCase", "(", "$", "str", ")", ";", "if", "(", "$", "processCharMap", ")", "{", "// Remove punctuation and diacritics", "$", "str", "=", "strtr", "(", "$", "str", ",", "self", "::", "_getCharMap", "(", ")", ")", ";", "}", "// Remove ignore-words?", "if", "(", "is_array", "(", "$", "ignore", ")", "&&", "!", "empty", "(", "$", "ignore", ")", ")", "{", "foreach", "(", "$", "ignore", "as", "$", "word", ")", "{", "$", "word", "=", "preg_quote", "(", "static", "::", "normalizeKeywords", "(", "$", "word", ")", ",", "'/'", ")", ";", "$", "str", "=", "preg_replace", "(", "\"/\\b{$word}\\b/u\"", ",", "''", ",", "$", "str", ")", ";", "}", "}", "// Strip out new lines and superfluous spaces", "$", "str", "=", "preg_replace", "(", "'/[\\n\\r]+/u'", ",", "' '", ",", "$", "str", ")", ";", "$", "str", "=", "preg_replace", "(", "'/\\s{2,}/u'", ",", "' '", ",", "$", "str", ")", ";", "// Trim white space", "$", "str", "=", "trim", "(", "$", "str", ")", ";", "return", "$", "str", ";", "}" ]
规范化搜索关键词 @param string[]|string $str The dirty keywords @param array $ignore Ignore words to strip out @param bool $processCharMap Whether to remove punctuation and diacritics (default is true) @return string The cleansed keywords.
[ "规范化搜索关键词" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/SearchHelper.php#L24-L64
yuncms/framework
src/helpers/SearchHelper.php
SearchHelper._getCharMap
private static function _getCharMap(): array { // Keep local copy static $map = []; if (empty($map)) { // This will replace accented chars with non-accented chars foreach (StringHelper::asciiCharMap() as $asciiChar => $charsArray) { foreach ($charsArray as $char) { $map[$char] = $asciiChar; } } // Replace punctuation with a space foreach (self::_getPunctuation() as $value) { $map[$value] = ' '; } } // Return the char map return $map; }
php
private static function _getCharMap(): array { // Keep local copy static $map = []; if (empty($map)) { // This will replace accented chars with non-accented chars foreach (StringHelper::asciiCharMap() as $asciiChar => $charsArray) { foreach ($charsArray as $char) { $map[$char] = $asciiChar; } } // Replace punctuation with a space foreach (self::_getPunctuation() as $value) { $map[$value] = ' '; } } // Return the char map return $map; }
[ "private", "static", "function", "_getCharMap", "(", ")", ":", "array", "{", "// Keep local copy", "static", "$", "map", "=", "[", "]", ";", "if", "(", "empty", "(", "$", "map", ")", ")", "{", "// This will replace accented chars with non-accented chars", "foreach", "(", "StringHelper", "::", "asciiCharMap", "(", ")", "as", "$", "asciiChar", "=>", "$", "charsArray", ")", "{", "foreach", "(", "$", "charsArray", "as", "$", "char", ")", "{", "$", "map", "[", "$", "char", "]", "=", "$", "asciiChar", ";", "}", "}", "// Replace punctuation with a space", "foreach", "(", "self", "::", "_getPunctuation", "(", ")", "as", "$", "value", ")", "{", "$", "map", "[", "$", "value", "]", "=", "' '", ";", "}", "}", "// Return the char map", "return", "$", "map", ";", "}" ]
Get array of chars to be used for conversion. @return array
[ "Get", "array", "of", "chars", "to", "be", "used", "for", "conversion", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/SearchHelper.php#L71-L92
gibilogic/crud-bundle
Utility/FlashableTrait.php
FlashableTrait.addUserFlash
protected function addUserFlash(SessionInterface $session, $type, $message) { $session->getFlashBag()->add($type, $message); }
php
protected function addUserFlash(SessionInterface $session, $type, $message) { $session->getFlashBag()->add($type, $message); }
[ "protected", "function", "addUserFlash", "(", "SessionInterface", "$", "session", ",", "$", "type", ",", "$", "message", ")", "{", "$", "session", "->", "getFlashBag", "(", ")", "->", "add", "(", "$", "type", ",", "$", "message", ")", ";", "}" ]
Adds a flash message to the given session. @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session @param string $type @param string $message
[ "Adds", "a", "flash", "message", "to", "the", "given", "session", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Utility/FlashableTrait.php#L64-L67
ClanCats/Core
src/classes/CCImage.php
CCImage.create
public static function create( $file, $type = null ) { // when no type is given use the file extension if ( is_null( $type ) ) { $type = CCStr::extension( $file ); // validate type if ( !in_array( $type, static::$available_image_types ) ) { $type = null; } } $image_data = getimagesize( $file ); if ( $image_data === false ) { return false; } $image = null; switch( $image_data['mime'] ) { case 'image/gif': $image = imagecreatefromgif( $file ); break; case 'image/jpeg'; $image = imagecreatefromjpeg( $file ); break; case 'image/png': $image = imagecreatefrompng( $file ); break; default: // we dont support other image types return false; break; } // when the image type is still null we are going to use // the mime type of the image if ( is_null( $type ) ) { $type = CCStr::suffix( $image_data['mime'], '/' ); } return new static( $image, $type ); }
php
public static function create( $file, $type = null ) { // when no type is given use the file extension if ( is_null( $type ) ) { $type = CCStr::extension( $file ); // validate type if ( !in_array( $type, static::$available_image_types ) ) { $type = null; } } $image_data = getimagesize( $file ); if ( $image_data === false ) { return false; } $image = null; switch( $image_data['mime'] ) { case 'image/gif': $image = imagecreatefromgif( $file ); break; case 'image/jpeg'; $image = imagecreatefromjpeg( $file ); break; case 'image/png': $image = imagecreatefrompng( $file ); break; default: // we dont support other image types return false; break; } // when the image type is still null we are going to use // the mime type of the image if ( is_null( $type ) ) { $type = CCStr::suffix( $image_data['mime'], '/' ); } return new static( $image, $type ); }
[ "public", "static", "function", "create", "(", "$", "file", ",", "$", "type", "=", "null", ")", "{", "// when no type is given use the file extension", "if", "(", "is_null", "(", "$", "type", ")", ")", "{", "$", "type", "=", "CCStr", "::", "extension", "(", "$", "file", ")", ";", "// validate type", "if", "(", "!", "in_array", "(", "$", "type", ",", "static", "::", "$", "available_image_types", ")", ")", "{", "$", "type", "=", "null", ";", "}", "}", "$", "image_data", "=", "getimagesize", "(", "$", "file", ")", ";", "if", "(", "$", "image_data", "===", "false", ")", "{", "return", "false", ";", "}", "$", "image", "=", "null", ";", "switch", "(", "$", "image_data", "[", "'mime'", "]", ")", "{", "case", "'image/gif'", ":", "$", "image", "=", "imagecreatefromgif", "(", "$", "file", ")", ";", "break", ";", "case", "'image/jpeg'", ";", "$", "image", "=", "imagecreatefromjpeg", "(", "$", "file", ")", ";", "break", ";", "case", "'image/png'", ":", "$", "image", "=", "imagecreatefrompng", "(", "$", "file", ")", ";", "break", ";", "default", ":", "// we dont support other image types", "return", "false", ";", "break", ";", "}", "// when the image type is still null we are going to use ", "// the mime type of the image ", "if", "(", "is_null", "(", "$", "type", ")", ")", "{", "$", "type", "=", "CCStr", "::", "suffix", "(", "$", "image_data", "[", "'mime'", "]", ",", "'/'", ")", ";", "}", "return", "new", "static", "(", "$", "image", ",", "$", "type", ")", ";", "}" ]
Create a image from file @param string $file @param string $type jpg|png|gif @return CCImage|false
[ "Create", "a", "image", "from", "file" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L57-L108
ClanCats/Core
src/classes/CCImage.php
CCImage.string
public static function string( $string, $type = null ) { $image = imagecreatefromstring( $string ); if ( $image !== false ) { return new static( $image, $type ); } return false; }
php
public static function string( $string, $type = null ) { $image = imagecreatefromstring( $string ); if ( $image !== false ) { return new static( $image, $type ); } return false; }
[ "public", "static", "function", "string", "(", "$", "string", ",", "$", "type", "=", "null", ")", "{", "$", "image", "=", "imagecreatefromstring", "(", "$", "string", ")", ";", "if", "(", "$", "image", "!==", "false", ")", "{", "return", "new", "static", "(", "$", "image", ",", "$", "type", ")", ";", "}", "return", "false", ";", "}" ]
Create an image from string @param string $string The image data string @param string $type jpg|png|gif @return CCImage|false
[ "Create", "an", "image", "from", "string" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L118-L128
ClanCats/Core
src/classes/CCImage.php
CCImage.aspect_ratio
public static function aspect_ratio( $width, $height, $proper = false ) { $ratio = $width / $height; if ( !$proper ) { return $ratio; } $tolerance = 1.e-6; $h1=1; $h2=0; $k1=0; $k2=1; $b = 1/$ratio; do { $b = 1/$b; $a = floor($b); $aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux; $aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux; $b = $b-$a; } while ( abs( $ratio-$h1 / $k1 ) > $ratio * $tolerance ); return $h1.":".$k1; }
php
public static function aspect_ratio( $width, $height, $proper = false ) { $ratio = $width / $height; if ( !$proper ) { return $ratio; } $tolerance = 1.e-6; $h1=1; $h2=0; $k1=0; $k2=1; $b = 1/$ratio; do { $b = 1/$b; $a = floor($b); $aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux; $aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux; $b = $b-$a; } while ( abs( $ratio-$h1 / $k1 ) > $ratio * $tolerance ); return $h1.":".$k1; }
[ "public", "static", "function", "aspect_ratio", "(", "$", "width", ",", "$", "height", ",", "$", "proper", "=", "false", ")", "{", "$", "ratio", "=", "$", "width", "/", "$", "height", ";", "if", "(", "!", "$", "proper", ")", "{", "return", "$", "ratio", ";", "}", "$", "tolerance", "=", "1.e-6", ";", "$", "h1", "=", "1", ";", "$", "h2", "=", "0", ";", "$", "k1", "=", "0", ";", "$", "k2", "=", "1", ";", "$", "b", "=", "1", "/", "$", "ratio", ";", "do", "{", "$", "b", "=", "1", "/", "$", "b", ";", "$", "a", "=", "floor", "(", "$", "b", ")", ";", "$", "aux", "=", "$", "h1", ";", "$", "h1", "=", "$", "a", "*", "$", "h1", "+", "$", "h2", ";", "$", "h2", "=", "$", "aux", ";", "$", "aux", "=", "$", "k1", ";", "$", "k1", "=", "$", "a", "*", "$", "k1", "+", "$", "k2", ";", "$", "k2", "=", "$", "aux", ";", "$", "b", "=", "$", "b", "-", "$", "a", ";", "}", "while", "(", "abs", "(", "$", "ratio", "-", "$", "h1", "/", "$", "k1", ")", ">", "$", "ratio", "*", "$", "tolerance", ")", ";", "return", "$", "h1", ".", "\":\"", ".", "$", "k1", ";", "}" ]
Calculate the aspect ratio @param int $width @param int $height @param bool $proper @return string @thanks to: http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/
[ "Calculate", "the", "aspect", "ratio" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L141-L165
ClanCats/Core
src/classes/CCImage.php
CCImage.reload_context_info
protected function reload_context_info() { $this->width = imagesx( $this->image_context ); $this->height = imagesy( $this->image_context ); }
php
protected function reload_context_info() { $this->width = imagesx( $this->image_context ); $this->height = imagesy( $this->image_context ); }
[ "protected", "function", "reload_context_info", "(", ")", "{", "$", "this", "->", "width", "=", "imagesx", "(", "$", "this", "->", "image_context", ")", ";", "$", "this", "->", "height", "=", "imagesy", "(", "$", "this", "->", "image_context", ")", ";", "}" ]
Reload the image dimension etc. @return void
[ "Reload", "the", "image", "dimension", "etc", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L221-L225
ClanCats/Core
src/classes/CCImage.php
CCImage.set_type
protected function set_type( $type, $overwrite = true ) { if ( !is_null( $type ) ) { if ( !in_array( $type, static::$available_image_types ) ) { throw new CCException( "CCImage - Invalid image type '".$type."'." ); } // don't allow jpg, set to jpeg if ( $type === 'jpg' ) { $type = 'jpeg'; } if ( $overwrite ) { $this->type = $type; } } return $type; }
php
protected function set_type( $type, $overwrite = true ) { if ( !is_null( $type ) ) { if ( !in_array( $type, static::$available_image_types ) ) { throw new CCException( "CCImage - Invalid image type '".$type."'." ); } // don't allow jpg, set to jpeg if ( $type === 'jpg' ) { $type = 'jpeg'; } if ( $overwrite ) { $this->type = $type; } } return $type; }
[ "protected", "function", "set_type", "(", "$", "type", ",", "$", "overwrite", "=", "true", ")", "{", "if", "(", "!", "is_null", "(", "$", "type", ")", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "static", "::", "$", "available_image_types", ")", ")", "{", "throw", "new", "CCException", "(", "\"CCImage - Invalid image type '\"", ".", "$", "type", ".", "\"'.\"", ")", ";", "}", "// don't allow jpg, set to jpeg", "if", "(", "$", "type", "===", "'jpg'", ")", "{", "$", "type", "=", "'jpeg'", ";", "}", "if", "(", "$", "overwrite", ")", "{", "$", "this", "->", "type", "=", "$", "type", ";", "}", "}", "return", "$", "type", ";", "}" ]
Set the current image type @param string $type The new image type @param string $overwrite Should the image keep this type? @return string
[ "Set", "the", "current", "image", "type" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L234-L256
ClanCats/Core
src/classes/CCImage.php
CCImage.save
public function save( $file, $quality = null, $type = null ) { $type = $this->set_type( $type ); // create directory if not exists if ( !is_null( $file ) ) { CCFile::mkdir( $file ); } switch( $type ) { // PNG images case 'png': if ( is_null( $quality ) ) { $quality = -1; } else { $quality = ( $quality / 100 ) * 9; } return imagepng( $this->image_context, $file, $quality ); break; // GIF images case 'gif': return imagegif( $this->image_context, $file ); break; // JPEG images case 'jpeg': default: if ( is_null( $quality ) ) { $quality = 90; } return imagejpeg( $this->image_context, $file, $quality ); break; } }
php
public function save( $file, $quality = null, $type = null ) { $type = $this->set_type( $type ); // create directory if not exists if ( !is_null( $file ) ) { CCFile::mkdir( $file ); } switch( $type ) { // PNG images case 'png': if ( is_null( $quality ) ) { $quality = -1; } else { $quality = ( $quality / 100 ) * 9; } return imagepng( $this->image_context, $file, $quality ); break; // GIF images case 'gif': return imagegif( $this->image_context, $file ); break; // JPEG images case 'jpeg': default: if ( is_null( $quality ) ) { $quality = 90; } return imagejpeg( $this->image_context, $file, $quality ); break; } }
[ "public", "function", "save", "(", "$", "file", ",", "$", "quality", "=", "null", ",", "$", "type", "=", "null", ")", "{", "$", "type", "=", "$", "this", "->", "set_type", "(", "$", "type", ")", ";", "// create directory if not exists", "if", "(", "!", "is_null", "(", "$", "file", ")", ")", "{", "CCFile", "::", "mkdir", "(", "$", "file", ")", ";", "}", "switch", "(", "$", "type", ")", "{", "// PNG images", "case", "'png'", ":", "if", "(", "is_null", "(", "$", "quality", ")", ")", "{", "$", "quality", "=", "-", "1", ";", "}", "else", "{", "$", "quality", "=", "(", "$", "quality", "/", "100", ")", "*", "9", ";", "}", "return", "imagepng", "(", "$", "this", "->", "image_context", ",", "$", "file", ",", "$", "quality", ")", ";", "break", ";", "// GIF images", "case", "'gif'", ":", "return", "imagegif", "(", "$", "this", "->", "image_context", ",", "$", "file", ")", ";", "break", ";", "// JPEG images", "case", "'jpeg'", ":", "default", ":", "if", "(", "is_null", "(", "$", "quality", ")", ")", "{", "$", "quality", "=", "90", ";", "}", "return", "imagejpeg", "(", "$", "this", "->", "image_context", ",", "$", "file", ",", "$", "quality", ")", ";", "break", ";", "}", "}" ]
Save the image When you set the file to null the image will be send to the output buffer. Examples: $image = CCImage::create( 'path/to/my/image.jpg' ); // save to file $image->save( 'my/new/image.jpg' ); // quality (80%) and type (gif) $image->save( 'my/new/image.gif', 'gif', 80 ); // send to output buffer $image->save( null ); @param string $file @param int $quality between 1-100 @param string $type @return bool
[ "Save", "the", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L278-L316
ClanCats/Core
src/classes/CCImage.php
CCImage.stream
public function stream( $quality = null, $type = null ) { $this->save( null, $quality, $type ); }
php
public function stream( $quality = null, $type = null ) { $this->save( null, $quality, $type ); }
[ "public", "function", "stream", "(", "$", "quality", "=", "null", ",", "$", "type", "=", "null", ")", "{", "$", "this", "->", "save", "(", "null", ",", "$", "quality", ",", "$", "type", ")", ";", "}" ]
Send the image to the output buffer @param int $quality @param string $type jpg|png|gif @return void
[ "Send", "the", "image", "to", "the", "output", "buffer" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L325-L328
ClanCats/Core
src/classes/CCImage.php
CCImage.stringify
public function stringify( $quality = null, $type = null ) { ob_start(); $this->stream( $quality, $type ); return ob_get_clean(); }
php
public function stringify( $quality = null, $type = null ) { ob_start(); $this->stream( $quality, $type ); return ob_get_clean(); }
[ "public", "function", "stringify", "(", "$", "quality", "=", "null", ",", "$", "type", "=", "null", ")", "{", "ob_start", "(", ")", ";", "$", "this", "->", "stream", "(", "$", "quality", ",", "$", "type", ")", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Return the image data as string @param int $quality @param string $type jpg|png|gif @return string
[ "Return", "the", "image", "data", "as", "string" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L337-L340
ClanCats/Core
src/classes/CCImage.php
CCImage.response
public function response( $quality = null, $type = null ) { $response = CCResponse::create( $this->stringify( $quality, $type ) ); if ( !is_null( $this->type ) ) { $response->header( 'Content-Type', 'image/'.$this->type ); } return $response; }
php
public function response( $quality = null, $type = null ) { $response = CCResponse::create( $this->stringify( $quality, $type ) ); if ( !is_null( $this->type ) ) { $response->header( 'Content-Type', 'image/'.$this->type ); } return $response; }
[ "public", "function", "response", "(", "$", "quality", "=", "null", ",", "$", "type", "=", "null", ")", "{", "$", "response", "=", "CCResponse", "::", "create", "(", "$", "this", "->", "stringify", "(", "$", "quality", ",", "$", "type", ")", ")", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "type", ")", ")", "{", "$", "response", "->", "header", "(", "'Content-Type'", ",", "'image/'", ".", "$", "this", "->", "type", ")", ";", "}", "return", "$", "response", ";", "}" ]
Create a CCRespone of the image @param string $quality The image quality @param string $type jpg|png|gif @return CCresponse
[ "Create", "a", "CCRespone", "of", "the", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L349-L359
ClanCats/Core
src/classes/CCImage.php
CCImage.resize
public function resize( $width, $height, $mode = null ) { // check for alternative syntax if ( strpos( $width, 'x' ) !== false ) { // mode is the secound param $mode = $height; $dimensions = explode( 'x', $width ); $width = $dimensions[0]; $height = $dimensions[1]; } // default mode if ( is_null( $mode ) ) { $mode = 'strict'; } // auto width if ( $width == 'auto' ) { $mode = 'portrait'; // in this case the $height is the first param $width = $height; } // auto height elseif ( $height == 'auto' ) { $mode = 'landscape'; } $method = 'resize_'.$mode; if ( !method_exists( $this, $method ) ) { throw new CCException( "CCImage::resize - Invalid resize method ".$mode."." ); } return call_user_func_array( array( $this, $method ), array( $width, $height ) ); }
php
public function resize( $width, $height, $mode = null ) { // check for alternative syntax if ( strpos( $width, 'x' ) !== false ) { // mode is the secound param $mode = $height; $dimensions = explode( 'x', $width ); $width = $dimensions[0]; $height = $dimensions[1]; } // default mode if ( is_null( $mode ) ) { $mode = 'strict'; } // auto width if ( $width == 'auto' ) { $mode = 'portrait'; // in this case the $height is the first param $width = $height; } // auto height elseif ( $height == 'auto' ) { $mode = 'landscape'; } $method = 'resize_'.$mode; if ( !method_exists( $this, $method ) ) { throw new CCException( "CCImage::resize - Invalid resize method ".$mode."." ); } return call_user_func_array( array( $this, $method ), array( $width, $height ) ); }
[ "public", "function", "resize", "(", "$", "width", ",", "$", "height", ",", "$", "mode", "=", "null", ")", "{", "// check for alternative syntax ", "if", "(", "strpos", "(", "$", "width", ",", "'x'", ")", "!==", "false", ")", "{", "// mode is the secound param", "$", "mode", "=", "$", "height", ";", "$", "dimensions", "=", "explode", "(", "'x'", ",", "$", "width", ")", ";", "$", "width", "=", "$", "dimensions", "[", "0", "]", ";", "$", "height", "=", "$", "dimensions", "[", "1", "]", ";", "}", "// default mode", "if", "(", "is_null", "(", "$", "mode", ")", ")", "{", "$", "mode", "=", "'strict'", ";", "}", "// auto width", "if", "(", "$", "width", "==", "'auto'", ")", "{", "$", "mode", "=", "'portrait'", ";", "// in this case the $height is the first param", "$", "width", "=", "$", "height", ";", "}", "// auto height", "elseif", "(", "$", "height", "==", "'auto'", ")", "{", "$", "mode", "=", "'landscape'", ";", "}", "$", "method", "=", "'resize_'", ".", "$", "mode", ";", "if", "(", "!", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "throw", "new", "CCException", "(", "\"CCImage::resize - Invalid resize method \"", ".", "$", "mode", ".", "\".\"", ")", ";", "}", "return", "call_user_func_array", "(", "array", "(", "$", "this", ",", "$", "method", ")", ",", "array", "(", "$", "width", ",", "$", "height", ")", ")", ";", "}" ]
Resize the image Examples: // simple resize $image->resize( '200x150', 'fill' ); // does the same as $image->resize( 200, 150, 'fill' ); // you can use auto values $image->resize( 500, 'auto' ); @param int $width @param int $height @param string $mode @return self
[ "Resize", "the", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L378-L418
ClanCats/Core
src/classes/CCImage.php
CCImage.resize_landscape
public function resize_landscape( $width, $ignore_me ) { // calculate height $height = $width * ( $this->height / $this->width ); return $this->resize_strict( $width, $height ); }
php
public function resize_landscape( $width, $ignore_me ) { // calculate height $height = $width * ( $this->height / $this->width ); return $this->resize_strict( $width, $height ); }
[ "public", "function", "resize_landscape", "(", "$", "width", ",", "$", "ignore_me", ")", "{", "// calculate height", "$", "height", "=", "$", "width", "*", "(", "$", "this", "->", "height", "/", "$", "this", "->", "width", ")", ";", "return", "$", "this", "->", "resize_strict", "(", "$", "width", ",", "$", "height", ")", ";", "}" ]
Resize the current image from width and keep aspect ratio @param int $width @param int $height @return self
[ "Resize", "the", "current", "image", "from", "width", "and", "keep", "aspect", "ratio" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L427-L433
ClanCats/Core
src/classes/CCImage.php
CCImage.resize_portrait
public function resize_portrait( $height, $ignore_me ) { // calculate width $width = $height * ( $this->width / $this->height ); return $this->resize_strict( $width, $height ); }
php
public function resize_portrait( $height, $ignore_me ) { // calculate width $width = $height * ( $this->width / $this->height ); return $this->resize_strict( $width, $height ); }
[ "public", "function", "resize_portrait", "(", "$", "height", ",", "$", "ignore_me", ")", "{", "// calculate width", "$", "width", "=", "$", "height", "*", "(", "$", "this", "->", "width", "/", "$", "this", "->", "height", ")", ";", "return", "$", "this", "->", "resize_strict", "(", "$", "width", ",", "$", "height", ")", ";", "}" ]
Resize the current image from height and keep aspect ratio @param int $width @param int $height @return self
[ "Resize", "the", "current", "image", "from", "height", "and", "keep", "aspect", "ratio" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L442-L448
ClanCats/Core
src/classes/CCImage.php
CCImage.resize_max
public function resize_max( $width, $height ) { $new_width = $this->width; $new_height = $this->height; if ( $new_width > $width ) { // set new with $new_width = $width; // calculate height $new_height = $new_width * ( $this->height / $this->width ); } if ( $new_height > $height ) { // set new height $new_height = $height; // calculate width $new_width = $new_height * ( $this->width / $this->height ); } return $this->resize_strict( $new_width, $new_height ); }
php
public function resize_max( $width, $height ) { $new_width = $this->width; $new_height = $this->height; if ( $new_width > $width ) { // set new with $new_width = $width; // calculate height $new_height = $new_width * ( $this->height / $this->width ); } if ( $new_height > $height ) { // set new height $new_height = $height; // calculate width $new_width = $new_height * ( $this->width / $this->height ); } return $this->resize_strict( $new_width, $new_height ); }
[ "public", "function", "resize_max", "(", "$", "width", ",", "$", "height", ")", "{", "$", "new_width", "=", "$", "this", "->", "width", ";", "$", "new_height", "=", "$", "this", "->", "height", ";", "if", "(", "$", "new_width", ">", "$", "width", ")", "{", "// set new with", "$", "new_width", "=", "$", "width", ";", "// calculate height", "$", "new_height", "=", "$", "new_width", "*", "(", "$", "this", "->", "height", "/", "$", "this", "->", "width", ")", ";", "}", "if", "(", "$", "new_height", ">", "$", "height", ")", "{", "// set new height", "$", "new_height", "=", "$", "height", ";", "// calculate width", "$", "new_width", "=", "$", "new_height", "*", "(", "$", "this", "->", "width", "/", "$", "this", "->", "height", ")", ";", "}", "return", "$", "this", "->", "resize_strict", "(", "$", "new_width", ",", "$", "new_height", ")", ";", "}" ]
Resize the image that it fits into a size doesn't crop and does not add a border @param int $width @param int $height @return self
[ "Resize", "the", "image", "that", "it", "fits", "into", "a", "size", "doesn", "t", "crop", "and", "does", "not", "add", "a", "border" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L457-L479
ClanCats/Core
src/classes/CCImage.php
CCImage.resize_fit
public function resize_fit( $width, $height, $background_color = '#fff' ) { $background = static::blank( $width, $height ); // make out actual image max size static::resize_max( $width, $height ); // make background white $background->fill_color( $background_color ); // add the layer $background->add_layer( $this, 'center', 'middle' ); // overwrite the image context $this->image_context = $background->image_context; // update properties $this->width = $width; $this->height = $height; // return self return $this; }
php
public function resize_fit( $width, $height, $background_color = '#fff' ) { $background = static::blank( $width, $height ); // make out actual image max size static::resize_max( $width, $height ); // make background white $background->fill_color( $background_color ); // add the layer $background->add_layer( $this, 'center', 'middle' ); // overwrite the image context $this->image_context = $background->image_context; // update properties $this->width = $width; $this->height = $height; // return self return $this; }
[ "public", "function", "resize_fit", "(", "$", "width", ",", "$", "height", ",", "$", "background_color", "=", "'#fff'", ")", "{", "$", "background", "=", "static", "::", "blank", "(", "$", "width", ",", "$", "height", ")", ";", "// make out actual image max size", "static", "::", "resize_max", "(", "$", "width", ",", "$", "height", ")", ";", "// make background white", "$", "background", "->", "fill_color", "(", "$", "background_color", ")", ";", "// add the layer", "$", "background", "->", "add_layer", "(", "$", "this", ",", "'center'", ",", "'middle'", ")", ";", "// overwrite the image context ", "$", "this", "->", "image_context", "=", "$", "background", "->", "image_context", ";", "// update properties", "$", "this", "->", "width", "=", "$", "width", ";", "$", "this", "->", "height", "=", "$", "height", ";", "// return self", "return", "$", "this", ";", "}" ]
Resize the image that it fits into a size doesn't crop adds a background layer @param int $width @param int $height @return self
[ "Resize", "the", "image", "that", "it", "fits", "into", "a", "size", "doesn", "t", "crop", "adds", "a", "background", "layer" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L488-L510
ClanCats/Core
src/classes/CCImage.php
CCImage.resize_fill
public function resize_fill( $width, $height ) { $original_aspect = $this->width / $this->height; $thumb_aspect = $width / $height; if ( $original_aspect >= $thumb_aspect ) { $new_height = $height; $new_width = $this->width / ($this->height / $height); } else { $new_width = $width; $new_height = $this->height / ($this->width / $width); } $x = 0 - ( $new_width - $width ) / 2; $y = 0 - ( $new_height - $height ) / 2; $result = imagecreatetruecolor( $width, $height ); imagecopyresampled( $result, $this->image_context, $x, $y, 0, 0, $new_width, $new_height, $this->width, $this->height ); // overwrite the image context $this->image_context = $result; // update properties $this->reload_context_info(); // return self return $this; }
php
public function resize_fill( $width, $height ) { $original_aspect = $this->width / $this->height; $thumb_aspect = $width / $height; if ( $original_aspect >= $thumb_aspect ) { $new_height = $height; $new_width = $this->width / ($this->height / $height); } else { $new_width = $width; $new_height = $this->height / ($this->width / $width); } $x = 0 - ( $new_width - $width ) / 2; $y = 0 - ( $new_height - $height ) / 2; $result = imagecreatetruecolor( $width, $height ); imagecopyresampled( $result, $this->image_context, $x, $y, 0, 0, $new_width, $new_height, $this->width, $this->height ); // overwrite the image context $this->image_context = $result; // update properties $this->reload_context_info(); // return self return $this; }
[ "public", "function", "resize_fill", "(", "$", "width", ",", "$", "height", ")", "{", "$", "original_aspect", "=", "$", "this", "->", "width", "/", "$", "this", "->", "height", ";", "$", "thumb_aspect", "=", "$", "width", "/", "$", "height", ";", "if", "(", "$", "original_aspect", ">=", "$", "thumb_aspect", ")", "{", "$", "new_height", "=", "$", "height", ";", "$", "new_width", "=", "$", "this", "->", "width", "/", "(", "$", "this", "->", "height", "/", "$", "height", ")", ";", "}", "else", "{", "$", "new_width", "=", "$", "width", ";", "$", "new_height", "=", "$", "this", "->", "height", "/", "(", "$", "this", "->", "width", "/", "$", "width", ")", ";", "}", "$", "x", "=", "0", "-", "(", "$", "new_width", "-", "$", "width", ")", "/", "2", ";", "$", "y", "=", "0", "-", "(", "$", "new_height", "-", "$", "height", ")", "/", "2", ";", "$", "result", "=", "imagecreatetruecolor", "(", "$", "width", ",", "$", "height", ")", ";", "imagecopyresampled", "(", "$", "result", ",", "$", "this", "->", "image_context", ",", "$", "x", ",", "$", "y", ",", "0", ",", "0", ",", "$", "new_width", ",", "$", "new_height", ",", "$", "this", "->", "width", ",", "$", "this", "->", "height", ")", ";", "// overwrite the image context ", "$", "this", "->", "image_context", "=", "$", "result", ";", "// update properties", "$", "this", "->", "reload_context_info", "(", ")", ";", "// return self", "return", "$", "this", ";", "}" ]
Resize the image to fill the new size. This will crop your image. @param int $width @param int $height @return self @thanks to: http://stackoverflow.com/questions/1855996/crop-image-in-php
[ "Resize", "the", "image", "to", "fill", "the", "new", "size", ".", "This", "will", "crop", "your", "image", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L521-L551
ClanCats/Core
src/classes/CCImage.php
CCImage.resize_strict
public function resize_strict( $width, $height ) { // check dimensions if ( !( $width > 0 ) || !( $height > 0 ) ) { throw new CCException( "CCImage::resize_strict - width and height can't be smaller then 1" ); } $result = imagecreatetruecolor( $width, $height ); imagecopyresampled( $result, $this->image_context, 0, 0, 0, 0, $width, $height, $this->width, $this->height ); // overwrite the image context $this->image_context = $result; // update properties $this->reload_context_info(); // return self return $this; }
php
public function resize_strict( $width, $height ) { // check dimensions if ( !( $width > 0 ) || !( $height > 0 ) ) { throw new CCException( "CCImage::resize_strict - width and height can't be smaller then 1" ); } $result = imagecreatetruecolor( $width, $height ); imagecopyresampled( $result, $this->image_context, 0, 0, 0, 0, $width, $height, $this->width, $this->height ); // overwrite the image context $this->image_context = $result; // update properties $this->reload_context_info(); // return self return $this; }
[ "public", "function", "resize_strict", "(", "$", "width", ",", "$", "height", ")", "{", "// check dimensions", "if", "(", "!", "(", "$", "width", ">", "0", ")", "||", "!", "(", "$", "height", ">", "0", ")", ")", "{", "throw", "new", "CCException", "(", "\"CCImage::resize_strict - width and height can't be smaller then 1\"", ")", ";", "}", "$", "result", "=", "imagecreatetruecolor", "(", "$", "width", ",", "$", "height", ")", ";", "imagecopyresampled", "(", "$", "result", ",", "$", "this", "->", "image_context", ",", "0", ",", "0", ",", "0", ",", "0", ",", "$", "width", ",", "$", "height", ",", "$", "this", "->", "width", ",", "$", "this", "->", "height", ")", ";", "// overwrite the image context ", "$", "this", "->", "image_context", "=", "$", "result", ";", "// update properties", "$", "this", "->", "reload_context_info", "(", ")", ";", "// return self", "return", "$", "this", ";", "}" ]
Resize the current image to strict dimensions @param int $width @param int $height @param string $mode @return self
[ "Resize", "the", "current", "image", "to", "strict", "dimensions" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L562-L581
ClanCats/Core
src/classes/CCImage.php
CCImage.crop
public function crop( $x, $y, $width, $height ) { // check for auto if ( $x == 'center' || $x == 'auto' ) { $x = ( $this->width / 2 ) - ( $width / 2 ); } if ( $y == 'middle' || $y == 'auto' ) { $y = ( $this->height / 2 ) - ( $height / 2 ); } $result = imagecreatetruecolor( $width, $height ); ImageCopyResampled( $result, $this->image_context, 0, 0, $x, $y, $width, $height, $width, $height ); $this->image_context = $result; // update properties $this->reload_context_info(); // return self return $this; }
php
public function crop( $x, $y, $width, $height ) { // check for auto if ( $x == 'center' || $x == 'auto' ) { $x = ( $this->width / 2 ) - ( $width / 2 ); } if ( $y == 'middle' || $y == 'auto' ) { $y = ( $this->height / 2 ) - ( $height / 2 ); } $result = imagecreatetruecolor( $width, $height ); ImageCopyResampled( $result, $this->image_context, 0, 0, $x, $y, $width, $height, $width, $height ); $this->image_context = $result; // update properties $this->reload_context_info(); // return self return $this; }
[ "public", "function", "crop", "(", "$", "x", ",", "$", "y", ",", "$", "width", ",", "$", "height", ")", "{", "// check for auto", "if", "(", "$", "x", "==", "'center'", "||", "$", "x", "==", "'auto'", ")", "{", "$", "x", "=", "(", "$", "this", "->", "width", "/", "2", ")", "-", "(", "$", "width", "/", "2", ")", ";", "}", "if", "(", "$", "y", "==", "'middle'", "||", "$", "y", "==", "'auto'", ")", "{", "$", "y", "=", "(", "$", "this", "->", "height", "/", "2", ")", "-", "(", "$", "height", "/", "2", ")", ";", "}", "$", "result", "=", "imagecreatetruecolor", "(", "$", "width", ",", "$", "height", ")", ";", "ImageCopyResampled", "(", "$", "result", ",", "$", "this", "->", "image_context", ",", "0", ",", "0", ",", "$", "x", ",", "$", "y", ",", "$", "width", ",", "$", "height", ",", "$", "width", ",", "$", "height", ")", ";", "$", "this", "->", "image_context", "=", "$", "result", ";", "// update properties", "$", "this", "->", "reload_context_info", "(", ")", ";", "// return self", "return", "$", "this", ";", "}" ]
Crop the current image This is a simplefied crop. @param int $x @param int $y @param int $width @param int $height @return self
[ "Crop", "the", "current", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L595-L618
ClanCats/Core
src/classes/CCImage.php
CCImage.add_layer
public function add_layer( CCImage $image, $x = 0, $y = 0, $alpha = 100 ) { // auto values if ( $x == 'center' || $x == 'auto' ) { $x = ( $this->width / 2 ) - ( $image->width / 2 ); } elseif ( $x == 'left' ) { $x = 0; } elseif ( $x == 'right' ) { $x = $this->width - $image->width; } if ( $y == 'middle' || $y == 'auto' ) { $y = ( $this->height / 2 ) - ( $image->height / 2 ); } elseif ( $x == 'top' ) { $x = 0; } elseif ( $x == 'bottom' ) { $x = $this->height - $image->height; } // run image copy imagecopymerge( $this->image_context, $image->image_context, $x, $y, 0, 0, $image->width, $image->height, $alpha ); return $this; }
php
public function add_layer( CCImage $image, $x = 0, $y = 0, $alpha = 100 ) { // auto values if ( $x == 'center' || $x == 'auto' ) { $x = ( $this->width / 2 ) - ( $image->width / 2 ); } elseif ( $x == 'left' ) { $x = 0; } elseif ( $x == 'right' ) { $x = $this->width - $image->width; } if ( $y == 'middle' || $y == 'auto' ) { $y = ( $this->height / 2 ) - ( $image->height / 2 ); } elseif ( $x == 'top' ) { $x = 0; } elseif ( $x == 'bottom' ) { $x = $this->height - $image->height; } // run image copy imagecopymerge( $this->image_context, $image->image_context, $x, $y, 0, 0, $image->width, $image->height, $alpha ); return $this; }
[ "public", "function", "add_layer", "(", "CCImage", "$", "image", ",", "$", "x", "=", "0", ",", "$", "y", "=", "0", ",", "$", "alpha", "=", "100", ")", "{", "// auto values", "if", "(", "$", "x", "==", "'center'", "||", "$", "x", "==", "'auto'", ")", "{", "$", "x", "=", "(", "$", "this", "->", "width", "/", "2", ")", "-", "(", "$", "image", "->", "width", "/", "2", ")", ";", "}", "elseif", "(", "$", "x", "==", "'left'", ")", "{", "$", "x", "=", "0", ";", "}", "elseif", "(", "$", "x", "==", "'right'", ")", "{", "$", "x", "=", "$", "this", "->", "width", "-", "$", "image", "->", "width", ";", "}", "if", "(", "$", "y", "==", "'middle'", "||", "$", "y", "==", "'auto'", ")", "{", "$", "y", "=", "(", "$", "this", "->", "height", "/", "2", ")", "-", "(", "$", "image", "->", "height", "/", "2", ")", ";", "}", "elseif", "(", "$", "x", "==", "'top'", ")", "{", "$", "x", "=", "0", ";", "}", "elseif", "(", "$", "x", "==", "'bottom'", ")", "{", "$", "x", "=", "$", "this", "->", "height", "-", "$", "image", "->", "height", ";", "}", "// run image copy", "imagecopymerge", "(", "$", "this", "->", "image_context", ",", "$", "image", "->", "image_context", ",", "$", "x", ",", "$", "y", ",", "0", ",", "0", ",", "$", "image", "->", "width", ",", "$", "image", "->", "height", ",", "$", "alpha", ")", ";", "return", "$", "this", ";", "}" ]
add an layer to the current image @param CCImage $image @param int $x @param int $y @return self
[ "add", "an", "layer", "to", "the", "current", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L629-L662
ClanCats/Core
src/classes/CCImage.php
CCImage.fill_color
public function fill_color( $color, $alpha = 1 ) { $alpha = $alpha * 127; // parse the color $color = CCColor::create( $color ); $color = imagecolorallocatealpha( $this->image_context, $color->RGB[0], $color->RGB[1], $color->RGB[2], $alpha ); // run image fill imagefill( $this->image_context, 0, 0, $color ); return $this; }
php
public function fill_color( $color, $alpha = 1 ) { $alpha = $alpha * 127; // parse the color $color = CCColor::create( $color ); $color = imagecolorallocatealpha( $this->image_context, $color->RGB[0], $color->RGB[1], $color->RGB[2], $alpha ); // run image fill imagefill( $this->image_context, 0, 0, $color ); return $this; }
[ "public", "function", "fill_color", "(", "$", "color", ",", "$", "alpha", "=", "1", ")", "{", "$", "alpha", "=", "$", "alpha", "*", "127", ";", "// parse the color", "$", "color", "=", "CCColor", "::", "create", "(", "$", "color", ")", ";", "$", "color", "=", "imagecolorallocatealpha", "(", "$", "this", "->", "image_context", ",", "$", "color", "->", "RGB", "[", "0", "]", ",", "$", "color", "->", "RGB", "[", "1", "]", ",", "$", "color", "->", "RGB", "[", "2", "]", ",", "$", "alpha", ")", ";", "// run image fill", "imagefill", "(", "$", "this", "->", "image_context", ",", "0", ",", "0", ",", "$", "color", ")", ";", "return", "$", "this", ";", "}" ]
fill the current image with an color you can pass an array with rgb or hex string @param mixed $color @return self
[ "fill", "the", "current", "image", "with", "an", "color", "you", "can", "pass", "an", "array", "with", "rgb", "or", "hex", "string" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L671-L683
ClanCats/Core
src/classes/CCImage.php
CCImage.blur
public function blur( $ratio = 5 ) { for ($x=0; $x<$ratio; $x++) { imagefilter($this->image_context, IMG_FILTER_GAUSSIAN_BLUR); //$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 1.0, 2.0), array(1.0, 2.0, 1.0)); //imageconvolution($this->image_context, $gaussian, 16, 0); } return $this; }
php
public function blur( $ratio = 5 ) { for ($x=0; $x<$ratio; $x++) { imagefilter($this->image_context, IMG_FILTER_GAUSSIAN_BLUR); //$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 1.0, 2.0), array(1.0, 2.0, 1.0)); //imageconvolution($this->image_context, $gaussian, 16, 0); } return $this; }
[ "public", "function", "blur", "(", "$", "ratio", "=", "5", ")", "{", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<", "$", "ratio", ";", "$", "x", "++", ")", "{", "imagefilter", "(", "$", "this", "->", "image_context", ",", "IMG_FILTER_GAUSSIAN_BLUR", ")", ";", "//$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 1.0, 2.0), array(1.0, 2.0, 1.0));", "//imageconvolution($this->image_context, $gaussian, 16, 0);", "}", "return", "$", "this", ";", "}" ]
Blur the image using the gaussian blur. @param int $ratio @return self
[ "Blur", "the", "image", "using", "the", "gaussian", "blur", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L691-L701
ClanCats/Core
src/classes/CCImage.php
CCImage.get_luminance
public function get_luminance( $num_samples = 10 ) { $x_step = (int) $this->width / $num_samples; $y_step = (int) $this->height / $num_samples; $total_lum = 0; $sample_no = 1; for ( $x=0; $x<$this->width; $x+=$x_step ) { for ( $y=0; $y<$this->height; $y+=$y_step ) { $rgb = imagecolorat($this->image_context, $x, $y); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $lum = ($r+$r+$b+$g+$g+$g)/6; $total_lum += $lum; $sample_no++; } } return (int) ( $total_lum / $sample_no ); }
php
public function get_luminance( $num_samples = 10 ) { $x_step = (int) $this->width / $num_samples; $y_step = (int) $this->height / $num_samples; $total_lum = 0; $sample_no = 1; for ( $x=0; $x<$this->width; $x+=$x_step ) { for ( $y=0; $y<$this->height; $y+=$y_step ) { $rgb = imagecolorat($this->image_context, $x, $y); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $lum = ($r+$r+$b+$g+$g+$g)/6; $total_lum += $lum; $sample_no++; } } return (int) ( $total_lum / $sample_no ); }
[ "public", "function", "get_luminance", "(", "$", "num_samples", "=", "10", ")", "{", "$", "x_step", "=", "(", "int", ")", "$", "this", "->", "width", "/", "$", "num_samples", ";", "$", "y_step", "=", "(", "int", ")", "$", "this", "->", "height", "/", "$", "num_samples", ";", "$", "total_lum", "=", "0", ";", "$", "sample_no", "=", "1", ";", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<", "$", "this", "->", "width", ";", "$", "x", "+=", "$", "x_step", ")", "{", "for", "(", "$", "y", "=", "0", ";", "$", "y", "<", "$", "this", "->", "height", ";", "$", "y", "+=", "$", "y_step", ")", "{", "$", "rgb", "=", "imagecolorat", "(", "$", "this", "->", "image_context", ",", "$", "x", ",", "$", "y", ")", ";", "$", "r", "=", "(", "$", "rgb", ">>", "16", ")", "&", "0xFF", ";", "$", "g", "=", "(", "$", "rgb", ">>", "8", ")", "&", "0xFF", ";", "$", "b", "=", "$", "rgb", "&", "0xFF", ";", "$", "lum", "=", "(", "$", "r", "+", "$", "r", "+", "$", "b", "+", "$", "g", "+", "$", "g", "+", "$", "g", ")", "/", "6", ";", "$", "total_lum", "+=", "$", "lum", ";", "$", "sample_no", "++", ";", "}", "}", "return", "(", "int", ")", "(", "$", "total_lum", "/", "$", "sample_no", ")", ";", "}" ]
Get the average luminance of the image @param int $num_samples @return int ( 1-255 ) @thanks to: http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
[ "Get", "the", "average", "luminance", "of", "the", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L711-L736
ClanCats/Core
src/classes/CCImage.php
CCImage.flip
function flip( $mode ) { $width = $this->width; $height = $this->height; $src_x = 0; $src_y = 0; $src_width = $width; $src_height = $height; switch ( $mode ) { case 'vertical': $src_y = $height -1; $src_height = -$height; break; case 'horizontal': $src_x = $width -1; $src_width = -$width; break; case 'both': $src_x = $width -1; $src_y = $height -1; $src_width = -$width; $src_height = -$height; break; } $imgdest = imagecreatetruecolor( $width, $height ); if ( imagecopyresampled( $imgdest, $this->image_context, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) ) { $this->image_context = $imgdest; } return $this->image_context; }
php
function flip( $mode ) { $width = $this->width; $height = $this->height; $src_x = 0; $src_y = 0; $src_width = $width; $src_height = $height; switch ( $mode ) { case 'vertical': $src_y = $height -1; $src_height = -$height; break; case 'horizontal': $src_x = $width -1; $src_width = -$width; break; case 'both': $src_x = $width -1; $src_y = $height -1; $src_width = -$width; $src_height = -$height; break; } $imgdest = imagecreatetruecolor( $width, $height ); if ( imagecopyresampled( $imgdest, $this->image_context, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) ) { $this->image_context = $imgdest; } return $this->image_context; }
[ "function", "flip", "(", "$", "mode", ")", "{", "$", "width", "=", "$", "this", "->", "width", ";", "$", "height", "=", "$", "this", "->", "height", ";", "$", "src_x", "=", "0", ";", "$", "src_y", "=", "0", ";", "$", "src_width", "=", "$", "width", ";", "$", "src_height", "=", "$", "height", ";", "switch", "(", "$", "mode", ")", "{", "case", "'vertical'", ":", "$", "src_y", "=", "$", "height", "-", "1", ";", "$", "src_height", "=", "-", "$", "height", ";", "break", ";", "case", "'horizontal'", ":", "$", "src_x", "=", "$", "width", "-", "1", ";", "$", "src_width", "=", "-", "$", "width", ";", "break", ";", "case", "'both'", ":", "$", "src_x", "=", "$", "width", "-", "1", ";", "$", "src_y", "=", "$", "height", "-", "1", ";", "$", "src_width", "=", "-", "$", "width", ";", "$", "src_height", "=", "-", "$", "height", ";", "break", ";", "}", "$", "imgdest", "=", "imagecreatetruecolor", "(", "$", "width", ",", "$", "height", ")", ";", "if", "(", "imagecopyresampled", "(", "$", "imgdest", ",", "$", "this", "->", "image_context", ",", "0", ",", "0", ",", "$", "src_x", ",", "$", "src_y", ",", "$", "width", ",", "$", "height", ",", "$", "src_width", ",", "$", "src_height", ")", ")", "{", "$", "this", "->", "image_context", "=", "$", "imgdest", ";", "}", "return", "$", "this", "->", "image_context", ";", "}" ]
Flip an image @param string $mode vertical, horizontal, both @return self
[ "Flip", "an", "image" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCImage.php#L744-L783
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.workAll
public function workAll(array $folders = array(), array $extensions = array(), $deep = false, array $exclusions = array()) { if ($folders === array()) { $folders = $this->assetsSource; } if ($extensions === array()) { $extensions = array_keys($this->filters); } $assets = []; foreach ($extensions as $extension) { $files = array(); foreach ($folders as $folder) { try { $files = array_merge($files, $this->fileCollector->parse($folder, array($extension), $deep, $exclusions)); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('FileCollector: ' . $e); } } foreach ($files as $file) { $assets[] = $this->work($file); } } return $assets; }
php
public function workAll(array $folders = array(), array $extensions = array(), $deep = false, array $exclusions = array()) { if ($folders === array()) { $folders = $this->assetsSource; } if ($extensions === array()) { $extensions = array_keys($this->filters); } $assets = []; foreach ($extensions as $extension) { $files = array(); foreach ($folders as $folder) { try { $files = array_merge($files, $this->fileCollector->parse($folder, array($extension), $deep, $exclusions)); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('FileCollector: ' . $e); } } foreach ($files as $file) { $assets[] = $this->work($file); } } return $assets; }
[ "public", "function", "workAll", "(", "array", "$", "folders", "=", "array", "(", ")", ",", "array", "$", "extensions", "=", "array", "(", ")", ",", "$", "deep", "=", "false", ",", "array", "$", "exclusions", "=", "array", "(", ")", ")", "{", "if", "(", "$", "folders", "===", "array", "(", ")", ")", "{", "$", "folders", "=", "$", "this", "->", "assetsSource", ";", "}", "if", "(", "$", "extensions", "===", "array", "(", ")", ")", "{", "$", "extensions", "=", "array_keys", "(", "$", "this", "->", "filters", ")", ";", "}", "$", "assets", "=", "[", "]", ";", "foreach", "(", "$", "extensions", "as", "$", "extension", ")", "{", "$", "files", "=", "array", "(", ")", ";", "foreach", "(", "$", "folders", "as", "$", "folder", ")", "{", "try", "{", "$", "files", "=", "array_merge", "(", "$", "files", ",", "$", "this", "->", "fileCollector", "->", "parse", "(", "$", "folder", ",", "array", "(", "$", "extension", ")", ",", "$", "deep", ",", "$", "exclusions", ")", ")", ";", "}", "catch", "(", "PhassetsInternalException", "$", "e", ")", "{", "$", "this", "->", "loadedLogger", "->", "error", "(", "'FileCollector: '", ".", "$", "e", ")", ";", "}", "}", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "assets", "[", "]", "=", "$", "this", "->", "work", "(", "$", "file", ")", ";", "}", "}", "return", "$", "assets", ";", "}" ]
Same as work(), except it operates on an array of folder of assets sources. @param array $folders Which folders to look in (absolute paths); if not provided, "assets_source" will be used instead @param array $extensions Which files should be processed; if not provided, all extensions having a filter assigned will be used @param bool $deep Whether to search in sub-dirs or not @param array $exclusions Array of filenames to be removed from processing @return Asset[] array of Asset instances for each file found and processed
[ "Same", "as", "work", "()", "except", "it", "operates", "on", "an", "array", "of", "folder", "of", "assets", "sources", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L122-L151
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.work
public function work($file, $customFilters = null, $customDeployer = null) { // Create the Asset instance foreach ($this->assetsSource as $source) { if (is_file($source . DIRECTORY_SEPARATOR . $file)) { $asset = $this->objectsFactory->buildAsset($source . DIRECTORY_SEPARATOR . $file); } } if (!isset($asset)) { $asset = $this->objectsFactory->buildAsset($file); } // Assemble the $filters array of fully qualified filters class names if (is_array($customFilters)) { $filters = $customFilters; } else { $ext = $asset->getExtension(); $filters = isset($this->filters[$ext]) ? $this->filters[$ext] : array(); } // Decide which deployer will be used. if (is_string($customDeployer)) { $deployer = $customDeployer; } else { $deployer = $this->loadedDeployer; } // Is previously cached? $cacheKey = $this->computeCacheKey($asset->getFullPath(), $filters, $deployer); $cacheValue = $this->loadedCacheAdapter->get($cacheKey); if ($cacheValue !== false) { $asset->setOutputUrl($cacheValue); return $asset; } // If there is any different extension, then set it first $this->applyFilterOutputExtension($filters, $asset); // Is previously deployed? if (isset($this->deployersInstances[$deployer]) && $this->deployersInstances[$deployer]->isPreviouslyDeployed($asset)) { // Cache the result $cacheValue = $asset->getOutputUrl(); $this->loadedCacheAdapter->save($cacheKey, $cacheValue, $this->cacheTtl); return $asset; } // Pass the asset through all filters. $this->filterAsset($filters, $asset); // All set! Let's deploy now. $this->deployAsset($deployer, $asset); // Cache the result $cacheValue = $asset->getOutputUrl(); $this->loadedCacheAdapter->save($cacheKey, $cacheValue, $this->cacheTtl); return $asset; }
php
public function work($file, $customFilters = null, $customDeployer = null) { // Create the Asset instance foreach ($this->assetsSource as $source) { if (is_file($source . DIRECTORY_SEPARATOR . $file)) { $asset = $this->objectsFactory->buildAsset($source . DIRECTORY_SEPARATOR . $file); } } if (!isset($asset)) { $asset = $this->objectsFactory->buildAsset($file); } // Assemble the $filters array of fully qualified filters class names if (is_array($customFilters)) { $filters = $customFilters; } else { $ext = $asset->getExtension(); $filters = isset($this->filters[$ext]) ? $this->filters[$ext] : array(); } // Decide which deployer will be used. if (is_string($customDeployer)) { $deployer = $customDeployer; } else { $deployer = $this->loadedDeployer; } // Is previously cached? $cacheKey = $this->computeCacheKey($asset->getFullPath(), $filters, $deployer); $cacheValue = $this->loadedCacheAdapter->get($cacheKey); if ($cacheValue !== false) { $asset->setOutputUrl($cacheValue); return $asset; } // If there is any different extension, then set it first $this->applyFilterOutputExtension($filters, $asset); // Is previously deployed? if (isset($this->deployersInstances[$deployer]) && $this->deployersInstances[$deployer]->isPreviouslyDeployed($asset)) { // Cache the result $cacheValue = $asset->getOutputUrl(); $this->loadedCacheAdapter->save($cacheKey, $cacheValue, $this->cacheTtl); return $asset; } // Pass the asset through all filters. $this->filterAsset($filters, $asset); // All set! Let's deploy now. $this->deployAsset($deployer, $asset); // Cache the result $cacheValue = $asset->getOutputUrl(); $this->loadedCacheAdapter->save($cacheKey, $cacheValue, $this->cacheTtl); return $asset; }
[ "public", "function", "work", "(", "$", "file", ",", "$", "customFilters", "=", "null", ",", "$", "customDeployer", "=", "null", ")", "{", "// Create the Asset instance", "foreach", "(", "$", "this", "->", "assetsSource", "as", "$", "source", ")", "{", "if", "(", "is_file", "(", "$", "source", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ")", ")", "{", "$", "asset", "=", "$", "this", "->", "objectsFactory", "->", "buildAsset", "(", "$", "source", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ")", ";", "}", "}", "if", "(", "!", "isset", "(", "$", "asset", ")", ")", "{", "$", "asset", "=", "$", "this", "->", "objectsFactory", "->", "buildAsset", "(", "$", "file", ")", ";", "}", "// Assemble the $filters array of fully qualified filters class names", "if", "(", "is_array", "(", "$", "customFilters", ")", ")", "{", "$", "filters", "=", "$", "customFilters", ";", "}", "else", "{", "$", "ext", "=", "$", "asset", "->", "getExtension", "(", ")", ";", "$", "filters", "=", "isset", "(", "$", "this", "->", "filters", "[", "$", "ext", "]", ")", "?", "$", "this", "->", "filters", "[", "$", "ext", "]", ":", "array", "(", ")", ";", "}", "// Decide which deployer will be used.", "if", "(", "is_string", "(", "$", "customDeployer", ")", ")", "{", "$", "deployer", "=", "$", "customDeployer", ";", "}", "else", "{", "$", "deployer", "=", "$", "this", "->", "loadedDeployer", ";", "}", "// Is previously cached?", "$", "cacheKey", "=", "$", "this", "->", "computeCacheKey", "(", "$", "asset", "->", "getFullPath", "(", ")", ",", "$", "filters", ",", "$", "deployer", ")", ";", "$", "cacheValue", "=", "$", "this", "->", "loadedCacheAdapter", "->", "get", "(", "$", "cacheKey", ")", ";", "if", "(", "$", "cacheValue", "!==", "false", ")", "{", "$", "asset", "->", "setOutputUrl", "(", "$", "cacheValue", ")", ";", "return", "$", "asset", ";", "}", "// If there is any different extension, then set it first", "$", "this", "->", "applyFilterOutputExtension", "(", "$", "filters", ",", "$", "asset", ")", ";", "// Is previously deployed?", "if", "(", "isset", "(", "$", "this", "->", "deployersInstances", "[", "$", "deployer", "]", ")", "&&", "$", "this", "->", "deployersInstances", "[", "$", "deployer", "]", "->", "isPreviouslyDeployed", "(", "$", "asset", ")", ")", "{", "// Cache the result", "$", "cacheValue", "=", "$", "asset", "->", "getOutputUrl", "(", ")", ";", "$", "this", "->", "loadedCacheAdapter", "->", "save", "(", "$", "cacheKey", ",", "$", "cacheValue", ",", "$", "this", "->", "cacheTtl", ")", ";", "return", "$", "asset", ";", "}", "// Pass the asset through all filters.", "$", "this", "->", "filterAsset", "(", "$", "filters", ",", "$", "asset", ")", ";", "// All set! Let's deploy now.", "$", "this", "->", "deployAsset", "(", "$", "deployer", ",", "$", "asset", ")", ";", "// Cache the result", "$", "cacheValue", "=", "$", "asset", "->", "getOutputUrl", "(", ")", ";", "$", "this", "->", "loadedCacheAdapter", "->", "save", "(", "$", "cacheKey", ",", "$", "cacheValue", ",", "$", "this", "->", "cacheTtl", ")", ";", "return", "$", "asset", ";", "}" ]
Processes and deploys an asset and returns an Asset instance with modified properties, according to used filters and deployers. @param string $file file name to be searched through "assets_source" @param null|array $customFilters Overrides "filter" setting @param null|string $customDeployer Overrides the loaded deployer @return Asset The created Asset instance
[ "Processes", "and", "deploys", "an", "asset", "and", "returns", "an", "Asset", "instance", "with", "modified", "properties", "according", "to", "used", "filters", "and", "deployers", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L163-L224
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.applyFilterOutputExtension
private function applyFilterOutputExtension(array $filters, Asset $asset) { foreach ($filters as $filter) { if ($this->loadFilter($filter)) { try { $this->filtersInstances[$filter]->setOutputExtension($asset); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('An error occurred while filtering the asset: ' . $e); } } } }
php
private function applyFilterOutputExtension(array $filters, Asset $asset) { foreach ($filters as $filter) { if ($this->loadFilter($filter)) { try { $this->filtersInstances[$filter]->setOutputExtension($asset); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('An error occurred while filtering the asset: ' . $e); } } } }
[ "private", "function", "applyFilterOutputExtension", "(", "array", "$", "filters", ",", "Asset", "$", "asset", ")", "{", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "if", "(", "$", "this", "->", "loadFilter", "(", "$", "filter", ")", ")", "{", "try", "{", "$", "this", "->", "filtersInstances", "[", "$", "filter", "]", "->", "setOutputExtension", "(", "$", "asset", ")", ";", "}", "catch", "(", "PhassetsInternalException", "$", "e", ")", "{", "$", "this", "->", "loadedLogger", "->", "error", "(", "'An error occurred while filtering the asset: '", ".", "$", "e", ")", ";", "}", "}", "}", "}" ]
Applies the setOutputExtension() from a list of filters (fully qualified class names) to an Asset instance. @param array $filters Array of the fully qualified filters class names @param Asset $asset Instance to be modified
[ "Applies", "the", "setOutputExtension", "()", "from", "a", "list", "of", "filters", "(", "fully", "qualified", "class", "names", ")", "to", "an", "Asset", "instance", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L233-L244
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.filterAsset
private function filterAsset(array $filters, Asset $asset) { $asset->setOutputExtension(null); foreach ($filters as $filter) { if ($this->loadFilter($filter)) { try { $this->filtersInstances[$filter]->filter($asset); $this->filtersInstances[$filter]->setOutputExtension($asset); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('An error occurred while filtering the asset: ' . $e); } } } }
php
private function filterAsset(array $filters, Asset $asset) { $asset->setOutputExtension(null); foreach ($filters as $filter) { if ($this->loadFilter($filter)) { try { $this->filtersInstances[$filter]->filter($asset); $this->filtersInstances[$filter]->setOutputExtension($asset); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('An error occurred while filtering the asset: ' . $e); } } } }
[ "private", "function", "filterAsset", "(", "array", "$", "filters", ",", "Asset", "$", "asset", ")", "{", "$", "asset", "->", "setOutputExtension", "(", "null", ")", ";", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "if", "(", "$", "this", "->", "loadFilter", "(", "$", "filter", ")", ")", "{", "try", "{", "$", "this", "->", "filtersInstances", "[", "$", "filter", "]", "->", "filter", "(", "$", "asset", ")", ";", "$", "this", "->", "filtersInstances", "[", "$", "filter", "]", "->", "setOutputExtension", "(", "$", "asset", ")", ";", "}", "catch", "(", "PhassetsInternalException", "$", "e", ")", "{", "$", "this", "->", "loadedLogger", "->", "error", "(", "'An error occurred while filtering the asset: '", ".", "$", "e", ")", ";", "}", "}", "}", "}" ]
Applies a list of filters (fully qualified class names) to an Asset instance. @param array $filters Array of the fully qualified filters class names @param Asset $asset Instance to be modified
[ "Applies", "a", "list", "of", "filters", "(", "fully", "qualified", "class", "names", ")", "to", "an", "Asset", "instance", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L253-L267
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.deployAsset
private function deployAsset($deploy, Asset $asset) { if ($this->loadDeployer($deploy)) { try { $this->deployersInstances[$deploy]->deploy($asset); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('An error occurred while deploying the asset: ' . $e); } } }
php
private function deployAsset($deploy, Asset $asset) { if ($this->loadDeployer($deploy)) { try { $this->deployersInstances[$deploy]->deploy($asset); } catch (PhassetsInternalException $e) { $this->loadedLogger->error('An error occurred while deploying the asset: ' . $e); } } }
[ "private", "function", "deployAsset", "(", "$", "deploy", ",", "Asset", "$", "asset", ")", "{", "if", "(", "$", "this", "->", "loadDeployer", "(", "$", "deploy", ")", ")", "{", "try", "{", "$", "this", "->", "deployersInstances", "[", "$", "deploy", "]", "->", "deploy", "(", "$", "asset", ")", ";", "}", "catch", "(", "PhassetsInternalException", "$", "e", ")", "{", "$", "this", "->", "loadedLogger", "->", "error", "(", "'An error occurred while deploying the asset: '", ".", "$", "e", ")", ";", "}", "}", "}" ]
Tries to load a deployer and passes the Asset instance through it. @param string $deploy Deployer to load/use @param Asset $asset
[ "Tries", "to", "load", "a", "deployer", "and", "passes", "the", "Asset", "instance", "through", "it", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L275-L284
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.loadFilter
private function loadFilter($class) { if (isset($this->filtersInstances[$class])) { return true; } $filter = $this->objectsFactory->buildFilter($class, $this->loadedConfigurator); if ($filter === false) { $this->loadedLogger->warning('Could not load ' . $class . ' filter.'); return false; } $this->filtersInstances[$class] = $filter; $this->loadedLogger->debug('Filter ' . $class . ' found & loaded.'); return true; }
php
private function loadFilter($class) { if (isset($this->filtersInstances[$class])) { return true; } $filter = $this->objectsFactory->buildFilter($class, $this->loadedConfigurator); if ($filter === false) { $this->loadedLogger->warning('Could not load ' . $class . ' filter.'); return false; } $this->filtersInstances[$class] = $filter; $this->loadedLogger->debug('Filter ' . $class . ' found & loaded.'); return true; }
[ "private", "function", "loadFilter", "(", "$", "class", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "filtersInstances", "[", "$", "class", "]", ")", ")", "{", "return", "true", ";", "}", "$", "filter", "=", "$", "this", "->", "objectsFactory", "->", "buildFilter", "(", "$", "class", ",", "$", "this", "->", "loadedConfigurator", ")", ";", "if", "(", "$", "filter", "===", "false", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'Could not load '", ".", "$", "class", ".", "' filter.'", ")", ";", "return", "false", ";", "}", "$", "this", "->", "filtersInstances", "[", "$", "class", "]", "=", "$", "filter", ";", "$", "this", "->", "loadedLogger", "->", "debug", "(", "'Filter '", ".", "$", "class", ".", "' found & loaded.'", ")", ";", "return", "true", ";", "}" ]
Try to create & load an instance of a given Filter class name. @param string $class @return bool Whether the loading succeeded or not
[ "Try", "to", "create", "&", "load", "an", "instance", "of", "a", "given", "Filter", "class", "name", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L345-L363
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.loadDeployer
private function loadDeployer($class) { if (isset($this->deployersInstances[$class])) { return true; } $deployer = $this->objectsFactory->buildDeployer($class, $this->loadedConfigurator, $this->loadedCacheAdapter); if ($deployer === false) { $this->loadedLogger->warning('Could not load ' . $class . ' deployer.'); return false; } try { $deployer->isSupported(); } catch (PhassetsInternalException $e) { $this->loadedLogger->warning($class . ' deployer is not supported: ' . $e); } $this->deployersInstances[$class] = $deployer; $this->loadedLogger->debug('Deployer ' . $class . ' found & loaded.'); return true; }
php
private function loadDeployer($class) { if (isset($this->deployersInstances[$class])) { return true; } $deployer = $this->objectsFactory->buildDeployer($class, $this->loadedConfigurator, $this->loadedCacheAdapter); if ($deployer === false) { $this->loadedLogger->warning('Could not load ' . $class . ' deployer.'); return false; } try { $deployer->isSupported(); } catch (PhassetsInternalException $e) { $this->loadedLogger->warning($class . ' deployer is not supported: ' . $e); } $this->deployersInstances[$class] = $deployer; $this->loadedLogger->debug('Deployer ' . $class . ' found & loaded.'); return true; }
[ "private", "function", "loadDeployer", "(", "$", "class", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "deployersInstances", "[", "$", "class", "]", ")", ")", "{", "return", "true", ";", "}", "$", "deployer", "=", "$", "this", "->", "objectsFactory", "->", "buildDeployer", "(", "$", "class", ",", "$", "this", "->", "loadedConfigurator", ",", "$", "this", "->", "loadedCacheAdapter", ")", ";", "if", "(", "$", "deployer", "===", "false", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'Could not load '", ".", "$", "class", ".", "' deployer.'", ")", ";", "return", "false", ";", "}", "try", "{", "$", "deployer", "->", "isSupported", "(", ")", ";", "}", "catch", "(", "PhassetsInternalException", "$", "e", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "$", "class", ".", "' deployer is not supported: '", ".", "$", "e", ")", ";", "}", "$", "this", "->", "deployersInstances", "[", "$", "class", "]", "=", "$", "deployer", ";", "$", "this", "->", "loadedLogger", "->", "debug", "(", "'Deployer '", ".", "$", "class", ".", "' found & loaded.'", ")", ";", "return", "true", ";", "}" ]
Try to create & load an instance of a given Deployer class name. @param string $class @return bool Whether the loading succeeded or not
[ "Try", "to", "create", "&", "load", "an", "instance", "of", "a", "given", "Deployer", "class", "name", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L371-L395
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.loadAssetsManager
private function loadAssetsManager($class) { if (isset($this->assetsMergerInstances[$class])) { return true; } $merger = $this->objectsFactory->buildAssetsMerger($class, $this->loadedConfigurator); if ($merger === false) { $this->loadedLogger->warning('Could not load ' . $class . ' merger.'); return false; } $this->assetsMergerInstances[$class] = $merger; $this->loadedLogger->debug('Assets merger ' . $class . ' found & loaded.'); return true; }
php
private function loadAssetsManager($class) { if (isset($this->assetsMergerInstances[$class])) { return true; } $merger = $this->objectsFactory->buildAssetsMerger($class, $this->loadedConfigurator); if ($merger === false) { $this->loadedLogger->warning('Could not load ' . $class . ' merger.'); return false; } $this->assetsMergerInstances[$class] = $merger; $this->loadedLogger->debug('Assets merger ' . $class . ' found & loaded.'); return true; }
[ "private", "function", "loadAssetsManager", "(", "$", "class", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "assetsMergerInstances", "[", "$", "class", "]", ")", ")", "{", "return", "true", ";", "}", "$", "merger", "=", "$", "this", "->", "objectsFactory", "->", "buildAssetsMerger", "(", "$", "class", ",", "$", "this", "->", "loadedConfigurator", ")", ";", "if", "(", "$", "merger", "===", "false", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'Could not load '", ".", "$", "class", ".", "' merger.'", ")", ";", "return", "false", ";", "}", "$", "this", "->", "assetsMergerInstances", "[", "$", "class", "]", "=", "$", "merger", ";", "$", "this", "->", "loadedLogger", "->", "debug", "(", "'Assets merger '", ".", "$", "class", ".", "' found & loaded.'", ")", ";", "return", "true", ";", "}" ]
Try to create & load an instance of a given AssetsMerger class name. @param string $class Fully qualified class name @return bool Whether the loading succeeded or not
[ "Try", "to", "create", "&", "load", "an", "instance", "of", "a", "given", "AssetsMerger", "class", "name", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L403-L421
kattsoftware/phassets
src/Phassets/Phassets.php
Phassets.readConfig
private function readConfig() { // Logging if ($this->loadedLogger === null) { $logger = $this->loadedConfigurator->getConfig('logger', 'adapter'); $this->setLogger($logger); if ($this->loadedLogger === null) { $this->setLogger(DummyLogger::class); } } // Caching if ($this->loadedCacheAdapter === null) { $cacheAdapter = $this->loadedConfigurator->getConfig('cache', 'adapter'); $this->setCacheAdapter($cacheAdapter); if ($this->loadedCacheAdapter === null) { $this->setCacheAdapter(DummyCacheAdapter::class); } } $cacheTtl = $this->loadedConfigurator->getConfig('cache', 'ttl'); $this->cacheTtl = is_numeric($cacheTtl) ? $cacheTtl : 3600; // Configuration loading // Look-up for assets_source $this->assetsSource = $this->loadedConfigurator->getConfig('assets_source'); if (empty($this->assetsSource)) { $this->loadedLogger->warning('Could not load the "assets_source" setting.'); } // "assets_source" can be an array of paths. $this->assetsSource = (array)$this->assetsSource; // Loading the filters $filters = $this->loadedConfigurator->getConfig('filters'); if (is_array($filters)) { $this->filters = $filters; foreach ($filters as $extensionFilters) { foreach ($extensionFilters as $filter) { $this->loadFilter($filter); } } } else { $this->loadedLogger->warning('"filters" setting is not an array; no filters loaded...'); } // Loading the main or backup deployer $deployers = $this->loadedConfigurator->getConfig('deployers'); if (is_array($deployers)) { if (isset($deployers['main'])) { $backupLoaded = $this->loadDeployer($deployers['main']); if (!$backupLoaded) { $this->loadedLogger->warning('Could not load the main deployer ' . $deployers['main']); } else { $this->loadedDeployer = $deployers['main']; $this->loadedLogger->debug('Main deployer loaded: ' . $deployers['main']); } } else { $this->loadedLogger->warning('There is no main deployer set in configuration.'); } if ($this->loadedDeployer === null) { if (isset($deployers['backup'])) { $backupLoaded = $this->loadDeployer($deployers['backup']); if (!$backupLoaded) { $this->loadedLogger->warning('Could not load the backup deployer ' . $deployers['backup']); } else { $this->loadedDeployer = $deployers['backup']; $this->loadedLogger->debug('Backup deployer loaded: ' . $deployers['backup']); } } else { $this->loadedLogger->warning('There is no backup deployer set in configuration.'); } } } else { $this->loadedLogger->warning('"deployers" setting is not an array; no deployers loaded...'); } // Mergers $assetsMergers = $this->loadedConfigurator->getConfig('mergers'); if (is_array($assetsMergers)) { foreach ($assetsMergers as $ext => $assetsMerger) { if ($this->loadAssetsManager($assetsMerger)) { $this->assetsMergersList[$ext] = $assetsMerger; } } } }
php
private function readConfig() { // Logging if ($this->loadedLogger === null) { $logger = $this->loadedConfigurator->getConfig('logger', 'adapter'); $this->setLogger($logger); if ($this->loadedLogger === null) { $this->setLogger(DummyLogger::class); } } // Caching if ($this->loadedCacheAdapter === null) { $cacheAdapter = $this->loadedConfigurator->getConfig('cache', 'adapter'); $this->setCacheAdapter($cacheAdapter); if ($this->loadedCacheAdapter === null) { $this->setCacheAdapter(DummyCacheAdapter::class); } } $cacheTtl = $this->loadedConfigurator->getConfig('cache', 'ttl'); $this->cacheTtl = is_numeric($cacheTtl) ? $cacheTtl : 3600; // Configuration loading // Look-up for assets_source $this->assetsSource = $this->loadedConfigurator->getConfig('assets_source'); if (empty($this->assetsSource)) { $this->loadedLogger->warning('Could not load the "assets_source" setting.'); } // "assets_source" can be an array of paths. $this->assetsSource = (array)$this->assetsSource; // Loading the filters $filters = $this->loadedConfigurator->getConfig('filters'); if (is_array($filters)) { $this->filters = $filters; foreach ($filters as $extensionFilters) { foreach ($extensionFilters as $filter) { $this->loadFilter($filter); } } } else { $this->loadedLogger->warning('"filters" setting is not an array; no filters loaded...'); } // Loading the main or backup deployer $deployers = $this->loadedConfigurator->getConfig('deployers'); if (is_array($deployers)) { if (isset($deployers['main'])) { $backupLoaded = $this->loadDeployer($deployers['main']); if (!$backupLoaded) { $this->loadedLogger->warning('Could not load the main deployer ' . $deployers['main']); } else { $this->loadedDeployer = $deployers['main']; $this->loadedLogger->debug('Main deployer loaded: ' . $deployers['main']); } } else { $this->loadedLogger->warning('There is no main deployer set in configuration.'); } if ($this->loadedDeployer === null) { if (isset($deployers['backup'])) { $backupLoaded = $this->loadDeployer($deployers['backup']); if (!$backupLoaded) { $this->loadedLogger->warning('Could not load the backup deployer ' . $deployers['backup']); } else { $this->loadedDeployer = $deployers['backup']; $this->loadedLogger->debug('Backup deployer loaded: ' . $deployers['backup']); } } else { $this->loadedLogger->warning('There is no backup deployer set in configuration.'); } } } else { $this->loadedLogger->warning('"deployers" setting is not an array; no deployers loaded...'); } // Mergers $assetsMergers = $this->loadedConfigurator->getConfig('mergers'); if (is_array($assetsMergers)) { foreach ($assetsMergers as $ext => $assetsMerger) { if ($this->loadAssetsManager($assetsMerger)) { $this->assetsMergersList[$ext] = $assetsMerger; } } } }
[ "private", "function", "readConfig", "(", ")", "{", "// Logging", "if", "(", "$", "this", "->", "loadedLogger", "===", "null", ")", "{", "$", "logger", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'logger'", ",", "'adapter'", ")", ";", "$", "this", "->", "setLogger", "(", "$", "logger", ")", ";", "if", "(", "$", "this", "->", "loadedLogger", "===", "null", ")", "{", "$", "this", "->", "setLogger", "(", "DummyLogger", "::", "class", ")", ";", "}", "}", "// Caching", "if", "(", "$", "this", "->", "loadedCacheAdapter", "===", "null", ")", "{", "$", "cacheAdapter", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'cache'", ",", "'adapter'", ")", ";", "$", "this", "->", "setCacheAdapter", "(", "$", "cacheAdapter", ")", ";", "if", "(", "$", "this", "->", "loadedCacheAdapter", "===", "null", ")", "{", "$", "this", "->", "setCacheAdapter", "(", "DummyCacheAdapter", "::", "class", ")", ";", "}", "}", "$", "cacheTtl", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'cache'", ",", "'ttl'", ")", ";", "$", "this", "->", "cacheTtl", "=", "is_numeric", "(", "$", "cacheTtl", ")", "?", "$", "cacheTtl", ":", "3600", ";", "// Configuration loading", "// Look-up for assets_source", "$", "this", "->", "assetsSource", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'assets_source'", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "assetsSource", ")", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'Could not load the \"assets_source\" setting.'", ")", ";", "}", "// \"assets_source\" can be an array of paths.", "$", "this", "->", "assetsSource", "=", "(", "array", ")", "$", "this", "->", "assetsSource", ";", "// Loading the filters", "$", "filters", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'filters'", ")", ";", "if", "(", "is_array", "(", "$", "filters", ")", ")", "{", "$", "this", "->", "filters", "=", "$", "filters", ";", "foreach", "(", "$", "filters", "as", "$", "extensionFilters", ")", "{", "foreach", "(", "$", "extensionFilters", "as", "$", "filter", ")", "{", "$", "this", "->", "loadFilter", "(", "$", "filter", ")", ";", "}", "}", "}", "else", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'\"filters\" setting is not an array; no filters loaded...'", ")", ";", "}", "// Loading the main or backup deployer", "$", "deployers", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'deployers'", ")", ";", "if", "(", "is_array", "(", "$", "deployers", ")", ")", "{", "if", "(", "isset", "(", "$", "deployers", "[", "'main'", "]", ")", ")", "{", "$", "backupLoaded", "=", "$", "this", "->", "loadDeployer", "(", "$", "deployers", "[", "'main'", "]", ")", ";", "if", "(", "!", "$", "backupLoaded", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'Could not load the main deployer '", ".", "$", "deployers", "[", "'main'", "]", ")", ";", "}", "else", "{", "$", "this", "->", "loadedDeployer", "=", "$", "deployers", "[", "'main'", "]", ";", "$", "this", "->", "loadedLogger", "->", "debug", "(", "'Main deployer loaded: '", ".", "$", "deployers", "[", "'main'", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'There is no main deployer set in configuration.'", ")", ";", "}", "if", "(", "$", "this", "->", "loadedDeployer", "===", "null", ")", "{", "if", "(", "isset", "(", "$", "deployers", "[", "'backup'", "]", ")", ")", "{", "$", "backupLoaded", "=", "$", "this", "->", "loadDeployer", "(", "$", "deployers", "[", "'backup'", "]", ")", ";", "if", "(", "!", "$", "backupLoaded", ")", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'Could not load the backup deployer '", ".", "$", "deployers", "[", "'backup'", "]", ")", ";", "}", "else", "{", "$", "this", "->", "loadedDeployer", "=", "$", "deployers", "[", "'backup'", "]", ";", "$", "this", "->", "loadedLogger", "->", "debug", "(", "'Backup deployer loaded: '", ".", "$", "deployers", "[", "'backup'", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'There is no backup deployer set in configuration.'", ")", ";", "}", "}", "}", "else", "{", "$", "this", "->", "loadedLogger", "->", "warning", "(", "'\"deployers\" setting is not an array; no deployers loaded...'", ")", ";", "}", "// Mergers", "$", "assetsMergers", "=", "$", "this", "->", "loadedConfigurator", "->", "getConfig", "(", "'mergers'", ")", ";", "if", "(", "is_array", "(", "$", "assetsMergers", ")", ")", "{", "foreach", "(", "$", "assetsMergers", "as", "$", "ext", "=>", "$", "assetsMerger", ")", "{", "if", "(", "$", "this", "->", "loadAssetsManager", "(", "$", "assetsMerger", ")", ")", "{", "$", "this", "->", "assetsMergersList", "[", "$", "ext", "]", "=", "$", "assetsMerger", ";", "}", "}", "}", "}" ]
After the Configurator was loaded, try to complete the load of other settings.
[ "After", "the", "Configurator", "was", "loaded", "try", "to", "complete", "the", "load", "of", "other", "settings", "." ]
train
https://github.com/kattsoftware/phassets/blob/cc982cf1941eb5776287d64f027218bd4835ed2b/src/Phassets/Phassets.php#L426-L527
webtown-php/KunstmaanExtensionBundle
src/Configuration/SearchableEntityConfiguration.php
SearchableEntityConfiguration.populateIndex
public function populateIndex() { $this->buildDocumentsByManager($this->doctrine); if ($this->mongo) { $this->buildDocumentsByManager($this->mongo); } if (!empty($this->documents)) { $response = $this->searchProvider->addDocuments($this->documents); $this->documents = []; } }
php
public function populateIndex() { $this->buildDocumentsByManager($this->doctrine); if ($this->mongo) { $this->buildDocumentsByManager($this->mongo); } if (!empty($this->documents)) { $response = $this->searchProvider->addDocuments($this->documents); $this->documents = []; } }
[ "public", "function", "populateIndex", "(", ")", "{", "$", "this", "->", "buildDocumentsByManager", "(", "$", "this", "->", "doctrine", ")", ";", "if", "(", "$", "this", "->", "mongo", ")", "{", "$", "this", "->", "buildDocumentsByManager", "(", "$", "this", "->", "mongo", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "documents", ")", ")", "{", "$", "response", "=", "$", "this", "->", "searchProvider", "->", "addDocuments", "(", "$", "this", "->", "documents", ")", ";", "$", "this", "->", "documents", "=", "[", "]", ";", "}", "}" ]
Populate the indexes
[ "Populate", "the", "indexes" ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/Configuration/SearchableEntityConfiguration.php#L99-L111
webtown-php/KunstmaanExtensionBundle
src/Configuration/SearchableEntityConfiguration.php
SearchableEntityConfiguration.indexEntity
public function indexEntity(SearchableEntityInterface $entity) { foreach ($this->locales as $locale) { $this->addEntityToIndex($entity, $locale); } if (!empty($this->documents)) { $response = $this->searchProvider->addDocuments($this->documents); $this->documents = []; } }
php
public function indexEntity(SearchableEntityInterface $entity) { foreach ($this->locales as $locale) { $this->addEntityToIndex($entity, $locale); } if (!empty($this->documents)) { $response = $this->searchProvider->addDocuments($this->documents); $this->documents = []; } }
[ "public", "function", "indexEntity", "(", "SearchableEntityInterface", "$", "entity", ")", "{", "foreach", "(", "$", "this", "->", "locales", "as", "$", "locale", ")", "{", "$", "this", "->", "addEntityToIndex", "(", "$", "entity", ",", "$", "locale", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "documents", ")", ")", "{", "$", "response", "=", "$", "this", "->", "searchProvider", "->", "addDocuments", "(", "$", "this", "->", "documents", ")", ";", "$", "this", "->", "documents", "=", "[", "]", ";", "}", "}" ]
@param SearchableEntityInterface $entity @todo (Chris) Teszt kellene még hozzá
[ "@param", "SearchableEntityInterface", "$entity" ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/Configuration/SearchableEntityConfiguration.php#L144-L154
webtown-php/KunstmaanExtensionBundle
src/Configuration/SearchableEntityConfiguration.php
SearchableEntityConfiguration.deleteEntity
public function deleteEntity(SearchableEntityInterface $entity) { foreach ($this->locales as $locale) { $uid = $this->getDocUid($entity, $locale); $indexType = $this->indexType; $this->searchProvider->deleteDocument($this->indexName, $indexType, $uid); } }
php
public function deleteEntity(SearchableEntityInterface $entity) { foreach ($this->locales as $locale) { $uid = $this->getDocUid($entity, $locale); $indexType = $this->indexType; $this->searchProvider->deleteDocument($this->indexName, $indexType, $uid); } }
[ "public", "function", "deleteEntity", "(", "SearchableEntityInterface", "$", "entity", ")", "{", "foreach", "(", "$", "this", "->", "locales", "as", "$", "locale", ")", "{", "$", "uid", "=", "$", "this", "->", "getDocUid", "(", "$", "entity", ",", "$", "locale", ")", ";", "$", "indexType", "=", "$", "this", "->", "indexType", ";", "$", "this", "->", "searchProvider", "->", "deleteDocument", "(", "$", "this", "->", "indexName", ",", "$", "indexType", ",", "$", "uid", ")", ";", "}", "}" ]
@param SearchableEntityInterface $entity @todo (Chris) Teszt kellene még hozzá
[ "@param", "SearchableEntityInterface", "$entity" ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/Configuration/SearchableEntityConfiguration.php#L161-L168
webtown-php/KunstmaanExtensionBundle
src/Configuration/SearchableEntityConfiguration.php
SearchableEntityConfiguration.addCustomData
protected function addCustomData(SearchableEntityInterface $entity, &$doc) { $event = new IndexEntityEvent($entity, $doc); $this->eventDispatcher->dispatch(IndexEntityEvent::EVENT_NAME, $event); $doc = $event->getDoc(); }
php
protected function addCustomData(SearchableEntityInterface $entity, &$doc) { $event = new IndexEntityEvent($entity, $doc); $this->eventDispatcher->dispatch(IndexEntityEvent::EVENT_NAME, $event); $doc = $event->getDoc(); }
[ "protected", "function", "addCustomData", "(", "SearchableEntityInterface", "$", "entity", ",", "&", "$", "doc", ")", "{", "$", "event", "=", "new", "IndexEntityEvent", "(", "$", "entity", ",", "$", "doc", ")", ";", "$", "this", "->", "eventDispatcher", "->", "dispatch", "(", "IndexEntityEvent", "::", "EVENT_NAME", ",", "$", "event", ")", ";", "$", "doc", "=", "$", "event", "->", "getDoc", "(", ")", ";", "}" ]
Add custom data to index document (you can override to add custom fields to the search index) @param SearchableEntityInterface $entity @param array $doc @todo (Chris) Ehhez külön teszt kellene.
[ "Add", "custom", "data", "to", "index", "document", "(", "you", "can", "override", "to", "add", "custom", "fields", "to", "the", "search", "index", ")" ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/Configuration/SearchableEntityConfiguration.php#L239-L245
webtown-php/KunstmaanExtensionBundle
src/Configuration/SearchableEntityConfiguration.php
SearchableEntityConfiguration.removeHtml
protected function removeHtml($text) { // Remove HTML markup $result = strip_tags($text); // Decode HTML entities $result = trim(html_entity_decode($result, ENT_QUOTES)); return $result; }
php
protected function removeHtml($text) { // Remove HTML markup $result = strip_tags($text); // Decode HTML entities $result = trim(html_entity_decode($result, ENT_QUOTES)); return $result; }
[ "protected", "function", "removeHtml", "(", "$", "text", ")", "{", "// Remove HTML markup", "$", "result", "=", "strip_tags", "(", "$", "text", ")", ";", "// Decode HTML entities", "$", "result", "=", "trim", "(", "html_entity_decode", "(", "$", "result", ",", "ENT_QUOTES", ")", ")", ";", "return", "$", "result", ";", "}" ]
Removes all HTML markup & decode HTML entities @param $text @return string
[ "Removes", "all", "HTML", "markup", "&", "decode", "HTML", "entities" ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/Configuration/SearchableEntityConfiguration.php#L254-L263
antonmedv/silicone
src/Silicone/Controller.php
Controller.render
protected function render($view, array $parameters = array(), Response $response = null) { return $this->app->render($view, $parameters, $response); }
php
protected function render($view, array $parameters = array(), Response $response = null) { return $this->app->render($view, $parameters, $response); }
[ "protected", "function", "render", "(", "$", "view", ",", "array", "$", "parameters", "=", "array", "(", ")", ",", "Response", "$", "response", "=", "null", ")", "{", "return", "$", "this", "->", "app", "->", "render", "(", "$", "view", ",", "$", "parameters", ",", "$", "response", ")", ";", "}" ]
Render to response twig views. @param $view @param array $parameters @param Response $response @return Response
[ "Render", "to", "response", "twig", "views", "." ]
train
https://github.com/antonmedv/silicone/blob/e4a67ed41f0f419984df642b303f2a491c9a3933/src/Silicone/Controller.php#L40-L43
webforge-labs/psc-cms
lib/Psc/CMS/AbstractTabsContentItem2.php
AbstractTabsContentItem2.getTabsURL
public function getTabsURL(Array $qvars = array()) { if (isset($this->tabsUrl)) { return $this->tabsUrl; } return URLHelper::getURL('/'.implode('/',$this->getTabsId()), URLHelper::RELATIVE, $qvars); }
php
public function getTabsURL(Array $qvars = array()) { if (isset($this->tabsUrl)) { return $this->tabsUrl; } return URLHelper::getURL('/'.implode('/',$this->getTabsId()), URLHelper::RELATIVE, $qvars); }
[ "public", "function", "getTabsURL", "(", "Array", "$", "qvars", "=", "array", "(", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "tabsUrl", ")", ")", "{", "return", "$", "this", "->", "tabsUrl", ";", "}", "return", "URLHelper", "::", "getURL", "(", "'/'", ".", "implode", "(", "'/'", ",", "$", "this", "->", "getTabsId", "(", ")", ")", ",", "URLHelper", "::", "RELATIVE", ",", "$", "qvars", ")", ";", "}" ]
@return string @TODO relativeURL wie simpleURL wäre geil
[ "@return", "string" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/AbstractTabsContentItem2.php#L79-L84
left-right/center
src/controllers/TableController.php
TableController.index
public function index() { if (!Auth::check()) return LoginController::getIndex(); # Trail Trail::clear(); $tables = array_where(config('center.tables'), function($key, $value) { return !$value->hidden; }); $groups = $objects = []; foreach ($tables as $table) { $latest = DB::table($table->name) ->leftJoin(config('center.db.users') . ' as u2', $table->name . '.updated_by', '=', 'u2.id') ->select('u2.name as updated_name', $table->name . '.updated_at') ->orderBy($table->name . '.updated_at', 'desc') ->first(); if (!isset($groups[$table->list_grouping])) $groups[$table->list_grouping] = []; $groups[$table->list_grouping][] = (object) [ 'title' => $table->title, 'list_grouping' => $table->list_grouping, 'link' => action('\LeftRight\Center\Controllers\RowController@index', $table->name), 'updated_name' => isset($latest->updated_name) ? $latest->updated_name : '', 'updated_at' => isset($latest->updated_at) ? $latest->updated_at : '', 'count' => number_format(DB::table($table->name)->count()), ]; } foreach ($groups as $group) $objects = array_merge($objects, $group); $table = new Table; $table->rows($objects); $table->column('title', 'string', trans('center::site.table')); $table->column('count', 'integer', trans('center::site.count')); $table->column('updated_name', 'updated_name', trans('center::site.updated_name')); $table->column('updated_at', 'updated_at', trans('center::site.updated_at')); $table->groupBy('list_grouping'); $table = $table->draw('tables'); return view('center::tables.index', compact('table')); }
php
public function index() { if (!Auth::check()) return LoginController::getIndex(); # Trail Trail::clear(); $tables = array_where(config('center.tables'), function($key, $value) { return !$value->hidden; }); $groups = $objects = []; foreach ($tables as $table) { $latest = DB::table($table->name) ->leftJoin(config('center.db.users') . ' as u2', $table->name . '.updated_by', '=', 'u2.id') ->select('u2.name as updated_name', $table->name . '.updated_at') ->orderBy($table->name . '.updated_at', 'desc') ->first(); if (!isset($groups[$table->list_grouping])) $groups[$table->list_grouping] = []; $groups[$table->list_grouping][] = (object) [ 'title' => $table->title, 'list_grouping' => $table->list_grouping, 'link' => action('\LeftRight\Center\Controllers\RowController@index', $table->name), 'updated_name' => isset($latest->updated_name) ? $latest->updated_name : '', 'updated_at' => isset($latest->updated_at) ? $latest->updated_at : '', 'count' => number_format(DB::table($table->name)->count()), ]; } foreach ($groups as $group) $objects = array_merge($objects, $group); $table = new Table; $table->rows($objects); $table->column('title', 'string', trans('center::site.table')); $table->column('count', 'integer', trans('center::site.count')); $table->column('updated_name', 'updated_name', trans('center::site.updated_name')); $table->column('updated_at', 'updated_at', trans('center::site.updated_at')); $table->groupBy('list_grouping'); $table = $table->draw('tables'); return view('center::tables.index', compact('table')); }
[ "public", "function", "index", "(", ")", "{", "if", "(", "!", "Auth", "::", "check", "(", ")", ")", "return", "LoginController", "::", "getIndex", "(", ")", ";", "# Trail", "Trail", "::", "clear", "(", ")", ";", "$", "tables", "=", "array_where", "(", "config", "(", "'center.tables'", ")", ",", "function", "(", "$", "key", ",", "$", "value", ")", "{", "return", "!", "$", "value", "->", "hidden", ";", "}", ")", ";", "$", "groups", "=", "$", "objects", "=", "[", "]", ";", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "$", "latest", "=", "DB", "::", "table", "(", "$", "table", "->", "name", ")", "->", "leftJoin", "(", "config", "(", "'center.db.users'", ")", ".", "' as u2'", ",", "$", "table", "->", "name", ".", "'.updated_by'", ",", "'='", ",", "'u2.id'", ")", "->", "select", "(", "'u2.name as updated_name'", ",", "$", "table", "->", "name", ".", "'.updated_at'", ")", "->", "orderBy", "(", "$", "table", "->", "name", ".", "'.updated_at'", ",", "'desc'", ")", "->", "first", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "groups", "[", "$", "table", "->", "list_grouping", "]", ")", ")", "$", "groups", "[", "$", "table", "->", "list_grouping", "]", "=", "[", "]", ";", "$", "groups", "[", "$", "table", "->", "list_grouping", "]", "[", "]", "=", "(", "object", ")", "[", "'title'", "=>", "$", "table", "->", "title", ",", "'list_grouping'", "=>", "$", "table", "->", "list_grouping", ",", "'link'", "=>", "action", "(", "'\\LeftRight\\Center\\Controllers\\RowController@index'", ",", "$", "table", "->", "name", ")", ",", "'updated_name'", "=>", "isset", "(", "$", "latest", "->", "updated_name", ")", "?", "$", "latest", "->", "updated_name", ":", "''", ",", "'updated_at'", "=>", "isset", "(", "$", "latest", "->", "updated_at", ")", "?", "$", "latest", "->", "updated_at", ":", "''", ",", "'count'", "=>", "number_format", "(", "DB", "::", "table", "(", "$", "table", "->", "name", ")", "->", "count", "(", ")", ")", ",", "]", ";", "}", "foreach", "(", "$", "groups", "as", "$", "group", ")", "$", "objects", "=", "array_merge", "(", "$", "objects", ",", "$", "group", ")", ";", "$", "table", "=", "new", "Table", ";", "$", "table", "->", "rows", "(", "$", "objects", ")", ";", "$", "table", "->", "column", "(", "'title'", ",", "'string'", ",", "trans", "(", "'center::site.table'", ")", ")", ";", "$", "table", "->", "column", "(", "'count'", ",", "'integer'", ",", "trans", "(", "'center::site.count'", ")", ")", ";", "$", "table", "->", "column", "(", "'updated_name'", ",", "'updated_name'", ",", "trans", "(", "'center::site.updated_name'", ")", ")", ";", "$", "table", "->", "column", "(", "'updated_at'", ",", "'updated_at'", ",", "trans", "(", "'center::site.updated_at'", ")", ")", ";", "$", "table", "->", "groupBy", "(", "'list_grouping'", ")", ";", "$", "table", "=", "$", "table", "->", "draw", "(", "'tables'", ")", ";", "return", "view", "(", "'center::tables.index'", ",", "compact", "(", "'table'", ")", ")", ";", "}" ]
# Display list for home page
[ "#", "Display", "list", "for", "home", "page" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/controllers/TableController.php#L15-L55
left-right/center
src/controllers/TableController.php
TableController.permissions
public function permissions($table) { $table = config('center.tables.' . $table); $permissions = DB::table(config('center.db.permissions'))->where('table', $table->name)->lists('level', 'user_id'); $users = DB::table(config('center.db.users'))->get(); foreach ($users as &$user) { $user->level = (isset($permissions[$user->id])) ? $permissions[$user->id] : null; } $permission_levels = LoginController::getPermissionLevels(); return view('center::tables.permissions', compact('users', 'table', 'permission_levels')); }
php
public function permissions($table) { $table = config('center.tables.' . $table); $permissions = DB::table(config('center.db.permissions'))->where('table', $table->name)->lists('level', 'user_id'); $users = DB::table(config('center.db.users'))->get(); foreach ($users as &$user) { $user->level = (isset($permissions[$user->id])) ? $permissions[$user->id] : null; } $permission_levels = LoginController::getPermissionLevels(); return view('center::tables.permissions', compact('users', 'table', 'permission_levels')); }
[ "public", "function", "permissions", "(", "$", "table", ")", "{", "$", "table", "=", "config", "(", "'center.tables.'", ".", "$", "table", ")", ";", "$", "permissions", "=", "DB", "::", "table", "(", "config", "(", "'center.db.permissions'", ")", ")", "->", "where", "(", "'table'", ",", "$", "table", "->", "name", ")", "->", "lists", "(", "'level'", ",", "'user_id'", ")", ";", "$", "users", "=", "DB", "::", "table", "(", "config", "(", "'center.db.users'", ")", ")", "->", "get", "(", ")", ";", "foreach", "(", "$", "users", "as", "&", "$", "user", ")", "{", "$", "user", "->", "level", "=", "(", "isset", "(", "$", "permissions", "[", "$", "user", "->", "id", "]", ")", ")", "?", "$", "permissions", "[", "$", "user", "->", "id", "]", ":", "null", ";", "}", "$", "permission_levels", "=", "LoginController", "::", "getPermissionLevels", "(", ")", ";", "return", "view", "(", "'center::tables.permissions'", ",", "compact", "(", "'users'", ",", "'table'", ",", "'permission_levels'", ")", ")", ";", "}" ]
# Edit table permissions page
[ "#", "Edit", "table", "permissions", "page" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/controllers/TableController.php#L58-L67
left-right/center
src/controllers/TableController.php
TableController.savePermissions
public function savePermissions($table) { DB::table(config('center.db.permissions'))->where('table', $table)->delete(); foreach (Request::input('permissions') as $user=>$level) { if (!empty($level)) { DB::table(config('center.db.permissions'))->insert([ 'table' => $table, 'user_id' => $user, 'level' => $level, ]); } } LoginController::updateUserPermissions(); return redirect(action('\LeftRight\Center\Controllers\RowController@index', $table))->with('message', trans('center::site.permissions_update_success')); }
php
public function savePermissions($table) { DB::table(config('center.db.permissions'))->where('table', $table)->delete(); foreach (Request::input('permissions') as $user=>$level) { if (!empty($level)) { DB::table(config('center.db.permissions'))->insert([ 'table' => $table, 'user_id' => $user, 'level' => $level, ]); } } LoginController::updateUserPermissions(); return redirect(action('\LeftRight\Center\Controllers\RowController@index', $table))->with('message', trans('center::site.permissions_update_success')); }
[ "public", "function", "savePermissions", "(", "$", "table", ")", "{", "DB", "::", "table", "(", "config", "(", "'center.db.permissions'", ")", ")", "->", "where", "(", "'table'", ",", "$", "table", ")", "->", "delete", "(", ")", ";", "foreach", "(", "Request", "::", "input", "(", "'permissions'", ")", "as", "$", "user", "=>", "$", "level", ")", "{", "if", "(", "!", "empty", "(", "$", "level", ")", ")", "{", "DB", "::", "table", "(", "config", "(", "'center.db.permissions'", ")", ")", "->", "insert", "(", "[", "'table'", "=>", "$", "table", ",", "'user_id'", "=>", "$", "user", ",", "'level'", "=>", "$", "level", ",", "]", ")", ";", "}", "}", "LoginController", "::", "updateUserPermissions", "(", ")", ";", "return", "redirect", "(", "action", "(", "'\\LeftRight\\Center\\Controllers\\RowController@index'", ",", "$", "table", ")", ")", "->", "with", "(", "'message'", ",", "trans", "(", "'center::site.permissions_update_success'", ")", ")", ";", "}" ]
# Handle table permissions update
[ "#", "Handle", "table", "permissions", "update" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/controllers/TableController.php#L70-L83
left-right/center
src/controllers/TableController.php
TableController.export
public function export($table) { $table = config('center.tables.' . $table); if (empty($table->export)) return false; //throw new exception? Excel::create($table->title, function($excel) use ($table) { $excel->setTitle($table->title)->sheet($table->title, function($sheet) use ($table) { //fetch data $results = DB::table($table->name); foreach ($table->order_by as $column=>$direction) { $results->orderBy($column, $direction); } $results = $results->get(); //output array $rows = []; foreach ($results as $result) { $row = []; foreach ($table->export as $field) { $row[trans('center::' . $table->name . '.fields.' . $field)] = $result->{$field}; } $rows[] = $row; } /*format columns $sheet->setColumnFormat([ 'E' => '0.00', ]);*/ $sheet->with($rows)->freezeFirstRow()->row(1, function ($row) { $row->setFontWeight('bold'); $row->setBackground('#FFFFEE'); $row->setBorder('none', 'none', 'bottom', 'none'); })->setHeight(1, 30); /* $sheet->cells('A1:F1', function($cells) { $cells->setFontWeight('bold'); });*/ }); })->download('xlsx'); }
php
public function export($table) { $table = config('center.tables.' . $table); if (empty($table->export)) return false; //throw new exception? Excel::create($table->title, function($excel) use ($table) { $excel->setTitle($table->title)->sheet($table->title, function($sheet) use ($table) { //fetch data $results = DB::table($table->name); foreach ($table->order_by as $column=>$direction) { $results->orderBy($column, $direction); } $results = $results->get(); //output array $rows = []; foreach ($results as $result) { $row = []; foreach ($table->export as $field) { $row[trans('center::' . $table->name . '.fields.' . $field)] = $result->{$field}; } $rows[] = $row; } /*format columns $sheet->setColumnFormat([ 'E' => '0.00', ]);*/ $sheet->with($rows)->freezeFirstRow()->row(1, function ($row) { $row->setFontWeight('bold'); $row->setBackground('#FFFFEE'); $row->setBorder('none', 'none', 'bottom', 'none'); })->setHeight(1, 30); /* $sheet->cells('A1:F1', function($cells) { $cells->setFontWeight('bold'); });*/ }); })->download('xlsx'); }
[ "public", "function", "export", "(", "$", "table", ")", "{", "$", "table", "=", "config", "(", "'center.tables.'", ".", "$", "table", ")", ";", "if", "(", "empty", "(", "$", "table", "->", "export", ")", ")", "return", "false", ";", "//throw new exception?", "Excel", "::", "create", "(", "$", "table", "->", "title", ",", "function", "(", "$", "excel", ")", "use", "(", "$", "table", ")", "{", "$", "excel", "->", "setTitle", "(", "$", "table", "->", "title", ")", "->", "sheet", "(", "$", "table", "->", "title", ",", "function", "(", "$", "sheet", ")", "use", "(", "$", "table", ")", "{", "//fetch data", "$", "results", "=", "DB", "::", "table", "(", "$", "table", "->", "name", ")", ";", "foreach", "(", "$", "table", "->", "order_by", "as", "$", "column", "=>", "$", "direction", ")", "{", "$", "results", "->", "orderBy", "(", "$", "column", ",", "$", "direction", ")", ";", "}", "$", "results", "=", "$", "results", "->", "get", "(", ")", ";", "//output array", "$", "rows", "=", "[", "]", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "$", "row", "=", "[", "]", ";", "foreach", "(", "$", "table", "->", "export", "as", "$", "field", ")", "{", "$", "row", "[", "trans", "(", "'center::'", ".", "$", "table", "->", "name", ".", "'.fields.'", ".", "$", "field", ")", "]", "=", "$", "result", "->", "{", "$", "field", "}", ";", "}", "$", "rows", "[", "]", "=", "$", "row", ";", "}", "/*format columns\n\t\t\t\t\t$sheet->setColumnFormat([\n\t\t\t\t\t\t'E' => '0.00',\n\t\t\t\t\t]);*/", "$", "sheet", "->", "with", "(", "$", "rows", ")", "->", "freezeFirstRow", "(", ")", "->", "row", "(", "1", ",", "function", "(", "$", "row", ")", "{", "$", "row", "->", "setFontWeight", "(", "'bold'", ")", ";", "$", "row", "->", "setBackground", "(", "'#FFFFEE'", ")", ";", "$", "row", "->", "setBorder", "(", "'none'", ",", "'none'", ",", "'bottom'", ",", "'none'", ")", ";", "}", ")", "->", "setHeight", "(", "1", ",", "30", ")", ";", "/*\n\t\t\t\t\t$sheet->cells('A1:F1', function($cells) {\n\t\t\t\t\t\t$cells->setFontWeight('bold');\n\t\t\t\t\t});*/", "}", ")", ";", "}", ")", "->", "download", "(", "'xlsx'", ")", ";", "}" ]
export instances
[ "export", "instances" ]
train
https://github.com/left-right/center/blob/47c225538475ca3e87fa49f31a323b6e6bd4eff2/src/controllers/TableController.php#L86-L132
zodream/thirdparty
src/OAuth/QQ.php
QQ.decodeJson
protected function decodeJson($data) { if (strpos($data, 'callback') !== false) { $leftPos = strpos($data, '('); $rightPos = strrpos($data, ')'); $data = substr($data, $leftPos + 1, $rightPos - $leftPos -1); } return Json::decode($data); }
php
protected function decodeJson($data) { if (strpos($data, 'callback') !== false) { $leftPos = strpos($data, '('); $rightPos = strrpos($data, ')'); $data = substr($data, $leftPos + 1, $rightPos - $leftPos -1); } return Json::decode($data); }
[ "protected", "function", "decodeJson", "(", "$", "data", ")", "{", "if", "(", "strpos", "(", "$", "data", ",", "'callback'", ")", "!==", "false", ")", "{", "$", "leftPos", "=", "strpos", "(", "$", "data", ",", "'('", ")", ";", "$", "rightPos", "=", "strrpos", "(", "$", "data", ",", "')'", ")", ";", "$", "data", "=", "substr", "(", "$", "data", ",", "$", "leftPos", "+", "1", ",", "$", "rightPos", "-", "$", "leftPos", "-", "1", ")", ";", "}", "return", "Json", "::", "decode", "(", "$", "data", ")", ";", "}" ]
解密 json @param $data @return mixed
[ "解密", "json" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/OAuth/QQ.php#L88-L95
drupalwxt/pco_cities
modules/custom/pco_cities_ext/challenge_pages/src/EventSubscriber/ChallengePagesRedirectSubscriber.php
ChallengePagesRedirectSubscriber.redirectMyContentTypeNode
public function redirectMyContentTypeNode(GetResponseEvent $event) { $request = $event->getRequest(); $language = $this->languageManager->getCurrentLanguage()->getId(); if ($request->attributes->get('_route') !== 'entity.node.canonical') { return; } if ($request->attributes->get('node')->getType() !== 'challenge') { return; } // $redirect_url = Url::fromUri('entity:node/123');. $node = $request->attributes->get('node'); if ($language == 'fr') { $redirect_url = '/fr/defis/' . $node->getTranslation('fr')->get('field_friendly_url')->getValue()[0]['value']; } else { $redirect_url = '/en/challenges/' . $node->get('field_friendly_url')->getValue()[0]['value']; } $response = new RedirectResponse($redirect_url, 301); $event->setResponse($response); }
php
public function redirectMyContentTypeNode(GetResponseEvent $event) { $request = $event->getRequest(); $language = $this->languageManager->getCurrentLanguage()->getId(); if ($request->attributes->get('_route') !== 'entity.node.canonical') { return; } if ($request->attributes->get('node')->getType() !== 'challenge') { return; } // $redirect_url = Url::fromUri('entity:node/123');. $node = $request->attributes->get('node'); if ($language == 'fr') { $redirect_url = '/fr/defis/' . $node->getTranslation('fr')->get('field_friendly_url')->getValue()[0]['value']; } else { $redirect_url = '/en/challenges/' . $node->get('field_friendly_url')->getValue()[0]['value']; } $response = new RedirectResponse($redirect_url, 301); $event->setResponse($response); }
[ "public", "function", "redirectMyContentTypeNode", "(", "GetResponseEvent", "$", "event", ")", "{", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "$", "language", "=", "$", "this", "->", "languageManager", "->", "getCurrentLanguage", "(", ")", "->", "getId", "(", ")", ";", "if", "(", "$", "request", "->", "attributes", "->", "get", "(", "'_route'", ")", "!==", "'entity.node.canonical'", ")", "{", "return", ";", "}", "if", "(", "$", "request", "->", "attributes", "->", "get", "(", "'node'", ")", "->", "getType", "(", ")", "!==", "'challenge'", ")", "{", "return", ";", "}", "// $redirect_url = Url::fromUri('entity:node/123');.", "$", "node", "=", "$", "request", "->", "attributes", "->", "get", "(", "'node'", ")", ";", "if", "(", "$", "language", "==", "'fr'", ")", "{", "$", "redirect_url", "=", "'/fr/defis/'", ".", "$", "node", "->", "getTranslation", "(", "'fr'", ")", "->", "get", "(", "'field_friendly_url'", ")", "->", "getValue", "(", ")", "[", "0", "]", "[", "'value'", "]", ";", "}", "else", "{", "$", "redirect_url", "=", "'/en/challenges/'", ".", "$", "node", "->", "get", "(", "'field_friendly_url'", ")", "->", "getValue", "(", ")", "[", "0", "]", "[", "'value'", "]", ";", "}", "$", "response", "=", "new", "RedirectResponse", "(", "$", "redirect_url", ",", "301", ")", ";", "$", "event", "->", "setResponse", "(", "$", "response", ")", ";", "}" ]
Redirect requests for challenge go to custom module controller route. @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
[ "Redirect", "requests", "for", "challenge", "go", "to", "custom", "module", "controller", "route", "." ]
train
https://github.com/drupalwxt/pco_cities/blob/589651ac4478ce629dd9ad9cf2e15ad1a9de368a/modules/custom/pco_cities_ext/challenge_pages/src/EventSubscriber/ChallengePagesRedirectSubscriber.php#L50-L73
factorio-item-browser/export-data
src/Entity/Recipe/Ingredient.php
Ingredient.writeData
public function writeData(): array { $dataBuilder = new DataBuilder(); $dataBuilder->setString('t', $this->type, '') ->setString('n', $this->name, '') ->setFloat('a', $this->amount, 1.) ->setInteger('o', $this->order, 0); return $dataBuilder->getData(); }
php
public function writeData(): array { $dataBuilder = new DataBuilder(); $dataBuilder->setString('t', $this->type, '') ->setString('n', $this->name, '') ->setFloat('a', $this->amount, 1.) ->setInteger('o', $this->order, 0); return $dataBuilder->getData(); }
[ "public", "function", "writeData", "(", ")", ":", "array", "{", "$", "dataBuilder", "=", "new", "DataBuilder", "(", ")", ";", "$", "dataBuilder", "->", "setString", "(", "'t'", ",", "$", "this", "->", "type", ",", "''", ")", "->", "setString", "(", "'n'", ",", "$", "this", "->", "name", ",", "''", ")", "->", "setFloat", "(", "'a'", ",", "$", "this", "->", "amount", ",", "1.", ")", "->", "setInteger", "(", "'o'", ",", "$", "this", "->", "order", ",", "0", ")", ";", "return", "$", "dataBuilder", "->", "getData", "(", ")", ";", "}" ]
Writes the entity data to an array. @return array
[ "Writes", "the", "entity", "data", "to", "an", "array", "." ]
train
https://github.com/factorio-item-browser/export-data/blob/1413b2eed0fbfed0521457ac7ef0d668ac30c212/src/Entity/Recipe/Ingredient.php#L128-L136
factorio-item-browser/export-data
src/Entity/Recipe/Ingredient.php
Ingredient.readData
public function readData(DataContainer $data) { $this->type = $data->getString('t', ''); $this->name = $data->getString('n', ''); $this->amount = $data->getFloat('a', 1.); $this->order = $data->getInteger('o', 0); return $this; }
php
public function readData(DataContainer $data) { $this->type = $data->getString('t', ''); $this->name = $data->getString('n', ''); $this->amount = $data->getFloat('a', 1.); $this->order = $data->getInteger('o', 0); return $this; }
[ "public", "function", "readData", "(", "DataContainer", "$", "data", ")", "{", "$", "this", "->", "type", "=", "$", "data", "->", "getString", "(", "'t'", ",", "''", ")", ";", "$", "this", "->", "name", "=", "$", "data", "->", "getString", "(", "'n'", ",", "''", ")", ";", "$", "this", "->", "amount", "=", "$", "data", "->", "getFloat", "(", "'a'", ",", "1.", ")", ";", "$", "this", "->", "order", "=", "$", "data", "->", "getInteger", "(", "'o'", ",", "0", ")", ";", "return", "$", "this", ";", "}" ]
Reads the entity data. @param DataContainer $data @return $this
[ "Reads", "the", "entity", "data", "." ]
train
https://github.com/factorio-item-browser/export-data/blob/1413b2eed0fbfed0521457ac7ef0d668ac30c212/src/Entity/Recipe/Ingredient.php#L143-L150
factorio-item-browser/export-data
src/Entity/Recipe/Ingredient.php
Ingredient.calculateHash
public function calculateHash(): string { return EntityUtils::calculateHashOfArray([ $this->type, $this->name, $this->amount, $this->order, ]); }
php
public function calculateHash(): string { return EntityUtils::calculateHashOfArray([ $this->type, $this->name, $this->amount, $this->order, ]); }
[ "public", "function", "calculateHash", "(", ")", ":", "string", "{", "return", "EntityUtils", "::", "calculateHashOfArray", "(", "[", "$", "this", "->", "type", ",", "$", "this", "->", "name", ",", "$", "this", "->", "amount", ",", "$", "this", "->", "order", ",", "]", ")", ";", "}" ]
Calculates a hash value representing the entity. @return string
[ "Calculates", "a", "hash", "value", "representing", "the", "entity", "." ]
train
https://github.com/factorio-item-browser/export-data/blob/1413b2eed0fbfed0521457ac7ef0d668ac30c212/src/Entity/Recipe/Ingredient.php#L156-L164
yuncms/framework
src/user/models/ResendForm.php
ResendForm.resend
public function resend() { if (!$this->validate()) { return false; } /** @var UserToken $token */ $token = new UserToken(['user_id' => $this->user->id, 'type' => UserToken::TYPE_CONFIRMATION]); $token->save(false); Yii::$app->sendMail($this->user->email,Yii::t('yuncms', 'Confirm account on {0}', Yii::$app->name),'user/confirmation',['user' => $this->user, 'token' => $token]); Yii::$app->session->setFlash('info', Yii::t('yuncms', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.')); return true; }
php
public function resend() { if (!$this->validate()) { return false; } /** @var UserToken $token */ $token = new UserToken(['user_id' => $this->user->id, 'type' => UserToken::TYPE_CONFIRMATION]); $token->save(false); Yii::$app->sendMail($this->user->email,Yii::t('yuncms', 'Confirm account on {0}', Yii::$app->name),'user/confirmation',['user' => $this->user, 'token' => $token]); Yii::$app->session->setFlash('info', Yii::t('yuncms', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.')); return true; }
[ "public", "function", "resend", "(", ")", "{", "if", "(", "!", "$", "this", "->", "validate", "(", ")", ")", "{", "return", "false", ";", "}", "/** @var UserToken $token */", "$", "token", "=", "new", "UserToken", "(", "[", "'user_id'", "=>", "$", "this", "->", "user", "->", "id", ",", "'type'", "=>", "UserToken", "::", "TYPE_CONFIRMATION", "]", ")", ";", "$", "token", "->", "save", "(", "false", ")", ";", "Yii", "::", "$", "app", "->", "sendMail", "(", "$", "this", "->", "user", "->", "email", ",", "Yii", "::", "t", "(", "'yuncms'", ",", "'Confirm account on {0}'", ",", "Yii", "::", "$", "app", "->", "name", ")", ",", "'user/confirmation'", ",", "[", "'user'", "=>", "$", "this", "->", "user", ",", "'token'", "=>", "$", "token", "]", ")", ";", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'info'", ",", "Yii", "::", "t", "(", "'yuncms'", ",", "'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'", ")", ")", ";", "return", "true", ";", "}" ]
Creates new confirmation token and sends it to the user. @return boolean
[ "Creates", "new", "confirmation", "token", "and", "sends", "it", "to", "the", "user", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/models/ResendForm.php#L83-L94
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Shared/XMLWriter.php
PHPWord_Shared_XMLWriter.getData
public function getData() { if ($this->_tempFileName == '') { return $this->_xmlWriter->outputMemory(true); } else { $this->_xmlWriter->flush(); return file_get_contents($this->_tempFileName); } }
php
public function getData() { if ($this->_tempFileName == '') { return $this->_xmlWriter->outputMemory(true); } else { $this->_xmlWriter->flush(); return file_get_contents($this->_tempFileName); } }
[ "public", "function", "getData", "(", ")", "{", "if", "(", "$", "this", "->", "_tempFileName", "==", "''", ")", "{", "return", "$", "this", "->", "_xmlWriter", "->", "outputMemory", "(", "true", ")", ";", "}", "else", "{", "$", "this", "->", "_xmlWriter", "->", "flush", "(", ")", ";", "return", "file_get_contents", "(", "$", "this", "->", "_tempFileName", ")", ";", "}", "}" ]
Get written data @return $data
[ "Get", "written", "data" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Shared/XMLWriter.php#L106-L113
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Shared/XMLWriter.php
PHPWord_Shared_XMLWriter.writeRaw
public function writeRaw($text) { if (isset($this->_xmlWriter) && is_object($this->_xmlWriter) && (method_exists($this->_xmlWriter, 'writeRaw'))) { return $this->_xmlWriter->writeRaw($text); } return $this->text($text); }
php
public function writeRaw($text) { if (isset($this->_xmlWriter) && is_object($this->_xmlWriter) && (method_exists($this->_xmlWriter, 'writeRaw'))) { return $this->_xmlWriter->writeRaw($text); } return $this->text($text); }
[ "public", "function", "writeRaw", "(", "$", "text", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_xmlWriter", ")", "&&", "is_object", "(", "$", "this", "->", "_xmlWriter", ")", "&&", "(", "method_exists", "(", "$", "this", "->", "_xmlWriter", ",", "'writeRaw'", ")", ")", ")", "{", "return", "$", "this", "->", "_xmlWriter", "->", "writeRaw", "(", "$", "text", ")", ";", "}", "return", "$", "this", "->", "text", "(", "$", "text", ")", ";", "}" ]
Fallback method for writeRaw, introduced in PHP 5.2 @param string $text @return string
[ "Fallback", "method", "for", "writeRaw", "introduced", "in", "PHP", "5", ".", "2" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Shared/XMLWriter.php#L135-L142
xtcommerce/shop-appstore-lib
src/XTCommerce/ShopAppstoreLib/Client/OAuth.php
OAuth.authenticate
public function authenticate($force = false) { if($this->accessToken !== null && !$force) { return false; } $headers = array( 'Authorization' => 'Basic ' . base64_encode($this->getClientId() . ':' . $this->getClientSecret()), 'Accept-Language' => $this->getLocale() . ';q=0.8', 'Content-Type' => 'application/x-www-form-urlencoded' ); $headers = $this->injectUserAgent($headers); $res = $this->getHttpClient()->post( $this->entrypoint . '/oauth/token', array( 'code' => $this->getAuthCode() ), array( 'grant_type' => 'authorization_code' ), $headers ); if(!$res || isset($res['data']['error'])){ throw new OAuthException($res['data']['error'], Exception::API_ERROR); } $this->accessToken = $res['data']['access_token']; $this->refreshToken = $res['data']['refresh_token']; $this->expiresIn = (int)$res['data']['expires_in']; $this->scopes = explode(',', $res['data']['scope']); return $res['data']; }
php
public function authenticate($force = false) { if($this->accessToken !== null && !$force) { return false; } $headers = array( 'Authorization' => 'Basic ' . base64_encode($this->getClientId() . ':' . $this->getClientSecret()), 'Accept-Language' => $this->getLocale() . ';q=0.8', 'Content-Type' => 'application/x-www-form-urlencoded' ); $headers = $this->injectUserAgent($headers); $res = $this->getHttpClient()->post( $this->entrypoint . '/oauth/token', array( 'code' => $this->getAuthCode() ), array( 'grant_type' => 'authorization_code' ), $headers ); if(!$res || isset($res['data']['error'])){ throw new OAuthException($res['data']['error'], Exception::API_ERROR); } $this->accessToken = $res['data']['access_token']; $this->refreshToken = $res['data']['refresh_token']; $this->expiresIn = (int)$res['data']['expires_in']; $this->scopes = explode(',', $res['data']['scope']); return $res['data']; }
[ "public", "function", "authenticate", "(", "$", "force", "=", "false", ")", "{", "if", "(", "$", "this", "->", "accessToken", "!==", "null", "&&", "!", "$", "force", ")", "{", "return", "false", ";", "}", "$", "headers", "=", "array", "(", "'Authorization'", "=>", "'Basic '", ".", "base64_encode", "(", "$", "this", "->", "getClientId", "(", ")", ".", "':'", ".", "$", "this", "->", "getClientSecret", "(", ")", ")", ",", "'Accept-Language'", "=>", "$", "this", "->", "getLocale", "(", ")", ".", "';q=0.8'", ",", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", ")", ";", "$", "headers", "=", "$", "this", "->", "injectUserAgent", "(", "$", "headers", ")", ";", "$", "res", "=", "$", "this", "->", "getHttpClient", "(", ")", "->", "post", "(", "$", "this", "->", "entrypoint", ".", "'/oauth/token'", ",", "array", "(", "'code'", "=>", "$", "this", "->", "getAuthCode", "(", ")", ")", ",", "array", "(", "'grant_type'", "=>", "'authorization_code'", ")", ",", "$", "headers", ")", ";", "if", "(", "!", "$", "res", "||", "isset", "(", "$", "res", "[", "'data'", "]", "[", "'error'", "]", ")", ")", "{", "throw", "new", "OAuthException", "(", "$", "res", "[", "'data'", "]", "[", "'error'", "]", ",", "Exception", "::", "API_ERROR", ")", ";", "}", "$", "this", "->", "accessToken", "=", "$", "res", "[", "'data'", "]", "[", "'access_token'", "]", ";", "$", "this", "->", "refreshToken", "=", "$", "res", "[", "'data'", "]", "[", "'refresh_token'", "]", ";", "$", "this", "->", "expiresIn", "=", "(", "int", ")", "$", "res", "[", "'data'", "]", "[", "'expires_in'", "]", ";", "$", "this", "->", "scopes", "=", "explode", "(", "','", ",", "$", "res", "[", "'data'", "]", "[", "'scope'", "]", ")", ";", "return", "$", "res", "[", "'data'", "]", ";", "}" ]
Authentication @param boolean $force @throws \XTCommerce\ShopAppstoreLib\Exception\Exception @return \stdClass Example output: { access_token: 'xxxxx', refresh_token: 'xxxxx', expires_in: '3600', token_type: 'bearer', scope: 'products_read,orders_read' }
[ "Authentication" ]
train
https://github.com/xtcommerce/shop-appstore-lib/blob/b12637502f74e8d1288cf47817e4c02b7f507c3b/src/XTCommerce/ShopAppstoreLib/Client/OAuth.php#L105-L138
xtcommerce/shop-appstore-lib
src/XTCommerce/ShopAppstoreLib/Client/OAuth.php
OAuth.refreshTokens
public function refreshTokens() { $headers = array( 'Content-Type' => 'application/x-www-form-urlencoded' ); $headers = $this->injectUserAgent($headers); $res = $this->getHttpClient()->post($this->entrypoint . '/oauth/token', array( 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'refresh_token' => $this->getRefreshToken() ), array( 'grant_type'=>'refresh_token' ), $headers); if(!$res || !empty($res['data']['error'])){ throw new Exception($res['error'], Exception::API_ERROR); } $this->accessToken = $res['data']['access_token']; $this->refreshToken = $res['data']['refresh_token']; $this->expiresIn = (int)$res['data']['expires_in']; $this->scopes = explode(',', $res['data']['scope']); return $res['data']; }
php
public function refreshTokens() { $headers = array( 'Content-Type' => 'application/x-www-form-urlencoded' ); $headers = $this->injectUserAgent($headers); $res = $this->getHttpClient()->post($this->entrypoint . '/oauth/token', array( 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'refresh_token' => $this->getRefreshToken() ), array( 'grant_type'=>'refresh_token' ), $headers); if(!$res || !empty($res['data']['error'])){ throw new Exception($res['error'], Exception::API_ERROR); } $this->accessToken = $res['data']['access_token']; $this->refreshToken = $res['data']['refresh_token']; $this->expiresIn = (int)$res['data']['expires_in']; $this->scopes = explode(',', $res['data']['scope']); return $res['data']; }
[ "public", "function", "refreshTokens", "(", ")", "{", "$", "headers", "=", "array", "(", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", ")", ";", "$", "headers", "=", "$", "this", "->", "injectUserAgent", "(", "$", "headers", ")", ";", "$", "res", "=", "$", "this", "->", "getHttpClient", "(", ")", "->", "post", "(", "$", "this", "->", "entrypoint", ".", "'/oauth/token'", ",", "array", "(", "'client_id'", "=>", "$", "this", "->", "getClientId", "(", ")", ",", "'client_secret'", "=>", "$", "this", "->", "getClientSecret", "(", ")", ",", "'refresh_token'", "=>", "$", "this", "->", "getRefreshToken", "(", ")", ")", ",", "array", "(", "'grant_type'", "=>", "'refresh_token'", ")", ",", "$", "headers", ")", ";", "if", "(", "!", "$", "res", "||", "!", "empty", "(", "$", "res", "[", "'data'", "]", "[", "'error'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "$", "res", "[", "'error'", "]", ",", "Exception", "::", "API_ERROR", ")", ";", "}", "$", "this", "->", "accessToken", "=", "$", "res", "[", "'data'", "]", "[", "'access_token'", "]", ";", "$", "this", "->", "refreshToken", "=", "$", "res", "[", "'data'", "]", "[", "'refresh_token'", "]", ";", "$", "this", "->", "expiresIn", "=", "(", "int", ")", "$", "res", "[", "'data'", "]", "[", "'expires_in'", "]", ";", "$", "this", "->", "scopes", "=", "explode", "(", "','", ",", "$", "res", "[", "'data'", "]", "[", "'scope'", "]", ")", ";", "return", "$", "res", "[", "'data'", "]", ";", "}" ]
Refresh OAuth tokens @return array @throws \XTCommerce\ShopAppstoreLib\Exception\Exception
[ "Refresh", "OAuth", "tokens" ]
train
https://github.com/xtcommerce/shop-appstore-lib/blob/b12637502f74e8d1288cf47817e4c02b7f507c3b/src/XTCommerce/ShopAppstoreLib/Client/OAuth.php#L146-L172
GrahamDeprecated/CMS-Core
src/migrations/2013_11_02_105203_add_version_to_comments.php
AddVersionToComments.up
public function up() { Schema::table('comments', function ($table) { $table->integer('version')->unsigned()->default(1); }); foreach (CommentProvider::all() as $comment) { $comment->update(array('version' => 1)); } }
php
public function up() { Schema::table('comments', function ($table) { $table->integer('version')->unsigned()->default(1); }); foreach (CommentProvider::all() as $comment) { $comment->update(array('version' => 1)); } }
[ "public", "function", "up", "(", ")", "{", "Schema", "::", "table", "(", "'comments'", ",", "function", "(", "$", "table", ")", "{", "$", "table", "->", "integer", "(", "'version'", ")", "->", "unsigned", "(", ")", "->", "default", "(", "1", ")", ";", "}", ")", ";", "foreach", "(", "CommentProvider", "::", "all", "(", ")", "as", "$", "comment", ")", "{", "$", "comment", "->", "update", "(", "array", "(", "'version'", "=>", "1", ")", ")", ";", "}", "}" ]
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/GrahamDeprecated/CMS-Core/blob/5603e2bfa2fac6cf46ca3ed62d21518f2f653675/src/migrations/2013_11_02_105203_add_version_to_comments.php#L37-L46
yuncms/framework
src/user/models/UserAuthItem.php
UserAuthItem.find
public static function find($id) { $item = self::getAuthManager()->getRole($id); if ($item !== null) { return new self($item); } return null; }
php
public static function find($id) { $item = self::getAuthManager()->getRole($id); if ($item !== null) { return new self($item); } return null; }
[ "public", "static", "function", "find", "(", "$", "id", ")", "{", "$", "item", "=", "self", "::", "getAuthManager", "(", ")", "->", "getRole", "(", "$", "id", ")", ";", "if", "(", "$", "item", "!==", "null", ")", "{", "return", "new", "self", "(", "$", "item", ")", ";", "}", "return", "null", ";", "}" ]
Find role @param string $id @return null|\self @throws \yii\base\InvalidConfigException
[ "Find", "role" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/models/UserAuthItem.php#L161-L168
yuncms/framework
src/user/models/UserAuthItem.php
UserAuthItem.addChildren
public function addChildren($items) { $manager = self::getAuthManager(); $success = 0; if ($this->_item) { foreach ($items as $name) { $child = $manager->getPermission($name); if ($this->type == Item::TYPE_ROLE && $child === null) { $child = $manager->getRole($name); } try { $manager->addChild($this->_item, $child); $success++; } catch (\Exception $exc) { Yii::error($exc->getMessage(), __METHOD__); } } } if ($success > 0) { UserRBACHelper::invalidate(); } return $success; }
php
public function addChildren($items) { $manager = self::getAuthManager(); $success = 0; if ($this->_item) { foreach ($items as $name) { $child = $manager->getPermission($name); if ($this->type == Item::TYPE_ROLE && $child === null) { $child = $manager->getRole($name); } try { $manager->addChild($this->_item, $child); $success++; } catch (\Exception $exc) { Yii::error($exc->getMessage(), __METHOD__); } } } if ($success > 0) { UserRBACHelper::invalidate(); } return $success; }
[ "public", "function", "addChildren", "(", "$", "items", ")", "{", "$", "manager", "=", "self", "::", "getAuthManager", "(", ")", ";", "$", "success", "=", "0", ";", "if", "(", "$", "this", "->", "_item", ")", "{", "foreach", "(", "$", "items", "as", "$", "name", ")", "{", "$", "child", "=", "$", "manager", "->", "getPermission", "(", "$", "name", ")", ";", "if", "(", "$", "this", "->", "type", "==", "Item", "::", "TYPE_ROLE", "&&", "$", "child", "===", "null", ")", "{", "$", "child", "=", "$", "manager", "->", "getRole", "(", "$", "name", ")", ";", "}", "try", "{", "$", "manager", "->", "addChild", "(", "$", "this", "->", "_item", ",", "$", "child", ")", ";", "$", "success", "++", ";", "}", "catch", "(", "\\", "Exception", "$", "exc", ")", "{", "Yii", "::", "error", "(", "$", "exc", "->", "getMessage", "(", ")", ",", "__METHOD__", ")", ";", "}", "}", "}", "if", "(", "$", "success", ">", "0", ")", "{", "UserRBACHelper", "::", "invalidate", "(", ")", ";", "}", "return", "$", "success", ";", "}" ]
Adds an item as a child of another item. @param array $items @return integer @throws \yii\base\InvalidConfigException
[ "Adds", "an", "item", "as", "a", "child", "of", "another", "item", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/user/models/UserAuthItem.php#L212-L234
webforge-labs/psc-cms
lib/Psc/Net/HTTP/Request.php
Request.infer
public static function infer(SfRequest $sfRequest = NULL) { if (!isset($sfRequest)) { $sfRequest = SfRequest::createFromGlobals(); } // alternativ könnten wir den code aus sf kopieren oder sf mal patchen.. $method = NULL; switch ($sfRequest->getMethod()) { // wertet schon X-HTTP-METHOD-OVERRIDE aus case 'POST': $method = Request::POST; break; case 'PUT': $method = Request::PUT; break; case 'DELETE': $method = Request::DELETE; break; case 'PATCH': $method = Request::PATCH; break; case 'GET': default: $method = Request::GET; break; } $request = new Request($method, rawurldecode($sfRequest->getPathInfo())); $request->setQuery($sfRequest->query->all()); $request->setReferer($sfRequest->server->get('HTTP_REFERER')); $request->setUserAgent($sfRequest->server->get('HTTP_USER_AGENT')); $request->setPreferredLanguages($sfRequest->getLanguages()); $header = $request->getHeader(); foreach ($sfRequest->headers->all() as $key => $value) { // wir verschönern hier z.B. X_REQUESTED_WITH zu X-Requested-With $key = mb_strtolower($key); $key = \Psc\Preg::replace_callback($key, '/(^|-)([a-z]{1})/', function ($m) { return ($m[1] === '' ? NULL : '-').mb_strtoupper($m[2]); }); // das ist voll doof, aber aus legacy gründen müssen wir das machen // schöner wäre auch die sf Requests / Header zu benutzen, dann wären wir durch if (count($value) === 1) { // unwrap arrays mit nur einem eintrag $value = current($value); } $header->setField($key, $value); } /* Body */ if (mb_strpos($request->getHeaderField('Content-Type'), 'application/x-www-form-urlencoded') === 0) { $request->setBody($sfRequest->request->all()); } elseif(mb_strpos($request->getHeaderField('Content-Type'), 'multipart/form-data') === 0) { $request->setBody($sfRequest->request->all()); $files = array(); foreach ($sfRequest->files->all() as $key => $sfFile) { if ($sfFile instanceof \Symfony\Component\HttpFoundation\File\UploadedFile) { if (!$sfFile->isValid()) { throw new \Psc\Exception('Cannot Upload File: '.$sfFile->getClientOriginalName().' Error Code: '.$sfFile->getErorr().' size: '.$sfFile->getClientSize()); } else { $files[$key] = $f = new \Psc\System\UploadedFile($sfFile->getPathName()); $f->setOriginalName($sfFile->getClientOriginalName()); } $request->setFiles($files); } // FIXME else: kann auch ein array von files sein oder ein array von array ... // aber wie machen wir das in den files array rein? } } else { $request->setBody($sfRequest->getContent()); // really raw } return $request; }
php
public static function infer(SfRequest $sfRequest = NULL) { if (!isset($sfRequest)) { $sfRequest = SfRequest::createFromGlobals(); } // alternativ könnten wir den code aus sf kopieren oder sf mal patchen.. $method = NULL; switch ($sfRequest->getMethod()) { // wertet schon X-HTTP-METHOD-OVERRIDE aus case 'POST': $method = Request::POST; break; case 'PUT': $method = Request::PUT; break; case 'DELETE': $method = Request::DELETE; break; case 'PATCH': $method = Request::PATCH; break; case 'GET': default: $method = Request::GET; break; } $request = new Request($method, rawurldecode($sfRequest->getPathInfo())); $request->setQuery($sfRequest->query->all()); $request->setReferer($sfRequest->server->get('HTTP_REFERER')); $request->setUserAgent($sfRequest->server->get('HTTP_USER_AGENT')); $request->setPreferredLanguages($sfRequest->getLanguages()); $header = $request->getHeader(); foreach ($sfRequest->headers->all() as $key => $value) { // wir verschönern hier z.B. X_REQUESTED_WITH zu X-Requested-With $key = mb_strtolower($key); $key = \Psc\Preg::replace_callback($key, '/(^|-)([a-z]{1})/', function ($m) { return ($m[1] === '' ? NULL : '-').mb_strtoupper($m[2]); }); // das ist voll doof, aber aus legacy gründen müssen wir das machen // schöner wäre auch die sf Requests / Header zu benutzen, dann wären wir durch if (count($value) === 1) { // unwrap arrays mit nur einem eintrag $value = current($value); } $header->setField($key, $value); } /* Body */ if (mb_strpos($request->getHeaderField('Content-Type'), 'application/x-www-form-urlencoded') === 0) { $request->setBody($sfRequest->request->all()); } elseif(mb_strpos($request->getHeaderField('Content-Type'), 'multipart/form-data') === 0) { $request->setBody($sfRequest->request->all()); $files = array(); foreach ($sfRequest->files->all() as $key => $sfFile) { if ($sfFile instanceof \Symfony\Component\HttpFoundation\File\UploadedFile) { if (!$sfFile->isValid()) { throw new \Psc\Exception('Cannot Upload File: '.$sfFile->getClientOriginalName().' Error Code: '.$sfFile->getErorr().' size: '.$sfFile->getClientSize()); } else { $files[$key] = $f = new \Psc\System\UploadedFile($sfFile->getPathName()); $f->setOriginalName($sfFile->getClientOriginalName()); } $request->setFiles($files); } // FIXME else: kann auch ein array von files sein oder ein array von array ... // aber wie machen wir das in den files array rein? } } else { $request->setBody($sfRequest->getContent()); // really raw } return $request; }
[ "public", "static", "function", "infer", "(", "SfRequest", "$", "sfRequest", "=", "NULL", ")", "{", "if", "(", "!", "isset", "(", "$", "sfRequest", ")", ")", "{", "$", "sfRequest", "=", "SfRequest", "::", "createFromGlobals", "(", ")", ";", "}", "// alternativ könnten wir den code aus sf kopieren oder sf mal patchen..", "$", "method", "=", "NULL", ";", "switch", "(", "$", "sfRequest", "->", "getMethod", "(", ")", ")", "{", "// wertet schon X-HTTP-METHOD-OVERRIDE aus", "case", "'POST'", ":", "$", "method", "=", "Request", "::", "POST", ";", "break", ";", "case", "'PUT'", ":", "$", "method", "=", "Request", "::", "PUT", ";", "break", ";", "case", "'DELETE'", ":", "$", "method", "=", "Request", "::", "DELETE", ";", "break", ";", "case", "'PATCH'", ":", "$", "method", "=", "Request", "::", "PATCH", ";", "break", ";", "case", "'GET'", ":", "default", ":", "$", "method", "=", "Request", "::", "GET", ";", "break", ";", "}", "$", "request", "=", "new", "Request", "(", "$", "method", ",", "rawurldecode", "(", "$", "sfRequest", "->", "getPathInfo", "(", ")", ")", ")", ";", "$", "request", "->", "setQuery", "(", "$", "sfRequest", "->", "query", "->", "all", "(", ")", ")", ";", "$", "request", "->", "setReferer", "(", "$", "sfRequest", "->", "server", "->", "get", "(", "'HTTP_REFERER'", ")", ")", ";", "$", "request", "->", "setUserAgent", "(", "$", "sfRequest", "->", "server", "->", "get", "(", "'HTTP_USER_AGENT'", ")", ")", ";", "$", "request", "->", "setPreferredLanguages", "(", "$", "sfRequest", "->", "getLanguages", "(", ")", ")", ";", "$", "header", "=", "$", "request", "->", "getHeader", "(", ")", ";", "foreach", "(", "$", "sfRequest", "->", "headers", "->", "all", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "// wir verschönern hier z.B. X_REQUESTED_WITH zu X-Requested-With", "$", "key", "=", "mb_strtolower", "(", "$", "key", ")", ";", "$", "key", "=", "\\", "Psc", "\\", "Preg", "::", "replace_callback", "(", "$", "key", ",", "'/(^|-)([a-z]{1})/'", ",", "function", "(", "$", "m", ")", "{", "return", "(", "$", "m", "[", "1", "]", "===", "''", "?", "NULL", ":", "'-'", ")", ".", "mb_strtoupper", "(", "$", "m", "[", "2", "]", ")", ";", "}", ")", ";", "// das ist voll doof, aber aus legacy gründen müssen wir das machen", "// schöner wäre auch die sf Requests / Header zu benutzen, dann wären wir durch", "if", "(", "count", "(", "$", "value", ")", "===", "1", ")", "{", "// unwrap arrays mit nur einem eintrag", "$", "value", "=", "current", "(", "$", "value", ")", ";", "}", "$", "header", "->", "setField", "(", "$", "key", ",", "$", "value", ")", ";", "}", "/* Body */", "if", "(", "mb_strpos", "(", "$", "request", "->", "getHeaderField", "(", "'Content-Type'", ")", ",", "'application/x-www-form-urlencoded'", ")", "===", "0", ")", "{", "$", "request", "->", "setBody", "(", "$", "sfRequest", "->", "request", "->", "all", "(", ")", ")", ";", "}", "elseif", "(", "mb_strpos", "(", "$", "request", "->", "getHeaderField", "(", "'Content-Type'", ")", ",", "'multipart/form-data'", ")", "===", "0", ")", "{", "$", "request", "->", "setBody", "(", "$", "sfRequest", "->", "request", "->", "all", "(", ")", ")", ";", "$", "files", "=", "array", "(", ")", ";", "foreach", "(", "$", "sfRequest", "->", "files", "->", "all", "(", ")", "as", "$", "key", "=>", "$", "sfFile", ")", "{", "if", "(", "$", "sfFile", "instanceof", "\\", "Symfony", "\\", "Component", "\\", "HttpFoundation", "\\", "File", "\\", "UploadedFile", ")", "{", "if", "(", "!", "$", "sfFile", "->", "isValid", "(", ")", ")", "{", "throw", "new", "\\", "Psc", "\\", "Exception", "(", "'Cannot Upload File: '", ".", "$", "sfFile", "->", "getClientOriginalName", "(", ")", ".", "' Error Code: '", ".", "$", "sfFile", "->", "getErorr", "(", ")", ".", "' size: '", ".", "$", "sfFile", "->", "getClientSize", "(", ")", ")", ";", "}", "else", "{", "$", "files", "[", "$", "key", "]", "=", "$", "f", "=", "new", "\\", "Psc", "\\", "System", "\\", "UploadedFile", "(", "$", "sfFile", "->", "getPathName", "(", ")", ")", ";", "$", "f", "->", "setOriginalName", "(", "$", "sfFile", "->", "getClientOriginalName", "(", ")", ")", ";", "}", "$", "request", "->", "setFiles", "(", "$", "files", ")", ";", "}", "// FIXME else: kann auch ein array von files sein oder ein array von array ...", "// aber wie machen wir das in den files array rein?", "}", "}", "else", "{", "$", "request", "->", "setBody", "(", "$", "sfRequest", "->", "getContent", "(", ")", ")", ";", "// really raw", "}", "return", "$", "request", ";", "}" ]
Erstellt einen Request aus den Umgebungsvariablen wird eine Umgebungsvariable mit NULL übergeben (oder ausgelassen), wird die global Umgebungsvariable genommen infer() ist also äquivalent mit: infer($_GET, $_POST, $_COOKIE, $_SERVER) ist $_GET['mod_rewrite_request'] gesetzt wird dies als resource genommen @TODO Symfony hierfür nehmen (am besten ganz ersetzen) @deprecated das übergeben von Variablen ist strongly discouraged!
[ "Erstellt", "einen", "Request", "aus", "den", "Umgebungsvariablen" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Net/HTTP/Request.php#L99-L182
webforge-labs/psc-cms
lib/Psc/Net/HTTP/Request.php
Request.setBody
public function setBody($body) { if (is_array($body) || is_object($body)) $this->body = (object) $body; else $this->body = $body; return $this; }
php
public function setBody($body) { if (is_array($body) || is_object($body)) $this->body = (object) $body; else $this->body = $body; return $this; }
[ "public", "function", "setBody", "(", "$", "body", ")", "{", "if", "(", "is_array", "(", "$", "body", ")", "||", "is_object", "(", "$", "body", ")", ")", "$", "this", "->", "body", "=", "(", "object", ")", "$", "body", ";", "else", "$", "this", "->", "body", "=", "$", "body", ";", "return", "$", "this", ";", "}" ]
Setzt den RequestBody wird intern als stdClass umgewandelt, wenn es object oder array ist
[ "Setzt", "den", "RequestBody" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Net/HTTP/Request.php#L266-L272
afrittella/back-project
src/database/migrations/2017_02_03_164144_modify_users_table.php
ModifyUsersTable.up
public function up() { Schema::table('users', function(Blueprint $table) { $table->renameColumn('name', 'username'); $table->boolean('confirmed')->default(0); $table->string('confirmation_code')->nullable(); }); }
php
public function up() { Schema::table('users', function(Blueprint $table) { $table->renameColumn('name', 'username'); $table->boolean('confirmed')->default(0); $table->string('confirmation_code')->nullable(); }); }
[ "public", "function", "up", "(", ")", "{", "Schema", "::", "table", "(", "'users'", ",", "function", "(", "Blueprint", "$", "table", ")", "{", "$", "table", "->", "renameColumn", "(", "'name'", ",", "'username'", ")", ";", "$", "table", "->", "boolean", "(", "'confirmed'", ")", "->", "default", "(", "0", ")", ";", "$", "table", "->", "string", "(", "'confirmation_code'", ")", "->", "nullable", "(", ")", ";", "}", ")", ";", "}" ]
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/afrittella/back-project/blob/e1aa2e3ee03d453033f75a4b16f073c60b5f32d1/src/database/migrations/2017_02_03_164144_modify_users_table.php#L14-L21
GrahamDeprecated/CMS-Core
src/Seeds/PostsTableSeeder.php
PostsTableSeeder.run
public function run() { DB::table('posts')->delete(); $post = array( 'title' => 'Hello World', 'summary' => 'This is the first blog post.', 'body' => 'This is an example blog post.', 'user_id' => 1, 'created_at' => new DateTime, 'updated_at' => new DateTime ); DB::table('posts')->insert($post); }
php
public function run() { DB::table('posts')->delete(); $post = array( 'title' => 'Hello World', 'summary' => 'This is the first blog post.', 'body' => 'This is an example blog post.', 'user_id' => 1, 'created_at' => new DateTime, 'updated_at' => new DateTime ); DB::table('posts')->insert($post); }
[ "public", "function", "run", "(", ")", "{", "DB", "::", "table", "(", "'posts'", ")", "->", "delete", "(", ")", ";", "$", "post", "=", "array", "(", "'title'", "=>", "'Hello World'", ",", "'summary'", "=>", "'This is the first blog post.'", ",", "'body'", "=>", "'This is an example blog post.'", ",", "'user_id'", "=>", "1", ",", "'created_at'", "=>", "new", "DateTime", ",", "'updated_at'", "=>", "new", "DateTime", ")", ";", "DB", "::", "table", "(", "'posts'", ")", "->", "insert", "(", "$", "post", ")", ";", "}" ]
Run the database seeding. @return void
[ "Run", "the", "database", "seeding", "." ]
train
https://github.com/GrahamDeprecated/CMS-Core/blob/5603e2bfa2fac6cf46ca3ed62d21518f2f653675/src/Seeds/PostsTableSeeder.php#L39-L53
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClassConstant.php
GClassConstant.php
public function php($baseIndent = 0) { $php = $this->phpDocBlock($baseIndent); $php .= str_repeat(' ',$baseIndent); $php .= 'const '.$this->name; $php .= ' = '.$this->exportPropertyValue($this->getValue()); return $php; }
php
public function php($baseIndent = 0) { $php = $this->phpDocBlock($baseIndent); $php .= str_repeat(' ',$baseIndent); $php .= 'const '.$this->name; $php .= ' = '.$this->exportPropertyValue($this->getValue()); return $php; }
[ "public", "function", "php", "(", "$", "baseIndent", "=", "0", ")", "{", "$", "php", "=", "$", "this", "->", "phpDocBlock", "(", "$", "baseIndent", ")", ";", "$", "php", ".=", "str_repeat", "(", "' '", ",", "$", "baseIndent", ")", ";", "$", "php", ".=", "'const '", ".", "$", "this", "->", "name", ";", "$", "php", ".=", "' = '", ".", "$", "this", "->", "exportPropertyValue", "(", "$", "this", "->", "getValue", "(", ")", ")", ";", "return", "$", "php", ";", "}" ]
Gibt den PHP Code für die Konstante zurück
[ "Gibt", "den", "PHP", "Code", "für", "die", "Konstante", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClassConstant.php#L37-L46
digitalkaoz/versioneye-php
src/Output/Me.php
Me.profile
public function profile(OutputInterface $output, array $response) { $this->printList($output, ['Fullname', 'Username', 'Email', 'Admin', 'Notifications'], ['fullname', 'username', 'email', 'admin', 'notifications'], $response, function ($key, $value) { if ('Notifications' !== $key) { return $value; } return sprintf('%d / %d', $value['new'], $value['total']); } ); }
php
public function profile(OutputInterface $output, array $response) { $this->printList($output, ['Fullname', 'Username', 'Email', 'Admin', 'Notifications'], ['fullname', 'username', 'email', 'admin', 'notifications'], $response, function ($key, $value) { if ('Notifications' !== $key) { return $value; } return sprintf('%d / %d', $value['new'], $value['total']); } ); }
[ "public", "function", "profile", "(", "OutputInterface", "$", "output", ",", "array", "$", "response", ")", "{", "$", "this", "->", "printList", "(", "$", "output", ",", "[", "'Fullname'", ",", "'Username'", ",", "'Email'", ",", "'Admin'", ",", "'Notifications'", "]", ",", "[", "'fullname'", ",", "'username'", ",", "'email'", ",", "'admin'", ",", "'notifications'", "]", ",", "$", "response", ",", "function", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "'Notifications'", "!==", "$", "key", ")", "{", "return", "$", "value", ";", "}", "return", "sprintf", "(", "'%d / %d'", ",", "$", "value", "[", "'new'", "]", ",", "$", "value", "[", "'total'", "]", ")", ";", "}", ")", ";", "}" ]
output for the profile api. @param OutputInterface $output @param array $response
[ "output", "for", "the", "profile", "api", "." ]
train
https://github.com/digitalkaoz/versioneye-php/blob/7b8eb9cdc83e01138dda0e709c07e3beb6aad136/src/Output/Me.php#L20-L34
digitalkaoz/versioneye-php
src/Output/Me.php
Me.comments
public function comments(OutputInterface $output, array $response) { $table = $this->createTable($output); $table->setHeaders(['Name', 'Language', 'Version', 'Type', 'Date', 'Comment']); foreach ($response['comments'] as $comment) { $table->addRow([$comment['product']['name'], $comment['product']['language'], $comment['product']['version'], $comment['product']['prod_type'], $comment['created_at'], $comment['comment']]); } $table->render($output); }
php
public function comments(OutputInterface $output, array $response) { $table = $this->createTable($output); $table->setHeaders(['Name', 'Language', 'Version', 'Type', 'Date', 'Comment']); foreach ($response['comments'] as $comment) { $table->addRow([$comment['product']['name'], $comment['product']['language'], $comment['product']['version'], $comment['product']['prod_type'], $comment['created_at'], $comment['comment']]); } $table->render($output); }
[ "public", "function", "comments", "(", "OutputInterface", "$", "output", ",", "array", "$", "response", ")", "{", "$", "table", "=", "$", "this", "->", "createTable", "(", "$", "output", ")", ";", "$", "table", "->", "setHeaders", "(", "[", "'Name'", ",", "'Language'", ",", "'Version'", ",", "'Type'", ",", "'Date'", ",", "'Comment'", "]", ")", ";", "foreach", "(", "$", "response", "[", "'comments'", "]", "as", "$", "comment", ")", "{", "$", "table", "->", "addRow", "(", "[", "$", "comment", "[", "'product'", "]", "[", "'name'", "]", ",", "$", "comment", "[", "'product'", "]", "[", "'language'", "]", ",", "$", "comment", "[", "'product'", "]", "[", "'version'", "]", ",", "$", "comment", "[", "'product'", "]", "[", "'prod_type'", "]", ",", "$", "comment", "[", "'created_at'", "]", ",", "$", "comment", "[", "'comment'", "]", "]", ")", ";", "}", "$", "table", "->", "render", "(", "$", "output", ")", ";", "}" ]
output for the comments api. @param OutputInterface $output @param array $response
[ "output", "for", "the", "comments", "api", "." ]
train
https://github.com/digitalkaoz/versioneye-php/blob/7b8eb9cdc83e01138dda0e709c07e3beb6aad136/src/Output/Me.php#L64-L75
webforge-labs/psc-cms
lib/Psc/HTML/Page.php
Page.setOpen
public function setOpen() { $this->body->setOption('closeTag',FALSE); $this->html->setOption('closeTag',FALSE); return $this; }
php
public function setOpen() { $this->body->setOption('closeTag',FALSE); $this->html->setOption('closeTag',FALSE); return $this; }
[ "public", "function", "setOpen", "(", ")", "{", "$", "this", "->", "body", "->", "setOption", "(", "'closeTag'", ",", "FALSE", ")", ";", "$", "this", "->", "html", "->", "setOption", "(", "'closeTag'", ",", "FALSE", ")", ";", "return", "$", "this", ";", "}" ]
Missbraucht die Klasse als "Header" für eine HTML Datei wird dies gesetzt, endet das html bei <body> (öffnen) es muss dann body und html von hand geschlossen werden $html = new \Psc\HTML\Page(); $html->setOpen(); print $html; // hier goes the content print $html->getClose();
[ "Missbraucht", "die", "Klasse", "als", "Header", "für", "eine", "HTML", "Datei" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/HTML/Page.php#L128-L132
webforge-labs/psc-cms
lib/Psc/HTML/Page.php
Page.setMeta
public function setMeta($name, $content = NULL, $httpEquiv = FALSE, $scheme = NULL) { $meta = HTML::Tag('meta'); $meta->setOption('selfClosing',TRUE); if ($content === NULL) { /* löschen */ $this->removeMeta($name); } else { /* im W3C steht "may be used in place" ... d.h. man könnte auch name und http-equiv gleichzeitig benutzen http://www.w3.org/TR/html4/struct/global.html#edef-META */ if (isset($name)) { if (!$httpEquiv) $meta->setAttribute('name',$name); else $meta->setAttribute('http-equiv',$name); } if (isset($scheme)) $meta->setAttribute('scheme',$scheme); if ($content !== FALSE) { $meta->setAttribute('content',$content); } /* meta tags liegen im head in der root ebene, d.h. wir suchen ob es dort schon ein meta tag gibt, wenn es eins gibt ersetzen wir dies, ansonsten fügen wir es hinzu */ /* schlüssel des meta tags suchen (wenn vorhanden) */ $key = NULL; foreach ($this->head->content as $itemKey => $item) { if ($item instanceof Tag && $item->getTag() == 'meta' && ($item->getAttribute('name') == $name || $item->getAttribute('http-equiv') == $name)) { $key = $itemKey; break; } } if ($key !== NULL) { $this->head->content[$key] =& $meta; } else { $this->head->content[] =& $meta; } } return $meta; }
php
public function setMeta($name, $content = NULL, $httpEquiv = FALSE, $scheme = NULL) { $meta = HTML::Tag('meta'); $meta->setOption('selfClosing',TRUE); if ($content === NULL) { /* löschen */ $this->removeMeta($name); } else { /* im W3C steht "may be used in place" ... d.h. man könnte auch name und http-equiv gleichzeitig benutzen http://www.w3.org/TR/html4/struct/global.html#edef-META */ if (isset($name)) { if (!$httpEquiv) $meta->setAttribute('name',$name); else $meta->setAttribute('http-equiv',$name); } if (isset($scheme)) $meta->setAttribute('scheme',$scheme); if ($content !== FALSE) { $meta->setAttribute('content',$content); } /* meta tags liegen im head in der root ebene, d.h. wir suchen ob es dort schon ein meta tag gibt, wenn es eins gibt ersetzen wir dies, ansonsten fügen wir es hinzu */ /* schlüssel des meta tags suchen (wenn vorhanden) */ $key = NULL; foreach ($this->head->content as $itemKey => $item) { if ($item instanceof Tag && $item->getTag() == 'meta' && ($item->getAttribute('name') == $name || $item->getAttribute('http-equiv') == $name)) { $key = $itemKey; break; } } if ($key !== NULL) { $this->head->content[$key] =& $meta; } else { $this->head->content[] =& $meta; } } return $meta; }
[ "public", "function", "setMeta", "(", "$", "name", ",", "$", "content", "=", "NULL", ",", "$", "httpEquiv", "=", "FALSE", ",", "$", "scheme", "=", "NULL", ")", "{", "$", "meta", "=", "HTML", "::", "Tag", "(", "'meta'", ")", ";", "$", "meta", "->", "setOption", "(", "'selfClosing'", ",", "TRUE", ")", ";", "if", "(", "$", "content", "===", "NULL", ")", "{", "/* löschen */", "$", "this", "->", "removeMeta", "(", "$", "name", ")", ";", "}", "else", "{", "/* im W3C steht \"may be used in place\" ... d.h. man könnte auch name und http-equiv gleichzeitig benutzen \n http://www.w3.org/TR/html4/struct/global.html#edef-META\n */", "if", "(", "isset", "(", "$", "name", ")", ")", "{", "if", "(", "!", "$", "httpEquiv", ")", "$", "meta", "->", "setAttribute", "(", "'name'", ",", "$", "name", ")", ";", "else", "$", "meta", "->", "setAttribute", "(", "'http-equiv'", ",", "$", "name", ")", ";", "}", "if", "(", "isset", "(", "$", "scheme", ")", ")", "$", "meta", "->", "setAttribute", "(", "'scheme'", ",", "$", "scheme", ")", ";", "if", "(", "$", "content", "!==", "FALSE", ")", "{", "$", "meta", "->", "setAttribute", "(", "'content'", ",", "$", "content", ")", ";", "}", "/* meta tags liegen im head in der root ebene, d.h. wir suchen ob es dort schon ein meta tag gibt,\n wenn es eins gibt ersetzen wir dies, ansonsten fügen wir es hinzu \n */", "/* schlüssel des meta tags suchen (wenn vorhanden) */", "$", "key", "=", "NULL", ";", "foreach", "(", "$", "this", "->", "head", "->", "content", "as", "$", "itemKey", "=>", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "Tag", "&&", "$", "item", "->", "getTag", "(", ")", "==", "'meta'", "&&", "(", "$", "item", "->", "getAttribute", "(", "'name'", ")", "==", "$", "name", "||", "$", "item", "->", "getAttribute", "(", "'http-equiv'", ")", "==", "$", "name", ")", ")", "{", "$", "key", "=", "$", "itemKey", ";", "break", ";", "}", "}", "if", "(", "$", "key", "!==", "NULL", ")", "{", "$", "this", "->", "head", "->", "content", "[", "$", "key", "]", "=", "&", "$", "meta", ";", "}", "else", "{", "$", "this", "->", "head", "->", "content", "[", "]", "=", "&", "$", "meta", ";", "}", "}", "return", "$", "meta", ";", "}" ]
Setzt ein Meta Attribut wird <var>$content</var> leer gelassen oder auf NULL gesetzt, wird das Meta Attribut gelöscht @param string $name der Name des Meta Attributes @param string $content der Wert des Meta Attributes @return Tag<meta>
[ "Setzt", "ein", "Meta", "Attribut" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/HTML/Page.php#L146-L192
webforge-labs/psc-cms
lib/Psc/HTML/Page.php
Page.setContentType
public function setContentType($contentType) { $this->contentType = $contentType; $ct = $this->contentType; if (isset($this->charset)) $ct .= '; charset='.$this->charset; $this->setMeta('content-type',$ct, TRUE); }
php
public function setContentType($contentType) { $this->contentType = $contentType; $ct = $this->contentType; if (isset($this->charset)) $ct .= '; charset='.$this->charset; $this->setMeta('content-type',$ct, TRUE); }
[ "public", "function", "setContentType", "(", "$", "contentType", ")", "{", "$", "this", "->", "contentType", "=", "$", "contentType", ";", "$", "ct", "=", "$", "this", "->", "contentType", ";", "if", "(", "isset", "(", "$", "this", "->", "charset", ")", ")", "$", "ct", ".=", "'; charset='", ".", "$", "this", "->", "charset", ";", "$", "this", "->", "setMeta", "(", "'content-type'", ",", "$", "ct", ",", "TRUE", ")", ";", "}" ]
/* Doofe Setter und Mini Funktionen
[ "/", "*", "Doofe", "Setter", "und", "Mini", "Funktionen" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/HTML/Page.php#L205-L213