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
dms-org/package.blog
src/Infrastructure/Persistence/BlogArticleMapper.php
BlogArticleMapper.define
protected function define(MapperDefinition $map) { $map->type(BlogArticle::class); $map->toTable('articles'); $map->idToPrimaryKey('id'); $map->column($map->getOrm()->getNamespace() . 'author_id')->asUnsignedInt(); $map->relation(BlogArticle::AUTHOR) ->to(BlogAuthor::class) ->manyToOne() ->withBidirectionalRelation(BlogAuthor::ARTICLES) ->withRelatedIdAs($map->getOrm()->getNamespace() . 'author_id'); $map->column($map->getOrm()->getNamespace() . 'category_id')->nullable()->asUnsignedInt(); $map->relation(BlogArticle::CATEGORY) ->to(BlogCategory::class) ->manyToOne() ->withBidirectionalRelation(BlogCategory::ARTICLES) ->withRelatedIdAs($map->getOrm()->getNamespace() . 'category_id'); $map->relation(BlogArticle::COMMENTS) ->to(BlogArticleComment::class) ->toMany() ->identifying() ->withBidirectionalRelation(BlogArticleComment::ARTICLE) ->orderByDesc('posted_at') ->withParentIdAs($map->getOrm()->getNamespace() . 'article_id'); $map->property(BlogArticle::TITLE)->to('title')->asVarchar(255); $map->property(BlogArticle::SUB_TITLE)->to('sub_title')->asVarchar(255); $map->property(BlogArticle::SLUG)->to('slug')->unique()->asVarchar(255); $map->property(BlogArticle::EXTRACT)->to('extract')->asText(); $map->embedded(BlogArticle::FEATURED_IMAGE) ->withIssetColumn('featured_image') ->using(new ImageMapper('featured_image', 'featured_image_file_name', $this->blogConfiguration->getFeaturedImagePath())); $map->embedded(BlogArticle::DATE)->using(new DateMapper('date')); $map->embedded(BlogArticle::ARTICLE_CONTENT)->withIssetColumn('article_content')->using(HtmlMapper::withLongText('article_content')); $map->property(BlogArticle::ALLOW_SHARING)->to('allow_sharing')->asBool(); $map->property(BlogArticle::ALLOW_COMMENTING)->to('allow_commenting')->asBool(); $map->property(BlogArticle::PUBLISHED)->to('published')->asBool(); $map->embedded(BlogArticle::CREATED_AT)->using(new DateTimeMapper('created_at')); $map->embedded(BlogArticle::UPDATED_AT)->using(new DateTimeMapper('updated_at')); MetadataMapper::mapMetadataToJsonColumn($map, 'metadata'); }
php
protected function define(MapperDefinition $map) { $map->type(BlogArticle::class); $map->toTable('articles'); $map->idToPrimaryKey('id'); $map->column($map->getOrm()->getNamespace() . 'author_id')->asUnsignedInt(); $map->relation(BlogArticle::AUTHOR) ->to(BlogAuthor::class) ->manyToOne() ->withBidirectionalRelation(BlogAuthor::ARTICLES) ->withRelatedIdAs($map->getOrm()->getNamespace() . 'author_id'); $map->column($map->getOrm()->getNamespace() . 'category_id')->nullable()->asUnsignedInt(); $map->relation(BlogArticle::CATEGORY) ->to(BlogCategory::class) ->manyToOne() ->withBidirectionalRelation(BlogCategory::ARTICLES) ->withRelatedIdAs($map->getOrm()->getNamespace() . 'category_id'); $map->relation(BlogArticle::COMMENTS) ->to(BlogArticleComment::class) ->toMany() ->identifying() ->withBidirectionalRelation(BlogArticleComment::ARTICLE) ->orderByDesc('posted_at') ->withParentIdAs($map->getOrm()->getNamespace() . 'article_id'); $map->property(BlogArticle::TITLE)->to('title')->asVarchar(255); $map->property(BlogArticle::SUB_TITLE)->to('sub_title')->asVarchar(255); $map->property(BlogArticle::SLUG)->to('slug')->unique()->asVarchar(255); $map->property(BlogArticle::EXTRACT)->to('extract')->asText(); $map->embedded(BlogArticle::FEATURED_IMAGE) ->withIssetColumn('featured_image') ->using(new ImageMapper('featured_image', 'featured_image_file_name', $this->blogConfiguration->getFeaturedImagePath())); $map->embedded(BlogArticle::DATE)->using(new DateMapper('date')); $map->embedded(BlogArticle::ARTICLE_CONTENT)->withIssetColumn('article_content')->using(HtmlMapper::withLongText('article_content')); $map->property(BlogArticle::ALLOW_SHARING)->to('allow_sharing')->asBool(); $map->property(BlogArticle::ALLOW_COMMENTING)->to('allow_commenting')->asBool(); $map->property(BlogArticle::PUBLISHED)->to('published')->asBool(); $map->embedded(BlogArticle::CREATED_AT)->using(new DateTimeMapper('created_at')); $map->embedded(BlogArticle::UPDATED_AT)->using(new DateTimeMapper('updated_at')); MetadataMapper::mapMetadataToJsonColumn($map, 'metadata'); }
[ "protected", "function", "define", "(", "MapperDefinition", "$", "map", ")", "{", "$", "map", "->", "type", "(", "BlogArticle", "::", "class", ")", ";", "$", "map", "->", "toTable", "(", "'articles'", ")", ";", "$", "map", "->", "idToPrimaryKey", "(", "'id'", ")", ";", "$", "map", "->", "column", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'author_id'", ")", "->", "asUnsignedInt", "(", ")", ";", "$", "map", "->", "relation", "(", "BlogArticle", "::", "AUTHOR", ")", "->", "to", "(", "BlogAuthor", "::", "class", ")", "->", "manyToOne", "(", ")", "->", "withBidirectionalRelation", "(", "BlogAuthor", "::", "ARTICLES", ")", "->", "withRelatedIdAs", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'author_id'", ")", ";", "$", "map", "->", "column", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'category_id'", ")", "->", "nullable", "(", ")", "->", "asUnsignedInt", "(", ")", ";", "$", "map", "->", "relation", "(", "BlogArticle", "::", "CATEGORY", ")", "->", "to", "(", "BlogCategory", "::", "class", ")", "->", "manyToOne", "(", ")", "->", "withBidirectionalRelation", "(", "BlogCategory", "::", "ARTICLES", ")", "->", "withRelatedIdAs", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'category_id'", ")", ";", "$", "map", "->", "relation", "(", "BlogArticle", "::", "COMMENTS", ")", "->", "to", "(", "BlogArticleComment", "::", "class", ")", "->", "toMany", "(", ")", "->", "identifying", "(", ")", "->", "withBidirectionalRelation", "(", "BlogArticleComment", "::", "ARTICLE", ")", "->", "orderByDesc", "(", "'posted_at'", ")", "->", "withParentIdAs", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'article_id'", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "TITLE", ")", "->", "to", "(", "'title'", ")", "->", "asVarchar", "(", "255", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "SUB_TITLE", ")", "->", "to", "(", "'sub_title'", ")", "->", "asVarchar", "(", "255", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "SLUG", ")", "->", "to", "(", "'slug'", ")", "->", "unique", "(", ")", "->", "asVarchar", "(", "255", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "EXTRACT", ")", "->", "to", "(", "'extract'", ")", "->", "asText", "(", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticle", "::", "FEATURED_IMAGE", ")", "->", "withIssetColumn", "(", "'featured_image'", ")", "->", "using", "(", "new", "ImageMapper", "(", "'featured_image'", ",", "'featured_image_file_name'", ",", "$", "this", "->", "blogConfiguration", "->", "getFeaturedImagePath", "(", ")", ")", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticle", "::", "DATE", ")", "->", "using", "(", "new", "DateMapper", "(", "'date'", ")", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticle", "::", "ARTICLE_CONTENT", ")", "->", "withIssetColumn", "(", "'article_content'", ")", "->", "using", "(", "HtmlMapper", "::", "withLongText", "(", "'article_content'", ")", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "ALLOW_SHARING", ")", "->", "to", "(", "'allow_sharing'", ")", "->", "asBool", "(", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "ALLOW_COMMENTING", ")", "->", "to", "(", "'allow_commenting'", ")", "->", "asBool", "(", ")", ";", "$", "map", "->", "property", "(", "BlogArticle", "::", "PUBLISHED", ")", "->", "to", "(", "'published'", ")", "->", "asBool", "(", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticle", "::", "CREATED_AT", ")", "->", "using", "(", "new", "DateTimeMapper", "(", "'created_at'", ")", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticle", "::", "UPDATED_AT", ")", "->", "using", "(", "new", "DateTimeMapper", "(", "'updated_at'", ")", ")", ";", "MetadataMapper", "::", "mapMetadataToJsonColumn", "(", "$", "map", ",", "'metadata'", ")", ";", "}" ]
Defines the entity mapper @param MapperDefinition $map @return void
[ "Defines", "the", "entity", "mapper" ]
train
https://github.com/dms-org/package.blog/blob/1500f6fad20d81289a0dfa617fc1c54699f01e16/src/Infrastructure/Persistence/BlogArticleMapper.php#L42-L99
milkyway-multimedia/ss-mwm-formfields
src/Composite/HasOneCompositeField.php
HasOneCompositeField.saveInto
public function saveInto(DataObjectInterface $parent) { $record = $this->record; $parent->flushCache(false); // Flush session cache in case a relation id was changed during form->saveInto if (!$record) { $relName = substr($this->name, -2) == 'ID' ? substr($this->name, -2, 2) : $this->name; if ($parent->hasMethod($relName)) { $record = $parent->$relName(); } } $fields = $this->FieldList(false); $form = $this->formFromFieldList($fields, $this->value); if ($record) { $formDataFields = $form->Fields()->dataFields(); foreach ($formDataFields as $dataField) { if (($dataField instanceof $this) && $dataField !== $this) { $dataField->saveInto($record); } } if (!$this->allowEmpty && !$record->exists() && !count($this->recursiveArrayFilter($form->Data))) { return; } $form->saveInto($record); unset($form); $record->flushCache(false); // Save extra data into field if (count($this->extraData)) { $record->castedUpdate($this->extraData); } if (!$record->exists() && count($this->defaultFromParent)) { foreach ($this->defaultFromParent as $pField => $rField) { if (is_numeric($pField)) { if ($record->$rField) { continue; } $record->setCastedField($rField, $parent->$rField); } else { if ($record->$pField) { continue; } $record->setCastedField($rField, $parent->$pField); } } } if (count($this->overrideFromParent)) { foreach ($this->overrideFromParent as $pField => $rField) { if (is_numeric($pField)) { $record->setCastedField($rField, $parent->$rField); } else { $record->setCastedField($rField, $parent->$pField); } } } $record->write(); $fieldName = substr($this->name, -2) == 'ID' ? $this->name : $this->name . 'ID'; $parent->$fieldName = $record->ID; } elseif ($parent) { $data = $form->Data; unset($form); if (count($this->extraData)) { $data = array_merge($data, $this->extraData); } $field = $this->name; $parent->$field = $data; } }
php
public function saveInto(DataObjectInterface $parent) { $record = $this->record; $parent->flushCache(false); // Flush session cache in case a relation id was changed during form->saveInto if (!$record) { $relName = substr($this->name, -2) == 'ID' ? substr($this->name, -2, 2) : $this->name; if ($parent->hasMethod($relName)) { $record = $parent->$relName(); } } $fields = $this->FieldList(false); $form = $this->formFromFieldList($fields, $this->value); if ($record) { $formDataFields = $form->Fields()->dataFields(); foreach ($formDataFields as $dataField) { if (($dataField instanceof $this) && $dataField !== $this) { $dataField->saveInto($record); } } if (!$this->allowEmpty && !$record->exists() && !count($this->recursiveArrayFilter($form->Data))) { return; } $form->saveInto($record); unset($form); $record->flushCache(false); // Save extra data into field if (count($this->extraData)) { $record->castedUpdate($this->extraData); } if (!$record->exists() && count($this->defaultFromParent)) { foreach ($this->defaultFromParent as $pField => $rField) { if (is_numeric($pField)) { if ($record->$rField) { continue; } $record->setCastedField($rField, $parent->$rField); } else { if ($record->$pField) { continue; } $record->setCastedField($rField, $parent->$pField); } } } if (count($this->overrideFromParent)) { foreach ($this->overrideFromParent as $pField => $rField) { if (is_numeric($pField)) { $record->setCastedField($rField, $parent->$rField); } else { $record->setCastedField($rField, $parent->$pField); } } } $record->write(); $fieldName = substr($this->name, -2) == 'ID' ? $this->name : $this->name . 'ID'; $parent->$fieldName = $record->ID; } elseif ($parent) { $data = $form->Data; unset($form); if (count($this->extraData)) { $data = array_merge($data, $this->extraData); } $field = $this->name; $parent->$field = $data; } }
[ "public", "function", "saveInto", "(", "DataObjectInterface", "$", "parent", ")", "{", "$", "record", "=", "$", "this", "->", "record", ";", "$", "parent", "->", "flushCache", "(", "false", ")", ";", "// Flush session cache in case a relation id was changed during form->saveInto", "if", "(", "!", "$", "record", ")", "{", "$", "relName", "=", "substr", "(", "$", "this", "->", "name", ",", "-", "2", ")", "==", "'ID'", "?", "substr", "(", "$", "this", "->", "name", ",", "-", "2", ",", "2", ")", ":", "$", "this", "->", "name", ";", "if", "(", "$", "parent", "->", "hasMethod", "(", "$", "relName", ")", ")", "{", "$", "record", "=", "$", "parent", "->", "$", "relName", "(", ")", ";", "}", "}", "$", "fields", "=", "$", "this", "->", "FieldList", "(", "false", ")", ";", "$", "form", "=", "$", "this", "->", "formFromFieldList", "(", "$", "fields", ",", "$", "this", "->", "value", ")", ";", "if", "(", "$", "record", ")", "{", "$", "formDataFields", "=", "$", "form", "->", "Fields", "(", ")", "->", "dataFields", "(", ")", ";", "foreach", "(", "$", "formDataFields", "as", "$", "dataField", ")", "{", "if", "(", "(", "$", "dataField", "instanceof", "$", "this", ")", "&&", "$", "dataField", "!==", "$", "this", ")", "{", "$", "dataField", "->", "saveInto", "(", "$", "record", ")", ";", "}", "}", "if", "(", "!", "$", "this", "->", "allowEmpty", "&&", "!", "$", "record", "->", "exists", "(", ")", "&&", "!", "count", "(", "$", "this", "->", "recursiveArrayFilter", "(", "$", "form", "->", "Data", ")", ")", ")", "{", "return", ";", "}", "$", "form", "->", "saveInto", "(", "$", "record", ")", ";", "unset", "(", "$", "form", ")", ";", "$", "record", "->", "flushCache", "(", "false", ")", ";", "// Save extra data into field", "if", "(", "count", "(", "$", "this", "->", "extraData", ")", ")", "{", "$", "record", "->", "castedUpdate", "(", "$", "this", "->", "extraData", ")", ";", "}", "if", "(", "!", "$", "record", "->", "exists", "(", ")", "&&", "count", "(", "$", "this", "->", "defaultFromParent", ")", ")", "{", "foreach", "(", "$", "this", "->", "defaultFromParent", "as", "$", "pField", "=>", "$", "rField", ")", "{", "if", "(", "is_numeric", "(", "$", "pField", ")", ")", "{", "if", "(", "$", "record", "->", "$", "rField", ")", "{", "continue", ";", "}", "$", "record", "->", "setCastedField", "(", "$", "rField", ",", "$", "parent", "->", "$", "rField", ")", ";", "}", "else", "{", "if", "(", "$", "record", "->", "$", "pField", ")", "{", "continue", ";", "}", "$", "record", "->", "setCastedField", "(", "$", "rField", ",", "$", "parent", "->", "$", "pField", ")", ";", "}", "}", "}", "if", "(", "count", "(", "$", "this", "->", "overrideFromParent", ")", ")", "{", "foreach", "(", "$", "this", "->", "overrideFromParent", "as", "$", "pField", "=>", "$", "rField", ")", "{", "if", "(", "is_numeric", "(", "$", "pField", ")", ")", "{", "$", "record", "->", "setCastedField", "(", "$", "rField", ",", "$", "parent", "->", "$", "rField", ")", ";", "}", "else", "{", "$", "record", "->", "setCastedField", "(", "$", "rField", ",", "$", "parent", "->", "$", "pField", ")", ";", "}", "}", "}", "$", "record", "->", "write", "(", ")", ";", "$", "fieldName", "=", "substr", "(", "$", "this", "->", "name", ",", "-", "2", ")", "==", "'ID'", "?", "$", "this", "->", "name", ":", "$", "this", "->", "name", ".", "'ID'", ";", "$", "parent", "->", "$", "fieldName", "=", "$", "record", "->", "ID", ";", "}", "elseif", "(", "$", "parent", ")", "{", "$", "data", "=", "$", "form", "->", "Data", ";", "unset", "(", "$", "form", ")", ";", "if", "(", "count", "(", "$", "this", "->", "extraData", ")", ")", "{", "$", "data", "=", "array_merge", "(", "$", "data", ",", "$", "this", "->", "extraData", ")", ";", "}", "$", "field", "=", "$", "this", "->", "name", ";", "$", "parent", "->", "$", "field", "=", "$", "data", ";", "}", "}" ]
This method takes care of saving all the form data @param DataObjectInterface $parent
[ "This", "method", "takes", "care", "of", "saving", "all", "the", "form", "data" ]
train
https://github.com/milkyway-multimedia/ss-mwm-formfields/blob/b98d84d494c92d6881dcea50c9c8334e5f487e1d/src/Composite/HasOneCompositeField.php#L268-L349
seeruo/framework
src/Command/ServerCommand.php
ServerCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { try { $port = $this->config['port'] ?: 9001; $public = $this->config['public'] ?: 'Public'; $output->writeln([ '<bg=red;>=================================</>', '请在浏览器里预览网站效果', '地址:http://localhost:'.$port, '<bg=red;>=================================</>' ]); // open explorer if ( $this->config['auto_open'] ) { if (strstr(PHP_OS, 'WIN')) { $win_cmd = "cd ".ROOT." && ". 'explorer http://localhost:'.$port; system($win_cmd); }else{ $mac_cmd = "cd ".ROOT." && ". 'open http://localhost:'.$port; system($mac_cmd); } } // 为了减少复杂度,直接使用php自带的调试服务器 $cmd = "cd ".ROOT." && ". 'php -S ' . 'localhost:'.$port . ' -t ' . $public; system($cmd); } catch (Exception $e) { $output->writeln('<bg=red;>Start Server Error</>'); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { try { $port = $this->config['port'] ?: 9001; $public = $this->config['public'] ?: 'Public'; $output->writeln([ '<bg=red;>=================================</>', '请在浏览器里预览网站效果', '地址:http://localhost:'.$port, '<bg=red;>=================================</>' ]); // open explorer if ( $this->config['auto_open'] ) { if (strstr(PHP_OS, 'WIN')) { $win_cmd = "cd ".ROOT." && ". 'explorer http://localhost:'.$port; system($win_cmd); }else{ $mac_cmd = "cd ".ROOT." && ". 'open http://localhost:'.$port; system($mac_cmd); } } // 为了减少复杂度,直接使用php自带的调试服务器 $cmd = "cd ".ROOT." && ". 'php -S ' . 'localhost:'.$port . ' -t ' . $public; system($cmd); } catch (Exception $e) { $output->writeln('<bg=red;>Start Server Error</>'); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "try", "{", "$", "port", "=", "$", "this", "->", "config", "[", "'port'", "]", "?", ":", "9001", ";", "$", "public", "=", "$", "this", "->", "config", "[", "'public'", "]", "?", ":", "'Public'", ";", "$", "output", "->", "writeln", "(", "[", "'<bg=red;>=================================</>'", ",", "'请在浏览器里预览网站效果',", "", "'地址:http://localhost:'.$port", ",", "", "", "", "'<bg=red;>=================================</>'", "]", ")", ";", "// open explorer", "if", "(", "$", "this", "->", "config", "[", "'auto_open'", "]", ")", "{", "if", "(", "strstr", "(", "PHP_OS", ",", "'WIN'", ")", ")", "{", "$", "win_cmd", "=", "\"cd \"", ".", "ROOT", ".", "\" && \"", ".", "'explorer http://localhost:'", ".", "$", "port", ";", "system", "(", "$", "win_cmd", ")", ";", "}", "else", "{", "$", "mac_cmd", "=", "\"cd \"", ".", "ROOT", ".", "\" && \"", ".", "'open http://localhost:'", ".", "$", "port", ";", "system", "(", "$", "mac_cmd", ")", ";", "}", "}", "// 为了减少复杂度,直接使用php自带的调试服务器", "$", "cmd", "=", "\"cd \"", ".", "ROOT", ".", "\" && \"", ".", "'php -S '", ".", "'localhost:'", ".", "$", "port", ".", "' -t '", ".", "$", "public", ";", "system", "(", "$", "cmd", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "'<bg=red;>Start Server Error</>'", ")", ";", "}", "}" ]
[执行命令] @DateTime 2018-12-13 @param InputInterface $input 输入对象 @param OutputInterface $output 输出对象
[ "[", "执行命令", "]" ]
train
https://github.com/seeruo/framework/blob/689c6e95bc95fe2ae037e056d8228820dd08d7e9/src/Command/ServerCommand.php#L45-L73
joomla-framework/crypt
src/Cipher/Crypto.php
Crypto.decrypt
public function decrypt($data, Key $key) { // Validate key. if ($key->getType() !== 'crypto') { throw new InvalidKeyTypeException('crypto', $key->getType()); } // Decrypt the data. try { return DefuseCrypto::decrypt($data, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); } catch (WrongKeyOrModifiedCiphertextException $ex) { throw new \RuntimeException('DANGER! DANGER! The ciphertext has been tampered with!', $ex->getCode(), $ex); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex); } }
php
public function decrypt($data, Key $key) { // Validate key. if ($key->getType() !== 'crypto') { throw new InvalidKeyTypeException('crypto', $key->getType()); } // Decrypt the data. try { return DefuseCrypto::decrypt($data, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); } catch (WrongKeyOrModifiedCiphertextException $ex) { throw new \RuntimeException('DANGER! DANGER! The ciphertext has been tampered with!', $ex->getCode(), $ex); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex); } }
[ "public", "function", "decrypt", "(", "$", "data", ",", "Key", "$", "key", ")", "{", "// Validate key.", "if", "(", "$", "key", "->", "getType", "(", ")", "!==", "'crypto'", ")", "{", "throw", "new", "InvalidKeyTypeException", "(", "'crypto'", ",", "$", "key", "->", "getType", "(", ")", ")", ";", "}", "// Decrypt the data.", "try", "{", "return", "DefuseCrypto", "::", "decrypt", "(", "$", "data", ",", "DefuseKey", "::", "loadFromAsciiSafeString", "(", "$", "key", "->", "getPrivate", "(", ")", ")", ")", ";", "}", "catch", "(", "WrongKeyOrModifiedCiphertextException", "$", "ex", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'DANGER! DANGER! The ciphertext has been tampered with!'", ",", "$", "ex", "->", "getCode", "(", ")", ",", "$", "ex", ")", ";", "}", "catch", "(", "EnvironmentIsBrokenException", "$", "ex", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot safely perform decryption'", ",", "$", "ex", "->", "getCode", "(", ")", ",", "$", "ex", ")", ";", "}", "}" ]
Method to decrypt a data string. @param string $data The encrypted string to decrypt. @param Key $key The key object to use for decryption. @return string The decrypted data string. @since __DEPLOY_VERSION__ @throws \InvalidArgumentException @throws \RuntimeException
[ "Method", "to", "decrypt", "a", "data", "string", "." ]
train
https://github.com/joomla-framework/crypt/blob/5b24370bd5f07d2b305f66e62294c6d10a3f619d/src/Cipher/Crypto.php#L39-L60
joomla-framework/crypt
src/Cipher/Crypto.php
Crypto.encrypt
public function encrypt($data, Key $key) { // Validate key. if ($key->getType() !== 'crypto') { throw new InvalidKeyTypeException('crypto', $key->getType()); } // Encrypt the data. try { return DefuseCrypto::encrypt($data, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); } }
php
public function encrypt($data, Key $key) { // Validate key. if ($key->getType() !== 'crypto') { throw new InvalidKeyTypeException('crypto', $key->getType()); } // Encrypt the data. try { return DefuseCrypto::encrypt($data, DefuseKey::loadFromAsciiSafeString($key->getPrivate())); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); } }
[ "public", "function", "encrypt", "(", "$", "data", ",", "Key", "$", "key", ")", "{", "// Validate key.", "if", "(", "$", "key", "->", "getType", "(", ")", "!==", "'crypto'", ")", "{", "throw", "new", "InvalidKeyTypeException", "(", "'crypto'", ",", "$", "key", "->", "getType", "(", ")", ")", ";", "}", "// Encrypt the data.", "try", "{", "return", "DefuseCrypto", "::", "encrypt", "(", "$", "data", ",", "DefuseKey", "::", "loadFromAsciiSafeString", "(", "$", "key", "->", "getPrivate", "(", ")", ")", ")", ";", "}", "catch", "(", "EnvironmentIsBrokenException", "$", "ex", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot safely perform encryption'", ",", "$", "ex", "->", "getCode", "(", ")", ",", "$", "ex", ")", ";", "}", "}" ]
Method to encrypt a data string. @param string $data The data string to encrypt. @param Key $key The key object to use for encryption. @return string The encrypted data string. @since __DEPLOY_VERSION__ @throws \InvalidArgumentException @throws \RuntimeException
[ "Method", "to", "encrypt", "a", "data", "string", "." ]
train
https://github.com/joomla-framework/crypt/blob/5b24370bd5f07d2b305f66e62294c6d10a3f619d/src/Cipher/Crypto.php#L74-L91
joomla-framework/crypt
src/Cipher/Crypto.php
Crypto.generateKey
public function generateKey(array $options = []) { // Generate the encryption key. try { $public = DefuseKey::createNewRandomKey(); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely create a key', $ex->getCode(), $ex); } // Create the new encryption key object. return new Key('crypto', $public->saveToAsciiSafeString(), $public->getRawBytes()); }
php
public function generateKey(array $options = []) { // Generate the encryption key. try { $public = DefuseKey::createNewRandomKey(); } catch (EnvironmentIsBrokenException $ex) { throw new \RuntimeException('Cannot safely create a key', $ex->getCode(), $ex); } // Create the new encryption key object. return new Key('crypto', $public->saveToAsciiSafeString(), $public->getRawBytes()); }
[ "public", "function", "generateKey", "(", "array", "$", "options", "=", "[", "]", ")", "{", "// Generate the encryption key.", "try", "{", "$", "public", "=", "DefuseKey", "::", "createNewRandomKey", "(", ")", ";", "}", "catch", "(", "EnvironmentIsBrokenException", "$", "ex", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot safely create a key'", ",", "$", "ex", "->", "getCode", "(", ")", ",", "$", "ex", ")", ";", "}", "// Create the new encryption key object.", "return", "new", "Key", "(", "'crypto'", ",", "$", "public", "->", "saveToAsciiSafeString", "(", ")", ",", "$", "public", "->", "getRawBytes", "(", ")", ")", ";", "}" ]
Method to generate a new encryption key object. @param array $options Key generation options. @return Key @since __DEPLOY_VERSION__ @throws \RuntimeException
[ "Method", "to", "generate", "a", "new", "encryption", "key", "object", "." ]
train
https://github.com/joomla-framework/crypt/blob/5b24370bd5f07d2b305f66e62294c6d10a3f619d/src/Cipher/Crypto.php#L103-L117
ClanCats/Core
src/bundles/Session/Manager/File.php
Manager_File.read
public function read( $id ) { if ( $this->has( $id ) ) { return unserialize( \CCFile::read( $this->file_path( $id ) ) ); } return array(); }
php
public function read( $id ) { if ( $this->has( $id ) ) { return unserialize( \CCFile::read( $this->file_path( $id ) ) ); } return array(); }
[ "public", "function", "read", "(", "$", "id", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "id", ")", ")", "{", "return", "unserialize", "(", "\\", "CCFile", "::", "read", "(", "$", "this", "->", "file_path", "(", "$", "id", ")", ")", ")", ";", "}", "return", "array", "(", ")", ";", "}" ]
Read data from the session dirver @param string $id The session id key. @return array
[ "Read", "data", "from", "the", "session", "dirver" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/bundles/Session/Manager/File.php#L20-L28
ClanCats/Core
src/bundles/Session/Manager/File.php
Manager_File.write
public function write( $id, $data ) { if ( !\CCFile::write( $this->file_path( $id ), serialize( $data ) ) ) { \CCError::exception( new Exception( 'Could not write session file.' ) ); } return true; }
php
public function write( $id, $data ) { if ( !\CCFile::write( $this->file_path( $id ), serialize( $data ) ) ) { \CCError::exception( new Exception( 'Could not write session file.' ) ); } return true; }
[ "public", "function", "write", "(", "$", "id", ",", "$", "data", ")", "{", "if", "(", "!", "\\", "CCFile", "::", "write", "(", "$", "this", "->", "file_path", "(", "$", "id", ")", ",", "serialize", "(", "$", "data", ")", ")", ")", "{", "\\", "CCError", "::", "exception", "(", "new", "Exception", "(", "'Could not write session file.'", ")", ")", ";", "}", "return", "true", ";", "}" ]
Check if a session with the given key already exists @param string $id The session id key. @param array $data @return bool
[ "Check", "if", "a", "session", "with", "the", "given", "key", "already", "exists" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/bundles/Session/Manager/File.php#L48-L55
ClanCats/Core
src/bundles/Session/Manager/File.php
Manager_File.gc
public function gc( $time ) { foreach( \CCFile::ls( \CCStorage::path( 'sessions/*' ) ) as $file ) { if ( ( filemtime( $file ) - ( time() - $time ) ) < 0 ) { if ( !\CCFile::delete( $file ) ) { throw new Exception( "Manager_File::gc - cannot delete session file." ); } } } }
php
public function gc( $time ) { foreach( \CCFile::ls( \CCStorage::path( 'sessions/*' ) ) as $file ) { if ( ( filemtime( $file ) - ( time() - $time ) ) < 0 ) { if ( !\CCFile::delete( $file ) ) { throw new Exception( "Manager_File::gc - cannot delete session file." ); } } } }
[ "public", "function", "gc", "(", "$", "time", ")", "{", "foreach", "(", "\\", "CCFile", "::", "ls", "(", "\\", "CCStorage", "::", "path", "(", "'sessions/*'", ")", ")", "as", "$", "file", ")", "{", "if", "(", "(", "filemtime", "(", "$", "file", ")", "-", "(", "time", "(", ")", "-", "$", "time", ")", ")", "<", "0", ")", "{", "if", "(", "!", "\\", "CCFile", "::", "delete", "(", "$", "file", ")", ")", "{", "throw", "new", "Exception", "(", "\"Manager_File::gc - cannot delete session file.\"", ")", ";", "}", "}", "}", "}" ]
Delete session that are older than the given time in secounds @param int $time @return void
[ "Delete", "session", "that", "are", "older", "than", "the", "given", "time", "in", "secounds" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/bundles/Session/Manager/File.php#L63-L75
phpmob/changmin
src/PhpMob/Sylius/Grid/FieldType/SprintfFieldType.php
SprintfFieldType.render
public function render(Field $field, $data, array $options) { $value = $this->dataExtractor->get($field, $data); $field->setOptions($options); return sprintf($options['format'], is_string($value) ? htmlspecialchars($value) : $value); }
php
public function render(Field $field, $data, array $options) { $value = $this->dataExtractor->get($field, $data); $field->setOptions($options); return sprintf($options['format'], is_string($value) ? htmlspecialchars($value) : $value); }
[ "public", "function", "render", "(", "Field", "$", "field", ",", "$", "data", ",", "array", "$", "options", ")", "{", "$", "value", "=", "$", "this", "->", "dataExtractor", "->", "get", "(", "$", "field", ",", "$", "data", ")", ";", "$", "field", "->", "setOptions", "(", "$", "options", ")", ";", "return", "sprintf", "(", "$", "options", "[", "'format'", "]", ",", "is_string", "(", "$", "value", ")", "?", "htmlspecialchars", "(", "$", "value", ")", ":", "$", "value", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/Sylius/Grid/FieldType/SprintfFieldType.php#L42-L48
xinix-technology/norm
src/Norm/Connection/MongoConnection.php
MongoConnection.marshall
public function marshall($object) { if ($object instanceof NDateTime || $object instanceof DT || $object instanceof NDate) { return new MongoDate($object->getTimestamp()); } elseif ($object instanceof NormArray) { return $object->toArray(); } elseif ($object instanceof \Norm\Type\Collection) { return $object->toObject(); } else { return parent::marshall($object); } }
php
public function marshall($object) { if ($object instanceof NDateTime || $object instanceof DT || $object instanceof NDate) { return new MongoDate($object->getTimestamp()); } elseif ($object instanceof NormArray) { return $object->toArray(); } elseif ($object instanceof \Norm\Type\Collection) { return $object->toObject(); } else { return parent::marshall($object); } }
[ "public", "function", "marshall", "(", "$", "object", ")", "{", "if", "(", "$", "object", "instanceof", "NDateTime", "||", "$", "object", "instanceof", "DT", "||", "$", "object", "instanceof", "NDate", ")", "{", "return", "new", "MongoDate", "(", "$", "object", "->", "getTimestamp", "(", ")", ")", ";", "}", "elseif", "(", "$", "object", "instanceof", "NormArray", ")", "{", "return", "$", "object", "->", "toArray", "(", ")", ";", "}", "elseif", "(", "$", "object", "instanceof", "\\", "Norm", "\\", "Type", "\\", "Collection", ")", "{", "return", "$", "object", "->", "toObject", "(", ")", ";", "}", "else", "{", "return", "parent", "::", "marshall", "(", "$", "object", ")", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/xinix-technology/norm/blob/c357f7d3a75d05324dd84b8f6a968a094c53d603/src/Norm/Connection/MongoConnection.php#L189-L202
titon/db
src/Titon/Db/Driver/ResultSet/PdoResultSet.php
PdoResultSet.count
public function count() { $this->execute(); $count = (int) $this->_statement->fetchColumn(); $this->close(); return $count; }
php
public function count() { $this->execute(); $count = (int) $this->_statement->fetchColumn(); $this->close(); return $count; }
[ "public", "function", "count", "(", ")", "{", "$", "this", "->", "execute", "(", ")", ";", "$", "count", "=", "(", "int", ")", "$", "this", "->", "_statement", "->", "fetchColumn", "(", ")", ";", "$", "this", "->", "close", "(", ")", ";", "return", "$", "count", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/titon/db/blob/fbc5159d1ce9d2139759c9367565986981485604/src/Titon/Db/Driver/ResultSet/PdoResultSet.php#L56-L64
titon/db
src/Titon/Db/Driver/ResultSet/PdoResultSet.php
PdoResultSet.execute
public function execute() { if ($this->hasExecuted()) { return $this; } $startTime = microtime(); if ($this->_statement->execute()) { if (preg_match('/^(update|insert|delete)/i', $this->_statement->queryString)) { $this->_count = $this->_statement->rowCount(); } else { $this->_count = 1; } $this->_time = number_format(microtime() - $startTime, 5); $this->_success = true; } $this->_executed = true; return $this; }
php
public function execute() { if ($this->hasExecuted()) { return $this; } $startTime = microtime(); if ($this->_statement->execute()) { if (preg_match('/^(update|insert|delete)/i', $this->_statement->queryString)) { $this->_count = $this->_statement->rowCount(); } else { $this->_count = 1; } $this->_time = number_format(microtime() - $startTime, 5); $this->_success = true; } $this->_executed = true; return $this; }
[ "public", "function", "execute", "(", ")", "{", "if", "(", "$", "this", "->", "hasExecuted", "(", ")", ")", "{", "return", "$", "this", ";", "}", "$", "startTime", "=", "microtime", "(", ")", ";", "if", "(", "$", "this", "->", "_statement", "->", "execute", "(", ")", ")", "{", "if", "(", "preg_match", "(", "'/^(update|insert|delete)/i'", ",", "$", "this", "->", "_statement", "->", "queryString", ")", ")", "{", "$", "this", "->", "_count", "=", "$", "this", "->", "_statement", "->", "rowCount", "(", ")", ";", "}", "else", "{", "$", "this", "->", "_count", "=", "1", ";", "}", "$", "this", "->", "_time", "=", "number_format", "(", "microtime", "(", ")", "-", "$", "startTime", ",", "5", ")", ";", "$", "this", "->", "_success", "=", "true", ";", "}", "$", "this", "->", "_executed", "=", "true", ";", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/titon/db/blob/fbc5159d1ce9d2139759c9367565986981485604/src/Titon/Db/Driver/ResultSet/PdoResultSet.php#L69-L90
titon/db
src/Titon/Db/Driver/ResultSet/PdoResultSet.php
PdoResultSet.find
public function find() { $this->execute(); $statement = $this->_statement; $columnMeta = []; $columnCount = $statement->columnCount(); if ($columnCount) { foreach (range(0, $columnCount - 1) as $index) { try { $columnMeta[] = $statement->getColumnMeta($index); } catch (PDOException $e) { $columnMeta = []; break; } } } // Fetch associated records if no meta data // This solves issues in SQLite where meta fails on complex records if (empty($columnMeta)) { $results = $statement->fetchAll(PDO::FETCH_ASSOC); // Else use the meta data for building } else { $aliasMap = $this->_mapAliases(); $results = []; while ($row = $statement->fetch(PDO::FETCH_NUM)) { $joins = []; $result = []; foreach ($row as $index => $value) { $column = $columnMeta[$index]; $name = $column['name']; $alias = ''; // @codeCoverageIgnoreStart // For drivers that alias fields as Alias__column if (strpos($name, '__') !== false) { list($alias, $name) = explode('__', $name, 2); // PostgreSQL lowercases the aliases, so we need to map them in the next step $column['table'] = $alias; } if (isset($column['table'])) { // For drivers that only return the table if (isset($aliasMap[$column['table']])) { $alias = $aliasMap[$column['table']]; // For drivers that return the actual alias } else { $alias = $column['table']; } } // @codeCoverageIgnoreEnd $joins[$alias][$name] = $value; } foreach ($joins as $join => $data) { if (empty($result)) { $result = $data; // Aliased/count sometimes fields don't have a table } else if (empty($join)) { $result = array_merge($result, $data); } else { $result[$join] = $data; } } $results[] = $result; } } $this->close(); return $results; }
php
public function find() { $this->execute(); $statement = $this->_statement; $columnMeta = []; $columnCount = $statement->columnCount(); if ($columnCount) { foreach (range(0, $columnCount - 1) as $index) { try { $columnMeta[] = $statement->getColumnMeta($index); } catch (PDOException $e) { $columnMeta = []; break; } } } // Fetch associated records if no meta data // This solves issues in SQLite where meta fails on complex records if (empty($columnMeta)) { $results = $statement->fetchAll(PDO::FETCH_ASSOC); // Else use the meta data for building } else { $aliasMap = $this->_mapAliases(); $results = []; while ($row = $statement->fetch(PDO::FETCH_NUM)) { $joins = []; $result = []; foreach ($row as $index => $value) { $column = $columnMeta[$index]; $name = $column['name']; $alias = ''; // @codeCoverageIgnoreStart // For drivers that alias fields as Alias__column if (strpos($name, '__') !== false) { list($alias, $name) = explode('__', $name, 2); // PostgreSQL lowercases the aliases, so we need to map them in the next step $column['table'] = $alias; } if (isset($column['table'])) { // For drivers that only return the table if (isset($aliasMap[$column['table']])) { $alias = $aliasMap[$column['table']]; // For drivers that return the actual alias } else { $alias = $column['table']; } } // @codeCoverageIgnoreEnd $joins[$alias][$name] = $value; } foreach ($joins as $join => $data) { if (empty($result)) { $result = $data; // Aliased/count sometimes fields don't have a table } else if (empty($join)) { $result = array_merge($result, $data); } else { $result[$join] = $data; } } $results[] = $result; } } $this->close(); return $results; }
[ "public", "function", "find", "(", ")", "{", "$", "this", "->", "execute", "(", ")", ";", "$", "statement", "=", "$", "this", "->", "_statement", ";", "$", "columnMeta", "=", "[", "]", ";", "$", "columnCount", "=", "$", "statement", "->", "columnCount", "(", ")", ";", "if", "(", "$", "columnCount", ")", "{", "foreach", "(", "range", "(", "0", ",", "$", "columnCount", "-", "1", ")", "as", "$", "index", ")", "{", "try", "{", "$", "columnMeta", "[", "]", "=", "$", "statement", "->", "getColumnMeta", "(", "$", "index", ")", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "$", "columnMeta", "=", "[", "]", ";", "break", ";", "}", "}", "}", "// Fetch associated records if no meta data", "// This solves issues in SQLite where meta fails on complex records", "if", "(", "empty", "(", "$", "columnMeta", ")", ")", "{", "$", "results", "=", "$", "statement", "->", "fetchAll", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "// Else use the meta data for building", "}", "else", "{", "$", "aliasMap", "=", "$", "this", "->", "_mapAliases", "(", ")", ";", "$", "results", "=", "[", "]", ";", "while", "(", "$", "row", "=", "$", "statement", "->", "fetch", "(", "PDO", "::", "FETCH_NUM", ")", ")", "{", "$", "joins", "=", "[", "]", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "row", "as", "$", "index", "=>", "$", "value", ")", "{", "$", "column", "=", "$", "columnMeta", "[", "$", "index", "]", ";", "$", "name", "=", "$", "column", "[", "'name'", "]", ";", "$", "alias", "=", "''", ";", "// @codeCoverageIgnoreStart", "// For drivers that alias fields as Alias__column", "if", "(", "strpos", "(", "$", "name", ",", "'__'", ")", "!==", "false", ")", "{", "list", "(", "$", "alias", ",", "$", "name", ")", "=", "explode", "(", "'__'", ",", "$", "name", ",", "2", ")", ";", "// PostgreSQL lowercases the aliases, so we need to map them in the next step", "$", "column", "[", "'table'", "]", "=", "$", "alias", ";", "}", "if", "(", "isset", "(", "$", "column", "[", "'table'", "]", ")", ")", "{", "// For drivers that only return the table", "if", "(", "isset", "(", "$", "aliasMap", "[", "$", "column", "[", "'table'", "]", "]", ")", ")", "{", "$", "alias", "=", "$", "aliasMap", "[", "$", "column", "[", "'table'", "]", "]", ";", "// For drivers that return the actual alias", "}", "else", "{", "$", "alias", "=", "$", "column", "[", "'table'", "]", ";", "}", "}", "// @codeCoverageIgnoreEnd", "$", "joins", "[", "$", "alias", "]", "[", "$", "name", "]", "=", "$", "value", ";", "}", "foreach", "(", "$", "joins", "as", "$", "join", "=>", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "result", "=", "$", "data", ";", "// Aliased/count sometimes fields don't have a table", "}", "else", "if", "(", "empty", "(", "$", "join", ")", ")", "{", "$", "result", "=", "array_merge", "(", "$", "result", ",", "$", "data", ")", ";", "}", "else", "{", "$", "result", "[", "$", "join", "]", "=", "$", "data", ";", "}", "}", "$", "results", "[", "]", "=", "$", "result", ";", "}", "}", "$", "this", "->", "close", "(", ")", ";", "return", "$", "results", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/titon/db/blob/fbc5159d1ce9d2139759c9367565986981485604/src/Titon/Db/Driver/ResultSet/PdoResultSet.php#L95-L176
titon/db
src/Titon/Db/Driver/ResultSet/PdoResultSet.php
PdoResultSet.getStatement
public function getStatement() { return $this->cache(__METHOD__, function() { $statement = preg_replace("/ {2,}/", " ", $this->_statement->queryString); // Trim spaces foreach ($this->getParams() as $param) { switch ($param[1]) { case PDO::PARAM_NULL: $value = 'NULL'; break; case PDO::PARAM_INT: case PDO::PARAM_BOOL: $value = (int) $param[0]; break; default: $value = "'" . (string) $param[0] . "'"; break; } $statement = preg_replace('/\?/', $value, $statement, 1); } return $statement; }); }
php
public function getStatement() { return $this->cache(__METHOD__, function() { $statement = preg_replace("/ {2,}/", " ", $this->_statement->queryString); // Trim spaces foreach ($this->getParams() as $param) { switch ($param[1]) { case PDO::PARAM_NULL: $value = 'NULL'; break; case PDO::PARAM_INT: case PDO::PARAM_BOOL: $value = (int) $param[0]; break; default: $value = "'" . (string) $param[0] . "'"; break; } $statement = preg_replace('/\?/', $value, $statement, 1); } return $statement; }); }
[ "public", "function", "getStatement", "(", ")", "{", "return", "$", "this", "->", "cache", "(", "__METHOD__", ",", "function", "(", ")", "{", "$", "statement", "=", "preg_replace", "(", "\"/ {2,}/\"", ",", "\" \"", ",", "$", "this", "->", "_statement", "->", "queryString", ")", ";", "// Trim spaces", "foreach", "(", "$", "this", "->", "getParams", "(", ")", "as", "$", "param", ")", "{", "switch", "(", "$", "param", "[", "1", "]", ")", "{", "case", "PDO", "::", "PARAM_NULL", ":", "$", "value", "=", "'NULL'", ";", "break", ";", "case", "PDO", "::", "PARAM_INT", ":", "case", "PDO", "::", "PARAM_BOOL", ":", "$", "value", "=", "(", "int", ")", "$", "param", "[", "0", "]", ";", "break", ";", "default", ":", "$", "value", "=", "\"'\"", ".", "(", "string", ")", "$", "param", "[", "0", "]", ".", "\"'\"", ";", "break", ";", "}", "$", "statement", "=", "preg_replace", "(", "'/\\?/'", ",", "$", "value", ",", "$", "statement", ",", "1", ")", ";", "}", "return", "$", "statement", ";", "}", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/titon/db/blob/fbc5159d1ce9d2139759c9367565986981485604/src/Titon/Db/Driver/ResultSet/PdoResultSet.php#L181-L198
titon/db
src/Titon/Db/Driver/ResultSet/PdoResultSet.php
PdoResultSet._mapAliases
protected function _mapAliases() { return $this->cache(__METHOD__, function() { $query = $this->getQuery(); if (!$query) { return []; } $alias = $query->getAlias(); $map = [ $query->getTable() => $alias, strtolower($alias) => $alias ]; foreach ($query->getJoins() as $join) { $joinAlias = $join->getAlias(); $map[$join->getTable()] = $joinAlias; $map[strtolower($joinAlias)] = $joinAlias; } return $map; }); }
php
protected function _mapAliases() { return $this->cache(__METHOD__, function() { $query = $this->getQuery(); if (!$query) { return []; } $alias = $query->getAlias(); $map = [ $query->getTable() => $alias, strtolower($alias) => $alias ]; foreach ($query->getJoins() as $join) { $joinAlias = $join->getAlias(); $map[$join->getTable()] = $joinAlias; $map[strtolower($joinAlias)] = $joinAlias; } return $map; }); }
[ "protected", "function", "_mapAliases", "(", ")", "{", "return", "$", "this", "->", "cache", "(", "__METHOD__", ",", "function", "(", ")", "{", "$", "query", "=", "$", "this", "->", "getQuery", "(", ")", ";", "if", "(", "!", "$", "query", ")", "{", "return", "[", "]", ";", "}", "$", "alias", "=", "$", "query", "->", "getAlias", "(", ")", ";", "$", "map", "=", "[", "$", "query", "->", "getTable", "(", ")", "=>", "$", "alias", ",", "strtolower", "(", "$", "alias", ")", "=>", "$", "alias", "]", ";", "foreach", "(", "$", "query", "->", "getJoins", "(", ")", "as", "$", "join", ")", "{", "$", "joinAlias", "=", "$", "join", "->", "getAlias", "(", ")", ";", "$", "map", "[", "$", "join", "->", "getTable", "(", ")", "]", "=", "$", "joinAlias", ";", "$", "map", "[", "strtolower", "(", "$", "joinAlias", ")", "]", "=", "$", "joinAlias", ";", "}", "return", "$", "map", ";", "}", ")", ";", "}" ]
Return a mapping of table to alias for the primary table and joins. @return array
[ "Return", "a", "mapping", "of", "table", "to", "alias", "for", "the", "primary", "table", "and", "joins", "." ]
train
https://github.com/titon/db/blob/fbc5159d1ce9d2139759c9367565986981485604/src/Titon/Db/Driver/ResultSet/PdoResultSet.php#L218-L241
flipboxstudio/orm-manager
src/Flipbox/OrmManager/OrmManagerServiceProvider.php
OrmManagerServiceProvider.register
public function register() { $this->mergeConfigFrom(__DIR__.'/Config/orm.php', 'orm'); $this->app->singleton('orm.database', function ($app) { return new DatabaseConnection($app['db']); }); $this->app->singleton('orm.manager', function ($app) { return new ModelManager($app['config'], $app['orm.database']); }); $this->commands([ Consoles\ModelList::class, Consoles\ModelDetail::class, Consoles\ModelConnect::class, Consoles\ModelBothConnect::class, Consoles\ModelAutoConnect::class, ]); }
php
public function register() { $this->mergeConfigFrom(__DIR__.'/Config/orm.php', 'orm'); $this->app->singleton('orm.database', function ($app) { return new DatabaseConnection($app['db']); }); $this->app->singleton('orm.manager', function ($app) { return new ModelManager($app['config'], $app['orm.database']); }); $this->commands([ Consoles\ModelList::class, Consoles\ModelDetail::class, Consoles\ModelConnect::class, Consoles\ModelBothConnect::class, Consoles\ModelAutoConnect::class, ]); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/Config/orm.php'", ",", "'orm'", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "'orm.database'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "DatabaseConnection", "(", "$", "app", "[", "'db'", "]", ")", ";", "}", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "'orm.manager'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "ModelManager", "(", "$", "app", "[", "'config'", "]", ",", "$", "app", "[", "'orm.database'", "]", ")", ";", "}", ")", ";", "$", "this", "->", "commands", "(", "[", "Consoles", "\\", "ModelList", "::", "class", ",", "Consoles", "\\", "ModelDetail", "::", "class", ",", "Consoles", "\\", "ModelConnect", "::", "class", ",", "Consoles", "\\", "ModelBothConnect", "::", "class", ",", "Consoles", "\\", "ModelAutoConnect", "::", "class", ",", "]", ")", ";", "}" ]
Register any application services.
[ "Register", "any", "application", "services", "." ]
train
https://github.com/flipboxstudio/orm-manager/blob/4288426517f53d05177b8729c4ba94c5beca9a98/src/Flipbox/OrmManager/OrmManagerServiceProvider.php#L22-L41
shiftio/safestream-php-sdk
src/Video/VideoClient.php
VideoClient.create
public function create(Video $video, $waitForIngest = 0) { if(is_null($video)) { throw new VideoClientException("No video provided"); } if(is_null($video->sourceUrl) || !filter_var($video->sourceUrl, FILTER_VALIDATE_URL)) { throw new VideoClientException("Invalid source URL"); } $ingestedStatus = "INGESTED"; try { // Make the request to the SafeStream REST API $videoResponse = $this->post($this->apiResourcePath, $video); // Wait for the video to be ingested before returning // TODO: Have the ingest wait be on a separate thread if($waitForIngest > 0 && !$ingestedStatus == $videoResponse->status) { $startTime = round(microtime(true) * 1000); $ingested = false; while(!$ingested && (round(microtime(true) * 1000) - $startTime) < $waitForIngest) { $test = $this->find($video->key); if($ingestedStatus == $videoResponse->status) { return $test; } sleep(3); } throw new VideoClientException("Timeout reached waiting for video to be ingested"); } else { return $videoResponse; } } catch(SafeStreamHttpException $e) { throw new VideoClientException($e); } }
php
public function create(Video $video, $waitForIngest = 0) { if(is_null($video)) { throw new VideoClientException("No video provided"); } if(is_null($video->sourceUrl) || !filter_var($video->sourceUrl, FILTER_VALIDATE_URL)) { throw new VideoClientException("Invalid source URL"); } $ingestedStatus = "INGESTED"; try { // Make the request to the SafeStream REST API $videoResponse = $this->post($this->apiResourcePath, $video); // Wait for the video to be ingested before returning // TODO: Have the ingest wait be on a separate thread if($waitForIngest > 0 && !$ingestedStatus == $videoResponse->status) { $startTime = round(microtime(true) * 1000); $ingested = false; while(!$ingested && (round(microtime(true) * 1000) - $startTime) < $waitForIngest) { $test = $this->find($video->key); if($ingestedStatus == $videoResponse->status) { return $test; } sleep(3); } throw new VideoClientException("Timeout reached waiting for video to be ingested"); } else { return $videoResponse; } } catch(SafeStreamHttpException $e) { throw new VideoClientException($e); } }
[ "public", "function", "create", "(", "Video", "$", "video", ",", "$", "waitForIngest", "=", "0", ")", "{", "if", "(", "is_null", "(", "$", "video", ")", ")", "{", "throw", "new", "VideoClientException", "(", "\"No video provided\"", ")", ";", "}", "if", "(", "is_null", "(", "$", "video", "->", "sourceUrl", ")", "||", "!", "filter_var", "(", "$", "video", "->", "sourceUrl", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "throw", "new", "VideoClientException", "(", "\"Invalid source URL\"", ")", ";", "}", "$", "ingestedStatus", "=", "\"INGESTED\"", ";", "try", "{", "// Make the request to the SafeStream REST API", "$", "videoResponse", "=", "$", "this", "->", "post", "(", "$", "this", "->", "apiResourcePath", ",", "$", "video", ")", ";", "// Wait for the video to be ingested before returning", "// TODO: Have the ingest wait be on a separate thread", "if", "(", "$", "waitForIngest", ">", "0", "&&", "!", "$", "ingestedStatus", "==", "$", "videoResponse", "->", "status", ")", "{", "$", "startTime", "=", "round", "(", "microtime", "(", "true", ")", "*", "1000", ")", ";", "$", "ingested", "=", "false", ";", "while", "(", "!", "$", "ingested", "&&", "(", "round", "(", "microtime", "(", "true", ")", "*", "1000", ")", "-", "$", "startTime", ")", "<", "$", "waitForIngest", ")", "{", "$", "test", "=", "$", "this", "->", "find", "(", "$", "video", "->", "key", ")", ";", "if", "(", "$", "ingestedStatus", "==", "$", "videoResponse", "->", "status", ")", "{", "return", "$", "test", ";", "}", "sleep", "(", "3", ")", ";", "}", "throw", "new", "VideoClientException", "(", "\"Timeout reached waiting for video to be ingested\"", ")", ";", "}", "else", "{", "return", "$", "videoResponse", ";", "}", "}", "catch", "(", "SafeStreamHttpException", "$", "e", ")", "{", "throw", "new", "VideoClientException", "(", "$", "e", ")", ";", "}", "}" ]
Creates a new video allowing a specific timeout while waiting for the video to downloaded and encoded. If not timeout is set then the function will return immediately, before the ingest is complete. The video cannot be watermarked until it has been ingested at which point the video status will be INGESTED. This will block until either the video is ingested OR the timeout is reached. @param Video $video @param int $waitForIngest: Time in millis to wait for the video to be ingested @return mixed: The newly created video @throws VideoClientException
[ "Creates", "a", "new", "video", "allowing", "a", "specific", "timeout", "while", "waiting", "for", "the", "video", "to", "downloaded", "and", "encoded", ".", "If", "not", "timeout", "is", "set", "then", "the", "function", "will", "return", "immediately", "before", "the", "ingest", "is", "complete", ".", "The", "video", "cannot", "be", "watermarked", "until", "it", "has", "been", "ingested", "at", "which", "point", "the", "video", "status", "will", "be", "INGESTED", "." ]
train
https://github.com/shiftio/safestream-php-sdk/blob/1957cd5574725b24da1bbff9059aa30a9ca123c2/src/Video/VideoClient.php#L77-L114
shiftio/safestream-php-sdk
src/Video/VideoClient.php
VideoClient.find
public function find($videoKey) { if(is_null($videoKey) || empty($videoKey)) { throw new VideoClientException("A key is needed to fnd a video"); } try { // Request the video from the SafeStream REST API $videos = $this->get(sprintf("%s?key=%s", $this->apiResourcePath, $videoKey)); return $videos[0]; } catch (SafeStreamHttpException $e) { throw new VideoClientException($e); } }
php
public function find($videoKey) { if(is_null($videoKey) || empty($videoKey)) { throw new VideoClientException("A key is needed to fnd a video"); } try { // Request the video from the SafeStream REST API $videos = $this->get(sprintf("%s?key=%s", $this->apiResourcePath, $videoKey)); return $videos[0]; } catch (SafeStreamHttpException $e) { throw new VideoClientException($e); } }
[ "public", "function", "find", "(", "$", "videoKey", ")", "{", "if", "(", "is_null", "(", "$", "videoKey", ")", "||", "empty", "(", "$", "videoKey", ")", ")", "{", "throw", "new", "VideoClientException", "(", "\"A key is needed to fnd a video\"", ")", ";", "}", "try", "{", "// Request the video from the SafeStream REST API", "$", "videos", "=", "$", "this", "->", "get", "(", "sprintf", "(", "\"%s?key=%s\"", ",", "$", "this", "->", "apiResourcePath", ",", "$", "videoKey", ")", ")", ";", "return", "$", "videos", "[", "0", "]", ";", "}", "catch", "(", "SafeStreamHttpException", "$", "e", ")", "{", "throw", "new", "VideoClientException", "(", "$", "e", ")", ";", "}", "}" ]
Gets an existing video by it's key. @param $videoKey: If no key was passed in when creating the video then the key will be the source URL of the video @return mixed: An existing video {@link Video} @throws VideoClientException
[ "Gets", "an", "existing", "video", "by", "it", "s", "key", "." ]
train
https://github.com/shiftio/safestream-php-sdk/blob/1957cd5574725b24da1bbff9059aa30a9ca123c2/src/Video/VideoClient.php#L124-L137
zodream/thirdparty
src/ALi/BaseALi.php
BaseALi.getRsa
public function getRsa() { $rsa = new Rsa(); $rsa->setPrivateKey(empty($this->getPrivateKeyFile()) || !$this->getPrivateKeyFile()->exist() ? $this->privateKey : $this->getPrivateKeyFile()) ->setPublicKey(empty($this->getPublicKeyFile()) || !$this->getPublicKeyFile()->exist() ? $this->publicKey : $this->getPublicKeyFile()) ->setPadding(self::RSA2 == $this->getSignType() ? OPENSSL_ALGO_SHA256 : OPENSSL_PKCS1_PADDING); return $rsa; }
php
public function getRsa() { $rsa = new Rsa(); $rsa->setPrivateKey(empty($this->getPrivateKeyFile()) || !$this->getPrivateKeyFile()->exist() ? $this->privateKey : $this->getPrivateKeyFile()) ->setPublicKey(empty($this->getPublicKeyFile()) || !$this->getPublicKeyFile()->exist() ? $this->publicKey : $this->getPublicKeyFile()) ->setPadding(self::RSA2 == $this->getSignType() ? OPENSSL_ALGO_SHA256 : OPENSSL_PKCS1_PADDING); return $rsa; }
[ "public", "function", "getRsa", "(", ")", "{", "$", "rsa", "=", "new", "Rsa", "(", ")", ";", "$", "rsa", "->", "setPrivateKey", "(", "empty", "(", "$", "this", "->", "getPrivateKeyFile", "(", ")", ")", "||", "!", "$", "this", "->", "getPrivateKeyFile", "(", ")", "->", "exist", "(", ")", "?", "$", "this", "->", "privateKey", ":", "$", "this", "->", "getPrivateKeyFile", "(", ")", ")", "->", "setPublicKey", "(", "empty", "(", "$", "this", "->", "getPublicKeyFile", "(", ")", ")", "||", "!", "$", "this", "->", "getPublicKeyFile", "(", ")", "->", "exist", "(", ")", "?", "$", "this", "->", "publicKey", ":", "$", "this", "->", "getPublicKeyFile", "(", ")", ")", "->", "setPadding", "(", "self", "::", "RSA2", "==", "$", "this", "->", "getSignType", "(", ")", "?", "OPENSSL_ALGO_SHA256", ":", "OPENSSL_PKCS1_PADDING", ")", ";", "return", "$", "rsa", ";", "}" ]
获取rsa
[ "获取rsa" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/BaseALi.php#L139-L148
zodream/thirdparty
src/ALi/BaseALi.php
BaseALi.encodeContent
protected function encodeContent(array $args) { $data = []; foreach ($args as $key => $item) { $data[] = sprintf('"%s":"%s"', $key, $item); } $arg = '{'.implode(',', $data).'}'; if (!empty($this->encryptKey) && $this->encryptType == self::AES) { return (new Aes($this->encryptKey))->encrypt($arg); } return $arg; }
php
protected function encodeContent(array $args) { $data = []; foreach ($args as $key => $item) { $data[] = sprintf('"%s":"%s"', $key, $item); } $arg = '{'.implode(',', $data).'}'; if (!empty($this->encryptKey) && $this->encryptType == self::AES) { return (new Aes($this->encryptKey))->encrypt($arg); } return $arg; }
[ "protected", "function", "encodeContent", "(", "array", "$", "args", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "$", "args", "as", "$", "key", "=>", "$", "item", ")", "{", "$", "data", "[", "]", "=", "sprintf", "(", "'\"%s\":\"%s\"'", ",", "$", "key", ",", "$", "item", ")", ";", "}", "$", "arg", "=", "'{'", ".", "implode", "(", "','", ",", "$", "data", ")", ".", "'}'", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "encryptKey", ")", "&&", "$", "this", "->", "encryptType", "==", "self", "::", "AES", ")", "{", "return", "(", "new", "Aes", "(", "$", "this", "->", "encryptKey", ")", ")", "->", "encrypt", "(", "$", "arg", ")", ";", "}", "return", "$", "arg", ";", "}" ]
合并biz_content @param array $args @return string
[ "合并biz_content" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/BaseALi.php#L163-L174
zodream/thirdparty
src/ALi/BaseALi.php
BaseALi.sign
public function sign($content) { if (is_array($content)) { $this->ignoreKeys = ['sign']; $content = $this->getSignContent($content); } if ($this->getSignType() == self::MD5) { return md5($content.$this->key); } return $this->getRsa()->sign($content); }
php
public function sign($content) { if (is_array($content)) { $this->ignoreKeys = ['sign']; $content = $this->getSignContent($content); } if ($this->getSignType() == self::MD5) { return md5($content.$this->key); } return $this->getRsa()->sign($content); }
[ "public", "function", "sign", "(", "$", "content", ")", "{", "if", "(", "is_array", "(", "$", "content", ")", ")", "{", "$", "this", "->", "ignoreKeys", "=", "[", "'sign'", "]", ";", "$", "content", "=", "$", "this", "->", "getSignContent", "(", "$", "content", ")", ";", "}", "if", "(", "$", "this", "->", "getSignType", "(", ")", "==", "self", "::", "MD5", ")", "{", "return", "md5", "(", "$", "content", ".", "$", "this", "->", "key", ")", ";", "}", "return", "$", "this", "->", "getRsa", "(", ")", "->", "sign", "(", "$", "content", ")", ";", "}" ]
签名 签名必须包括sign_type @param array|string $content @return string @throws \Exception
[ "签名", "签名必须包括sign_type" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/BaseALi.php#L183-L192
zodream/thirdparty
src/ALi/BaseALi.php
BaseALi.verify
public function verify($params, $sign = null) { list($content, $sign) = $this->getSignAndSource($params, $sign); $result = $this->verifyContent($content, $sign); if (!$result && strpos($content, '\\/') > 0) { $content = str_replace('\\/', '/', $content); return $this->verifyContent($content, $sign); } return $result; }
php
public function verify($params, $sign = null) { list($content, $sign) = $this->getSignAndSource($params, $sign); $result = $this->verifyContent($content, $sign); if (!$result && strpos($content, '\\/') > 0) { $content = str_replace('\\/', '/', $content); return $this->verifyContent($content, $sign); } return $result; }
[ "public", "function", "verify", "(", "$", "params", ",", "$", "sign", "=", "null", ")", "{", "list", "(", "$", "content", ",", "$", "sign", ")", "=", "$", "this", "->", "getSignAndSource", "(", "$", "params", ",", "$", "sign", ")", ";", "$", "result", "=", "$", "this", "->", "verifyContent", "(", "$", "content", ",", "$", "sign", ")", ";", "if", "(", "!", "$", "result", "&&", "strpos", "(", "$", "content", ",", "'\\\\/'", ")", ">", "0", ")", "{", "$", "content", "=", "str_replace", "(", "'\\\\/'", ",", "'/'", ",", "$", "content", ")", ";", "return", "$", "this", "->", "verifyContent", "(", "$", "content", ",", "$", "sign", ")", ";", "}", "return", "$", "result", ";", "}" ]
验签 验签不包括 sign_type @param array $params @param string $sign @return bool @throws \Exception
[ "验签", "验签不包括", "sign_type" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/BaseALi.php#L216-L224
shrink0r/workflux
src/State/StateTrait.php
StateTrait.execute
public function execute(InputInterface $input): OutputInterface { $this->validator->validateInput($this, $input); $output = $this->generateOutput($input); $this->validator->validateOutput($this, $output); return $output; }
php
public function execute(InputInterface $input): OutputInterface { $this->validator->validateInput($this, $input); $output = $this->generateOutput($input); $this->validator->validateOutput($this, $output); return $output; }
[ "public", "function", "execute", "(", "InputInterface", "$", "input", ")", ":", "OutputInterface", "{", "$", "this", "->", "validator", "->", "validateInput", "(", "$", "this", ",", "$", "input", ")", ";", "$", "output", "=", "$", "this", "->", "generateOutput", "(", "$", "input", ")", ";", "$", "this", "->", "validator", "->", "validateOutput", "(", "$", "this", ",", "$", "output", ")", ";", "return", "$", "output", ";", "}" ]
@param InputInterface $input @return OutputInterface
[ "@param", "InputInterface", "$input" ]
train
https://github.com/shrink0r/workflux/blob/008f45c64f52b1f795ab7f6ddbfc1a55580254d9/src/State/StateTrait.php#L63-L69
shrink0r/workflux
src/State/StateTrait.php
StateTrait.generateOutput
private function generateOutput(InputInterface $input): OutputInterface { return new Output( $this->name, array_merge( $this->evaluateInputExports($input), $this->generateOutputParams($input) ) ); }
php
private function generateOutput(InputInterface $input): OutputInterface { return new Output( $this->name, array_merge( $this->evaluateInputExports($input), $this->generateOutputParams($input) ) ); }
[ "private", "function", "generateOutput", "(", "InputInterface", "$", "input", ")", ":", "OutputInterface", "{", "return", "new", "Output", "(", "$", "this", "->", "name", ",", "array_merge", "(", "$", "this", "->", "evaluateInputExports", "(", "$", "input", ")", ",", "$", "this", "->", "generateOutputParams", "(", "$", "input", ")", ")", ")", ";", "}" ]
@param InputInterface $input @return OutputInterface
[ "@param", "InputInterface", "$input" ]
train
https://github.com/shrink0r/workflux/blob/008f45c64f52b1f795ab7f6ddbfc1a55580254d9/src/State/StateTrait.php#L135-L144
shrink0r/workflux
src/State/StateTrait.php
StateTrait.evaluateInputExports
private function evaluateInputExports(InputInterface $input): array { $exports = []; foreach ($this->getSetting('_output', []) as $key => $value) { $exports[$key] = $this->expression_engine->evaluate($value, [ 'input' => $input ]); } return $exports; }
php
private function evaluateInputExports(InputInterface $input): array { $exports = []; foreach ($this->getSetting('_output', []) as $key => $value) { $exports[$key] = $this->expression_engine->evaluate($value, [ 'input' => $input ]); } return $exports; }
[ "private", "function", "evaluateInputExports", "(", "InputInterface", "$", "input", ")", ":", "array", "{", "$", "exports", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getSetting", "(", "'_output'", ",", "[", "]", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "exports", "[", "$", "key", "]", "=", "$", "this", "->", "expression_engine", "->", "evaluate", "(", "$", "value", ",", "[", "'input'", "=>", "$", "input", "]", ")", ";", "}", "return", "$", "exports", ";", "}" ]
@param InputInterface $input @return mixed[]
[ "@param", "InputInterface", "$input" ]
train
https://github.com/shrink0r/workflux/blob/008f45c64f52b1f795ab7f6ddbfc1a55580254d9/src/State/StateTrait.php#L151-L158
webforge-labs/psc-cms
lib/Psc/TPL/ContentStream/Converter.php
Converter.shiftFirstEntry
public function shiftFirstEntry(ContentStream $cs, $type, \Closure $withFilter = NULL) { if (($entry = $cs->findFirst($type, $withFilter)) != NULL) { $vars = $this->convertEntryTemplateVariables($entry, $cs); $cs->removeEntry($entry); return $vars; } return NULL; }
php
public function shiftFirstEntry(ContentStream $cs, $type, \Closure $withFilter = NULL) { if (($entry = $cs->findFirst($type, $withFilter)) != NULL) { $vars = $this->convertEntryTemplateVariables($entry, $cs); $cs->removeEntry($entry); return $vars; } return NULL; }
[ "public", "function", "shiftFirstEntry", "(", "ContentStream", "$", "cs", ",", "$", "type", ",", "\\", "Closure", "$", "withFilter", "=", "NULL", ")", "{", "if", "(", "(", "$", "entry", "=", "$", "cs", "->", "findFirst", "(", "$", "type", ",", "$", "withFilter", ")", ")", "!=", "NULL", ")", "{", "$", "vars", "=", "$", "this", "->", "convertEntryTemplateVariables", "(", "$", "entry", ",", "$", "cs", ")", ";", "$", "cs", "->", "removeEntry", "(", "$", "entry", ")", ";", "return", "$", "vars", ";", "}", "return", "NULL", ";", "}" ]
Finds the first occurence of the entry, removes it and returns the template Variables for it if nothing is found NULL is returned if entry is found it will be removed from content stream and its variables will be returned if $withFilter is given the function has to return true to find the entry @param Closure $withFilter function ($entry) should return TRUE if the filter matches @return Scalar|NULL
[ "Finds", "the", "first", "occurence", "of", "the", "entry", "removes", "it", "and", "returns", "the", "template", "Variables", "for", "it" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/TPL/ContentStream/Converter.php#L139-L148
webforge-labs/psc-cms
lib/Psc/TPL/ContentStream/Converter.php
Converter.convertSerialized
public function convertSerialized(ContentStream $cs) { $serialized = array(); foreach ($cs->getEntries() as $entry) { if ($entry instanceof ContextAware) { $entry->setContext($this->context); } $serialized[] = $this->serializeEntry($entry); } return $serialized; }
php
public function convertSerialized(ContentStream $cs) { $serialized = array(); foreach ($cs->getEntries() as $entry) { if ($entry instanceof ContextAware) { $entry->setContext($this->context); } $serialized[] = $this->serializeEntry($entry); } return $serialized; }
[ "public", "function", "convertSerialized", "(", "ContentStream", "$", "cs", ")", "{", "$", "serialized", "=", "array", "(", ")", ";", "foreach", "(", "$", "cs", "->", "getEntries", "(", ")", "as", "$", "entry", ")", "{", "if", "(", "$", "entry", "instanceof", "ContextAware", ")", "{", "$", "entry", "->", "setContext", "(", "$", "this", "->", "context", ")", ";", "}", "$", "serialized", "[", "]", "=", "$", "this", "->", "serializeEntry", "(", "$", "entry", ")", ";", "}", "return", "$", "serialized", ";", "}" ]
Konvertiert den ContentStream in eine Repräsenation die nur aus einem Array besteht der Javascript LayoutManager kann dies mit unserialize() lesen und daraus widgets erstellen @return array
[ "Konvertiert", "den", "ContentStream", "in", "eine", "Repräsenation", "die", "nur", "aus", "einem", "Array", "besteht" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/TPL/ContentStream/Converter.php#L156-L169
webforge-labs/psc-cms
lib/Psc/TPL/ContentStream/Converter.php
Converter.convertUnserialized
public function convertUnserialized(Array $serialized, ContentStream $contentStream = NULL) { if (isset($contentStream)) { foreach ($serialized as $serializedEntry) { $entry = $this->unserializeEntry((object) $serializedEntry); $entry->setContentStream($contentStream); } return $contentStream; } else { $unserialized = array(); foreach ($serialized as $serializedEntry) { $unserialized[] = $this->unserializeEntry($serializedEntry); } } return $unserialized; }
php
public function convertUnserialized(Array $serialized, ContentStream $contentStream = NULL) { if (isset($contentStream)) { foreach ($serialized as $serializedEntry) { $entry = $this->unserializeEntry((object) $serializedEntry); $entry->setContentStream($contentStream); } return $contentStream; } else { $unserialized = array(); foreach ($serialized as $serializedEntry) { $unserialized[] = $this->unserializeEntry($serializedEntry); } } return $unserialized; }
[ "public", "function", "convertUnserialized", "(", "Array", "$", "serialized", ",", "ContentStream", "$", "contentStream", "=", "NULL", ")", "{", "if", "(", "isset", "(", "$", "contentStream", ")", ")", "{", "foreach", "(", "$", "serialized", "as", "$", "serializedEntry", ")", "{", "$", "entry", "=", "$", "this", "->", "unserializeEntry", "(", "(", "object", ")", "$", "serializedEntry", ")", ";", "$", "entry", "->", "setContentStream", "(", "$", "contentStream", ")", ";", "}", "return", "$", "contentStream", ";", "}", "else", "{", "$", "unserialized", "=", "array", "(", ")", ";", "foreach", "(", "$", "serialized", "as", "$", "serializedEntry", ")", "{", "$", "unserialized", "[", "]", "=", "$", "this", "->", "unserializeEntry", "(", "$", "serializedEntry", ")", ";", "}", "}", "return", "$", "unserialized", ";", "}" ]
Convertes an serialized ContentStream to the real object structure
[ "Convertes", "an", "serialized", "ContentStream", "to", "the", "real", "object", "structure" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/TPL/ContentStream/Converter.php#L183-L198
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.getContentManager
public function getContentManager() { if ($this->contentManager != null) { return $this->contentManager; } $this->contentManager = new ContentManager($this->options, $this->getContentService(), $this->getContentTypeService(), $this->getLocationService(), $this->getLocationManager()); if ($this->logger) { $this->contentManager->setLogger($this->logger); } return $this->contentManager; }
php
public function getContentManager() { if ($this->contentManager != null) { return $this->contentManager; } $this->contentManager = new ContentManager($this->options, $this->getContentService(), $this->getContentTypeService(), $this->getLocationService(), $this->getLocationManager()); if ($this->logger) { $this->contentManager->setLogger($this->logger); } return $this->contentManager; }
[ "public", "function", "getContentManager", "(", ")", "{", "if", "(", "$", "this", "->", "contentManager", "!=", "null", ")", "{", "return", "$", "this", "->", "contentManager", ";", "}", "$", "this", "->", "contentManager", "=", "new", "ContentManager", "(", "$", "this", "->", "options", ",", "$", "this", "->", "getContentService", "(", ")", ",", "$", "this", "->", "getContentTypeService", "(", ")", ",", "$", "this", "->", "getLocationService", "(", ")", ",", "$", "this", "->", "getLocationManager", "(", ")", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "contentManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}", "return", "$", "this", "->", "contentManager", ";", "}" ]
Returns content manager. @return ContentManager
[ "Returns", "content", "manager", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L79-L92
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.getLocationManager
public function getLocationManager() { if ($this->locationManager != null) { return $this->locationManager; } $this->locationManager = new LocationManager($this->getLocationService(), $this->getContentService()); if ($this->logger) { $this->locationManager->setLogger($this->logger); } return $this->locationManager; }
php
public function getLocationManager() { if ($this->locationManager != null) { return $this->locationManager; } $this->locationManager = new LocationManager($this->getLocationService(), $this->getContentService()); if ($this->logger) { $this->locationManager->setLogger($this->logger); } return $this->locationManager; }
[ "public", "function", "getLocationManager", "(", ")", "{", "if", "(", "$", "this", "->", "locationManager", "!=", "null", ")", "{", "return", "$", "this", "->", "locationManager", ";", "}", "$", "this", "->", "locationManager", "=", "new", "LocationManager", "(", "$", "this", "->", "getLocationService", "(", ")", ",", "$", "this", "->", "getContentService", "(", ")", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "locationManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}", "return", "$", "this", "->", "locationManager", ";", "}" ]
Returns location manager. @return LocationManager
[ "Returns", "location", "manager", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L99-L112
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.getContentTypeManager
public function getContentTypeManager() { if ($this->contentTypeManager != null) { return $this->contentTypeManager; } $this->contentTypeManager = new ContentTypeManager($this->getContentTypeService(), $this->getLanguageManager(), $this->getFieldDefinitionSubManager(), $this->getContentTypeGroupSubManager()); if ($this->logger) { $this->contentTypeManager->setLogger($this->logger); } return $this->contentTypeManager; }
php
public function getContentTypeManager() { if ($this->contentTypeManager != null) { return $this->contentTypeManager; } $this->contentTypeManager = new ContentTypeManager($this->getContentTypeService(), $this->getLanguageManager(), $this->getFieldDefinitionSubManager(), $this->getContentTypeGroupSubManager()); if ($this->logger) { $this->contentTypeManager->setLogger($this->logger); } return $this->contentTypeManager; }
[ "public", "function", "getContentTypeManager", "(", ")", "{", "if", "(", "$", "this", "->", "contentTypeManager", "!=", "null", ")", "{", "return", "$", "this", "->", "contentTypeManager", ";", "}", "$", "this", "->", "contentTypeManager", "=", "new", "ContentTypeManager", "(", "$", "this", "->", "getContentTypeService", "(", ")", ",", "$", "this", "->", "getLanguageManager", "(", ")", ",", "$", "this", "->", "getFieldDefinitionSubManager", "(", ")", ",", "$", "this", "->", "getContentTypeGroupSubManager", "(", ")", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "contentTypeManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}", "return", "$", "this", "->", "contentTypeManager", ";", "}" ]
Returns contenttype manager. @return ContentTypeManager
[ "Returns", "contenttype", "manager", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L119-L132
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.getLanguageManager
public function getLanguageManager() { if ($this->languageManager != null) { return $this->languageManager; } $this->languageManager = new LanguageManager($this->getLanguageService()); if ($this->logger) { $this->languageManager->setLogger($this->logger); } return $this->languageManager; }
php
public function getLanguageManager() { if ($this->languageManager != null) { return $this->languageManager; } $this->languageManager = new LanguageManager($this->getLanguageService()); if ($this->logger) { $this->languageManager->setLogger($this->logger); } return $this->languageManager; }
[ "public", "function", "getLanguageManager", "(", ")", "{", "if", "(", "$", "this", "->", "languageManager", "!=", "null", ")", "{", "return", "$", "this", "->", "languageManager", ";", "}", "$", "this", "->", "languageManager", "=", "new", "LanguageManager", "(", "$", "this", "->", "getLanguageService", "(", ")", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "languageManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}", "return", "$", "this", "->", "languageManager", ";", "}" ]
Returns language manager. @return LanguageManager
[ "Returns", "language", "manager", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L139-L152
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.getUserGroupManager
public function getUserGroupManager() { if ($this->userGroupManager != null) { return $this->userGroupManager; } $this->userGroupManager = new UserGroupManager($this->options, $this->getUserService(), $this->getContentService(), $this->getContentTypeService()); if ($this->logger) { $this->userGroupManager->setLogger($this->logger); } return $this->userGroupManager; }
php
public function getUserGroupManager() { if ($this->userGroupManager != null) { return $this->userGroupManager; } $this->userGroupManager = new UserGroupManager($this->options, $this->getUserService(), $this->getContentService(), $this->getContentTypeService()); if ($this->logger) { $this->userGroupManager->setLogger($this->logger); } return $this->userGroupManager; }
[ "public", "function", "getUserGroupManager", "(", ")", "{", "if", "(", "$", "this", "->", "userGroupManager", "!=", "null", ")", "{", "return", "$", "this", "->", "userGroupManager", ";", "}", "$", "this", "->", "userGroupManager", "=", "new", "UserGroupManager", "(", "$", "this", "->", "options", ",", "$", "this", "->", "getUserService", "(", ")", ",", "$", "this", "->", "getContentService", "(", ")", ",", "$", "this", "->", "getContentTypeService", "(", ")", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "userGroupManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}", "return", "$", "this", "->", "userGroupManager", ";", "}" ]
Returns user group manager. @return UserGroupManager
[ "Returns", "user", "group", "manager", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L159-L172
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.getUserManager
public function getUserManager() { if ($this->userManager != null) { return $this->userManager; } $this->userManager = new UserManager($this->options, $this->getUserService(), $this->getContentTypeService(), $this->getUserGroupManager()); if ($this->logger) { $this->userManager->setLogger($this->logger); } return $this->userManager; }
php
public function getUserManager() { if ($this->userManager != null) { return $this->userManager; } $this->userManager = new UserManager($this->options, $this->getUserService(), $this->getContentTypeService(), $this->getUserGroupManager()); if ($this->logger) { $this->userManager->setLogger($this->logger); } return $this->userManager; }
[ "public", "function", "getUserManager", "(", ")", "{", "if", "(", "$", "this", "->", "userManager", "!=", "null", ")", "{", "return", "$", "this", "->", "userManager", ";", "}", "$", "this", "->", "userManager", "=", "new", "UserManager", "(", "$", "this", "->", "options", ",", "$", "this", "->", "getUserService", "(", ")", ",", "$", "this", "->", "getContentTypeService", "(", ")", ",", "$", "this", "->", "getUserGroupManager", "(", ")", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "userManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}", "return", "$", "this", "->", "userManager", ";", "}" ]
Returns user manager. @return UserManager
[ "Returns", "user", "manager", "." ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L179-L192
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.createOrUpdate
public function createOrUpdate($object) { foreach ($this->getManagerMapping() as $class => $callable) { if ($object instanceof $class) { /** @var UpdaterInterface $manager */ $manager = call_user_func($callable); return $manager->createOrUpdate($object); } } throw new \InvalidArgumentException('Object is not supported for creation.'); }
php
public function createOrUpdate($object) { foreach ($this->getManagerMapping() as $class => $callable) { if ($object instanceof $class) { /** @var UpdaterInterface $manager */ $manager = call_user_func($callable); return $manager->createOrUpdate($object); } } throw new \InvalidArgumentException('Object is not supported for creation.'); }
[ "public", "function", "createOrUpdate", "(", "$", "object", ")", "{", "foreach", "(", "$", "this", "->", "getManagerMapping", "(", ")", "as", "$", "class", "=>", "$", "callable", ")", "{", "if", "(", "$", "object", "instanceof", "$", "class", ")", "{", "/** @var UpdaterInterface $manager */", "$", "manager", "=", "call_user_func", "(", "$", "callable", ")", ";", "return", "$", "manager", "->", "createOrUpdate", "(", "$", "object", ")", ";", "}", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Object is not supported for creation.'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L245-L257
transfer-framework/ezplatform
src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php
ObjectService.remove
public function remove($object) { foreach ($this->getManagerMapping() as $class => $callable) { if ($object instanceof $class) { /** @var RemoverInterface $manager */ $manager = call_user_func($callable); return $manager->remove($object); } } throw new \InvalidArgumentException('Object is not supported for deletion.'); }
php
public function remove($object) { foreach ($this->getManagerMapping() as $class => $callable) { if ($object instanceof $class) { /** @var RemoverInterface $manager */ $manager = call_user_func($callable); return $manager->remove($object); } } throw new \InvalidArgumentException('Object is not supported for deletion.'); }
[ "public", "function", "remove", "(", "$", "object", ")", "{", "foreach", "(", "$", "this", "->", "getManagerMapping", "(", ")", "as", "$", "class", "=>", "$", "callable", ")", "{", "if", "(", "$", "object", "instanceof", "$", "class", ")", "{", "/** @var RemoverInterface $manager */", "$", "manager", "=", "call_user_func", "(", "$", "callable", ")", ";", "return", "$", "manager", "->", "remove", "(", "$", "object", ")", ";", "}", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Object is not supported for deletion.'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/transfer-framework/ezplatform/blob/1b2d87caa1a6b79fd8fc78109c26a2d1d6359c2f/src/Transfer/EzPlatform/Repository/Manager/Core/ObjectService.php#L262-L274
OwlyCode/StreamingBird
src/Oauth.php
Oauth.getAuthorizationHeader
public function getAuthorizationHeader($url, array $params, array $overrides = []) { $headers = $this->prepareHeaders('POST', $url, $params, $overrides); $headers = implode(',', array_map(function($name, $value){ return sprintf('%s="%s"', $name, $value); }, array_keys($headers), $headers)); return sprintf('OAuth realm="",%s', $headers); }
php
public function getAuthorizationHeader($url, array $params, array $overrides = []) { $headers = $this->prepareHeaders('POST', $url, $params, $overrides); $headers = implode(',', array_map(function($name, $value){ return sprintf('%s="%s"', $name, $value); }, array_keys($headers), $headers)); return sprintf('OAuth realm="",%s', $headers); }
[ "public", "function", "getAuthorizationHeader", "(", "$", "url", ",", "array", "$", "params", ",", "array", "$", "overrides", "=", "[", "]", ")", "{", "$", "headers", "=", "$", "this", "->", "prepareHeaders", "(", "'POST'", ",", "$", "url", ",", "$", "params", ",", "$", "overrides", ")", ";", "$", "headers", "=", "implode", "(", "','", ",", "array_map", "(", "function", "(", "$", "name", ",", "$", "value", ")", "{", "return", "sprintf", "(", "'%s=\"%s\"'", ",", "$", "name", ",", "$", "value", ")", ";", "}", ",", "array_keys", "(", "$", "headers", ")", ",", "$", "headers", ")", ")", ";", "return", "sprintf", "(", "'OAuth realm=\"\",%s'", ",", "$", "headers", ")", ";", "}" ]
@param string $url @param array $params @return string
[ "@param", "string", "$url", "@param", "array", "$params" ]
train
https://github.com/OwlyCode/StreamingBird/blob/177fc8a9dc8f911865a5abd9ac8d4ef85cef4003/src/Oauth.php#L47-L56
OwlyCode/StreamingBird
src/Oauth.php
Oauth.prepareHeaders
protected function prepareHeaders($method, $url, array $params, array $overrides = []) { $oauth = array_merge([ 'oauth_consumer_key' => $this->consumerKey, 'oauth_nonce' => md5(uniqid(rand(), true)), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => time(), 'oauth_version' => '1.0A', 'oauth_token' => $this->oauthToken, ], $overrides); foreach ($oauth as $k => $v) { $oauth[$k] = rawurlencode($v); } foreach ($params as $k => $v) { $params[$k] = rawurlencode($v); } $sigParams = array_merge($oauth, $params); ksort($sigParams); $oauth['oauth_signature'] = rawurlencode($this->generateSignature($method, $url, $sigParams)); return $oauth; }
php
protected function prepareHeaders($method, $url, array $params, array $overrides = []) { $oauth = array_merge([ 'oauth_consumer_key' => $this->consumerKey, 'oauth_nonce' => md5(uniqid(rand(), true)), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => time(), 'oauth_version' => '1.0A', 'oauth_token' => $this->oauthToken, ], $overrides); foreach ($oauth as $k => $v) { $oauth[$k] = rawurlencode($v); } foreach ($params as $k => $v) { $params[$k] = rawurlencode($v); } $sigParams = array_merge($oauth, $params); ksort($sigParams); $oauth['oauth_signature'] = rawurlencode($this->generateSignature($method, $url, $sigParams)); return $oauth; }
[ "protected", "function", "prepareHeaders", "(", "$", "method", ",", "$", "url", ",", "array", "$", "params", ",", "array", "$", "overrides", "=", "[", "]", ")", "{", "$", "oauth", "=", "array_merge", "(", "[", "'oauth_consumer_key'", "=>", "$", "this", "->", "consumerKey", ",", "'oauth_nonce'", "=>", "md5", "(", "uniqid", "(", "rand", "(", ")", ",", "true", ")", ")", ",", "'oauth_signature_method'", "=>", "'HMAC-SHA1'", ",", "'oauth_timestamp'", "=>", "time", "(", ")", ",", "'oauth_version'", "=>", "'1.0A'", ",", "'oauth_token'", "=>", "$", "this", "->", "oauthToken", ",", "]", ",", "$", "overrides", ")", ";", "foreach", "(", "$", "oauth", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "oauth", "[", "$", "k", "]", "=", "rawurlencode", "(", "$", "v", ")", ";", "}", "foreach", "(", "$", "params", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "params", "[", "$", "k", "]", "=", "rawurlencode", "(", "$", "v", ")", ";", "}", "$", "sigParams", "=", "array_merge", "(", "$", "oauth", ",", "$", "params", ")", ";", "ksort", "(", "$", "sigParams", ")", ";", "$", "oauth", "[", "'oauth_signature'", "]", "=", "rawurlencode", "(", "$", "this", "->", "generateSignature", "(", "$", "method", ",", "$", "url", ",", "$", "sigParams", ")", ")", ";", "return", "$", "oauth", ";", "}" ]
Prepares oauth headers for a given request. @param string $method @param string $url @param array $params @return array
[ "Prepares", "oauth", "headers", "for", "a", "given", "request", "." ]
train
https://github.com/OwlyCode/StreamingBird/blob/177fc8a9dc8f911865a5abd9ac8d4ef85cef4003/src/Oauth.php#L67-L92
OwlyCode/StreamingBird
src/Oauth.php
Oauth.generateSignature
protected function generateSignature($method, $url, array $params) { $concat = implode('&', array_map(function($name, $value){ return sprintf('%s=%s', $name, $value); }, array_keys($params), $params)); $concatenatedParams = rawurlencode($concat); // normalize url $urlParts = parse_url($url); $scheme = strtolower($urlParts['scheme']); $host = strtolower($urlParts['host']); $port = isset($urlParts['port']) ? intval($urlParts['port']) : 0; $retval = strtolower($scheme) . '://' . strtolower($host); if (!empty($port) && (($scheme === 'http' && $port != 80) || ($scheme === 'https' && $port != 443))) { $retval .= ":{$port}"; } $retval .= $urlParts['path']; if (!empty($urlParts['query'])) { $retval .= "?{$urlParts['query']}"; } $normalizedUrl = rawurlencode($retval); $signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}"; # sign the signature string $key = rawurlencode($this->consumerSecret) . '&' . rawurlencode($this->oauthSecret); return base64_encode(hash_hmac('sha1', $signatureBaseString, $key, true)); }
php
protected function generateSignature($method, $url, array $params) { $concat = implode('&', array_map(function($name, $value){ return sprintf('%s=%s', $name, $value); }, array_keys($params), $params)); $concatenatedParams = rawurlencode($concat); // normalize url $urlParts = parse_url($url); $scheme = strtolower($urlParts['scheme']); $host = strtolower($urlParts['host']); $port = isset($urlParts['port']) ? intval($urlParts['port']) : 0; $retval = strtolower($scheme) . '://' . strtolower($host); if (!empty($port) && (($scheme === 'http' && $port != 80) || ($scheme === 'https' && $port != 443))) { $retval .= ":{$port}"; } $retval .= $urlParts['path']; if (!empty($urlParts['query'])) { $retval .= "?{$urlParts['query']}"; } $normalizedUrl = rawurlencode($retval); $signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}"; # sign the signature string $key = rawurlencode($this->consumerSecret) . '&' . rawurlencode($this->oauthSecret); return base64_encode(hash_hmac('sha1', $signatureBaseString, $key, true)); }
[ "protected", "function", "generateSignature", "(", "$", "method", ",", "$", "url", ",", "array", "$", "params", ")", "{", "$", "concat", "=", "implode", "(", "'&'", ",", "array_map", "(", "function", "(", "$", "name", ",", "$", "value", ")", "{", "return", "sprintf", "(", "'%s=%s'", ",", "$", "name", ",", "$", "value", ")", ";", "}", ",", "array_keys", "(", "$", "params", ")", ",", "$", "params", ")", ")", ";", "$", "concatenatedParams", "=", "rawurlencode", "(", "$", "concat", ")", ";", "// normalize url", "$", "urlParts", "=", "parse_url", "(", "$", "url", ")", ";", "$", "scheme", "=", "strtolower", "(", "$", "urlParts", "[", "'scheme'", "]", ")", ";", "$", "host", "=", "strtolower", "(", "$", "urlParts", "[", "'host'", "]", ")", ";", "$", "port", "=", "isset", "(", "$", "urlParts", "[", "'port'", "]", ")", "?", "intval", "(", "$", "urlParts", "[", "'port'", "]", ")", ":", "0", ";", "$", "retval", "=", "strtolower", "(", "$", "scheme", ")", ".", "'://'", ".", "strtolower", "(", "$", "host", ")", ";", "if", "(", "!", "empty", "(", "$", "port", ")", "&&", "(", "(", "$", "scheme", "===", "'http'", "&&", "$", "port", "!=", "80", ")", "||", "(", "$", "scheme", "===", "'https'", "&&", "$", "port", "!=", "443", ")", ")", ")", "{", "$", "retval", ".=", "\":{$port}\"", ";", "}", "$", "retval", ".=", "$", "urlParts", "[", "'path'", "]", ";", "if", "(", "!", "empty", "(", "$", "urlParts", "[", "'query'", "]", ")", ")", "{", "$", "retval", ".=", "\"?{$urlParts['query']}\"", ";", "}", "$", "normalizedUrl", "=", "rawurlencode", "(", "$", "retval", ")", ";", "$", "signatureBaseString", "=", "\"{$method}&{$normalizedUrl}&{$concatenatedParams}\"", ";", "# sign the signature string", "$", "key", "=", "rawurlencode", "(", "$", "this", "->", "consumerSecret", ")", ".", "'&'", ".", "rawurlencode", "(", "$", "this", "->", "oauthSecret", ")", ";", "return", "base64_encode", "(", "hash_hmac", "(", "'sha1'", ",", "$", "signatureBaseString", ",", "$", "key", ",", "true", ")", ")", ";", "}" ]
See https://dev.twitter.com/oauth/overview/creating-signatures @param string $method @param string $url @param array $params @return string
[ "See", "https", ":", "//", "dev", ".", "twitter", ".", "com", "/", "oauth", "/", "overview", "/", "creating", "-", "signatures" ]
train
https://github.com/OwlyCode/StreamingBird/blob/177fc8a9dc8f911865a5abd9ac8d4ef85cef4003/src/Oauth.php#L103-L134
CakeCMS/Core
src/View/Widget/MaterializeCss/CheckboxWidget.php
CheckboxWidget.render
public function render(array $data, ContextInterface $context) { $data += ['class' => '']; $data['class'] .= ' filled-in '; $data['class'] = trim($data['class']); return parent::render($data, $context); }
php
public function render(array $data, ContextInterface $context) { $data += ['class' => '']; $data['class'] .= ' filled-in '; $data['class'] = trim($data['class']); return parent::render($data, $context); }
[ "public", "function", "render", "(", "array", "$", "data", ",", "ContextInterface", "$", "context", ")", "{", "$", "data", "+=", "[", "'class'", "=>", "''", "]", ";", "$", "data", "[", "'class'", "]", ".=", "' filled-in '", ";", "$", "data", "[", "'class'", "]", "=", "trim", "(", "$", "data", "[", "'class'", "]", ")", ";", "return", "parent", "::", "render", "(", "$", "data", ",", "$", "context", ")", ";", "}" ]
Render a checkbox element. @param array $data The data to create a checkbox with. @param \Cake\View\Form\ContextInterface $context The current form context. @return string Generated HTML string.
[ "Render", "a", "checkbox", "element", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/View/Widget/MaterializeCss/CheckboxWidget.php#L36-L43
aedart/laravel-helpers
src/Traits/Auth/PasswordBrokerFactoryTrait.php
PasswordBrokerFactoryTrait.getPasswordBrokerFactory
public function getPasswordBrokerFactory(): ?PasswordBrokerFactory { if (!$this->hasPasswordBrokerFactory()) { $this->setPasswordBrokerFactory($this->getDefaultPasswordBrokerFactory()); } return $this->passwordBrokerFactory; }
php
public function getPasswordBrokerFactory(): ?PasswordBrokerFactory { if (!$this->hasPasswordBrokerFactory()) { $this->setPasswordBrokerFactory($this->getDefaultPasswordBrokerFactory()); } return $this->passwordBrokerFactory; }
[ "public", "function", "getPasswordBrokerFactory", "(", ")", ":", "?", "PasswordBrokerFactory", "{", "if", "(", "!", "$", "this", "->", "hasPasswordBrokerFactory", "(", ")", ")", "{", "$", "this", "->", "setPasswordBrokerFactory", "(", "$", "this", "->", "getDefaultPasswordBrokerFactory", "(", ")", ")", ";", "}", "return", "$", "this", "->", "passwordBrokerFactory", ";", "}" ]
Get password broker factory If no password broker factory has been set, this method will set and return a default password broker factory, if any such value is available @see getDefaultPasswordBrokerFactory() @return PasswordBrokerFactory|null password broker factory or null if none password broker factory has been set
[ "Get", "password", "broker", "factory" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Auth/PasswordBrokerFactoryTrait.php#L53-L59
mle86/php-wq
src/WQ/WorkServerAdapter/AffixAdapter.php
AffixAdapter.getNextQueueEntry
public function getNextQueueEntry($workQueue, int $timeout = self::DEFAULT_TIMEOUT): ?QueueEntry { $workQueue = (array)$workQueue; foreach ($workQueue as &$wq) { $wq = $this->fixQueueName($wq); } unset($wq); return $this->server->getNextQueueEntry($workQueue, $timeout); }
php
public function getNextQueueEntry($workQueue, int $timeout = self::DEFAULT_TIMEOUT): ?QueueEntry { $workQueue = (array)$workQueue; foreach ($workQueue as &$wq) { $wq = $this->fixQueueName($wq); } unset($wq); return $this->server->getNextQueueEntry($workQueue, $timeout); }
[ "public", "function", "getNextQueueEntry", "(", "$", "workQueue", ",", "int", "$", "timeout", "=", "self", "::", "DEFAULT_TIMEOUT", ")", ":", "?", "QueueEntry", "{", "$", "workQueue", "=", "(", "array", ")", "$", "workQueue", ";", "foreach", "(", "$", "workQueue", "as", "&", "$", "wq", ")", "{", "$", "wq", "=", "$", "this", "->", "fixQueueName", "(", "$", "wq", ")", ";", "}", "unset", "(", "$", "wq", ")", ";", "return", "$", "this", "->", "server", "->", "getNextQueueEntry", "(", "$", "workQueue", ",", "$", "timeout", ")", ";", "}" ]
Proxy methods: /////////////////////////////////////////////////////////
[ "Proxy", "methods", ":", "/////////////////////////////////////////////////////////" ]
train
https://github.com/mle86/php-wq/blob/e1ca1dcfd3d40edb0085f6dfa83d90db74253de4/src/WQ/WorkServerAdapter/AffixAdapter.php#L77-L86
aedart/laravel-helpers
src/Traits/Broadcasting/BroadcastTrait.php
BroadcastTrait.getBroadcast
public function getBroadcast(): ?Broadcaster { if (!$this->hasBroadcast()) { $this->setBroadcast($this->getDefaultBroadcast()); } return $this->broadcast; }
php
public function getBroadcast(): ?Broadcaster { if (!$this->hasBroadcast()) { $this->setBroadcast($this->getDefaultBroadcast()); } return $this->broadcast; }
[ "public", "function", "getBroadcast", "(", ")", ":", "?", "Broadcaster", "{", "if", "(", "!", "$", "this", "->", "hasBroadcast", "(", ")", ")", "{", "$", "this", "->", "setBroadcast", "(", "$", "this", "->", "getDefaultBroadcast", "(", ")", ")", ";", "}", "return", "$", "this", "->", "broadcast", ";", "}" ]
Get broadcast If no broadcast has been set, this method will set and return a default broadcast, if any such value is available @see getDefaultBroadcast() @return Broadcaster|null broadcast or null if none broadcast has been set
[ "Get", "broadcast" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Broadcasting/BroadcastTrait.php#L53-L59
aedart/laravel-helpers
src/Traits/Broadcasting/BroadcastTrait.php
BroadcastTrait.getDefaultBroadcast
public function getDefaultBroadcast(): ?Broadcaster { // By default, the Broadcast Facade does not return the // any actual broadcaster, but rather an // instance of a manager. // Therefore, we make sure only to obtain its // "broadcaster", to make sure that its only the // connection is obtained! $manager = Broadcast::getFacadeRoot(); if (isset($manager)) { return $manager->connection(); } return $manager; }
php
public function getDefaultBroadcast(): ?Broadcaster { // By default, the Broadcast Facade does not return the // any actual broadcaster, but rather an // instance of a manager. // Therefore, we make sure only to obtain its // "broadcaster", to make sure that its only the // connection is obtained! $manager = Broadcast::getFacadeRoot(); if (isset($manager)) { return $manager->connection(); } return $manager; }
[ "public", "function", "getDefaultBroadcast", "(", ")", ":", "?", "Broadcaster", "{", "// By default, the Broadcast Facade does not return the", "// any actual broadcaster, but rather an", "// instance of a manager.", "// Therefore, we make sure only to obtain its", "// \"broadcaster\", to make sure that its only the", "// connection is obtained!", "$", "manager", "=", "Broadcast", "::", "getFacadeRoot", "(", ")", ";", "if", "(", "isset", "(", "$", "manager", ")", ")", "{", "return", "$", "manager", "->", "connection", "(", ")", ";", "}", "return", "$", "manager", ";", "}" ]
Get a default broadcast value, if any is available @return Broadcaster|null A default broadcast value or Null if no default value is available
[ "Get", "a", "default", "broadcast", "value", "if", "any", "is", "available" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Broadcasting/BroadcastTrait.php#L76-L89
Chill-project/Main
Export/ExportManager.php
ExportManager.getExports
public function getExports($whereUserIsGranted = true) { foreach ($this->exports as $alias => $export) { if ($whereUserIsGranted) { if ($this->isGrantedForElement($export, null, null)) { yield $alias => $export; } } else { yield $alias => $export; } } }
php
public function getExports($whereUserIsGranted = true) { foreach ($this->exports as $alias => $export) { if ($whereUserIsGranted) { if ($this->isGrantedForElement($export, null, null)) { yield $alias => $export; } } else { yield $alias => $export; } } }
[ "public", "function", "getExports", "(", "$", "whereUserIsGranted", "=", "true", ")", "{", "foreach", "(", "$", "this", "->", "exports", "as", "$", "alias", "=>", "$", "export", ")", "{", "if", "(", "$", "whereUserIsGranted", ")", "{", "if", "(", "$", "this", "->", "isGrantedForElement", "(", "$", "export", ",", "null", ",", "null", ")", ")", "{", "yield", "$", "alias", "=>", "$", "export", ";", "}", "}", "else", "{", "yield", "$", "alias", "=>", "$", "export", ";", "}", "}", "}" ]
Return all exports. The exports's alias are the array's keys. @param boolean $whereUserIsGranted if true (default), restrict to user which are granted the right to execute the export @return ExportInterface[] an array where export's alias are keys
[ "Return", "all", "exports", ".", "The", "exports", "s", "alias", "are", "the", "array", "s", "keys", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L194-L205
Chill-project/Main
Export/ExportManager.php
ExportManager.getExport
public function getExport($alias) { if (!array_key_exists($alias, $this->exports)) { throw new \RuntimeException("The export with alias $alias is not known."); } return $this->exports[$alias]; }
php
public function getExport($alias) { if (!array_key_exists($alias, $this->exports)) { throw new \RuntimeException("The export with alias $alias is not known."); } return $this->exports[$alias]; }
[ "public", "function", "getExport", "(", "$", "alias", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "alias", ",", "$", "this", "->", "exports", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"The export with alias $alias is not known.\"", ")", ";", "}", "return", "$", "this", "->", "exports", "[", "$", "alias", "]", ";", "}" ]
Return an export by his alias @param string $alias @return ExportInterface @throws \RuntimeException
[ "Return", "an", "export", "by", "his", "alias" ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L214-L221
Chill-project/Main
Export/ExportManager.php
ExportManager.&
public function &getFiltersApplyingOn(ExportInterface $export, array $centers = null) { foreach ($this->filters as $alias => $filter) { if (in_array($filter->applyOn(), $export->supportsModifiers()) && $this->isGrantedForElement($filter, $export, $centers)) { yield $alias => $filter; } } }
php
public function &getFiltersApplyingOn(ExportInterface $export, array $centers = null) { foreach ($this->filters as $alias => $filter) { if (in_array($filter->applyOn(), $export->supportsModifiers()) && $this->isGrantedForElement($filter, $export, $centers)) { yield $alias => $filter; } } }
[ "public", "function", "&", "getFiltersApplyingOn", "(", "ExportInterface", "$", "export", ",", "array", "$", "centers", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "filters", "as", "$", "alias", "=>", "$", "filter", ")", "{", "if", "(", "in_array", "(", "$", "filter", "->", "applyOn", "(", ")", ",", "$", "export", "->", "supportsModifiers", "(", ")", ")", "&&", "$", "this", "->", "isGrantedForElement", "(", "$", "filter", ",", "$", "export", ",", "$", "centers", ")", ")", "{", "yield", "$", "alias", "=>", "$", "filter", ";", "}", "}", "}" ]
Return a \Generator containing filter which support type. If `$centers` is not null, restrict the given filters to the center the user have access to. if $centers is null, the function will returns all filters where the user has access in every centers he can reach (if the user can use the filter F in center A, but not in center B, the filter F will not be returned) @param \Chill\MainBundle\Entity\Center[] $centers the centers where the user have access to @return FilterInterface[] a \Generator that contains filters. The key is the filter's alias
[ "Return", "a", "\\", "Generator", "containing", "filter", "which", "support", "type", ".", "If", "$centers", "is", "not", "null", "restrict", "the", "given", "filters", "to", "the", "center", "the", "user", "have", "access", "to", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L297-L305
Chill-project/Main
Export/ExportManager.php
ExportManager.isGrantedForElement
public function isGrantedForElement(ExportElementInterface $element, ExportInterface $export = NULL, array $centers = null) { if ($element instanceof ExportInterface) { $role = $element->requiredRole(); } elseif ($element instanceof ModifierInterface ) { if (is_null($element->addRole())) { if (is_null($export)) { throw new \LogicException("The export should not be null: as the " . "ModifierInstance element is not an export, we should " . "be aware of the export to determine which role is required"); } else { $role = $export->requiredRole(); } } else { $role = $element->addRole(); } } else { throw new \LogicException("The element is not an ModifiersInterface or " . "an ExportInterface."); } if ($centers === null) { $centers = $this->authorizationHelper->getReachableCenters($this->user, $role); } if (count($centers) === 0) { return false; } foreach($centers as $center) { if ($this->authorizationChecker->isGranted($role->getRole(), $center) === false) { //debugging $this->logger->debug('user has no access to element', array( 'method' => __METHOD__, 'type' => get_class($element), 'center' => $center->getName() )); return false; } } return true; }
php
public function isGrantedForElement(ExportElementInterface $element, ExportInterface $export = NULL, array $centers = null) { if ($element instanceof ExportInterface) { $role = $element->requiredRole(); } elseif ($element instanceof ModifierInterface ) { if (is_null($element->addRole())) { if (is_null($export)) { throw new \LogicException("The export should not be null: as the " . "ModifierInstance element is not an export, we should " . "be aware of the export to determine which role is required"); } else { $role = $export->requiredRole(); } } else { $role = $element->addRole(); } } else { throw new \LogicException("The element is not an ModifiersInterface or " . "an ExportInterface."); } if ($centers === null) { $centers = $this->authorizationHelper->getReachableCenters($this->user, $role); } if (count($centers) === 0) { return false; } foreach($centers as $center) { if ($this->authorizationChecker->isGranted($role->getRole(), $center) === false) { //debugging $this->logger->debug('user has no access to element', array( 'method' => __METHOD__, 'type' => get_class($element), 'center' => $center->getName() )); return false; } } return true; }
[ "public", "function", "isGrantedForElement", "(", "ExportElementInterface", "$", "element", ",", "ExportInterface", "$", "export", "=", "NULL", ",", "array", "$", "centers", "=", "null", ")", "{", "if", "(", "$", "element", "instanceof", "ExportInterface", ")", "{", "$", "role", "=", "$", "element", "->", "requiredRole", "(", ")", ";", "}", "elseif", "(", "$", "element", "instanceof", "ModifierInterface", ")", "{", "if", "(", "is_null", "(", "$", "element", "->", "addRole", "(", ")", ")", ")", "{", "if", "(", "is_null", "(", "$", "export", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"The export should not be null: as the \"", ".", "\"ModifierInstance element is not an export, we should \"", ".", "\"be aware of the export to determine which role is required\"", ")", ";", "}", "else", "{", "$", "role", "=", "$", "export", "->", "requiredRole", "(", ")", ";", "}", "}", "else", "{", "$", "role", "=", "$", "element", "->", "addRole", "(", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "LogicException", "(", "\"The element is not an ModifiersInterface or \"", ".", "\"an ExportInterface.\"", ")", ";", "}", "if", "(", "$", "centers", "===", "null", ")", "{", "$", "centers", "=", "$", "this", "->", "authorizationHelper", "->", "getReachableCenters", "(", "$", "this", "->", "user", ",", "$", "role", ")", ";", "}", "if", "(", "count", "(", "$", "centers", ")", "===", "0", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "centers", "as", "$", "center", ")", "{", "if", "(", "$", "this", "->", "authorizationChecker", "->", "isGranted", "(", "$", "role", "->", "getRole", "(", ")", ",", "$", "center", ")", "===", "false", ")", "{", "//debugging", "$", "this", "->", "logger", "->", "debug", "(", "'user has no access to element'", ",", "array", "(", "'method'", "=>", "__METHOD__", ",", "'type'", "=>", "get_class", "(", "$", "element", ")", ",", "'center'", "=>", "$", "center", "->", "getName", "(", ")", ")", ")", ";", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Return true if the current user has access to the ExportElement for every center, false if the user hasn't access to element for at least one center. @param \Chill\MainBundle\Export\ExportElementInterface $element @param array|null $centers, if null, the function take into account all the reachables centers for the current user and the role given by element::requiredRole @return boolean
[ "Return", "true", "if", "the", "current", "user", "has", "access", "to", "the", "ExportElement", "for", "every", "center", "false", "if", "the", "user", "hasn", "t", "access", "to", "element", "for", "at", "least", "one", "center", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L315-L358
Chill-project/Main
Export/ExportManager.php
ExportManager.&
public function &getAggregatorsApplyingOn(ExportInterface $export, array $centers = null) { foreach ($this->aggregators as $alias => $aggregator) { if (in_array($aggregator->applyOn(), $export->supportsModifiers()) && $this->isGrantedForElement($aggregator, $export, $centers)) { yield $alias => $aggregator; } } }
php
public function &getAggregatorsApplyingOn(ExportInterface $export, array $centers = null) { foreach ($this->aggregators as $alias => $aggregator) { if (in_array($aggregator->applyOn(), $export->supportsModifiers()) && $this->isGrantedForElement($aggregator, $export, $centers)) { yield $alias => $aggregator; } } }
[ "public", "function", "&", "getAggregatorsApplyingOn", "(", "ExportInterface", "$", "export", ",", "array", "$", "centers", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "aggregators", "as", "$", "alias", "=>", "$", "aggregator", ")", "{", "if", "(", "in_array", "(", "$", "aggregator", "->", "applyOn", "(", ")", ",", "$", "export", "->", "supportsModifiers", "(", ")", ")", "&&", "$", "this", "->", "isGrantedForElement", "(", "$", "aggregator", ",", "$", "export", ",", "$", "centers", ")", ")", "{", "yield", "$", "alias", "=>", "$", "aggregator", ";", "}", "}", "}" ]
Return a \Generator containing aggregators which support type @return AggregatorInterface[] a \Generator that contains aggretagors. The key is the filter's alias
[ "Return", "a", "\\", "Generator", "containing", "aggregators", "which", "support", "type" ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L365-L373
Chill-project/Main
Export/ExportManager.php
ExportManager.generate
public function generate($exportAlias, array $pickedCentersData, array $data, array $formatterData) { $export = $this->getExport($exportAlias); //$qb = $this->em->createQueryBuilder(); $centers = $this->getPickedCenters($pickedCentersData); $query = $export->initiateQuery( $this->retrieveUsedModifiers($data), $this->buildCenterReachableScopes($centers, $export), $data[ExportType::EXPORT_KEY] ); if ($query instanceof \Doctrine\ORM\NativeQuery) { // throw an error if the export require other modifier, which is // not allowed when the export return a `NativeQuery` if (count($export->supportsModifiers()) > 0) { throw new \LogicException("The export with alias `$exportAlias` return " . "a `\Doctrine\ORM\NativeQuery` and supports modifiers, which is not " . "allowed. Either the method `supportsModifiers` should return an empty " . "array, or return a `Doctrine\ORM\QueryBuilder`"); } } elseif ($query instanceof QueryBuilder) { //handle filters $this->handleFilters($export, $query, $data[ExportType::FILTER_KEY], $centers); //handle aggregators $this->handleAggregators($export, $query, $data[ExportType::AGGREGATOR_KEY], $centers); $this->logger->debug('current query is '.$query->getDQL(), array( 'class' => self::class, 'function' => __FUNCTION__ )); } else { throw new \UnexpectedValueException("The method `intiateQuery` should return " . "a `\Doctrine\ORM\NativeQuery` or a `Doctrine\ORM\QueryBuilder` " . "object."); } $result = $export->getResult($query, $data[ExportType::EXPORT_KEY]); if (!is_array($result)) { throw new \UnexpectedValueException( sprintf( 'The result of the export should be an array, %s given', gettype($result) ) ); } /* @var $formatter Formatter\CSVFormatter */ $formatter = $this->getFormatter($this->getFormatterAlias($data)); $filters = array(); $aggregatorsData = array(); if ($query instanceof QueryBuilder) { $aggregators = $this->retrieveUsedAggregators($data[ExportType::AGGREGATOR_KEY]); foreach($aggregators as $alias => $aggregator) { $aggregatorsData[$alias] = $data[ExportType::AGGREGATOR_KEY][$alias]['form']; } } return $formatter->getResponse( $result, $formatterData, $exportAlias, $data[ExportType::EXPORT_KEY], $filters, $aggregatorsData); }
php
public function generate($exportAlias, array $pickedCentersData, array $data, array $formatterData) { $export = $this->getExport($exportAlias); //$qb = $this->em->createQueryBuilder(); $centers = $this->getPickedCenters($pickedCentersData); $query = $export->initiateQuery( $this->retrieveUsedModifiers($data), $this->buildCenterReachableScopes($centers, $export), $data[ExportType::EXPORT_KEY] ); if ($query instanceof \Doctrine\ORM\NativeQuery) { // throw an error if the export require other modifier, which is // not allowed when the export return a `NativeQuery` if (count($export->supportsModifiers()) > 0) { throw new \LogicException("The export with alias `$exportAlias` return " . "a `\Doctrine\ORM\NativeQuery` and supports modifiers, which is not " . "allowed. Either the method `supportsModifiers` should return an empty " . "array, or return a `Doctrine\ORM\QueryBuilder`"); } } elseif ($query instanceof QueryBuilder) { //handle filters $this->handleFilters($export, $query, $data[ExportType::FILTER_KEY], $centers); //handle aggregators $this->handleAggregators($export, $query, $data[ExportType::AGGREGATOR_KEY], $centers); $this->logger->debug('current query is '.$query->getDQL(), array( 'class' => self::class, 'function' => __FUNCTION__ )); } else { throw new \UnexpectedValueException("The method `intiateQuery` should return " . "a `\Doctrine\ORM\NativeQuery` or a `Doctrine\ORM\QueryBuilder` " . "object."); } $result = $export->getResult($query, $data[ExportType::EXPORT_KEY]); if (!is_array($result)) { throw new \UnexpectedValueException( sprintf( 'The result of the export should be an array, %s given', gettype($result) ) ); } /* @var $formatter Formatter\CSVFormatter */ $formatter = $this->getFormatter($this->getFormatterAlias($data)); $filters = array(); $aggregatorsData = array(); if ($query instanceof QueryBuilder) { $aggregators = $this->retrieveUsedAggregators($data[ExportType::AGGREGATOR_KEY]); foreach($aggregators as $alias => $aggregator) { $aggregatorsData[$alias] = $data[ExportType::AGGREGATOR_KEY][$alias]['form']; } } return $formatter->getResponse( $result, $formatterData, $exportAlias, $data[ExportType::EXPORT_KEY], $filters, $aggregatorsData); }
[ "public", "function", "generate", "(", "$", "exportAlias", ",", "array", "$", "pickedCentersData", ",", "array", "$", "data", ",", "array", "$", "formatterData", ")", "{", "$", "export", "=", "$", "this", "->", "getExport", "(", "$", "exportAlias", ")", ";", "//$qb = $this->em->createQueryBuilder();", "$", "centers", "=", "$", "this", "->", "getPickedCenters", "(", "$", "pickedCentersData", ")", ";", "$", "query", "=", "$", "export", "->", "initiateQuery", "(", "$", "this", "->", "retrieveUsedModifiers", "(", "$", "data", ")", ",", "$", "this", "->", "buildCenterReachableScopes", "(", "$", "centers", ",", "$", "export", ")", ",", "$", "data", "[", "ExportType", "::", "EXPORT_KEY", "]", ")", ";", "if", "(", "$", "query", "instanceof", "\\", "Doctrine", "\\", "ORM", "\\", "NativeQuery", ")", "{", "// throw an error if the export require other modifier, which is ", "// not allowed when the export return a `NativeQuery`", "if", "(", "count", "(", "$", "export", "->", "supportsModifiers", "(", ")", ")", ">", "0", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"The export with alias `$exportAlias` return \"", ".", "\"a `\\Doctrine\\ORM\\NativeQuery` and supports modifiers, which is not \"", ".", "\"allowed. Either the method `supportsModifiers` should return an empty \"", ".", "\"array, or return a `Doctrine\\ORM\\QueryBuilder`\"", ")", ";", "}", "}", "elseif", "(", "$", "query", "instanceof", "QueryBuilder", ")", "{", "//handle filters", "$", "this", "->", "handleFilters", "(", "$", "export", ",", "$", "query", ",", "$", "data", "[", "ExportType", "::", "FILTER_KEY", "]", ",", "$", "centers", ")", ";", "//handle aggregators", "$", "this", "->", "handleAggregators", "(", "$", "export", ",", "$", "query", ",", "$", "data", "[", "ExportType", "::", "AGGREGATOR_KEY", "]", ",", "$", "centers", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "'current query is '", ".", "$", "query", "->", "getDQL", "(", ")", ",", "array", "(", "'class'", "=>", "self", "::", "class", ",", "'function'", "=>", "__FUNCTION__", ")", ")", ";", "}", "else", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "\"The method `intiateQuery` should return \"", ".", "\"a `\\Doctrine\\ORM\\NativeQuery` or a `Doctrine\\ORM\\QueryBuilder` \"", ".", "\"object.\"", ")", ";", "}", "$", "result", "=", "$", "export", "->", "getResult", "(", "$", "query", ",", "$", "data", "[", "ExportType", "::", "EXPORT_KEY", "]", ")", ";", "if", "(", "!", "is_array", "(", "$", "result", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "sprintf", "(", "'The result of the export should be an array, %s given'", ",", "gettype", "(", "$", "result", ")", ")", ")", ";", "}", "/* @var $formatter Formatter\\CSVFormatter */", "$", "formatter", "=", "$", "this", "->", "getFormatter", "(", "$", "this", "->", "getFormatterAlias", "(", "$", "data", ")", ")", ";", "$", "filters", "=", "array", "(", ")", ";", "$", "aggregatorsData", "=", "array", "(", ")", ";", "if", "(", "$", "query", "instanceof", "QueryBuilder", ")", "{", "$", "aggregators", "=", "$", "this", "->", "retrieveUsedAggregators", "(", "$", "data", "[", "ExportType", "::", "AGGREGATOR_KEY", "]", ")", ";", "foreach", "(", "$", "aggregators", "as", "$", "alias", "=>", "$", "aggregator", ")", "{", "$", "aggregatorsData", "[", "$", "alias", "]", "=", "$", "data", "[", "ExportType", "::", "AGGREGATOR_KEY", "]", "[", "$", "alias", "]", "[", "'form'", "]", ";", "}", "}", "return", "$", "formatter", "->", "getResponse", "(", "$", "result", ",", "$", "formatterData", ",", "$", "exportAlias", ",", "$", "data", "[", "ExportType", "::", "EXPORT_KEY", "]", ",", "$", "filters", ",", "$", "aggregatorsData", ")", ";", "}" ]
Generate a response which contains the requested data. @param string $exportAlias @param mixed[] $data @return Response
[ "Generate", "a", "response", "which", "contains", "the", "requested", "data", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L382-L450
Chill-project/Main
Export/ExportManager.php
ExportManager.buildCenterReachableScopes
private function buildCenterReachableScopes(array $centers, ExportElementInterface $element) { $r = array(); foreach($centers as $center) { $r[] = array( 'center' => $center, 'circles' => $this->authorizationHelper->getReachableScopes($this->user, $element->requiredRole(), $center) ); } return $r; }
php
private function buildCenterReachableScopes(array $centers, ExportElementInterface $element) { $r = array(); foreach($centers as $center) { $r[] = array( 'center' => $center, 'circles' => $this->authorizationHelper->getReachableScopes($this->user, $element->requiredRole(), $center) ); } return $r; }
[ "private", "function", "buildCenterReachableScopes", "(", "array", "$", "centers", ",", "ExportElementInterface", "$", "element", ")", "{", "$", "r", "=", "array", "(", ")", ";", "foreach", "(", "$", "centers", "as", "$", "center", ")", "{", "$", "r", "[", "]", "=", "array", "(", "'center'", "=>", "$", "center", ",", "'circles'", "=>", "$", "this", "->", "authorizationHelper", "->", "getReachableScopes", "(", "$", "this", "->", "user", ",", "$", "element", "->", "requiredRole", "(", ")", ",", "$", "center", ")", ")", ";", "}", "return", "$", "r", ";", "}" ]
build the array required for defining centers and circles in the initiate queries of ExportElementsInterfaces @param \Chill\MainBundle\Entity\Center[] $centers
[ "build", "the", "array", "required", "for", "defining", "centers", "and", "circles", "in", "the", "initiate", "queries", "of", "ExportElementsInterfaces" ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L458-L470
Chill-project/Main
Export/ExportManager.php
ExportManager.getUsedAggregatorsAliases
public function getUsedAggregatorsAliases(array $data) { $aggregators = $this->retrieveUsedAggregators($data[ExportType::AGGREGATOR_KEY]); return array_keys(iterator_to_array($aggregators)); }
php
public function getUsedAggregatorsAliases(array $data) { $aggregators = $this->retrieveUsedAggregators($data[ExportType::AGGREGATOR_KEY]); return array_keys(iterator_to_array($aggregators)); }
[ "public", "function", "getUsedAggregatorsAliases", "(", "array", "$", "data", ")", "{", "$", "aggregators", "=", "$", "this", "->", "retrieveUsedAggregators", "(", "$", "data", "[", "ExportType", "::", "AGGREGATOR_KEY", "]", ")", ";", "return", "array_keys", "(", "iterator_to_array", "(", "$", "aggregators", ")", ")", ";", "}" ]
get the aggregators typse used in the form export data @param array $data the data from the export form @return string[]
[ "get", "the", "aggregators", "typse", "used", "in", "the", "form", "export", "data" ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L478-L483
Chill-project/Main
Export/ExportManager.php
ExportManager.retrieveUsedModifiers
private function retrieveUsedModifiers($data) { $usedTypes = array_merge( $this->retrieveUsedFiltersType($data[ExportType::FILTER_KEY]), $this->retrieveUsedAggregatorsType($data[ExportType::AGGREGATOR_KEY]) ); $this->logger->debug('Required types are '.implode(', ', $usedTypes), array('class' => self::class, 'function' => __FUNCTION__)); return array_unique($usedTypes); }
php
private function retrieveUsedModifiers($data) { $usedTypes = array_merge( $this->retrieveUsedFiltersType($data[ExportType::FILTER_KEY]), $this->retrieveUsedAggregatorsType($data[ExportType::AGGREGATOR_KEY]) ); $this->logger->debug('Required types are '.implode(', ', $usedTypes), array('class' => self::class, 'function' => __FUNCTION__)); return array_unique($usedTypes); }
[ "private", "function", "retrieveUsedModifiers", "(", "$", "data", ")", "{", "$", "usedTypes", "=", "array_merge", "(", "$", "this", "->", "retrieveUsedFiltersType", "(", "$", "data", "[", "ExportType", "::", "FILTER_KEY", "]", ")", ",", "$", "this", "->", "retrieveUsedAggregatorsType", "(", "$", "data", "[", "ExportType", "::", "AGGREGATOR_KEY", "]", ")", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "'Required types are '", ".", "implode", "(", "', '", ",", "$", "usedTypes", ")", ",", "array", "(", "'class'", "=>", "self", "::", "class", ",", "'function'", "=>", "__FUNCTION__", ")", ")", ";", "return", "array_unique", "(", "$", "usedTypes", ")", ";", "}" ]
parse the data to retrieve the used filters and aggregators @param mixed $data @return string[]
[ "parse", "the", "data", "to", "retrieve", "the", "used", "filters", "and", "aggregators" ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L514-L525
Chill-project/Main
Export/ExportManager.php
ExportManager.retrieveUsedFiltersType
private function retrieveUsedFiltersType($data) { $usedTypes = array(); foreach($data as $alias => $filterData) { if ($filterData['enabled'] == true){ $filter = $this->getFilter($alias); if (!in_array($filter->applyOn(), $usedTypes)) { array_push($usedTypes, $filter->applyOn()); } } } return $usedTypes; }
php
private function retrieveUsedFiltersType($data) { $usedTypes = array(); foreach($data as $alias => $filterData) { if ($filterData['enabled'] == true){ $filter = $this->getFilter($alias); if (!in_array($filter->applyOn(), $usedTypes)) { array_push($usedTypes, $filter->applyOn()); } } } return $usedTypes; }
[ "private", "function", "retrieveUsedFiltersType", "(", "$", "data", ")", "{", "$", "usedTypes", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "alias", "=>", "$", "filterData", ")", "{", "if", "(", "$", "filterData", "[", "'enabled'", "]", "==", "true", ")", "{", "$", "filter", "=", "$", "this", "->", "getFilter", "(", "$", "alias", ")", ";", "if", "(", "!", "in_array", "(", "$", "filter", "->", "applyOn", "(", ")", ",", "$", "usedTypes", ")", ")", "{", "array_push", "(", "$", "usedTypes", ",", "$", "filter", "->", "applyOn", "(", ")", ")", ";", "}", "}", "}", "return", "$", "usedTypes", ";", "}" ]
Retrieve the filter used in this export. @param mixed $data the data from the `filters` key of the ExportType @return array an array with types
[ "Retrieve", "the", "filter", "used", "in", "this", "export", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L533-L546
Chill-project/Main
Export/ExportManager.php
ExportManager.handleFilters
private function handleFilters( ExportInterface $export, QueryBuilder $qb, $data, array $centers) { $filters = $this->retrieveUsedFilters($data); foreach($filters as $alias => $filter) { if ($this->isGrantedForElement($filter, $export, $centers) === false) { throw new UnauthorizedHttpException("You are not authorized to " . "use the filter ".$filter->getTitle()); } $formData = $data[$alias]; $this->logger->debug('alter query by filter '.$alias, array( 'class' => self::class, 'function' => __FUNCTION__ )); $filter->alterQuery($qb, $formData['form']); } }
php
private function handleFilters( ExportInterface $export, QueryBuilder $qb, $data, array $centers) { $filters = $this->retrieveUsedFilters($data); foreach($filters as $alias => $filter) { if ($this->isGrantedForElement($filter, $export, $centers) === false) { throw new UnauthorizedHttpException("You are not authorized to " . "use the filter ".$filter->getTitle()); } $formData = $data[$alias]; $this->logger->debug('alter query by filter '.$alias, array( 'class' => self::class, 'function' => __FUNCTION__ )); $filter->alterQuery($qb, $formData['form']); } }
[ "private", "function", "handleFilters", "(", "ExportInterface", "$", "export", ",", "QueryBuilder", "$", "qb", ",", "$", "data", ",", "array", "$", "centers", ")", "{", "$", "filters", "=", "$", "this", "->", "retrieveUsedFilters", "(", "$", "data", ")", ";", "foreach", "(", "$", "filters", "as", "$", "alias", "=>", "$", "filter", ")", "{", "if", "(", "$", "this", "->", "isGrantedForElement", "(", "$", "filter", ",", "$", "export", ",", "$", "centers", ")", "===", "false", ")", "{", "throw", "new", "UnauthorizedHttpException", "(", "\"You are not authorized to \"", ".", "\"use the filter \"", ".", "$", "filter", "->", "getTitle", "(", ")", ")", ";", "}", "$", "formData", "=", "$", "data", "[", "$", "alias", "]", ";", "$", "this", "->", "logger", "->", "debug", "(", "'alter query by filter '", ".", "$", "alias", ",", "array", "(", "'class'", "=>", "self", "::", "class", ",", "'function'", "=>", "__FUNCTION__", ")", ")", ";", "$", "filter", "->", "alterQuery", "(", "$", "qb", ",", "$", "formData", "[", "'form'", "]", ")", ";", "}", "}" ]
alter the query with selected filters. This function check the acl. @param ExportInterface $export @param QueryBuilder $qb @param mixed $data the data under the initial 'filters' data @param \Chill\MainBundle\Entity\Center[] $centers the picked centers @throw UnauthorizedHttpException if the user is not authorized
[ "alter", "the", "query", "with", "selected", "filters", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L603-L625
Chill-project/Main
Export/ExportManager.php
ExportManager.handleAggregators
private function handleAggregators( ExportInterface $export, QueryBuilder $qb, $data, array $center) { $aggregators = $this->retrieveUsedAggregators($data); foreach ($aggregators as $alias => $aggregator) { $formData = $data[$alias]; $aggregator->alterQuery($qb, $formData['form']); } }
php
private function handleAggregators( ExportInterface $export, QueryBuilder $qb, $data, array $center) { $aggregators = $this->retrieveUsedAggregators($data); foreach ($aggregators as $alias => $aggregator) { $formData = $data[$alias]; $aggregator->alterQuery($qb, $formData['form']); } }
[ "private", "function", "handleAggregators", "(", "ExportInterface", "$", "export", ",", "QueryBuilder", "$", "qb", ",", "$", "data", ",", "array", "$", "center", ")", "{", "$", "aggregators", "=", "$", "this", "->", "retrieveUsedAggregators", "(", "$", "data", ")", ";", "foreach", "(", "$", "aggregators", "as", "$", "alias", "=>", "$", "aggregator", ")", "{", "$", "formData", "=", "$", "data", "[", "$", "alias", "]", ";", "$", "aggregator", "->", "alterQuery", "(", "$", "qb", ",", "$", "formData", "[", "'form'", "]", ")", ";", "}", "}" ]
Alter the query with selected aggregators Check for acl. If an user is not authorized to see an aggregator, throw an UnauthorizedException. @param ExportInterface $export @param QueryBuilder $qb @param type $data @param \Chill\MainBundle\Entity\Center[] $centers the picked centers @throw UnauthorizedHttpException if the user is not authorized
[ "Alter", "the", "query", "with", "selected", "aggregators" ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Export/ExportManager.php#L639-L651
2amigos/yiifoundation
helpers/Nav.php
Nav.side
public static function side($items, $htmlOptions = array()) { ArrayHelper::addValue('class', Enum::NAV_SIDE, $htmlOptions); ob_start(); echo \CHtml::openTag('ul', $htmlOptions); foreach ($items as $item) { if (is_string($item)) // treat as divider echo \CHtml::tag('li', array('class' => Enum::NAV_DIVIDER)); else { $itemOptions = ArrayHelper::getValue($item, 'itemOptions', array()); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); $label = ArrayHelper::getValue($item, 'label', 'Item'); $url = ArrayHelper::getValue($item, 'url', '#'); echo \CHtml::openTag('li', $itemOptions); echo \CHtml::link($label, $url, $linkOptions); echo \CHtml::closeTag('li'); } } echo \CHtml::closeTag('ul'); return ob_get_clean(); }
php
public static function side($items, $htmlOptions = array()) { ArrayHelper::addValue('class', Enum::NAV_SIDE, $htmlOptions); ob_start(); echo \CHtml::openTag('ul', $htmlOptions); foreach ($items as $item) { if (is_string($item)) // treat as divider echo \CHtml::tag('li', array('class' => Enum::NAV_DIVIDER)); else { $itemOptions = ArrayHelper::getValue($item, 'itemOptions', array()); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); $label = ArrayHelper::getValue($item, 'label', 'Item'); $url = ArrayHelper::getValue($item, 'url', '#'); echo \CHtml::openTag('li', $itemOptions); echo \CHtml::link($label, $url, $linkOptions); echo \CHtml::closeTag('li'); } } echo \CHtml::closeTag('ul'); return ob_get_clean(); }
[ "public", "static", "function", "side", "(", "$", "items", ",", "$", "htmlOptions", "=", "array", "(", ")", ")", "{", "ArrayHelper", "::", "addValue", "(", "'class'", ",", "Enum", "::", "NAV_SIDE", ",", "$", "htmlOptions", ")", ";", "ob_start", "(", ")", ";", "echo", "\\", "CHtml", "::", "openTag", "(", "'ul'", ",", "$", "htmlOptions", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "if", "(", "is_string", "(", "$", "item", ")", ")", "// treat as divider", "echo", "\\", "CHtml", "::", "tag", "(", "'li'", ",", "array", "(", "'class'", "=>", "Enum", "::", "NAV_DIVIDER", ")", ")", ";", "else", "{", "$", "itemOptions", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'itemOptions'", ",", "array", "(", ")", ")", ";", "$", "linkOptions", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'linkOptions'", ",", "array", "(", ")", ")", ";", "$", "label", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'label'", ",", "'Item'", ")", ";", "$", "url", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'url'", ",", "'#'", ")", ";", "echo", "\\", "CHtml", "::", "openTag", "(", "'li'", ",", "$", "itemOptions", ")", ";", "echo", "\\", "CHtml", "::", "link", "(", "$", "label", ",", "$", "url", ",", "$", "linkOptions", ")", ";", "echo", "\\", "CHtml", "::", "closeTag", "(", "'li'", ")", ";", "}", "}", "echo", "\\", "CHtml", "::", "closeTag", "(", "'ul'", ")", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Generates a side nav @param array $items the link items to display as a side nav. The items have the following format: <pre> array('label'=>'Item', 'url'=>'#', 'linkOptions'=>array(), 'itemOptions'=>array()) </pre> @param array $htmlOptions @return string @see http://foundation.zurb.com/docs/components/side-nav.html
[ "Generates", "a", "side", "nav" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/helpers/Nav.php#L33-L56
2amigos/yiifoundation
helpers/Nav.php
Nav.sub
public static function sub($items, $htmlOptions = array()) { ArrayHelper::addValue('class', Enum::NAV_SUB, $htmlOptions); ob_start(); echo \CHtml::openTag('dl', $htmlOptions); foreach ($items as $item) { $itemOptions = ArrayHelper::getValue($item, 'itemOptions', array()); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); $label = ArrayHelper::getValue($item, 'label', 'Item'); $url = ArrayHelper::getValue($item, 'url', '#'); echo \CHtml::openTag('dt', $itemOptions); echo \CHtml::link($label, $url, $linkOptions); echo \CHtml::closeTag('dt'); } echo \CHtml::closeTag('dl'); return ob_get_clean(); }
php
public static function sub($items, $htmlOptions = array()) { ArrayHelper::addValue('class', Enum::NAV_SUB, $htmlOptions); ob_start(); echo \CHtml::openTag('dl', $htmlOptions); foreach ($items as $item) { $itemOptions = ArrayHelper::getValue($item, 'itemOptions', array()); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); $label = ArrayHelper::getValue($item, 'label', 'Item'); $url = ArrayHelper::getValue($item, 'url', '#'); echo \CHtml::openTag('dt', $itemOptions); echo \CHtml::link($label, $url, $linkOptions); echo \CHtml::closeTag('dt'); } echo \CHtml::closeTag('dl'); return ob_get_clean(); }
[ "public", "static", "function", "sub", "(", "$", "items", ",", "$", "htmlOptions", "=", "array", "(", ")", ")", "{", "ArrayHelper", "::", "addValue", "(", "'class'", ",", "Enum", "::", "NAV_SUB", ",", "$", "htmlOptions", ")", ";", "ob_start", "(", ")", ";", "echo", "\\", "CHtml", "::", "openTag", "(", "'dl'", ",", "$", "htmlOptions", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "itemOptions", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'itemOptions'", ",", "array", "(", ")", ")", ";", "$", "linkOptions", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'linkOptions'", ",", "array", "(", ")", ")", ";", "$", "label", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'label'", ",", "'Item'", ")", ";", "$", "url", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'url'", ",", "'#'", ")", ";", "echo", "\\", "CHtml", "::", "openTag", "(", "'dt'", ",", "$", "itemOptions", ")", ";", "echo", "\\", "CHtml", "::", "link", "(", "$", "label", ",", "$", "url", ",", "$", "linkOptions", ")", ";", "echo", "\\", "CHtml", "::", "closeTag", "(", "'dt'", ")", ";", "}", "echo", "\\", "CHtml", "::", "closeTag", "(", "'dl'", ")", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Generates a foundation sub nav @param array $items the link items to display as a side nav. The items have the following format: <pre> array('label'=>'Item', 'url'=>'#', 'linkOptions'=>array(), 'itemOptions'=>array()) </pre> @param array $htmlOptions @return string @see http://foundation.zurb.com/docs/components/sub-nav.html
[ "Generates", "a", "foundation", "sub", "nav" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/helpers/Nav.php#L69-L86
2amigos/yiifoundation
helpers/Nav.php
Nav.dropdown
public static function dropdown($items, $encodeLabels = true) { $li = array(); foreach ($items as $item) { if (is_string($item)) { $li[] = $item; continue; } if (!isset($item['label'])) { throw new InvalidConfigException("The 'label' option is required."); } $label = $encodeLabels ? \CHtml::encode($item['label']) : $item['label']; $options = ArrayHelper::getValue($item, 'options', array()); $items = ArrayHelper::getValue($item, 'items'); $url = \CHtml::normalizeUrl(ArrayHelper::getValue($item, 'url', '#')); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); if (ArrayHelper::getValue($item, 'active')) { ArrayHelper::addValue('class', 'active', $options); } if ($items !== null) { ArrayHelper::addValue('class', 'has-dropdown', $options); if (is_array($items)) { $items = static::dropdown($items, $encodeLabels); } } $li[] = \CHtml::tag('li', $options, \CHtml::link($label, $url, $linkOptions) . $items); } return \CHtml::tag('ul', array('class' => 'dropdown'), implode("\n", $li)); }
php
public static function dropdown($items, $encodeLabels = true) { $li = array(); foreach ($items as $item) { if (is_string($item)) { $li[] = $item; continue; } if (!isset($item['label'])) { throw new InvalidConfigException("The 'label' option is required."); } $label = $encodeLabels ? \CHtml::encode($item['label']) : $item['label']; $options = ArrayHelper::getValue($item, 'options', array()); $items = ArrayHelper::getValue($item, 'items'); $url = \CHtml::normalizeUrl(ArrayHelper::getValue($item, 'url', '#')); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); if (ArrayHelper::getValue($item, 'active')) { ArrayHelper::addValue('class', 'active', $options); } if ($items !== null) { ArrayHelper::addValue('class', 'has-dropdown', $options); if (is_array($items)) { $items = static::dropdown($items, $encodeLabels); } } $li[] = \CHtml::tag('li', $options, \CHtml::link($label, $url, $linkOptions) . $items); } return \CHtml::tag('ul', array('class' => 'dropdown'), implode("\n", $li)); }
[ "public", "static", "function", "dropdown", "(", "$", "items", ",", "$", "encodeLabels", "=", "true", ")", "{", "$", "li", "=", "array", "(", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "if", "(", "is_string", "(", "$", "item", ")", ")", "{", "$", "li", "[", "]", "=", "$", "item", ";", "continue", ";", "}", "if", "(", "!", "isset", "(", "$", "item", "[", "'label'", "]", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"The 'label' option is required.\"", ")", ";", "}", "$", "label", "=", "$", "encodeLabels", "?", "\\", "CHtml", "::", "encode", "(", "$", "item", "[", "'label'", "]", ")", ":", "$", "item", "[", "'label'", "]", ";", "$", "options", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'options'", ",", "array", "(", ")", ")", ";", "$", "items", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'items'", ")", ";", "$", "url", "=", "\\", "CHtml", "::", "normalizeUrl", "(", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'url'", ",", "'#'", ")", ")", ";", "$", "linkOptions", "=", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'linkOptions'", ",", "array", "(", ")", ")", ";", "if", "(", "ArrayHelper", "::", "getValue", "(", "$", "item", ",", "'active'", ")", ")", "{", "ArrayHelper", "::", "addValue", "(", "'class'", ",", "'active'", ",", "$", "options", ")", ";", "}", "if", "(", "$", "items", "!==", "null", ")", "{", "ArrayHelper", "::", "addValue", "(", "'class'", ",", "'has-dropdown'", ",", "$", "options", ")", ";", "if", "(", "is_array", "(", "$", "items", ")", ")", "{", "$", "items", "=", "static", "::", "dropdown", "(", "$", "items", ",", "$", "encodeLabels", ")", ";", "}", "}", "$", "li", "[", "]", "=", "\\", "CHtml", "::", "tag", "(", "'li'", ",", "$", "options", ",", "\\", "CHtml", "::", "link", "(", "$", "label", ",", "$", "url", ",", "$", "linkOptions", ")", ".", "$", "items", ")", ";", "}", "return", "\\", "CHtml", "::", "tag", "(", "'ul'", ",", "array", "(", "'class'", "=>", "'dropdown'", ")", ",", "implode", "(", "\"\\n\"", ",", "$", "li", ")", ")", ";", "}" ]
Renders menu items. It differs from [[Dropdown]] widget as it is factorial to render multi-level dropdown menus. @param array $items the items to render @param bool $encodeLabels whether to encode link labels or not @return string the resulting dropdown element. @throws \foundation\exception\InvalidConfigException
[ "Renders", "menu", "items", ".", "It", "differs", "from", "[[", "Dropdown", "]]", "widget", "as", "it", "is", "factorial", "to", "render", "multi", "-", "level", "dropdown", "menus", "." ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/helpers/Nav.php#L95-L126
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionIndex
public function actionIndex() { $auth = \Yii::$app->getAuthManager(); $items = $auth->getPermissions(); $dataProvider = new ArrayDataProvider(); $dataProvider->setModels($items); $lockFile = \Yii::getAlias('@runtime/jrbac-permission-init.lock'); if (file_exists($lockFile)) { chmod($lockFile, 0777); $lastTime = file_get_contents($lockFile); } else { touch($lockFile); $lastTime = 0; } return $this->render('index',[ 'dataProvider' => $dataProvider, 'lastTime' => $lastTime, ]); }
php
public function actionIndex() { $auth = \Yii::$app->getAuthManager(); $items = $auth->getPermissions(); $dataProvider = new ArrayDataProvider(); $dataProvider->setModels($items); $lockFile = \Yii::getAlias('@runtime/jrbac-permission-init.lock'); if (file_exists($lockFile)) { chmod($lockFile, 0777); $lastTime = file_get_contents($lockFile); } else { touch($lockFile); $lastTime = 0; } return $this->render('index',[ 'dataProvider' => $dataProvider, 'lastTime' => $lastTime, ]); }
[ "public", "function", "actionIndex", "(", ")", "{", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "items", "=", "$", "auth", "->", "getPermissions", "(", ")", ";", "$", "dataProvider", "=", "new", "ArrayDataProvider", "(", ")", ";", "$", "dataProvider", "->", "setModels", "(", "$", "items", ")", ";", "$", "lockFile", "=", "\\", "Yii", "::", "getAlias", "(", "'@runtime/jrbac-permission-init.lock'", ")", ";", "if", "(", "file_exists", "(", "$", "lockFile", ")", ")", "{", "chmod", "(", "$", "lockFile", ",", "0777", ")", ";", "$", "lastTime", "=", "file_get_contents", "(", "$", "lockFile", ")", ";", "}", "else", "{", "touch", "(", "$", "lockFile", ")", ";", "$", "lastTime", "=", "0", ";", "}", "return", "$", "this", "->", "render", "(", "'index'", ",", "[", "'dataProvider'", "=>", "$", "dataProvider", ",", "'lastTime'", "=>", "$", "lastTime", ",", "]", ")", ";", "}" ]
查看资源列表
[ "查看资源列表" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L18-L36
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionCreate
public function actionCreate() { $model = new PermissionForm(); $model->isNewRecord = true; if($model->load(\Yii::$app->getRequest()->post())) { $model->name = trim($model->name); if (!$model->name) { $model->addError('name', '资源标识不可为空'); } else { $auth = \Yii::$app->getAuthManager(); if($auth->getPermission($model->name)) { $model->addError('name','资源标识已存在'); } else { $item = $auth->createPermission($model->name); $item->description = trim($model->description); $item->ruleName = trim($model->ruleName) ? : NULL; if($auth->add($item)) { return $this->redirect(['index']); } } } } $rules = ArrayHelper::getColumn(\Yii::$app->getAuthManager()->getRules(),"name"); return $this->render('create',[ 'model'=>$model, 'rules'=>$rules, ]); }
php
public function actionCreate() { $model = new PermissionForm(); $model->isNewRecord = true; if($model->load(\Yii::$app->getRequest()->post())) { $model->name = trim($model->name); if (!$model->name) { $model->addError('name', '资源标识不可为空'); } else { $auth = \Yii::$app->getAuthManager(); if($auth->getPermission($model->name)) { $model->addError('name','资源标识已存在'); } else { $item = $auth->createPermission($model->name); $item->description = trim($model->description); $item->ruleName = trim($model->ruleName) ? : NULL; if($auth->add($item)) { return $this->redirect(['index']); } } } } $rules = ArrayHelper::getColumn(\Yii::$app->getAuthManager()->getRules(),"name"); return $this->render('create',[ 'model'=>$model, 'rules'=>$rules, ]); }
[ "public", "function", "actionCreate", "(", ")", "{", "$", "model", "=", "new", "PermissionForm", "(", ")", ";", "$", "model", "->", "isNewRecord", "=", "true", ";", "if", "(", "$", "model", "->", "load", "(", "\\", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", "->", "post", "(", ")", ")", ")", "{", "$", "model", "->", "name", "=", "trim", "(", "$", "model", "->", "name", ")", ";", "if", "(", "!", "$", "model", "->", "name", ")", "{", "$", "model", "->", "addError", "(", "'name'", ",", "'资源标识不可为空');", "", "", "}", "else", "{", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "if", "(", "$", "auth", "->", "getPermission", "(", "$", "model", "->", "name", ")", ")", "{", "$", "model", "->", "addError", "(", "'name'", ",", "'资源标识已存在');", "", "", "}", "else", "{", "$", "item", "=", "$", "auth", "->", "createPermission", "(", "$", "model", "->", "name", ")", ";", "$", "item", "->", "description", "=", "trim", "(", "$", "model", "->", "description", ")", ";", "$", "item", "->", "ruleName", "=", "trim", "(", "$", "model", "->", "ruleName", ")", "?", ":", "NULL", ";", "if", "(", "$", "auth", "->", "add", "(", "$", "item", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "[", "'index'", "]", ")", ";", "}", "}", "}", "}", "$", "rules", "=", "ArrayHelper", "::", "getColumn", "(", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", "->", "getRules", "(", ")", ",", "\"name\"", ")", ";", "return", "$", "this", "->", "render", "(", "'create'", ",", "[", "'model'", "=>", "$", "model", ",", "'rules'", "=>", "$", "rules", ",", "]", ")", ";", "}" ]
添加权限资源
[ "添加权限资源" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L39-L67
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionDelete
public function actionDelete($id='') { $name = $id; if (\Yii::$app->getRequest()->getIsPost()) { $auth = \Yii::$app->getAuthManager(); if($name) { $item = $auth->getPermission($name); if($item) $auth->remove($item); } else { if(isset($_POST['names']) && is_array($_POST['names'])) { $flag = true; try { foreach($_POST['names'] as $name) { if(!$auth->remove($auth->getPermission(trim($name)))) $flag = false; } return $flag ? 1 : 0; } catch(\Exception $e) { return 0; } } } } return $this->redirect(['index']); }
php
public function actionDelete($id='') { $name = $id; if (\Yii::$app->getRequest()->getIsPost()) { $auth = \Yii::$app->getAuthManager(); if($name) { $item = $auth->getPermission($name); if($item) $auth->remove($item); } else { if(isset($_POST['names']) && is_array($_POST['names'])) { $flag = true; try { foreach($_POST['names'] as $name) { if(!$auth->remove($auth->getPermission(trim($name)))) $flag = false; } return $flag ? 1 : 0; } catch(\Exception $e) { return 0; } } } } return $this->redirect(['index']); }
[ "public", "function", "actionDelete", "(", "$", "id", "=", "''", ")", "{", "$", "name", "=", "$", "id", ";", "if", "(", "\\", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", "->", "getIsPost", "(", ")", ")", "{", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "if", "(", "$", "name", ")", "{", "$", "item", "=", "$", "auth", "->", "getPermission", "(", "$", "name", ")", ";", "if", "(", "$", "item", ")", "$", "auth", "->", "remove", "(", "$", "item", ")", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "_POST", "[", "'names'", "]", ")", "&&", "is_array", "(", "$", "_POST", "[", "'names'", "]", ")", ")", "{", "$", "flag", "=", "true", ";", "try", "{", "foreach", "(", "$", "_POST", "[", "'names'", "]", "as", "$", "name", ")", "{", "if", "(", "!", "$", "auth", "->", "remove", "(", "$", "auth", "->", "getPermission", "(", "trim", "(", "$", "name", ")", ")", ")", ")", "$", "flag", "=", "false", ";", "}", "return", "$", "flag", "?", "1", ":", "0", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "0", ";", "}", "}", "}", "}", "return", "$", "this", "->", "redirect", "(", "[", "'index'", "]", ")", ";", "}" ]
删除权限资源
[ "删除权限资源" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L70-L93
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionUpdate
public function actionUpdate($id) { $name = $id; $model = new PermissionForm(); $model->isNewRecord = false; $auth = \Yii::$app->getAuthManager(); $item = $auth->getPermission($name); if($model->load(\Yii::$app->getRequest()->post())) { $model->name = trim($model->name); if (!$model->name) { $model->addError('name', '资源标识不可为空'); } else { $item->name = $model->name; $item->description = trim($model->description); $item->ruleName = trim($model->ruleName)? : NULL; if($auth->update($name,$item)) { return $this->redirect(['index']); } } } $model->name = $name; $model->description = $item->description; $model->ruleName = $item->ruleName; $rules = ArrayHelper::getColumn($auth->getRules(),"name"); return $this->render('update',[ 'model' => $model, 'rules' => $rules, ]); }
php
public function actionUpdate($id) { $name = $id; $model = new PermissionForm(); $model->isNewRecord = false; $auth = \Yii::$app->getAuthManager(); $item = $auth->getPermission($name); if($model->load(\Yii::$app->getRequest()->post())) { $model->name = trim($model->name); if (!$model->name) { $model->addError('name', '资源标识不可为空'); } else { $item->name = $model->name; $item->description = trim($model->description); $item->ruleName = trim($model->ruleName)? : NULL; if($auth->update($name,$item)) { return $this->redirect(['index']); } } } $model->name = $name; $model->description = $item->description; $model->ruleName = $item->ruleName; $rules = ArrayHelper::getColumn($auth->getRules(),"name"); return $this->render('update',[ 'model' => $model, 'rules' => $rules, ]); }
[ "public", "function", "actionUpdate", "(", "$", "id", ")", "{", "$", "name", "=", "$", "id", ";", "$", "model", "=", "new", "PermissionForm", "(", ")", ";", "$", "model", "->", "isNewRecord", "=", "false", ";", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "item", "=", "$", "auth", "->", "getPermission", "(", "$", "name", ")", ";", "if", "(", "$", "model", "->", "load", "(", "\\", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", "->", "post", "(", ")", ")", ")", "{", "$", "model", "->", "name", "=", "trim", "(", "$", "model", "->", "name", ")", ";", "if", "(", "!", "$", "model", "->", "name", ")", "{", "$", "model", "->", "addError", "(", "'name'", ",", "'资源标识不可为空');", "", "", "}", "else", "{", "$", "item", "->", "name", "=", "$", "model", "->", "name", ";", "$", "item", "->", "description", "=", "trim", "(", "$", "model", "->", "description", ")", ";", "$", "item", "->", "ruleName", "=", "trim", "(", "$", "model", "->", "ruleName", ")", "?", ":", "NULL", ";", "if", "(", "$", "auth", "->", "update", "(", "$", "name", ",", "$", "item", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "[", "'index'", "]", ")", ";", "}", "}", "}", "$", "model", "->", "name", "=", "$", "name", ";", "$", "model", "->", "description", "=", "$", "item", "->", "description", ";", "$", "model", "->", "ruleName", "=", "$", "item", "->", "ruleName", ";", "$", "rules", "=", "ArrayHelper", "::", "getColumn", "(", "$", "auth", "->", "getRules", "(", ")", ",", "\"name\"", ")", ";", "return", "$", "this", "->", "render", "(", "'update'", ",", "[", "'model'", "=>", "$", "model", ",", "'rules'", "=>", "$", "rules", ",", "]", ")", ";", "}" ]
编辑权限资源
[ "编辑权限资源" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L96-L128
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionView
public function actionView($id) { $name = $id; $auth = \Yii::$app->getAuthManager(); $item = $auth->getPermission($name); $subItems = $auth->getChildren($name); return $this->render('view',[ 'item' => $item, 'subItems' => $subItems ]); }
php
public function actionView($id) { $name = $id; $auth = \Yii::$app->getAuthManager(); $item = $auth->getPermission($name); $subItems = $auth->getChildren($name); return $this->render('view',[ 'item' => $item, 'subItems' => $subItems ]); }
[ "public", "function", "actionView", "(", "$", "id", ")", "{", "$", "name", "=", "$", "id", ";", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "item", "=", "$", "auth", "->", "getPermission", "(", "$", "name", ")", ";", "$", "subItems", "=", "$", "auth", "->", "getChildren", "(", "$", "name", ")", ";", "return", "$", "this", "->", "render", "(", "'view'", ",", "[", "'item'", "=>", "$", "item", ",", "'subItems'", "=>", "$", "subItems", "]", ")", ";", "}" ]
查看权限资源信息
[ "查看权限资源信息" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L131-L141
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionSubindex
public function actionSubindex($id) { $auth = \Yii::$app->getAuthManager(); $permission = $auth->getPermission($id); $allItems = $auth->getPermissions(); $subItems = $auth->getChildren($id); $dataProvider = new ArrayDataProvider(); $dataProvider->setModels($allItems); return $this->render('subindex',[ 'dataProvider' => $dataProvider, 'allItems' => $allItems, 'subItems' => $subItems, 'permission' => $permission ]); }
php
public function actionSubindex($id) { $auth = \Yii::$app->getAuthManager(); $permission = $auth->getPermission($id); $allItems = $auth->getPermissions(); $subItems = $auth->getChildren($id); $dataProvider = new ArrayDataProvider(); $dataProvider->setModels($allItems); return $this->render('subindex',[ 'dataProvider' => $dataProvider, 'allItems' => $allItems, 'subItems' => $subItems, 'permission' => $permission ]); }
[ "public", "function", "actionSubindex", "(", "$", "id", ")", "{", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "permission", "=", "$", "auth", "->", "getPermission", "(", "$", "id", ")", ";", "$", "allItems", "=", "$", "auth", "->", "getPermissions", "(", ")", ";", "$", "subItems", "=", "$", "auth", "->", "getChildren", "(", "$", "id", ")", ";", "$", "dataProvider", "=", "new", "ArrayDataProvider", "(", ")", ";", "$", "dataProvider", "->", "setModels", "(", "$", "allItems", ")", ";", "return", "$", "this", "->", "render", "(", "'subindex'", ",", "[", "'dataProvider'", "=>", "$", "dataProvider", ",", "'allItems'", "=>", "$", "allItems", ",", "'subItems'", "=>", "$", "subItems", ",", "'permission'", "=>", "$", "permission", "]", ")", ";", "}" ]
子权限列表
[ "子权限列表" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L144-L158
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionSetsub
public function actionSetsub($name) { if (\Yii::$app->getRequest()->getIsPost() && isset($_POST['act'],$_POST['val'])) { $auth = \Yii::$app->getAuthManager(); $permission = $auth->getPermission($name); $sub = $auth->getPermission($_POST['val']); try { $flag = true; if($_POST['act'] == 'add') { if(!$auth->addChild($permission, $sub)) $flag = false; } else if($_POST['act'] == 'del') { if(!$auth->removeChild($permission, $sub)) $flag = false; } else { $flag = false; } return $flag ? 1 : 0; } catch(\Exception $e) { return 0; } } return $this->redirect(['index']); }
php
public function actionSetsub($name) { if (\Yii::$app->getRequest()->getIsPost() && isset($_POST['act'],$_POST['val'])) { $auth = \Yii::$app->getAuthManager(); $permission = $auth->getPermission($name); $sub = $auth->getPermission($_POST['val']); try { $flag = true; if($_POST['act'] == 'add') { if(!$auth->addChild($permission, $sub)) $flag = false; } else if($_POST['act'] == 'del') { if(!$auth->removeChild($permission, $sub)) $flag = false; } else { $flag = false; } return $flag ? 1 : 0; } catch(\Exception $e) { return 0; } } return $this->redirect(['index']); }
[ "public", "function", "actionSetsub", "(", "$", "name", ")", "{", "if", "(", "\\", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", "->", "getIsPost", "(", ")", "&&", "isset", "(", "$", "_POST", "[", "'act'", "]", ",", "$", "_POST", "[", "'val'", "]", ")", ")", "{", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "permission", "=", "$", "auth", "->", "getPermission", "(", "$", "name", ")", ";", "$", "sub", "=", "$", "auth", "->", "getPermission", "(", "$", "_POST", "[", "'val'", "]", ")", ";", "try", "{", "$", "flag", "=", "true", ";", "if", "(", "$", "_POST", "[", "'act'", "]", "==", "'add'", ")", "{", "if", "(", "!", "$", "auth", "->", "addChild", "(", "$", "permission", ",", "$", "sub", ")", ")", "$", "flag", "=", "false", ";", "}", "else", "if", "(", "$", "_POST", "[", "'act'", "]", "==", "'del'", ")", "{", "if", "(", "!", "$", "auth", "->", "removeChild", "(", "$", "permission", ",", "$", "sub", ")", ")", "$", "flag", "=", "false", ";", "}", "else", "{", "$", "flag", "=", "false", ";", "}", "return", "$", "flag", "?", "1", ":", "0", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "0", ";", "}", "}", "return", "$", "this", "->", "redirect", "(", "[", "'index'", "]", ")", ";", "}" ]
子权限关联设置
[ "子权限关联设置" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L161-L182
JeanWolf/yii2-jrbac
controllers/PermissionController.php
PermissionController.actionInit
public function actionInit() { if (\Yii::$app->getRequest()->getIsPost() && \Yii::$app->getRequest()->getIsAjax()) { $clearExistPermissions = false;//是否清理现有资源列表 //为true时 会清理以 / 开头的 无有效path匹配的资源 $permissionList = []; //默认模块控制器权限列表 -- Start $moduleControllerList = []; $f_list = scandir(\Yii::$app->getControllerPath()); foreach ($f_list as $f_item) { if (StringHelper::endsWith($f_item, 'Controller.php')) { $fClassName = explode('.php', $f_item)[0]; $moduleControllerList[] = \Yii::$app->controllerNamespace.'\\'.$fClassName; } } $permissions = []; if ($moduleControllerList) { $permissions = JAction::getInstance()->getPermissionList($moduleControllerList, false); } $permissionList = ArrayHelper::merge($permissionList, $permissions); //默认模块控制器权限列表 -- End //自定义模块 -- Start $modules = \Yii::$app->getModules(); //配置中的模块 $excludeModules = ['gii','debug']; //排除模块 foreach ($modules as $moduleId => $module) { if (in_array($moduleId,$excludeModules)) { continue; } if (!$module instanceof Module) { $module = \Yii::$app->getModule($moduleId); } unset($module->module); $moduleControllerList = []; $f_list = scandir($module->getControllerPath()); foreach ($f_list as $f_item) { if (StringHelper::endsWith($f_item, 'Controller.php')) { $fClassName = explode('.php', $f_item)[0]; $moduleControllerList[] = $module->controllerNamespace.'\\'.$fClassName; } } $permissions = []; if ($moduleControllerList) { $permissions = JAction::getInstance()->getPermissionList($moduleControllerList, false); } $permissionList = ArrayHelper::merge($permissionList, $permissions); } $auth = \Yii::$app->getAuthManager(); $existPermissions = $auth->getPermissions(); if ($clearExistPermissions) { //清理符合初始化规则的无效权限资源 $existPermissionNames = ArrayHelper::getColumn($existPermissions, 'name'); $permissionNames = ArrayHelper::getColumn($permissionList, 'path'); foreach ($existPermissionNames as $existPermissionName) { if (StringHelper::startsWith($existPermissionName,'/') && !in_array($existPermissionName,$permissionNames)) { $auth->remove($existPermissions[$existPermissionName]); } } } foreach ($permissionList as $permission) { if (isset($existPermissions[$permission['path']])) { //更新已有资源 if ($existPermissions[$permission['path']]->description != $permission['description']) { $existPermissions[$permission['path']]->description = $permission['description']; $auth->update($permission['path'], $existPermissions[$permission['path']]); } } else { //添加新资源 $newPermission = $auth->createPermission($permission['path']); $newPermission->description = $permission['description']; $auth->add($newPermission); } } file_put_contents(\Yii::getAlias('@runtime/jrbac-permission-init.lock'), time()); exit('上次初始化时间:'.date("Y-m-d H:i")); } exit("error"); }
php
public function actionInit() { if (\Yii::$app->getRequest()->getIsPost() && \Yii::$app->getRequest()->getIsAjax()) { $clearExistPermissions = false;//是否清理现有资源列表 //为true时 会清理以 / 开头的 无有效path匹配的资源 $permissionList = []; //默认模块控制器权限列表 -- Start $moduleControllerList = []; $f_list = scandir(\Yii::$app->getControllerPath()); foreach ($f_list as $f_item) { if (StringHelper::endsWith($f_item, 'Controller.php')) { $fClassName = explode('.php', $f_item)[0]; $moduleControllerList[] = \Yii::$app->controllerNamespace.'\\'.$fClassName; } } $permissions = []; if ($moduleControllerList) { $permissions = JAction::getInstance()->getPermissionList($moduleControllerList, false); } $permissionList = ArrayHelper::merge($permissionList, $permissions); //默认模块控制器权限列表 -- End //自定义模块 -- Start $modules = \Yii::$app->getModules(); //配置中的模块 $excludeModules = ['gii','debug']; //排除模块 foreach ($modules as $moduleId => $module) { if (in_array($moduleId,$excludeModules)) { continue; } if (!$module instanceof Module) { $module = \Yii::$app->getModule($moduleId); } unset($module->module); $moduleControllerList = []; $f_list = scandir($module->getControllerPath()); foreach ($f_list as $f_item) { if (StringHelper::endsWith($f_item, 'Controller.php')) { $fClassName = explode('.php', $f_item)[0]; $moduleControllerList[] = $module->controllerNamespace.'\\'.$fClassName; } } $permissions = []; if ($moduleControllerList) { $permissions = JAction::getInstance()->getPermissionList($moduleControllerList, false); } $permissionList = ArrayHelper::merge($permissionList, $permissions); } $auth = \Yii::$app->getAuthManager(); $existPermissions = $auth->getPermissions(); if ($clearExistPermissions) { //清理符合初始化规则的无效权限资源 $existPermissionNames = ArrayHelper::getColumn($existPermissions, 'name'); $permissionNames = ArrayHelper::getColumn($permissionList, 'path'); foreach ($existPermissionNames as $existPermissionName) { if (StringHelper::startsWith($existPermissionName,'/') && !in_array($existPermissionName,$permissionNames)) { $auth->remove($existPermissions[$existPermissionName]); } } } foreach ($permissionList as $permission) { if (isset($existPermissions[$permission['path']])) { //更新已有资源 if ($existPermissions[$permission['path']]->description != $permission['description']) { $existPermissions[$permission['path']]->description = $permission['description']; $auth->update($permission['path'], $existPermissions[$permission['path']]); } } else { //添加新资源 $newPermission = $auth->createPermission($permission['path']); $newPermission->description = $permission['description']; $auth->add($newPermission); } } file_put_contents(\Yii::getAlias('@runtime/jrbac-permission-init.lock'), time()); exit('上次初始化时间:'.date("Y-m-d H:i")); } exit("error"); }
[ "public", "function", "actionInit", "(", ")", "{", "if", "(", "\\", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", "->", "getIsPost", "(", ")", "&&", "\\", "Yii", "::", "$", "app", "->", "getRequest", "(", ")", "->", "getIsAjax", "(", ")", ")", "{", "$", "clearExistPermissions", "=", "false", ";", "//是否清理现有资源列表", "//为true时 会清理以 / 开头的 无有效path匹配的资源", "$", "permissionList", "=", "[", "]", ";", "//默认模块控制器权限列表 -- Start", "$", "moduleControllerList", "=", "[", "]", ";", "$", "f_list", "=", "scandir", "(", "\\", "Yii", "::", "$", "app", "->", "getControllerPath", "(", ")", ")", ";", "foreach", "(", "$", "f_list", "as", "$", "f_item", ")", "{", "if", "(", "StringHelper", "::", "endsWith", "(", "$", "f_item", ",", "'Controller.php'", ")", ")", "{", "$", "fClassName", "=", "explode", "(", "'.php'", ",", "$", "f_item", ")", "[", "0", "]", ";", "$", "moduleControllerList", "[", "]", "=", "\\", "Yii", "::", "$", "app", "->", "controllerNamespace", ".", "'\\\\'", ".", "$", "fClassName", ";", "}", "}", "$", "permissions", "=", "[", "]", ";", "if", "(", "$", "moduleControllerList", ")", "{", "$", "permissions", "=", "JAction", "::", "getInstance", "(", ")", "->", "getPermissionList", "(", "$", "moduleControllerList", ",", "false", ")", ";", "}", "$", "permissionList", "=", "ArrayHelper", "::", "merge", "(", "$", "permissionList", ",", "$", "permissions", ")", ";", "//默认模块控制器权限列表 -- End", "//自定义模块 -- Start", "$", "modules", "=", "\\", "Yii", "::", "$", "app", "->", "getModules", "(", ")", ";", "//配置中的模块", "$", "excludeModules", "=", "[", "'gii'", ",", "'debug'", "]", ";", "//排除模块", "foreach", "(", "$", "modules", "as", "$", "moduleId", "=>", "$", "module", ")", "{", "if", "(", "in_array", "(", "$", "moduleId", ",", "$", "excludeModules", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "$", "module", "instanceof", "Module", ")", "{", "$", "module", "=", "\\", "Yii", "::", "$", "app", "->", "getModule", "(", "$", "moduleId", ")", ";", "}", "unset", "(", "$", "module", "->", "module", ")", ";", "$", "moduleControllerList", "=", "[", "]", ";", "$", "f_list", "=", "scandir", "(", "$", "module", "->", "getControllerPath", "(", ")", ")", ";", "foreach", "(", "$", "f_list", "as", "$", "f_item", ")", "{", "if", "(", "StringHelper", "::", "endsWith", "(", "$", "f_item", ",", "'Controller.php'", ")", ")", "{", "$", "fClassName", "=", "explode", "(", "'.php'", ",", "$", "f_item", ")", "[", "0", "]", ";", "$", "moduleControllerList", "[", "]", "=", "$", "module", "->", "controllerNamespace", ".", "'\\\\'", ".", "$", "fClassName", ";", "}", "}", "$", "permissions", "=", "[", "]", ";", "if", "(", "$", "moduleControllerList", ")", "{", "$", "permissions", "=", "JAction", "::", "getInstance", "(", ")", "->", "getPermissionList", "(", "$", "moduleControllerList", ",", "false", ")", ";", "}", "$", "permissionList", "=", "ArrayHelper", "::", "merge", "(", "$", "permissionList", ",", "$", "permissions", ")", ";", "}", "$", "auth", "=", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "existPermissions", "=", "$", "auth", "->", "getPermissions", "(", ")", ";", "if", "(", "$", "clearExistPermissions", ")", "{", "//清理符合初始化规则的无效权限资源", "$", "existPermissionNames", "=", "ArrayHelper", "::", "getColumn", "(", "$", "existPermissions", ",", "'name'", ")", ";", "$", "permissionNames", "=", "ArrayHelper", "::", "getColumn", "(", "$", "permissionList", ",", "'path'", ")", ";", "foreach", "(", "$", "existPermissionNames", "as", "$", "existPermissionName", ")", "{", "if", "(", "StringHelper", "::", "startsWith", "(", "$", "existPermissionName", ",", "'/'", ")", "&&", "!", "in_array", "(", "$", "existPermissionName", ",", "$", "permissionNames", ")", ")", "{", "$", "auth", "->", "remove", "(", "$", "existPermissions", "[", "$", "existPermissionName", "]", ")", ";", "}", "}", "}", "foreach", "(", "$", "permissionList", "as", "$", "permission", ")", "{", "if", "(", "isset", "(", "$", "existPermissions", "[", "$", "permission", "[", "'path'", "]", "]", ")", ")", "{", "//更新已有资源", "if", "(", "$", "existPermissions", "[", "$", "permission", "[", "'path'", "]", "]", "->", "description", "!=", "$", "permission", "[", "'description'", "]", ")", "{", "$", "existPermissions", "[", "$", "permission", "[", "'path'", "]", "]", "->", "description", "=", "$", "permission", "[", "'description'", "]", ";", "$", "auth", "->", "update", "(", "$", "permission", "[", "'path'", "]", ",", "$", "existPermissions", "[", "$", "permission", "[", "'path'", "]", "]", ")", ";", "}", "}", "else", "{", "//添加新资源", "$", "newPermission", "=", "$", "auth", "->", "createPermission", "(", "$", "permission", "[", "'path'", "]", ")", ";", "$", "newPermission", "->", "description", "=", "$", "permission", "[", "'description'", "]", ";", "$", "auth", "->", "add", "(", "$", "newPermission", ")", ";", "}", "}", "file_put_contents", "(", "\\", "Yii", "::", "getAlias", "(", "'@runtime/jrbac-permission-init.lock'", ")", ",", "time", "(", ")", ")", ";", "exit", "(", "'上次初始化时间:'.date(\"Y-m-d H", ":", "i\"))", ";", "", "", "", "", "}", "exit", "(", "\"error\"", ")", ";", "}" ]
自动扫描并初始化权限资源列表
[ "自动扫描并初始化权限资源列表" ]
train
https://github.com/JeanWolf/yii2-jrbac/blob/1e5c80038451bd5b385f83cb9344c3bd5edd85e0/controllers/PermissionController.php#L186-L268
webtown-php/KunstmaanExtensionBundle
src/Form/PageParts/GalleryPagePartAdminType.php
GalleryPagePartAdminType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder->add('folder', 'entity', [ 'required' => true, 'label' => 'wt_kuma_extension.gallery.form.folder.label', 'class' => 'KunstmaanMediaBundle:Folder', 'attr' => ['class' => 'col-sm-8'], 'empty_value' => 'wt_kuma_extension.gallery.form.folder.empty_value', 'property' => 'optionLabel', 'multiple' => false, 'expanded' => false, 'query_builder' => function (FolderRepository $r) { return $r->getChildrenQueryBuilder(); } ]) ; }
php
public function buildForm(FormBuilderInterface $builder, array $options) { parent::buildForm($builder, $options); $builder->add('folder', 'entity', [ 'required' => true, 'label' => 'wt_kuma_extension.gallery.form.folder.label', 'class' => 'KunstmaanMediaBundle:Folder', 'attr' => ['class' => 'col-sm-8'], 'empty_value' => 'wt_kuma_extension.gallery.form.folder.empty_value', 'property' => 'optionLabel', 'multiple' => false, 'expanded' => false, 'query_builder' => function (FolderRepository $r) { return $r->getChildrenQueryBuilder(); } ]) ; }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "parent", "::", "buildForm", "(", "$", "builder", ",", "$", "options", ")", ";", "$", "builder", "->", "add", "(", "'folder'", ",", "'entity'", ",", "[", "'required'", "=>", "true", ",", "'label'", "=>", "'wt_kuma_extension.gallery.form.folder.label'", ",", "'class'", "=>", "'KunstmaanMediaBundle:Folder'", ",", "'attr'", "=>", "[", "'class'", "=>", "'col-sm-8'", "]", ",", "'empty_value'", "=>", "'wt_kuma_extension.gallery.form.folder.empty_value'", ",", "'property'", "=>", "'optionLabel'", ",", "'multiple'", "=>", "false", ",", "'expanded'", "=>", "false", ",", "'query_builder'", "=>", "function", "(", "FolderRepository", "$", "r", ")", "{", "return", "$", "r", "->", "getChildrenQueryBuilder", "(", ")", ";", "}", "]", ")", ";", "}" ]
Builds the form. This method is called for each type in the hierarchy starting form the top most type. Type extensions can further modify the form. @param FormBuilderInterface $builder The form builder @param array $options The options @see FormTypeExtensionInterface::buildForm()
[ "Builds", "the", "form", "." ]
train
https://github.com/webtown-php/KunstmaanExtensionBundle/blob/86c656c131295fe1f3f7694fd4da1e5e454076b9/src/Form/PageParts/GalleryPagePartAdminType.php#L27-L45
aedart/laravel-helpers
src/Traits/View/ViewTrait.php
ViewTrait.getView
public function getView(): ?Factory { if (!$this->hasView()) { $this->setView($this->getDefaultView()); } return $this->view; }
php
public function getView(): ?Factory { if (!$this->hasView()) { $this->setView($this->getDefaultView()); } return $this->view; }
[ "public", "function", "getView", "(", ")", ":", "?", "Factory", "{", "if", "(", "!", "$", "this", "->", "hasView", "(", ")", ")", "{", "$", "this", "->", "setView", "(", "$", "this", "->", "getDefaultView", "(", ")", ")", ";", "}", "return", "$", "this", "->", "view", ";", "}" ]
Get view If no view has been set, this method will set and return a default view, if any such value is available @see getDefaultView() @return Factory|null view or null if none view has been set
[ "Get", "view" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/View/ViewTrait.php#L53-L59
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.boot
public function boot() { if (!$this->booted) { foreach ($this->container->getProviders() as $provider) { $provider->boot($this); } $this->booted = true; } }
php
public function boot() { if (!$this->booted) { foreach ($this->container->getProviders() as $provider) { $provider->boot($this); } $this->booted = true; } }
[ "public", "function", "boot", "(", ")", "{", "if", "(", "!", "$", "this", "->", "booted", ")", "{", "foreach", "(", "$", "this", "->", "container", "->", "getProviders", "(", ")", "as", "$", "provider", ")", "{", "$", "provider", "->", "boot", "(", "$", "this", ")", ";", "}", "$", "this", "->", "booted", "=", "true", ";", "}", "}" ]
Boots of the all providers of the application @access public @return void
[ "Boots", "of", "the", "all", "providers", "of", "the", "application" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L81-L90
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.getAppDir
public function getAppDir() { if (null === $this->container->getAppDir()) { $r = new \ReflectionObject($this); $this->container->setAppDir(str_replace('\\', '/', dirname($r->getFileName()))); } return $this->container->getAppDir(); }
php
public function getAppDir() { if (null === $this->container->getAppDir()) { $r = new \ReflectionObject($this); $this->container->setAppDir(str_replace('\\', '/', dirname($r->getFileName()))); } return $this->container->getAppDir(); }
[ "public", "function", "getAppDir", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "container", "->", "getAppDir", "(", ")", ")", "{", "$", "r", "=", "new", "\\", "ReflectionObject", "(", "$", "this", ")", ";", "$", "this", "->", "container", "->", "setAppDir", "(", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "dirname", "(", "$", "r", "->", "getFileName", "(", ")", ")", ")", ")", ";", "}", "return", "$", "this", "->", "container", "->", "getAppDir", "(", ")", ";", "}" ]
Get Application Dir @return string Application Dir
[ "Get", "Application", "Dir" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L139-L147
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.getInstance
public static function getInstance(array $userSettings = array()) { if (!self::$instance) { self::$instance = new self($userSettings); } return self::$instance; }
php
public static function getInstance(array $userSettings = array()) { if (!self::$instance) { self::$instance = new self($userSettings); } return self::$instance; }
[ "public", "static", "function", "getInstance", "(", "array", "$", "userSettings", "=", "array", "(", ")", ")", "{", "if", "(", "!", "self", "::", "$", "instance", ")", "{", "self", "::", "$", "instance", "=", "new", "self", "(", "$", "userSettings", ")", ";", "}", "return", "self", "::", "$", "instance", ";", "}" ]
Get instance of MVC @param array $userSettings @return MVC
[ "Get", "instance", "of", "MVC" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L192-L199
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.initRoutes
final protected function initRoutes() { $routes = $this->setRoutes(); foreach ($routes as $currentRoutes) { foreach ($currentRoutes as $route) { $this->container->addRoute($route); } } return $this; }
php
final protected function initRoutes() { $routes = $this->setRoutes(); foreach ($routes as $currentRoutes) { foreach ($currentRoutes as $route) { $this->container->addRoute($route); } } return $this; }
[ "final", "protected", "function", "initRoutes", "(", ")", "{", "$", "routes", "=", "$", "this", "->", "setRoutes", "(", ")", ";", "foreach", "(", "$", "routes", "as", "$", "currentRoutes", ")", "{", "foreach", "(", "$", "currentRoutes", "as", "$", "route", ")", "{", "$", "this", "->", "container", "->", "addRoute", "(", "$", "route", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Initialize Routes @return MVC @throws \LogicException
[ "Initialize", "Routes" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L307-L317
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.group
public function group() { $args = func_get_args(); $route = array_shift($args); $callable = array_pop($args); if (is_string($route) && is_callable($callable)) { call_user_func($callable, $route); } }
php
public function group() { $args = func_get_args(); $route = array_shift($args); $callable = array_pop($args); if (is_string($route) && is_callable($callable)) { call_user_func($callable, $route); } }
[ "public", "function", "group", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "$", "route", "=", "array_shift", "(", "$", "args", ")", ";", "$", "callable", "=", "array_pop", "(", "$", "args", ")", ";", "if", "(", "is_string", "(", "$", "route", ")", "&&", "is_callable", "(", "$", "callable", ")", ")", "{", "call_user_func", "(", "$", "callable", ",", "$", "route", ")", ";", "}", "}" ]
Add Group routes @access public @return void
[ "Add", "Group", "routes" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L325-L333
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.ajax
public function ajax($patternUri, $action, $name) { $route = new Route("ajax", $patternUri, $action, $name); $this->container->addRoute($route); return $route; }
php
public function ajax($patternUri, $action, $name) { $route = new Route("ajax", $patternUri, $action, $name); $this->container->addRoute($route); return $route; }
[ "public", "function", "ajax", "(", "$", "patternUri", ",", "$", "action", ",", "$", "name", ")", "{", "$", "route", "=", "new", "Route", "(", "\"ajax\"", ",", "$", "patternUri", ",", "$", "action", ",", "$", "name", ")", ";", "$", "this", "->", "container", "->", "addRoute", "(", "$", "route", ")", ";", "return", "$", "route", ";", "}" ]
Add AJAX route @access public @param string $patternUri @param string|\callable $action @paran string $name @return Route
[ "Add", "AJAX", "route" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L344-L349
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.registerProvider
public function registerProvider(Provider $provider) { $provider->register($this); $this->container->addProvider($provider); return $this; }
php
public function registerProvider(Provider $provider) { $provider->register($this); $this->container->addProvider($provider); return $this; }
[ "public", "function", "registerProvider", "(", "Provider", "$", "provider", ")", "{", "$", "provider", "->", "register", "(", "$", "this", ")", ";", "$", "this", "->", "container", "->", "addProvider", "(", "$", "provider", ")", ";", "return", "$", "this", ";", "}" ]
Register the providers @access public @param Provider $provider @return MVC
[ "Register", "the", "providers" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L499-L506
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.setRoutes
public function setRoutes() { $routesJsonFile = $this->getAppDir() . '/config/routes.json'; $routesPhpFile = $this->getAppDir() . '/config/routes.php'; $routes = array(); if (file_exists($routesJsonFile)) { $routes[] = json_decode(file_get_contents($routesJsonFile), true); } elseif (file_exists($routesPhpFile)) { $routes[] = require_once $routesPhpFile; } foreach ($this->container->getModules() as $module) { $extension = $module->getModuleExtension(); if (is_object($extension) && $extension instanceof Injection\Extension) { $routes[] = $extension->loadRoutes(); } } return $routes; }
php
public function setRoutes() { $routesJsonFile = $this->getAppDir() . '/config/routes.json'; $routesPhpFile = $this->getAppDir() . '/config/routes.php'; $routes = array(); if (file_exists($routesJsonFile)) { $routes[] = json_decode(file_get_contents($routesJsonFile), true); } elseif (file_exists($routesPhpFile)) { $routes[] = require_once $routesPhpFile; } foreach ($this->container->getModules() as $module) { $extension = $module->getModuleExtension(); if (is_object($extension) && $extension instanceof Injection\Extension) { $routes[] = $extension->loadRoutes(); } } return $routes; }
[ "public", "function", "setRoutes", "(", ")", "{", "$", "routesJsonFile", "=", "$", "this", "->", "getAppDir", "(", ")", ".", "'/config/routes.json'", ";", "$", "routesPhpFile", "=", "$", "this", "->", "getAppDir", "(", ")", ".", "'/config/routes.php'", ";", "$", "routes", "=", "array", "(", ")", ";", "if", "(", "file_exists", "(", "$", "routesJsonFile", ")", ")", "{", "$", "routes", "[", "]", "=", "json_decode", "(", "file_get_contents", "(", "$", "routesJsonFile", ")", ",", "true", ")", ";", "}", "elseif", "(", "file_exists", "(", "$", "routesPhpFile", ")", ")", "{", "$", "routes", "[", "]", "=", "require_once", "$", "routesPhpFile", ";", "}", "foreach", "(", "$", "this", "->", "container", "->", "getModules", "(", ")", "as", "$", "module", ")", "{", "$", "extension", "=", "$", "module", "->", "getModuleExtension", "(", ")", ";", "if", "(", "is_object", "(", "$", "extension", ")", "&&", "$", "extension", "instanceof", "Injection", "\\", "Extension", ")", "{", "$", "routes", "[", "]", "=", "$", "extension", "->", "loadRoutes", "(", ")", ";", "}", "}", "return", "$", "routes", ";", "}" ]
Set Routes from JSON|PHP File @return Route[]
[ "Set", "Routes", "from", "JSON|PHP", "File" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L547-L567
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.share
public static function share($callable) { if (!is_object($callable) || !method_exists($callable, '__invoke')) { throw new InvalidArgumentException('Callable is not a Closure or invokable object.'); } return function ($c) use ($callable) { static $object; if (null === $object) { $object = $callable($c); } return $object; }; }
php
public static function share($callable) { if (!is_object($callable) || !method_exists($callable, '__invoke')) { throw new InvalidArgumentException('Callable is not a Closure or invokable object.'); } return function ($c) use ($callable) { static $object; if (null === $object) { $object = $callable($c); } return $object; }; }
[ "public", "static", "function", "share", "(", "$", "callable", ")", "{", "if", "(", "!", "is_object", "(", "$", "callable", ")", "||", "!", "method_exists", "(", "$", "callable", ",", "'__invoke'", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Callable is not a Closure or invokable object.'", ")", ";", "}", "return", "function", "(", "$", "c", ")", "use", "(", "$", "callable", ")", "{", "static", "$", "object", ";", "if", "(", "null", "===", "$", "object", ")", "{", "$", "object", "=", "$", "callable", "(", "$", "c", ")", ";", "}", "return", "$", "object", ";", "}", ";", "}" ]
Share a clousure object or callback object @access public @param $callable @return callable @throws InvalidArgumentException
[ "Share", "a", "clousure", "object", "or", "callback", "object" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L577-L592
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.urlFor
public function urlFor($path, $type_name = 'asset', array $params = array()) { switch ($type_name) { case 'asset': return $this->container->getRequest()->getRootUri() . $path; break; case 'route': $routeUrl = $this->container->getRequest()->getRootUri($this->getSetting('debug')) . $this->container->getRoute($path)->getPatternUri(); return (!empty($params)) ? $routeUrl . '?' . http_build_query($params) : $routeUrl; break; } }
php
public function urlFor($path, $type_name = 'asset', array $params = array()) { switch ($type_name) { case 'asset': return $this->container->getRequest()->getRootUri() . $path; break; case 'route': $routeUrl = $this->container->getRequest()->getRootUri($this->getSetting('debug')) . $this->container->getRoute($path)->getPatternUri(); return (!empty($params)) ? $routeUrl . '?' . http_build_query($params) : $routeUrl; break; } }
[ "public", "function", "urlFor", "(", "$", "path", ",", "$", "type_name", "=", "'asset'", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "switch", "(", "$", "type_name", ")", "{", "case", "'asset'", ":", "return", "$", "this", "->", "container", "->", "getRequest", "(", ")", "->", "getRootUri", "(", ")", ".", "$", "path", ";", "break", ";", "case", "'route'", ":", "$", "routeUrl", "=", "$", "this", "->", "container", "->", "getRequest", "(", ")", "->", "getRootUri", "(", "$", "this", "->", "getSetting", "(", "'debug'", ")", ")", ".", "$", "this", "->", "container", "->", "getRoute", "(", "$", "path", ")", "->", "getPatternUri", "(", ")", ";", "return", "(", "!", "empty", "(", "$", "params", ")", ")", "?", "$", "routeUrl", ".", "'?'", ".", "http_build_query", "(", "$", "params", ")", ":", "$", "routeUrl", ";", "break", ";", "}", "}" ]
Return the url for the path given @param string $path Path url path or Route name if type_name is not uri @param string $type_name Url type uri|route @param array $params Array params route @return string
[ "Return", "the", "url", "for", "the", "path", "given" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L620-L631
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.notFound
public function notFound($action = null) { $methods = array("get", "post", "put", "delete", "ajax", "options", "head", "mobile"); $route = new Route($methods, '*', $action, 'notFound'); $this->container->addRoute($route); return $route; }
php
public function notFound($action = null) { $methods = array("get", "post", "put", "delete", "ajax", "options", "head", "mobile"); $route = new Route($methods, '*', $action, 'notFound'); $this->container->addRoute($route); return $route; }
[ "public", "function", "notFound", "(", "$", "action", "=", "null", ")", "{", "$", "methods", "=", "array", "(", "\"get\"", ",", "\"post\"", ",", "\"put\"", ",", "\"delete\"", ",", "\"ajax\"", ",", "\"options\"", ",", "\"head\"", ",", "\"mobile\"", ")", ";", "$", "route", "=", "new", "Route", "(", "$", "methods", ",", "'*'", ",", "$", "action", ",", "'notFound'", ")", ";", "$", "this", "->", "container", "->", "addRoute", "(", "$", "route", ")", ";", "return", "$", "route", ";", "}" ]
Not Found Handler @access public @param string|\callable $action Anything that returns true for is_callable() @return Route
[ "Not", "Found", "Handler" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L652-L658
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.data
public function data($json = false) { return ($json) ? $this->container->getRequest()->data->JSON : $this->container->getRequest()->data; }
php
public function data($json = false) { return ($json) ? $this->container->getRequest()->data->JSON : $this->container->getRequest()->data; }
[ "public", "function", "data", "(", "$", "json", "=", "false", ")", "{", "return", "(", "$", "json", ")", "?", "$", "this", "->", "container", "->", "getRequest", "(", ")", "->", "data", "->", "JSON", ":", "$", "this", "->", "container", "->", "getRequest", "(", ")", "->", "data", ";", "}" ]
Get the data of request @access public @return \stdClass
[ "Get", "the", "data", "of", "request" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L677-L680
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.render
public function render($template, $data = array(), $status = null) { if (!is_null($status) && headers_sent() === false) { header($this->container->getResponse()->_convert_status($status)); } $this->container->getView()->display($template, $data); }
php
public function render($template, $data = array(), $status = null) { if (!is_null($status) && headers_sent() === false) { header($this->container->getResponse()->_convert_status($status)); } $this->container->getView()->display($template, $data); }
[ "public", "function", "render", "(", "$", "template", ",", "$", "data", "=", "array", "(", ")", ",", "$", "status", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "status", ")", "&&", "headers_sent", "(", ")", "===", "false", ")", "{", "header", "(", "$", "this", "->", "container", "->", "getResponse", "(", ")", "->", "_convert_status", "(", "$", "status", ")", ")", ";", "}", "$", "this", "->", "container", "->", "getView", "(", ")", "->", "display", "(", "$", "template", ",", "$", "data", ")", ";", "}" ]
Render the template @access public @param string $template @param array $data @param int $status @return void
[ "Render", "the", "template" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L724-L730
simple-php-mvc/simple-php-mvc
src/MVC/MVC.php
MVC.run
public function run(HttpRequest $request = null) { if (!$this->container->getSetting('debug')) { error_reporting(0); } else { error_reporting(E_ALL); } if (!$request) { $request = $this->container->getRequest(); } try { $parsed = $this->container->getRouter()->parse($request, $this->container->getRoutes()); if ($parsed['found'] || $this->container->hasRoute('notFound')) { if (is_string($parsed['action'])) { # Extract class controller and method list($controller, $method) = explode('::', $parsed['action']); # initialize arguments $arguments = array(); # Create a reflection method $reflectionMethod = new \ReflectionMethod($controller, $method); $reflectionParams = $reflectionMethod->getParameters(); # Create arguments foreach ($reflectionParams as $param) { if ($paramClass = $param->getClass()) { $className = $paramClass->name; if ($className === 'MVC\\MVC' || $className === '\\MVC\\MVC') { $arguments[] = $this; } elseif ($className === 'MVC\\Server\\HttpRequest' || $className === '\\MVC\\Server\\HttpRequest') { $arguments[] = $request; } } else { foreach ($parsed['params'] as $keyRouteParam => $valueRouteParam) { if ($param->name === $keyRouteParam) { $arguments[] = $valueRouteParam; break; } } } } $response = call_user_func_array($reflectionMethod->getClosure(new $controller()), $arguments); if (is_array($response) && !isset($response['body'])) { throw new \LogicException("Invalid response array. Array response haven't body. Expected array('body' => 'string')"); } elseif (is_string($response)) { $response = array('body' => $response); } } elseif(is_callable($parsed['action'])) { $this->container->getRequest()->params = $parsed['params']; $response = call_user_func_array($parsed['action'], array_values($parsed['params'])); } else { throw new \LogicException('Route haven\'t action.'); } if ($this->container->hasProvider('monolog')) { $this->container->providers['monolog']->addInfo($response, $parsed); } $this->container->getResponse()->render($response); } else { if ($this->container->getSetting('debug')) { throw new \LogicException(sprintf('Route or Resource "%s" not found.', $request->url)); } $this->defaultNotFound(); } } catch (\Exception $e) { Error::run($e); } }
php
public function run(HttpRequest $request = null) { if (!$this->container->getSetting('debug')) { error_reporting(0); } else { error_reporting(E_ALL); } if (!$request) { $request = $this->container->getRequest(); } try { $parsed = $this->container->getRouter()->parse($request, $this->container->getRoutes()); if ($parsed['found'] || $this->container->hasRoute('notFound')) { if (is_string($parsed['action'])) { # Extract class controller and method list($controller, $method) = explode('::', $parsed['action']); # initialize arguments $arguments = array(); # Create a reflection method $reflectionMethod = new \ReflectionMethod($controller, $method); $reflectionParams = $reflectionMethod->getParameters(); # Create arguments foreach ($reflectionParams as $param) { if ($paramClass = $param->getClass()) { $className = $paramClass->name; if ($className === 'MVC\\MVC' || $className === '\\MVC\\MVC') { $arguments[] = $this; } elseif ($className === 'MVC\\Server\\HttpRequest' || $className === '\\MVC\\Server\\HttpRequest') { $arguments[] = $request; } } else { foreach ($parsed['params'] as $keyRouteParam => $valueRouteParam) { if ($param->name === $keyRouteParam) { $arguments[] = $valueRouteParam; break; } } } } $response = call_user_func_array($reflectionMethod->getClosure(new $controller()), $arguments); if (is_array($response) && !isset($response['body'])) { throw new \LogicException("Invalid response array. Array response haven't body. Expected array('body' => 'string')"); } elseif (is_string($response)) { $response = array('body' => $response); } } elseif(is_callable($parsed['action'])) { $this->container->getRequest()->params = $parsed['params']; $response = call_user_func_array($parsed['action'], array_values($parsed['params'])); } else { throw new \LogicException('Route haven\'t action.'); } if ($this->container->hasProvider('monolog')) { $this->container->providers['monolog']->addInfo($response, $parsed); } $this->container->getResponse()->render($response); } else { if ($this->container->getSetting('debug')) { throw new \LogicException(sprintf('Route or Resource "%s" not found.', $request->url)); } $this->defaultNotFound(); } } catch (\Exception $e) { Error::run($e); } }
[ "public", "function", "run", "(", "HttpRequest", "$", "request", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "container", "->", "getSetting", "(", "'debug'", ")", ")", "{", "error_reporting", "(", "0", ")", ";", "}", "else", "{", "error_reporting", "(", "E_ALL", ")", ";", "}", "if", "(", "!", "$", "request", ")", "{", "$", "request", "=", "$", "this", "->", "container", "->", "getRequest", "(", ")", ";", "}", "try", "{", "$", "parsed", "=", "$", "this", "->", "container", "->", "getRouter", "(", ")", "->", "parse", "(", "$", "request", ",", "$", "this", "->", "container", "->", "getRoutes", "(", ")", ")", ";", "if", "(", "$", "parsed", "[", "'found'", "]", "||", "$", "this", "->", "container", "->", "hasRoute", "(", "'notFound'", ")", ")", "{", "if", "(", "is_string", "(", "$", "parsed", "[", "'action'", "]", ")", ")", "{", "# Extract class controller and method", "list", "(", "$", "controller", ",", "$", "method", ")", "=", "explode", "(", "'::'", ",", "$", "parsed", "[", "'action'", "]", ")", ";", "# initialize arguments", "$", "arguments", "=", "array", "(", ")", ";", "# Create a reflection method", "$", "reflectionMethod", "=", "new", "\\", "ReflectionMethod", "(", "$", "controller", ",", "$", "method", ")", ";", "$", "reflectionParams", "=", "$", "reflectionMethod", "->", "getParameters", "(", ")", ";", "# Create arguments", "foreach", "(", "$", "reflectionParams", "as", "$", "param", ")", "{", "if", "(", "$", "paramClass", "=", "$", "param", "->", "getClass", "(", ")", ")", "{", "$", "className", "=", "$", "paramClass", "->", "name", ";", "if", "(", "$", "className", "===", "'MVC\\\\MVC'", "||", "$", "className", "===", "'\\\\MVC\\\\MVC'", ")", "{", "$", "arguments", "[", "]", "=", "$", "this", ";", "}", "elseif", "(", "$", "className", "===", "'MVC\\\\Server\\\\HttpRequest'", "||", "$", "className", "===", "'\\\\MVC\\\\Server\\\\HttpRequest'", ")", "{", "$", "arguments", "[", "]", "=", "$", "request", ";", "}", "}", "else", "{", "foreach", "(", "$", "parsed", "[", "'params'", "]", "as", "$", "keyRouteParam", "=>", "$", "valueRouteParam", ")", "{", "if", "(", "$", "param", "->", "name", "===", "$", "keyRouteParam", ")", "{", "$", "arguments", "[", "]", "=", "$", "valueRouteParam", ";", "break", ";", "}", "}", "}", "}", "$", "response", "=", "call_user_func_array", "(", "$", "reflectionMethod", "->", "getClosure", "(", "new", "$", "controller", "(", ")", ")", ",", "$", "arguments", ")", ";", "if", "(", "is_array", "(", "$", "response", ")", "&&", "!", "isset", "(", "$", "response", "[", "'body'", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"Invalid response array. Array response haven't body. Expected array('body' => 'string')\"", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "response", ")", ")", "{", "$", "response", "=", "array", "(", "'body'", "=>", "$", "response", ")", ";", "}", "}", "elseif", "(", "is_callable", "(", "$", "parsed", "[", "'action'", "]", ")", ")", "{", "$", "this", "->", "container", "->", "getRequest", "(", ")", "->", "params", "=", "$", "parsed", "[", "'params'", "]", ";", "$", "response", "=", "call_user_func_array", "(", "$", "parsed", "[", "'action'", "]", ",", "array_values", "(", "$", "parsed", "[", "'params'", "]", ")", ")", ";", "}", "else", "{", "throw", "new", "\\", "LogicException", "(", "'Route haven\\'t action.'", ")", ";", "}", "if", "(", "$", "this", "->", "container", "->", "hasProvider", "(", "'monolog'", ")", ")", "{", "$", "this", "->", "container", "->", "providers", "[", "'monolog'", "]", "->", "addInfo", "(", "$", "response", ",", "$", "parsed", ")", ";", "}", "$", "this", "->", "container", "->", "getResponse", "(", ")", "->", "render", "(", "$", "response", ")", ";", "}", "else", "{", "if", "(", "$", "this", "->", "container", "->", "getSetting", "(", "'debug'", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Route or Resource \"%s\" not found.'", ",", "$", "request", "->", "url", ")", ")", ";", "}", "$", "this", "->", "defaultNotFound", "(", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "Error", "::", "run", "(", "$", "e", ")", ";", "}", "}" ]
Run the aplication @access public @return void
[ "Run", "the", "aplication" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/MVC.php#L738-L809
nguyenanhung/nusoap
src/nusoap_client_mime.php
nusoap_client_mime.addAttachment
function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = FALSE) { if (!$cid) { $cid = md5(uniqid(time())); } $info['data'] = $data; $info['filename'] = $filename; $info['contenttype'] = $contenttype; $info['cid'] = $cid; $this->requestAttachments[] = $info; return $cid; }
php
function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = FALSE) { if (!$cid) { $cid = md5(uniqid(time())); } $info['data'] = $data; $info['filename'] = $filename; $info['contenttype'] = $contenttype; $info['cid'] = $cid; $this->requestAttachments[] = $info; return $cid; }
[ "function", "addAttachment", "(", "$", "data", ",", "$", "filename", "=", "''", ",", "$", "contenttype", "=", "'application/octet-stream'", ",", "$", "cid", "=", "FALSE", ")", "{", "if", "(", "!", "$", "cid", ")", "{", "$", "cid", "=", "md5", "(", "uniqid", "(", "time", "(", ")", ")", ")", ";", "}", "$", "info", "[", "'data'", "]", "=", "$", "data", ";", "$", "info", "[", "'filename'", "]", "=", "$", "filename", ";", "$", "info", "[", "'contenttype'", "]", "=", "$", "contenttype", ";", "$", "info", "[", "'cid'", "]", "=", "$", "cid", ";", "$", "this", "->", "requestAttachments", "[", "]", "=", "$", "info", ";", "return", "$", "cid", ";", "}" ]
adds a MIME attachment to the current request. If the $data parameter contains an empty string, this method will read the contents of the file named by the $filename parameter. If the $cid parameter is false, this method will generate the cid. @param string $data The data of the attachment @param string $filename The filename of the attachment (default is empty string) @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) @param string $cid The content-id (cid) of the attachment (default is false) @return string The content-id (cid) of the attachment @access public
[ "adds", "a", "MIME", "attachment", "to", "the", "current", "request", "." ]
train
https://github.com/nguyenanhung/nusoap/blob/a9b4d98f4f3fe748f8e5d9f8091dfc53585d2556/src/nusoap_client_mime.php#L93-L107
nguyenanhung/nusoap
src/nusoap_client_mime.php
nusoap_server_mime.parseRequest
function parseRequest($headers, $data) { $this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); $this->requestAttachments = []; if (strstr($headers['content-type'], 'multipart/related')) { $this->debug('Decode multipart/related'); $input = ''; foreach ($headers as $k => $v) { $input .= "$k: $v\r\n"; } $params['input'] = $input . "\r\n" . $data; $params['include_bodies'] = TRUE; $params['decode_bodies'] = TRUE; $params['decode_headers'] = TRUE; $structure = Mail_mimeDecode::decode($params); foreach ($structure->parts as $part) { if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) { $this->debug('Have root part of type ' . $part->headers['content-type']); $return = parent::parseRequest($part->headers, $part->body); } else { $this->debug('Have an attachment of type ' . $part->headers['content-type']); $info['data'] = $part->body; $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; $info['contenttype'] = $part->headers['content-type']; $info['cid'] = $part->headers['content-id']; $this->requestAttachments[] = $info; } } if (isset($return)) { return $return; } $this->setError('No root part found in multipart/related content'); return; } $this->debug('Not multipart/related'); return parent::parseRequest($headers, $data); }
php
function parseRequest($headers, $data) { $this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); $this->requestAttachments = []; if (strstr($headers['content-type'], 'multipart/related')) { $this->debug('Decode multipart/related'); $input = ''; foreach ($headers as $k => $v) { $input .= "$k: $v\r\n"; } $params['input'] = $input . "\r\n" . $data; $params['include_bodies'] = TRUE; $params['decode_bodies'] = TRUE; $params['decode_headers'] = TRUE; $structure = Mail_mimeDecode::decode($params); foreach ($structure->parts as $part) { if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) { $this->debug('Have root part of type ' . $part->headers['content-type']); $return = parent::parseRequest($part->headers, $part->body); } else { $this->debug('Have an attachment of type ' . $part->headers['content-type']); $info['data'] = $part->body; $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; $info['contenttype'] = $part->headers['content-type']; $info['cid'] = $part->headers['content-id']; $this->requestAttachments[] = $info; } } if (isset($return)) { return $return; } $this->setError('No root part found in multipart/related content'); return; } $this->debug('Not multipart/related'); return parent::parseRequest($headers, $data); }
[ "function", "parseRequest", "(", "$", "headers", ",", "$", "data", ")", "{", "$", "this", "->", "debug", "(", "'Entering parseRequest() for payload of length '", ".", "strlen", "(", "$", "data", ")", ".", "' and type of '", ".", "$", "headers", "[", "'content-type'", "]", ")", ";", "$", "this", "->", "requestAttachments", "=", "[", "]", ";", "if", "(", "strstr", "(", "$", "headers", "[", "'content-type'", "]", ",", "'multipart/related'", ")", ")", "{", "$", "this", "->", "debug", "(", "'Decode multipart/related'", ")", ";", "$", "input", "=", "''", ";", "foreach", "(", "$", "headers", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "input", ".=", "\"$k: $v\\r\\n\"", ";", "}", "$", "params", "[", "'input'", "]", "=", "$", "input", ".", "\"\\r\\n\"", ".", "$", "data", ";", "$", "params", "[", "'include_bodies'", "]", "=", "TRUE", ";", "$", "params", "[", "'decode_bodies'", "]", "=", "TRUE", ";", "$", "params", "[", "'decode_headers'", "]", "=", "TRUE", ";", "$", "structure", "=", "Mail_mimeDecode", "::", "decode", "(", "$", "params", ")", ";", "foreach", "(", "$", "structure", "->", "parts", "as", "$", "part", ")", "{", "if", "(", "!", "isset", "(", "$", "part", "->", "disposition", ")", "&&", "(", "strstr", "(", "$", "part", "->", "headers", "[", "'content-type'", "]", ",", "'text/xml'", ")", ")", ")", "{", "$", "this", "->", "debug", "(", "'Have root part of type '", ".", "$", "part", "->", "headers", "[", "'content-type'", "]", ")", ";", "$", "return", "=", "parent", "::", "parseRequest", "(", "$", "part", "->", "headers", ",", "$", "part", "->", "body", ")", ";", "}", "else", "{", "$", "this", "->", "debug", "(", "'Have an attachment of type '", ".", "$", "part", "->", "headers", "[", "'content-type'", "]", ")", ";", "$", "info", "[", "'data'", "]", "=", "$", "part", "->", "body", ";", "$", "info", "[", "'filename'", "]", "=", "isset", "(", "$", "part", "->", "d_parameters", "[", "'filename'", "]", ")", "?", "$", "part", "->", "d_parameters", "[", "'filename'", "]", ":", "''", ";", "$", "info", "[", "'contenttype'", "]", "=", "$", "part", "->", "headers", "[", "'content-type'", "]", ";", "$", "info", "[", "'cid'", "]", "=", "$", "part", "->", "headers", "[", "'content-id'", "]", ";", "$", "this", "->", "requestAttachments", "[", "]", "=", "$", "info", ";", "}", "}", "if", "(", "isset", "(", "$", "return", ")", ")", "{", "return", "$", "return", ";", "}", "$", "this", "->", "setError", "(", "'No root part found in multipart/related content'", ")", ";", "return", ";", "}", "$", "this", "->", "debug", "(", "'Not multipart/related'", ")", ";", "return", "parent", "::", "parseRequest", "(", "$", "headers", ",", "$", "data", ")", ";", "}" ]
processes SOAP message received from client @param array $headers The HTTP headers @param string $data unprocessed request data from client @return mixed value of the message, decoded into a PHP type @access private
[ "processes", "SOAP", "message", "received", "from", "client" ]
train
https://github.com/nguyenanhung/nusoap/blob/a9b4d98f4f3fe748f8e5d9f8091dfc53585d2556/src/nusoap_client_mime.php#L485-L527
miisieq/InfaktClient
src/Infakt/Mapper/InvoiceMapper.php
InvoiceMapper.map
public function map($data): Invoice { $services = []; foreach ($data['services'] as $service) { $services[] = (new Invoice\Service()) ->setId((int) $service['id']) ->setName($service['name']) ->setTaxSymbol($service['tax_symbol']) ->setUnit($service['unit']) ->setQuantity((float) $service['quantity']) ->setUnitNetPrice($this->mapPrice($service['unit_net_price'])) ->setUnitNetPriceBeforeDiscount($this->mapPrice($service['unit_net_price_before_discount'])) ->setNetPrice($this->mapPrice($service['net_price'])) ->setGrossPrice($this->mapPrice($service['gross_price'])) ->setTaxPrice($this->mapPrice($service['tax_price'])) ->setSymbol($service['symbol']) ->setDiscount((float) $service['discount']); } $invoice = (new Invoice()) ->setId((int) $data['id']) ->setNumber($data['number']) ->setInvoiceDate($this->mapDate($data['invoice_date'])) ->setCurrency($data['currency']) ->setPaidPrice($this->mapPrice($data['paid_price'])) ->setNotes($data['notes']) ->setKind($data['kind']) ->setPaymentMethod($data['payment_method']) ->setSellerSignature($data['seller_signature']) ->setRecipientSignature($data['recipient_signature']) ->setSaleDate($this->mapDate($data['sale_date'])) ->setStatus($data['status']) ->setPaymentDate($this->mapDate($data['payment_date'])) ->setPaidDate($this->mapDate($data['paid_date'])) ->setNetPrice($this->mapPrice($data['net_price'])) ->setTaxPrice($this->mapPrice($data['tax_price'])) ->setGrossPrice($this->mapPrice($data['gross_price'])) ->setClientId($data['client_id'] ? (int) $data['client_id'] : null) ->setClientCompanyName($data['client_company_name']) ->setClientStreet($data['client_street']) ->setClientCity($data['client_city']) ->setClientPostCode($data['client_post_code']) ->setClientTaxCode($data['client_tax_code']) ->setClientCountry($data['client_country']) ->setBankAccount($data['bank_account']) ->setBankName($data['bank_name']) ->setSwift($data['swift']) ->setVatExemptionReason($data['vat_exemption_reason'] ?: null) ->setSaleDate($this->mapDate($data['sale_date'])) ->setSaleType($data['sale_type']) ->setInvoiceDateKind($data['invoice_date_kind']) ->setServices($services) ->setExtensions((new Invoice\Extension()) ->setPayment((new Invoice\Extension\Payment()) ->setLink($data['extensions']['payments']['link']) ->setAvailable($data['extensions']['payments']['available'])) ->setShare((new Invoice\Extension\Share()) ->setLink($data['extensions']['shares']['link']) ->setAvailable($data['extensions']['payments']['available']) ->setValidUntil($this->mapDate($data['extensions']['shares']['valid_until']))) ); return $invoice; }
php
public function map($data): Invoice { $services = []; foreach ($data['services'] as $service) { $services[] = (new Invoice\Service()) ->setId((int) $service['id']) ->setName($service['name']) ->setTaxSymbol($service['tax_symbol']) ->setUnit($service['unit']) ->setQuantity((float) $service['quantity']) ->setUnitNetPrice($this->mapPrice($service['unit_net_price'])) ->setUnitNetPriceBeforeDiscount($this->mapPrice($service['unit_net_price_before_discount'])) ->setNetPrice($this->mapPrice($service['net_price'])) ->setGrossPrice($this->mapPrice($service['gross_price'])) ->setTaxPrice($this->mapPrice($service['tax_price'])) ->setSymbol($service['symbol']) ->setDiscount((float) $service['discount']); } $invoice = (new Invoice()) ->setId((int) $data['id']) ->setNumber($data['number']) ->setInvoiceDate($this->mapDate($data['invoice_date'])) ->setCurrency($data['currency']) ->setPaidPrice($this->mapPrice($data['paid_price'])) ->setNotes($data['notes']) ->setKind($data['kind']) ->setPaymentMethod($data['payment_method']) ->setSellerSignature($data['seller_signature']) ->setRecipientSignature($data['recipient_signature']) ->setSaleDate($this->mapDate($data['sale_date'])) ->setStatus($data['status']) ->setPaymentDate($this->mapDate($data['payment_date'])) ->setPaidDate($this->mapDate($data['paid_date'])) ->setNetPrice($this->mapPrice($data['net_price'])) ->setTaxPrice($this->mapPrice($data['tax_price'])) ->setGrossPrice($this->mapPrice($data['gross_price'])) ->setClientId($data['client_id'] ? (int) $data['client_id'] : null) ->setClientCompanyName($data['client_company_name']) ->setClientStreet($data['client_street']) ->setClientCity($data['client_city']) ->setClientPostCode($data['client_post_code']) ->setClientTaxCode($data['client_tax_code']) ->setClientCountry($data['client_country']) ->setBankAccount($data['bank_account']) ->setBankName($data['bank_name']) ->setSwift($data['swift']) ->setVatExemptionReason($data['vat_exemption_reason'] ?: null) ->setSaleDate($this->mapDate($data['sale_date'])) ->setSaleType($data['sale_type']) ->setInvoiceDateKind($data['invoice_date_kind']) ->setServices($services) ->setExtensions((new Invoice\Extension()) ->setPayment((new Invoice\Extension\Payment()) ->setLink($data['extensions']['payments']['link']) ->setAvailable($data['extensions']['payments']['available'])) ->setShare((new Invoice\Extension\Share()) ->setLink($data['extensions']['shares']['link']) ->setAvailable($data['extensions']['payments']['available']) ->setValidUntil($this->mapDate($data['extensions']['shares']['valid_until']))) ); return $invoice; }
[ "public", "function", "map", "(", "$", "data", ")", ":", "Invoice", "{", "$", "services", "=", "[", "]", ";", "foreach", "(", "$", "data", "[", "'services'", "]", "as", "$", "service", ")", "{", "$", "services", "[", "]", "=", "(", "new", "Invoice", "\\", "Service", "(", ")", ")", "->", "setId", "(", "(", "int", ")", "$", "service", "[", "'id'", "]", ")", "->", "setName", "(", "$", "service", "[", "'name'", "]", ")", "->", "setTaxSymbol", "(", "$", "service", "[", "'tax_symbol'", "]", ")", "->", "setUnit", "(", "$", "service", "[", "'unit'", "]", ")", "->", "setQuantity", "(", "(", "float", ")", "$", "service", "[", "'quantity'", "]", ")", "->", "setUnitNetPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "service", "[", "'unit_net_price'", "]", ")", ")", "->", "setUnitNetPriceBeforeDiscount", "(", "$", "this", "->", "mapPrice", "(", "$", "service", "[", "'unit_net_price_before_discount'", "]", ")", ")", "->", "setNetPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "service", "[", "'net_price'", "]", ")", ")", "->", "setGrossPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "service", "[", "'gross_price'", "]", ")", ")", "->", "setTaxPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "service", "[", "'tax_price'", "]", ")", ")", "->", "setSymbol", "(", "$", "service", "[", "'symbol'", "]", ")", "->", "setDiscount", "(", "(", "float", ")", "$", "service", "[", "'discount'", "]", ")", ";", "}", "$", "invoice", "=", "(", "new", "Invoice", "(", ")", ")", "->", "setId", "(", "(", "int", ")", "$", "data", "[", "'id'", "]", ")", "->", "setNumber", "(", "$", "data", "[", "'number'", "]", ")", "->", "setInvoiceDate", "(", "$", "this", "->", "mapDate", "(", "$", "data", "[", "'invoice_date'", "]", ")", ")", "->", "setCurrency", "(", "$", "data", "[", "'currency'", "]", ")", "->", "setPaidPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "data", "[", "'paid_price'", "]", ")", ")", "->", "setNotes", "(", "$", "data", "[", "'notes'", "]", ")", "->", "setKind", "(", "$", "data", "[", "'kind'", "]", ")", "->", "setPaymentMethod", "(", "$", "data", "[", "'payment_method'", "]", ")", "->", "setSellerSignature", "(", "$", "data", "[", "'seller_signature'", "]", ")", "->", "setRecipientSignature", "(", "$", "data", "[", "'recipient_signature'", "]", ")", "->", "setSaleDate", "(", "$", "this", "->", "mapDate", "(", "$", "data", "[", "'sale_date'", "]", ")", ")", "->", "setStatus", "(", "$", "data", "[", "'status'", "]", ")", "->", "setPaymentDate", "(", "$", "this", "->", "mapDate", "(", "$", "data", "[", "'payment_date'", "]", ")", ")", "->", "setPaidDate", "(", "$", "this", "->", "mapDate", "(", "$", "data", "[", "'paid_date'", "]", ")", ")", "->", "setNetPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "data", "[", "'net_price'", "]", ")", ")", "->", "setTaxPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "data", "[", "'tax_price'", "]", ")", ")", "->", "setGrossPrice", "(", "$", "this", "->", "mapPrice", "(", "$", "data", "[", "'gross_price'", "]", ")", ")", "->", "setClientId", "(", "$", "data", "[", "'client_id'", "]", "?", "(", "int", ")", "$", "data", "[", "'client_id'", "]", ":", "null", ")", "->", "setClientCompanyName", "(", "$", "data", "[", "'client_company_name'", "]", ")", "->", "setClientStreet", "(", "$", "data", "[", "'client_street'", "]", ")", "->", "setClientCity", "(", "$", "data", "[", "'client_city'", "]", ")", "->", "setClientPostCode", "(", "$", "data", "[", "'client_post_code'", "]", ")", "->", "setClientTaxCode", "(", "$", "data", "[", "'client_tax_code'", "]", ")", "->", "setClientCountry", "(", "$", "data", "[", "'client_country'", "]", ")", "->", "setBankAccount", "(", "$", "data", "[", "'bank_account'", "]", ")", "->", "setBankName", "(", "$", "data", "[", "'bank_name'", "]", ")", "->", "setSwift", "(", "$", "data", "[", "'swift'", "]", ")", "->", "setVatExemptionReason", "(", "$", "data", "[", "'vat_exemption_reason'", "]", "?", ":", "null", ")", "->", "setSaleDate", "(", "$", "this", "->", "mapDate", "(", "$", "data", "[", "'sale_date'", "]", ")", ")", "->", "setSaleType", "(", "$", "data", "[", "'sale_type'", "]", ")", "->", "setInvoiceDateKind", "(", "$", "data", "[", "'invoice_date_kind'", "]", ")", "->", "setServices", "(", "$", "services", ")", "->", "setExtensions", "(", "(", "new", "Invoice", "\\", "Extension", "(", ")", ")", "->", "setPayment", "(", "(", "new", "Invoice", "\\", "Extension", "\\", "Payment", "(", ")", ")", "->", "setLink", "(", "$", "data", "[", "'extensions'", "]", "[", "'payments'", "]", "[", "'link'", "]", ")", "->", "setAvailable", "(", "$", "data", "[", "'extensions'", "]", "[", "'payments'", "]", "[", "'available'", "]", ")", ")", "->", "setShare", "(", "(", "new", "Invoice", "\\", "Extension", "\\", "Share", "(", ")", ")", "->", "setLink", "(", "$", "data", "[", "'extensions'", "]", "[", "'shares'", "]", "[", "'link'", "]", ")", "->", "setAvailable", "(", "$", "data", "[", "'extensions'", "]", "[", "'payments'", "]", "[", "'available'", "]", ")", "->", "setValidUntil", "(", "$", "this", "->", "mapDate", "(", "$", "data", "[", "'extensions'", "]", "[", "'shares'", "]", "[", "'valid_until'", "]", ")", ")", ")", ")", ";", "return", "$", "invoice", ";", "}" ]
Map array to Invoice object. @param $data @return Invoice
[ "Map", "array", "to", "Invoice", "object", "." ]
train
https://github.com/miisieq/InfaktClient/blob/5f0ae58c7be32580f3c92c2a7e7a7808d83d4e81/src/Infakt/Mapper/InvoiceMapper.php#L22-L86
miisieq/InfaktClient
src/Infakt/Mapper/InvoiceMapper.php
InvoiceMapper.reverseMap
public function reverseMap(EntityInterface $entity): array { /** @var $entity Invoice */ $services = []; foreach ($entity->getServices() as $service) { $services[] = [ 'id' => $service->getId(), 'name' => $service->getName(), 'tax_symbol' => $service->getTaxSymbol(), 'unit' => $service->getUnit(), 'quantity' => $this->reverseMapQuantity($service->getQuantity()), 'unit_net_price' => $this->reverseMapPrice($service->getUnitNetPrice()), 'net_price' => $this->reverseMapPrice($service->getNetPrice()), 'gross_price' => $this->reverseMapPrice($service->getGrossPrice()), 'tax_price' => $this->reverseMapPrice($service->getTaxPrice()), 'symbol' => $service->getSymbol(), 'discount' => $service->getDiscount(), 'unit_net_price_before_discount' => $this->reverseMapPrice($service->getUnitNetPriceBeforeDiscount()), ]; } return [ 'id' => $entity->getId(), 'number' => $entity->getNumber(), 'currency' => $entity->getCurrency(), 'paid_price' => $this->reverseMapPrice($entity->getPaidPrice()), 'notes' => $entity->getNotes(), 'kind' => $entity->getKind(), 'payment_method' => $entity->getPaymentMethod(), 'recipient_signature' => $entity->getRecipientSignature(), 'seller_signature' => $entity->getSellerSignature(), 'invoice_date' => $this->reverseMapDate($entity->getInvoiceDate()), 'sale_date' => $this->reverseMapDate($entity->getSaleDate()), 'status' => $entity->getStatus(), 'payment_date' => $this->reverseMapDate($entity->getPaymentDate()), 'paid_date' => $this->reverseMapDate($entity->getPaidDate()), 'net_price' => $this->reverseMapPrice($entity->getNetPrice()), 'tax_price' => $this->reverseMapPrice($entity->getTaxPrice()), 'gross_price' => $this->reverseMapPrice($entity->getGrossPrice()), 'client_id' => $entity->getClientId(), 'client_company_name' => $entity->getClientCompanyName(), 'client_street' => $entity->getClientStreet(), 'client_city' => $entity->getClientCity(), 'client_post_code' => $entity->getClientPostCode(), 'client_tax_code' => $entity->getClientTaxCode(), 'client_country' => $entity->getClientCountry(), 'bank_name' => $entity->getBankName(), 'bank_account' => $entity->getBankAccount(), 'swift' => $entity->getSwift(), 'vat_exemption_reason' => $entity->getVatExemptionReason(), 'sale_type' => $entity->getSaleType(), 'invoice_date_kind' => $entity->getInvoiceDateKind(), 'services' => $services, ]; }
php
public function reverseMap(EntityInterface $entity): array { /** @var $entity Invoice */ $services = []; foreach ($entity->getServices() as $service) { $services[] = [ 'id' => $service->getId(), 'name' => $service->getName(), 'tax_symbol' => $service->getTaxSymbol(), 'unit' => $service->getUnit(), 'quantity' => $this->reverseMapQuantity($service->getQuantity()), 'unit_net_price' => $this->reverseMapPrice($service->getUnitNetPrice()), 'net_price' => $this->reverseMapPrice($service->getNetPrice()), 'gross_price' => $this->reverseMapPrice($service->getGrossPrice()), 'tax_price' => $this->reverseMapPrice($service->getTaxPrice()), 'symbol' => $service->getSymbol(), 'discount' => $service->getDiscount(), 'unit_net_price_before_discount' => $this->reverseMapPrice($service->getUnitNetPriceBeforeDiscount()), ]; } return [ 'id' => $entity->getId(), 'number' => $entity->getNumber(), 'currency' => $entity->getCurrency(), 'paid_price' => $this->reverseMapPrice($entity->getPaidPrice()), 'notes' => $entity->getNotes(), 'kind' => $entity->getKind(), 'payment_method' => $entity->getPaymentMethod(), 'recipient_signature' => $entity->getRecipientSignature(), 'seller_signature' => $entity->getSellerSignature(), 'invoice_date' => $this->reverseMapDate($entity->getInvoiceDate()), 'sale_date' => $this->reverseMapDate($entity->getSaleDate()), 'status' => $entity->getStatus(), 'payment_date' => $this->reverseMapDate($entity->getPaymentDate()), 'paid_date' => $this->reverseMapDate($entity->getPaidDate()), 'net_price' => $this->reverseMapPrice($entity->getNetPrice()), 'tax_price' => $this->reverseMapPrice($entity->getTaxPrice()), 'gross_price' => $this->reverseMapPrice($entity->getGrossPrice()), 'client_id' => $entity->getClientId(), 'client_company_name' => $entity->getClientCompanyName(), 'client_street' => $entity->getClientStreet(), 'client_city' => $entity->getClientCity(), 'client_post_code' => $entity->getClientPostCode(), 'client_tax_code' => $entity->getClientTaxCode(), 'client_country' => $entity->getClientCountry(), 'bank_name' => $entity->getBankName(), 'bank_account' => $entity->getBankAccount(), 'swift' => $entity->getSwift(), 'vat_exemption_reason' => $entity->getVatExemptionReason(), 'sale_type' => $entity->getSaleType(), 'invoice_date_kind' => $entity->getInvoiceDateKind(), 'services' => $services, ]; }
[ "public", "function", "reverseMap", "(", "EntityInterface", "$", "entity", ")", ":", "array", "{", "/** @var $entity Invoice */", "$", "services", "=", "[", "]", ";", "foreach", "(", "$", "entity", "->", "getServices", "(", ")", "as", "$", "service", ")", "{", "$", "services", "[", "]", "=", "[", "'id'", "=>", "$", "service", "->", "getId", "(", ")", ",", "'name'", "=>", "$", "service", "->", "getName", "(", ")", ",", "'tax_symbol'", "=>", "$", "service", "->", "getTaxSymbol", "(", ")", ",", "'unit'", "=>", "$", "service", "->", "getUnit", "(", ")", ",", "'quantity'", "=>", "$", "this", "->", "reverseMapQuantity", "(", "$", "service", "->", "getQuantity", "(", ")", ")", ",", "'unit_net_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "service", "->", "getUnitNetPrice", "(", ")", ")", ",", "'net_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "service", "->", "getNetPrice", "(", ")", ")", ",", "'gross_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "service", "->", "getGrossPrice", "(", ")", ")", ",", "'tax_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "service", "->", "getTaxPrice", "(", ")", ")", ",", "'symbol'", "=>", "$", "service", "->", "getSymbol", "(", ")", ",", "'discount'", "=>", "$", "service", "->", "getDiscount", "(", ")", ",", "'unit_net_price_before_discount'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "service", "->", "getUnitNetPriceBeforeDiscount", "(", ")", ")", ",", "]", ";", "}", "return", "[", "'id'", "=>", "$", "entity", "->", "getId", "(", ")", ",", "'number'", "=>", "$", "entity", "->", "getNumber", "(", ")", ",", "'currency'", "=>", "$", "entity", "->", "getCurrency", "(", ")", ",", "'paid_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "entity", "->", "getPaidPrice", "(", ")", ")", ",", "'notes'", "=>", "$", "entity", "->", "getNotes", "(", ")", ",", "'kind'", "=>", "$", "entity", "->", "getKind", "(", ")", ",", "'payment_method'", "=>", "$", "entity", "->", "getPaymentMethod", "(", ")", ",", "'recipient_signature'", "=>", "$", "entity", "->", "getRecipientSignature", "(", ")", ",", "'seller_signature'", "=>", "$", "entity", "->", "getSellerSignature", "(", ")", ",", "'invoice_date'", "=>", "$", "this", "->", "reverseMapDate", "(", "$", "entity", "->", "getInvoiceDate", "(", ")", ")", ",", "'sale_date'", "=>", "$", "this", "->", "reverseMapDate", "(", "$", "entity", "->", "getSaleDate", "(", ")", ")", ",", "'status'", "=>", "$", "entity", "->", "getStatus", "(", ")", ",", "'payment_date'", "=>", "$", "this", "->", "reverseMapDate", "(", "$", "entity", "->", "getPaymentDate", "(", ")", ")", ",", "'paid_date'", "=>", "$", "this", "->", "reverseMapDate", "(", "$", "entity", "->", "getPaidDate", "(", ")", ")", ",", "'net_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "entity", "->", "getNetPrice", "(", ")", ")", ",", "'tax_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "entity", "->", "getTaxPrice", "(", ")", ")", ",", "'gross_price'", "=>", "$", "this", "->", "reverseMapPrice", "(", "$", "entity", "->", "getGrossPrice", "(", ")", ")", ",", "'client_id'", "=>", "$", "entity", "->", "getClientId", "(", ")", ",", "'client_company_name'", "=>", "$", "entity", "->", "getClientCompanyName", "(", ")", ",", "'client_street'", "=>", "$", "entity", "->", "getClientStreet", "(", ")", ",", "'client_city'", "=>", "$", "entity", "->", "getClientCity", "(", ")", ",", "'client_post_code'", "=>", "$", "entity", "->", "getClientPostCode", "(", ")", ",", "'client_tax_code'", "=>", "$", "entity", "->", "getClientTaxCode", "(", ")", ",", "'client_country'", "=>", "$", "entity", "->", "getClientCountry", "(", ")", ",", "'bank_name'", "=>", "$", "entity", "->", "getBankName", "(", ")", ",", "'bank_account'", "=>", "$", "entity", "->", "getBankAccount", "(", ")", ",", "'swift'", "=>", "$", "entity", "->", "getSwift", "(", ")", ",", "'vat_exemption_reason'", "=>", "$", "entity", "->", "getVatExemptionReason", "(", ")", ",", "'sale_type'", "=>", "$", "entity", "->", "getSaleType", "(", ")", ",", "'invoice_date_kind'", "=>", "$", "entity", "->", "getInvoiceDateKind", "(", ")", ",", "'services'", "=>", "$", "services", ",", "]", ";", "}" ]
@param EntityInterface $entity @return array
[ "@param", "EntityInterface", "$entity" ]
train
https://github.com/miisieq/InfaktClient/blob/5f0ae58c7be32580f3c92c2a7e7a7808d83d4e81/src/Infakt/Mapper/InvoiceMapper.php#L93-L148
spiral-modules/auth
source/Auth/Middlewares/Firewalls/HttpAuthFirewall.php
HttpAuthFirewall.withRealm
public function withRealm(string $realm): self { $middleware = clone $this; $middleware->realm = $realm; return $middleware; }
php
public function withRealm(string $realm): self { $middleware = clone $this; $middleware->realm = $realm; return $middleware; }
[ "public", "function", "withRealm", "(", "string", "$", "realm", ")", ":", "self", "{", "$", "middleware", "=", "clone", "$", "this", ";", "$", "middleware", "->", "realm", "=", "$", "realm", ";", "return", "$", "middleware", ";", "}" ]
@param string $realm @return HttpAuthFirewall
[ "@param", "string", "$realm" ]
train
https://github.com/spiral-modules/auth/blob/24e2070028f7257e8192914556963a4794428a99/source/Auth/Middlewares/Firewalls/HttpAuthFirewall.php#L35-L41
spiral-modules/auth
source/Auth/Middlewares/Firewalls/HttpAuthFirewall.php
HttpAuthFirewall.denyAccess
public function denyAccess(Request $request, Response $response, callable $next) { return $response->withStatus(401)->withHeader( 'WWW-Authenticate', sprintf('Basic realm="%s"', $this->realm) ); }
php
public function denyAccess(Request $request, Response $response, callable $next) { return $response->withStatus(401)->withHeader( 'WWW-Authenticate', sprintf('Basic realm="%s"', $this->realm) ); }
[ "public", "function", "denyAccess", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "callable", "$", "next", ")", "{", "return", "$", "response", "->", "withStatus", "(", "401", ")", "->", "withHeader", "(", "'WWW-Authenticate'", ",", "sprintf", "(", "'Basic realm=\"%s\"'", ",", "$", "this", "->", "realm", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/spiral-modules/auth/blob/24e2070028f7257e8192914556963a4794428a99/source/Auth/Middlewares/Firewalls/HttpAuthFirewall.php#L46-L52
sparwelt/imgix-lib
src/ImgixServiceFactory.php
ImgixServiceFactory.createFromConfiguration
public static function createFromConfiguration(array $cdnConfiguration, array $filtersConfigurations = []) { $cdnSelector = new CdnSelector(...CdnConfigurationParser::parseArray($cdnConfiguration)); $urlGenerator = new ImgixUrlGenerator($cdnSelector); $attributeGenerator = new AttributeGenerator($urlGenerator); $imageRenderer = new ImageRenderer(); $imageTransformer = new ImageTransformer($attributeGenerator, $imageRenderer); $imageGenerator = new ImageGenerator($attributeGenerator, $imageRenderer); $htmlConverter = new HtmlTransformer($imageTransformer); return new ImgixService($urlGenerator, $attributeGenerator, $imageGenerator, $htmlConverter, $filtersConfigurations); }
php
public static function createFromConfiguration(array $cdnConfiguration, array $filtersConfigurations = []) { $cdnSelector = new CdnSelector(...CdnConfigurationParser::parseArray($cdnConfiguration)); $urlGenerator = new ImgixUrlGenerator($cdnSelector); $attributeGenerator = new AttributeGenerator($urlGenerator); $imageRenderer = new ImageRenderer(); $imageTransformer = new ImageTransformer($attributeGenerator, $imageRenderer); $imageGenerator = new ImageGenerator($attributeGenerator, $imageRenderer); $htmlConverter = new HtmlTransformer($imageTransformer); return new ImgixService($urlGenerator, $attributeGenerator, $imageGenerator, $htmlConverter, $filtersConfigurations); }
[ "public", "static", "function", "createFromConfiguration", "(", "array", "$", "cdnConfiguration", ",", "array", "$", "filtersConfigurations", "=", "[", "]", ")", "{", "$", "cdnSelector", "=", "new", "CdnSelector", "(", "...", "CdnConfigurationParser", "::", "parseArray", "(", "$", "cdnConfiguration", ")", ")", ";", "$", "urlGenerator", "=", "new", "ImgixUrlGenerator", "(", "$", "cdnSelector", ")", ";", "$", "attributeGenerator", "=", "new", "AttributeGenerator", "(", "$", "urlGenerator", ")", ";", "$", "imageRenderer", "=", "new", "ImageRenderer", "(", ")", ";", "$", "imageTransformer", "=", "new", "ImageTransformer", "(", "$", "attributeGenerator", ",", "$", "imageRenderer", ")", ";", "$", "imageGenerator", "=", "new", "ImageGenerator", "(", "$", "attributeGenerator", ",", "$", "imageRenderer", ")", ";", "$", "htmlConverter", "=", "new", "HtmlTransformer", "(", "$", "imageTransformer", ")", ";", "return", "new", "ImgixService", "(", "$", "urlGenerator", ",", "$", "attributeGenerator", ",", "$", "imageGenerator", ",", "$", "htmlConverter", ",", "$", "filtersConfigurations", ")", ";", "}" ]
@param array $cdnConfiguration @param array $filtersConfigurations @return ImgixService
[ "@param", "array", "$cdnConfiguration", "@param", "array", "$filtersConfigurations" ]
train
https://github.com/sparwelt/imgix-lib/blob/330e1db2bed71bc283e5a2da6246528f240939ec/src/ImgixServiceFactory.php#L27-L39
phpmob/changmin
src/PhpMob/CmsBundle/LocaleLoader/DatabaseLoader.php
DatabaseLoader.load
public function load($resource, $localeCode, $domain = 'messages') { $catalogue = new MessageCatalogue($localeCode); /** @var LocaleInterface $locale */ try { if (!$locale = $this->localeRepository->findOneBy(['code' => $localeCode])) { return $catalogue; } } catch (\Exception $e) { return $catalogue; } $translations = $locale->getTranslations(); if (!array_key_exists($domain, $translations)) { return $catalogue; } $translations = $translations[$domain]; $this->flatten($translations); foreach ($translations as $key => $message) { $catalogue->set($key, $message, $domain); } return $catalogue; }
php
public function load($resource, $localeCode, $domain = 'messages') { $catalogue = new MessageCatalogue($localeCode); /** @var LocaleInterface $locale */ try { if (!$locale = $this->localeRepository->findOneBy(['code' => $localeCode])) { return $catalogue; } } catch (\Exception $e) { return $catalogue; } $translations = $locale->getTranslations(); if (!array_key_exists($domain, $translations)) { return $catalogue; } $translations = $translations[$domain]; $this->flatten($translations); foreach ($translations as $key => $message) { $catalogue->set($key, $message, $domain); } return $catalogue; }
[ "public", "function", "load", "(", "$", "resource", ",", "$", "localeCode", ",", "$", "domain", "=", "'messages'", ")", "{", "$", "catalogue", "=", "new", "MessageCatalogue", "(", "$", "localeCode", ")", ";", "/** @var LocaleInterface $locale */", "try", "{", "if", "(", "!", "$", "locale", "=", "$", "this", "->", "localeRepository", "->", "findOneBy", "(", "[", "'code'", "=>", "$", "localeCode", "]", ")", ")", "{", "return", "$", "catalogue", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "$", "catalogue", ";", "}", "$", "translations", "=", "$", "locale", "->", "getTranslations", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "domain", ",", "$", "translations", ")", ")", "{", "return", "$", "catalogue", ";", "}", "$", "translations", "=", "$", "translations", "[", "$", "domain", "]", ";", "$", "this", "->", "flatten", "(", "$", "translations", ")", ";", "foreach", "(", "$", "translations", "as", "$", "key", "=>", "$", "message", ")", "{", "$", "catalogue", "->", "set", "(", "$", "key", ",", "$", "message", ",", "$", "domain", ")", ";", "}", "return", "$", "catalogue", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/CmsBundle/LocaleLoader/DatabaseLoader.php#L39-L67
rayrutjes/domain-foundation
src/Command/Handler/Registry/InMemoryCommandHandlerRegistry.php
InMemoryCommandHandlerRegistry.findCommandHandlerFor
public function findCommandHandlerFor(Command $command) { if (!isset($this->subscriptions[$command->commandName()])) { throw new CommandHandlerNotFoundException(sprintf('No handler was found for command %s', $command->commandName())); } return $this->subscriptions[$command->commandName()]; }
php
public function findCommandHandlerFor(Command $command) { if (!isset($this->subscriptions[$command->commandName()])) { throw new CommandHandlerNotFoundException(sprintf('No handler was found for command %s', $command->commandName())); } return $this->subscriptions[$command->commandName()]; }
[ "public", "function", "findCommandHandlerFor", "(", "Command", "$", "command", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "subscriptions", "[", "$", "command", "->", "commandName", "(", ")", "]", ")", ")", "{", "throw", "new", "CommandHandlerNotFoundException", "(", "sprintf", "(", "'No handler was found for command %s'", ",", "$", "command", "->", "commandName", "(", ")", ")", ")", ";", "}", "return", "$", "this", "->", "subscriptions", "[", "$", "command", "->", "commandName", "(", ")", "]", ";", "}" ]
@param Command $command @return CommandHandler @throws CommandHandlerNotFoundException
[ "@param", "Command", "$command" ]
train
https://github.com/rayrutjes/domain-foundation/blob/2bce7cd6a6612f718e70e3176589c1abf39d1a3e/src/Command/Handler/Registry/InMemoryCommandHandlerRegistry.php#L22-L29
devture/form
src/Devture/Component/Form/Validator/EmailValidator.php
EmailValidator.isValid
static public function isValid($email): bool { $atIndex = strrpos($email, '@'); if ($atIndex === false) { return false; } $domain = substr($email, $atIndex + 1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); if ($localLen < 1 || $localLen > 64) { // local part length exceeded return false; } $domainLen = strlen($domain); if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded return false; } if ($local[0] == '.' || $local[$localLen - 1] == '.') { // local part starts or ends with '.' return false; } if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots return false; } //Domain labels ..blah blah.., ending with an alphabetic or numeric character (RFC 1035 2.3.1). $lastDomainChar = $domain[$domainLen - 1]; if (!preg_match("/^[a-zA-Z0-9]$/", $lastDomainChar)) { return false; } if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part return false; } if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots return false; } if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) { return false; } } //An MX or an A record are both valid //If there's no MX record, email is sent to the same domain by default. $hasRecordMx = checkdnsrr($domain, 'MX'); if ($hasRecordMx) { return true; } //Checking for `invalid-domain.com` will return A matches for `invalid-domain.com.net` and similar //It's some dumb suggestion technique or something //These matches can be seen when running dns_get_record($domain, DNS_A); //To avoid them, we simply add a dot at the end of the domain name, //which tells it that it's FINAL and we don't want "suggestions". $hasRecordA = checkdnsrr($domain . '.', 'A'); if ($hasRecordA) { return true; } return false; }
php
static public function isValid($email): bool { $atIndex = strrpos($email, '@'); if ($atIndex === false) { return false; } $domain = substr($email, $atIndex + 1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); if ($localLen < 1 || $localLen > 64) { // local part length exceeded return false; } $domainLen = strlen($domain); if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded return false; } if ($local[0] == '.' || $local[$localLen - 1] == '.') { // local part starts or ends with '.' return false; } if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots return false; } //Domain labels ..blah blah.., ending with an alphabetic or numeric character (RFC 1035 2.3.1). $lastDomainChar = $domain[$domainLen - 1]; if (!preg_match("/^[a-zA-Z0-9]$/", $lastDomainChar)) { return false; } if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part return false; } if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots return false; } if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\", "", $local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\", "", $local))) { return false; } } //An MX or an A record are both valid //If there's no MX record, email is sent to the same domain by default. $hasRecordMx = checkdnsrr($domain, 'MX'); if ($hasRecordMx) { return true; } //Checking for `invalid-domain.com` will return A matches for `invalid-domain.com.net` and similar //It's some dumb suggestion technique or something //These matches can be seen when running dns_get_record($domain, DNS_A); //To avoid them, we simply add a dot at the end of the domain name, //which tells it that it's FINAL and we don't want "suggestions". $hasRecordA = checkdnsrr($domain . '.', 'A'); if ($hasRecordA) { return true; } return false; }
[ "static", "public", "function", "isValid", "(", "$", "email", ")", ":", "bool", "{", "$", "atIndex", "=", "strrpos", "(", "$", "email", ",", "'@'", ")", ";", "if", "(", "$", "atIndex", "===", "false", ")", "{", "return", "false", ";", "}", "$", "domain", "=", "substr", "(", "$", "email", ",", "$", "atIndex", "+", "1", ")", ";", "$", "local", "=", "substr", "(", "$", "email", ",", "0", ",", "$", "atIndex", ")", ";", "$", "localLen", "=", "strlen", "(", "$", "local", ")", ";", "if", "(", "$", "localLen", "<", "1", "||", "$", "localLen", ">", "64", ")", "{", "// local part length exceeded", "return", "false", ";", "}", "$", "domainLen", "=", "strlen", "(", "$", "domain", ")", ";", "if", "(", "$", "domainLen", "<", "1", "||", "$", "domainLen", ">", "255", ")", "{", "// domain part length exceeded", "return", "false", ";", "}", "if", "(", "$", "local", "[", "0", "]", "==", "'.'", "||", "$", "local", "[", "$", "localLen", "-", "1", "]", "==", "'.'", ")", "{", "// local part starts or ends with '.'", "return", "false", ";", "}", "if", "(", "preg_match", "(", "'/\\\\.\\\\./'", ",", "$", "local", ")", ")", "{", "// local part has two consecutive dots", "return", "false", ";", "}", "//Domain labels ..blah blah.., ending with an alphabetic or numeric character (RFC 1035 2.3.1).", "$", "lastDomainChar", "=", "$", "domain", "[", "$", "domainLen", "-", "1", "]", ";", "if", "(", "!", "preg_match", "(", "\"/^[a-zA-Z0-9]$/\"", ",", "$", "lastDomainChar", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "preg_match", "(", "'/^[A-Za-z0-9\\\\-\\\\.]+$/'", ",", "$", "domain", ")", ")", "{", "// character not valid in domain part", "return", "false", ";", "}", "if", "(", "preg_match", "(", "'/\\\\.\\\\./'", ",", "$", "domain", ")", ")", "{", "// domain part has two consecutive dots", "return", "false", ";", "}", "if", "(", "!", "preg_match", "(", "'/^(\\\\\\\\.|[A-Za-z0-9!#%&`_=\\\\/$\\'*+?^{}|~.-])+$/'", ",", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\"", ",", "$", "local", ")", ")", ")", "{", "// character not valid in local part unless", "// local part is quoted", "if", "(", "!", "preg_match", "(", "'/^\"(\\\\\\\\\"|[^\"])+\"$/'", ",", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\"", ",", "$", "local", ")", ")", ")", "{", "return", "false", ";", "}", "}", "//An MX or an A record are both valid", "//If there's no MX record, email is sent to the same domain by default.", "$", "hasRecordMx", "=", "checkdnsrr", "(", "$", "domain", ",", "'MX'", ")", ";", "if", "(", "$", "hasRecordMx", ")", "{", "return", "true", ";", "}", "//Checking for `invalid-domain.com` will return A matches for `invalid-domain.com.net` and similar", "//It's some dumb suggestion technique or something", "//These matches can be seen when running dns_get_record($domain, DNS_A);", "//To avoid them, we simply add a dot at the end of the domain name,", "//which tells it that it's FINAL and we don't want \"suggestions\".", "$", "hasRecordA", "=", "checkdnsrr", "(", "$", "domain", ".", "'.'", ",", "'A'", ")", ";", "if", "(", "$", "hasRecordA", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks whether the specified email looks legit. It first checks whether the email format is valid, and then uses some DNS checks to ensure the specified domain has an MX or an A record (both are considered valid). - May cause slowdown, because of DNS checks - Will report an email as invalid if the DNS system fails - Reports all domains as valid when using OpenDNS or a similar DNS service (every invalid domain resolves to opendns' IP address) @param string $email @return boolean
[ "Checks", "whether", "the", "specified", "email", "looks", "legit", ".", "It", "first", "checks", "whether", "the", "email", "format", "is", "valid", "and", "then", "uses", "some", "DNS", "checks", "to", "ensure", "the", "specified", "domain", "has", "an", "MX", "or", "an", "A", "record", "(", "both", "are", "considered", "valid", ")", ".", "-", "May", "cause", "slowdown", "because", "of", "DNS", "checks", "-", "Will", "report", "an", "email", "as", "invalid", "if", "the", "DNS", "system", "fails", "-", "Reports", "all", "domains", "as", "valid", "when", "using", "OpenDNS", "or", "a", "similar", "DNS", "service", "(", "every", "invalid", "domain", "resolves", "to", "opendns", "IP", "address", ")" ]
train
https://github.com/devture/form/blob/ecdba7a35ce76237965fef96bb4a960b855a7b36/src/Devture/Component/Form/Validator/EmailValidator.php#L17-L91
kevintweber/phpunit-markup-validators
src/Kevintweber/PhpunitMarkupValidators/Connector/Connector.php
Connector.execute
public function execute($type) { switch (strtolower($type)) { case 'markup': $curlOptArray = $this->getMarkupOpts(); break; case 'file': $curlOptArray = $this->getFileOpts(); break; case 'url': $curlOptArray = $this->getUrlOpts(); break; default: throw new \PHPUnit_Framework_Exception('Invalid type: '.$type); break; } $curlOptArray = $curlOptArray + array(CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ); // Throttle calls (if necessary). Throttle::delay(get_class($this)); $curl = curl_init(); curl_setopt_array($curl, $curlOptArray); if (!$response = curl_exec($curl)) { throw new \PHPUnit_Framework_Exception('Unable to validate. Error: '. curl_error($curl)); } curl_close($curl); return $response; }
php
public function execute($type) { switch (strtolower($type)) { case 'markup': $curlOptArray = $this->getMarkupOpts(); break; case 'file': $curlOptArray = $this->getFileOpts(); break; case 'url': $curlOptArray = $this->getUrlOpts(); break; default: throw new \PHPUnit_Framework_Exception('Invalid type: '.$type); break; } $curlOptArray = $curlOptArray + array(CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ); // Throttle calls (if necessary). Throttle::delay(get_class($this)); $curl = curl_init(); curl_setopt_array($curl, $curlOptArray); if (!$response = curl_exec($curl)) { throw new \PHPUnit_Framework_Exception('Unable to validate. Error: '. curl_error($curl)); } curl_close($curl); return $response; }
[ "public", "function", "execute", "(", "$", "type", ")", "{", "switch", "(", "strtolower", "(", "$", "type", ")", ")", "{", "case", "'markup'", ":", "$", "curlOptArray", "=", "$", "this", "->", "getMarkupOpts", "(", ")", ";", "break", ";", "case", "'file'", ":", "$", "curlOptArray", "=", "$", "this", "->", "getFileOpts", "(", ")", ";", "break", ";", "case", "'url'", ":", "$", "curlOptArray", "=", "$", "this", "->", "getUrlOpts", "(", ")", ";", "break", ";", "default", ":", "throw", "new", "\\", "PHPUnit_Framework_Exception", "(", "'Invalid type: '", ".", "$", "type", ")", ";", "break", ";", "}", "$", "curlOptArray", "=", "$", "curlOptArray", "+", "array", "(", "CURLOPT_RETURNTRANSFER", "=>", "true", ",", "CURLOPT_TIMEOUT", "=>", "10", ",", ")", ";", "// Throttle calls (if necessary).", "Throttle", "::", "delay", "(", "get_class", "(", "$", "this", ")", ")", ";", "$", "curl", "=", "curl_init", "(", ")", ";", "curl_setopt_array", "(", "$", "curl", ",", "$", "curlOptArray", ")", ";", "if", "(", "!", "$", "response", "=", "curl_exec", "(", "$", "curl", ")", ")", "{", "throw", "new", "\\", "PHPUnit_Framework_Exception", "(", "'Unable to validate. Error: '", ".", "curl_error", "(", "$", "curl", ")", ")", ";", "}", "curl_close", "(", "$", "curl", ")", ";", "return", "$", "response", ";", "}" ]
Will execute a cURL request. @param string $type The type of input. @return mixed The response from the web service.
[ "Will", "execute", "a", "cURL", "request", "." ]
train
https://github.com/kevintweber/phpunit-markup-validators/blob/bee48f48c7c1c9e811d1a4bedeca8f413d049cb3/src/Kevintweber/PhpunitMarkupValidators/Connector/Connector.php#L29-L66
kevintweber/phpunit-markup-validators
src/Kevintweber/PhpunitMarkupValidators/Connector/Connector.php
Connector.setUrl
public function setUrl($value) { if (filter_var($value, FILTER_VALIDATE_URL) === false) { throw new \PHPUnit_Framework_Exception("Url is not valid.\n"); } $this->url = $value; }
php
public function setUrl($value) { if (filter_var($value, FILTER_VALIDATE_URL) === false) { throw new \PHPUnit_Framework_Exception("Url is not valid.\n"); } $this->url = $value; }
[ "public", "function", "setUrl", "(", "$", "value", ")", "{", "if", "(", "filter_var", "(", "$", "value", ",", "FILTER_VALIDATE_URL", ")", "===", "false", ")", "{", "throw", "new", "\\", "PHPUnit_Framework_Exception", "(", "\"Url is not valid.\\n\"", ")", ";", "}", "$", "this", "->", "url", "=", "$", "value", ";", "}" ]
Setter for 'url'. @param string $value The new value of 'url'
[ "Setter", "for", "url", "." ]
train
https://github.com/kevintweber/phpunit-markup-validators/blob/bee48f48c7c1c9e811d1a4bedeca8f413d049cb3/src/Kevintweber/PhpunitMarkupValidators/Connector/Connector.php#L148-L155
boekkooi/tactician-amqp
src/Middleware/EnvelopeTransformerMiddleware.php
EnvelopeTransformerMiddleware.execute
public function execute($command, callable $next) { if ($command instanceof Command) { $command = $this->transformer->transformEnvelopeToCommand($command->getEnvelope()); } elseif ($command instanceof \AMQPEnvelope) { $command = $this->transformer->transformEnvelopeToCommand($command); } return $next($command); }
php
public function execute($command, callable $next) { if ($command instanceof Command) { $command = $this->transformer->transformEnvelopeToCommand($command->getEnvelope()); } elseif ($command instanceof \AMQPEnvelope) { $command = $this->transformer->transformEnvelopeToCommand($command); } return $next($command); }
[ "public", "function", "execute", "(", "$", "command", ",", "callable", "$", "next", ")", "{", "if", "(", "$", "command", "instanceof", "Command", ")", "{", "$", "command", "=", "$", "this", "->", "transformer", "->", "transformEnvelopeToCommand", "(", "$", "command", "->", "getEnvelope", "(", ")", ")", ";", "}", "elseif", "(", "$", "command", "instanceof", "\\", "AMQPEnvelope", ")", "{", "$", "command", "=", "$", "this", "->", "transformer", "->", "transformEnvelopeToCommand", "(", "$", "command", ")", ";", "}", "return", "$", "next", "(", "$", "command", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/boekkooi/tactician-amqp/blob/55cbb8b9e20aab7891e6a6090b248377c599360e/src/Middleware/EnvelopeTransformerMiddleware.php#L29-L38
terion-name/package-installer
src/Terion/PackageInstaller/PackageInstallerServiceProvider.php
PackageInstallerServiceProvider.bindInstallCommand
protected function bindInstallCommand() { $this->app['package.install'] = $this->app->share(function ($app) { return $app->make('Terion\PackageInstaller\PackageInstallCommand'); }); $this->app['package.process'] = $this->app->share(function ($app) { return $app->make('Terion\PackageInstaller\PackageProcessCommand'); }); }
php
protected function bindInstallCommand() { $this->app['package.install'] = $this->app->share(function ($app) { return $app->make('Terion\PackageInstaller\PackageInstallCommand'); }); $this->app['package.process'] = $this->app->share(function ($app) { return $app->make('Terion\PackageInstaller\PackageProcessCommand'); }); }
[ "protected", "function", "bindInstallCommand", "(", ")", "{", "$", "this", "->", "app", "[", "'package.install'", "]", "=", "$", "this", "->", "app", "->", "share", "(", "function", "(", "$", "app", ")", "{", "return", "$", "app", "->", "make", "(", "'Terion\\PackageInstaller\\PackageInstallCommand'", ")", ";", "}", ")", ";", "$", "this", "->", "app", "[", "'package.process'", "]", "=", "$", "this", "->", "app", "->", "share", "(", "function", "(", "$", "app", ")", "{", "return", "$", "app", "->", "make", "(", "'Terion\\PackageInstaller\\PackageProcessCommand'", ")", ";", "}", ")", ";", "}" ]
Bind command to IoC
[ "Bind", "command", "to", "IoC" ]
train
https://github.com/terion-name/package-installer/blob/a1f53085b0b5dbbcc308476f61188103051bd201/src/Terion/PackageInstaller/PackageInstallerServiceProvider.php#L67-L75
spiral-modules/scaffolder
source/Scaffolder/Declarations/RequestDeclaration.php
RequestDeclaration.declareField
public function declareField(string $field, string $type, string $source, string $origin = null) { $schema = $this->constant('SCHEMA')->getValue(); $setters = $this->constant('SETTERS')->getValue(); $validates = $this->constant('VALIDATES')->getValue(); if (!isset($this->mapping[$type])) { $schema[$field] = $source . ':' . ($origin ? $origin : $field); $this->constant('SCHEMA')->setValue($schema); return; } $definition = $this->mapping[$type]; //Source can depend on type $source = $definition['source']; $schema[$field] = $source . ':' . ($origin ? $origin : $field); if (!empty($definition['setter'])) { //Pre-defined setter $setters[$field] = $definition['setter']; } if (!empty($definition['validates'])) { //Pre-defined validation $validates[$field] = $definition['validates']; } $this->constant('SCHEMA')->setValue($schema); $this->constant('SETTERS')->setValue($setters); $this->constant('VALIDATES')->setValue($validates); }
php
public function declareField(string $field, string $type, string $source, string $origin = null) { $schema = $this->constant('SCHEMA')->getValue(); $setters = $this->constant('SETTERS')->getValue(); $validates = $this->constant('VALIDATES')->getValue(); if (!isset($this->mapping[$type])) { $schema[$field] = $source . ':' . ($origin ? $origin : $field); $this->constant('SCHEMA')->setValue($schema); return; } $definition = $this->mapping[$type]; //Source can depend on type $source = $definition['source']; $schema[$field] = $source . ':' . ($origin ? $origin : $field); if (!empty($definition['setter'])) { //Pre-defined setter $setters[$field] = $definition['setter']; } if (!empty($definition['validates'])) { //Pre-defined validation $validates[$field] = $definition['validates']; } $this->constant('SCHEMA')->setValue($schema); $this->constant('SETTERS')->setValue($setters); $this->constant('VALIDATES')->setValue($validates); }
[ "public", "function", "declareField", "(", "string", "$", "field", ",", "string", "$", "type", ",", "string", "$", "source", ",", "string", "$", "origin", "=", "null", ")", "{", "$", "schema", "=", "$", "this", "->", "constant", "(", "'SCHEMA'", ")", "->", "getValue", "(", ")", ";", "$", "setters", "=", "$", "this", "->", "constant", "(", "'SETTERS'", ")", "->", "getValue", "(", ")", ";", "$", "validates", "=", "$", "this", "->", "constant", "(", "'VALIDATES'", ")", "->", "getValue", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "mapping", "[", "$", "type", "]", ")", ")", "{", "$", "schema", "[", "$", "field", "]", "=", "$", "source", ".", "':'", ".", "(", "$", "origin", "?", "$", "origin", ":", "$", "field", ")", ";", "$", "this", "->", "constant", "(", "'SCHEMA'", ")", "->", "setValue", "(", "$", "schema", ")", ";", "return", ";", "}", "$", "definition", "=", "$", "this", "->", "mapping", "[", "$", "type", "]", ";", "//Source can depend on type", "$", "source", "=", "$", "definition", "[", "'source'", "]", ";", "$", "schema", "[", "$", "field", "]", "=", "$", "source", ".", "':'", ".", "(", "$", "origin", "?", "$", "origin", ":", "$", "field", ")", ";", "if", "(", "!", "empty", "(", "$", "definition", "[", "'setter'", "]", ")", ")", "{", "//Pre-defined setter", "$", "setters", "[", "$", "field", "]", "=", "$", "definition", "[", "'setter'", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "definition", "[", "'validates'", "]", ")", ")", "{", "//Pre-defined validation", "$", "validates", "[", "$", "field", "]", "=", "$", "definition", "[", "'validates'", "]", ";", "}", "$", "this", "->", "constant", "(", "'SCHEMA'", ")", "->", "setValue", "(", "$", "schema", ")", ";", "$", "this", "->", "constant", "(", "'SETTERS'", ")", "->", "setValue", "(", "$", "setters", ")", ";", "$", "this", "->", "constant", "(", "'VALIDATES'", ")", "->", "setValue", "(", "$", "validates", ")", ";", "}" ]
Add new field to request and generate default filters and validations if type presented in mapping. @param string $field @param string $type @param string $source @param string $origin
[ "Add", "new", "field", "to", "request", "and", "generate", "default", "filters", "and", "validations", "if", "type", "presented", "in", "mapping", "." ]
train
https://github.com/spiral-modules/scaffolder/blob/9be9dd0da6e4b02232db24e797fe5c288afbbddf/source/Scaffolder/Declarations/RequestDeclaration.php#L50-L83
spiral-modules/scaffolder
source/Scaffolder/Declarations/RequestDeclaration.php
RequestDeclaration.declareStructure
protected function declareStructure() { $this->constant('SCHEMA')->setValue([]); $this->constant('SETTERS')->setValue([]); $this->constant('VALIDATES')->setValue([]); }
php
protected function declareStructure() { $this->constant('SCHEMA')->setValue([]); $this->constant('SETTERS')->setValue([]); $this->constant('VALIDATES')->setValue([]); }
[ "protected", "function", "declareStructure", "(", ")", "{", "$", "this", "->", "constant", "(", "'SCHEMA'", ")", "->", "setValue", "(", "[", "]", ")", ";", "$", "this", "->", "constant", "(", "'SETTERS'", ")", "->", "setValue", "(", "[", "]", ")", ";", "$", "this", "->", "constant", "(", "'VALIDATES'", ")", "->", "setValue", "(", "[", "]", ")", ";", "}" ]
Declare record entity structure.
[ "Declare", "record", "entity", "structure", "." ]
train
https://github.com/spiral-modules/scaffolder/blob/9be9dd0da6e4b02232db24e797fe5c288afbbddf/source/Scaffolder/Declarations/RequestDeclaration.php#L88-L93