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
kambalabs/KmbPermission
src/KmbPermission/Assertion/MustBeAdminAssignedToEnvironmentOrAncestor.php
MustBeAdminAssignedToEnvironmentOrAncestor.assert
public function assert(AuthorizationService $authorizationService, $context = null) { /** @var EnvironmentInterface $context */ /** @var UserInterface $identity */ $identity = $authorizationService->getIdentity(); if ($identity->getRole() === UserInterface::ROLE_USER) { return false; } if ($authorizationService->isGranted('manageAllEnv', $context) || ($context != null && $context->hasUser($identity))) { return true; } if ($context == null) { return false; } if (!$context->hasParent()) { return false; } $parent = $context->getParent(); return $parent->hasUser($identity) || $authorizationService->isGranted('manageEnv', $parent); }
php
public function assert(AuthorizationService $authorizationService, $context = null) { /** @var EnvironmentInterface $context */ /** @var UserInterface $identity */ $identity = $authorizationService->getIdentity(); if ($identity->getRole() === UserInterface::ROLE_USER) { return false; } if ($authorizationService->isGranted('manageAllEnv', $context) || ($context != null && $context->hasUser($identity))) { return true; } if ($context == null) { return false; } if (!$context->hasParent()) { return false; } $parent = $context->getParent(); return $parent->hasUser($identity) || $authorizationService->isGranted('manageEnv', $parent); }
[ "public", "function", "assert", "(", "AuthorizationService", "$", "authorizationService", ",", "$", "context", "=", "null", ")", "{", "/** @var EnvironmentInterface $context */", "/** @var UserInterface $identity */", "$", "identity", "=", "$", "authorizationService", "->", "getIdentity", "(", ")", ";", "if", "(", "$", "identity", "->", "getRole", "(", ")", "===", "UserInterface", "::", "ROLE_USER", ")", "{", "return", "false", ";", "}", "if", "(", "$", "authorizationService", "->", "isGranted", "(", "'manageAllEnv'", ",", "$", "context", ")", "||", "(", "$", "context", "!=", "null", "&&", "$", "context", "->", "hasUser", "(", "$", "identity", ")", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "context", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "context", "->", "hasParent", "(", ")", ")", "{", "return", "false", ";", "}", "$", "parent", "=", "$", "context", "->", "getParent", "(", ")", ";", "return", "$", "parent", "->", "hasUser", "(", "$", "identity", ")", "||", "$", "authorizationService", "->", "isGranted", "(", "'manageEnv'", ",", "$", "parent", ")", ";", "}" ]
Check if this assertion is true @param AuthorizationService $authorizationService @param mixed $context @return bool
[ "Check", "if", "this", "assertion", "is", "true" ]
train
https://github.com/kambalabs/KmbPermission/blob/1fa446bd830611c55d304c200d48ae2474edbd03/src/KmbPermission/Assertion/MustBeAdminAssignedToEnvironmentOrAncestor.php#L37-L62
ming123jew/mediamanage
model/MediamanageCategory.php
MediamanageCategory.Lists
public function Lists($pagesize=10){ //如启用mongodb则使用mongodb if($this->mongodb){ $res = $this->mongodbLists($pagesize); return $res; exit(0); } //mysql // 查询状态为1的用户数据 并且每页显示10条数据 $list = self::where('status',1)->paginate($pagesize); // 获取分页显示 $page = $list->render(); $res['list'] = $list; $res['page'] = $page; return $res; }
php
public function Lists($pagesize=10){ //如启用mongodb则使用mongodb if($this->mongodb){ $res = $this->mongodbLists($pagesize); return $res; exit(0); } //mysql // 查询状态为1的用户数据 并且每页显示10条数据 $list = self::where('status',1)->paginate($pagesize); // 获取分页显示 $page = $list->render(); $res['list'] = $list; $res['page'] = $page; return $res; }
[ "public", "function", "Lists", "(", "$", "pagesize", "=", "10", ")", "{", "//如启用mongodb则使用mongodb", "if", "(", "$", "this", "->", "mongodb", ")", "{", "$", "res", "=", "$", "this", "->", "mongodbLists", "(", "$", "pagesize", ")", ";", "return", "$", "res", ";", "exit", "(", "0", ")", ";", "}", "//mysql", "// 查询状态为1的用户数据 并且每页显示10条数据", "$", "list", "=", "self", "::", "where", "(", "'status'", ",", "1", ")", "->", "paginate", "(", "$", "pagesize", ")", ";", "// 获取分页显示", "$", "page", "=", "$", "list", "->", "render", "(", ")", ";", "$", "res", "[", "'list'", "]", "=", "$", "list", ";", "$", "res", "[", "'page'", "]", "=", "$", "page", ";", "return", "$", "res", ";", "}" ]
列表 @param number $pagesize @return array
[ "列表" ]
train
https://github.com/ming123jew/mediamanage/blob/de6a1482990fb7e41e81b232d738e545de7cc977/model/MediamanageCategory.php#L20-L38
Talesoft/tale-framework
src/Tale/Debug/Profiler.php
Profiler.record
public function record( $name = null ) { $snapshot = Snapshot::create(); $record = new Profiler\Record( $this, $name, $snapshot, $this->_lastRecord ); $this->_records[] = $record; $this->_lastRecord = $record; if( !$this->_startRecord ) $this->_startRecord = $record; return $this; }
php
public function record( $name = null ) { $snapshot = Snapshot::create(); $record = new Profiler\Record( $this, $name, $snapshot, $this->_lastRecord ); $this->_records[] = $record; $this->_lastRecord = $record; if( !$this->_startRecord ) $this->_startRecord = $record; return $this; }
[ "public", "function", "record", "(", "$", "name", "=", "null", ")", "{", "$", "snapshot", "=", "Snapshot", "::", "create", "(", ")", ";", "$", "record", "=", "new", "Profiler", "\\", "Record", "(", "$", "this", ",", "$", "name", ",", "$", "snapshot", ",", "$", "this", "->", "_lastRecord", ")", ";", "$", "this", "->", "_records", "[", "]", "=", "$", "record", ";", "$", "this", "->", "_lastRecord", "=", "$", "record", ";", "if", "(", "!", "$", "this", "->", "_startRecord", ")", "$", "this", "->", "_startRecord", "=", "$", "record", ";", "return", "$", "this", ";", "}" ]
@param null $name @return $this
[ "@param", "null", "$name" ]
train
https://github.com/Talesoft/tale-framework/blob/739a7011c6dad409a51c4bcfbcf4b4ffbc8cba49/src/Tale/Debug/Profiler.php#L81-L93
Talesoft/tale-framework
src/Tale/Debug/Profiler.php
Profiler.generateHtml
public function generateHtml( $withOutput = false ) { $th = [ 'Name/ID', 'Execution Time', 'Total Execution Time', 'Memory', 'Total Memory', 'Memory Peak', 'Avg. Memory Peak', 'Real Memory', 'Total Real Memory', 'Real Memory Peak', 'Avg. Real Memory Peak' ]; $m = new Manipulator( 'div' ); $tbl = $m->setCss( [ 'font-family' => 'monospace', 'font-size' => '8px', 'color' => '#333' ] ) ->table ->tableCols( $th ); foreach( $this->_records as $record ) { $fromStart = $record->getAbsoluteResult(); $fromLast = $record->getResult(); if( !$fromLast ) $fromLast = $fromStart; $tr = $tbl->append( 'tr' ); $tr->append( 'th' ) ->setText( $record->getName() ); foreach( [ $fromLast->getTime(), $fromStart->getTime() ] as $time ) { $time = $time * 1000; $tr->append( 'td' ) ->append( 'label[title="'.$time.' ms"]' ) ->setText( StringUtil::timify( $time ) ); } foreach( [ $fromLast->getMemoryUsage(), $fromStart->getMemoryUsage(), $fromLast->getMemoryUsagePeak(), $fromStart->getMemoryUsagePeak(), $fromLast->getRealMemoryUsage(), $fromStart->getRealMemoryUsage(), $fromLast->getRealMemoryUsagePeak(), $fromStart->getRealMemoryUsagePeak() ] as $bytes ) $tr->append( 'td' ) ->append( 'label[title="'.$bytes.' Byte"]' ) ->setText( StringUtil::bytify( $bytes ) ); } $m->find( 'table' )->setCss( [ 'width' => '100%' ] ); $m->find( 'td, th' )->setCss( [ 'border' => '1px solid #ccc' ] ); $m->find( 'td' )->setCss( [ 'text-align' => 'right' ] ); $m->find( 'tr:even, tbody th' )->setCss( [ 'background' => '#efefef' ] ); return $m; }
php
public function generateHtml( $withOutput = false ) { $th = [ 'Name/ID', 'Execution Time', 'Total Execution Time', 'Memory', 'Total Memory', 'Memory Peak', 'Avg. Memory Peak', 'Real Memory', 'Total Real Memory', 'Real Memory Peak', 'Avg. Real Memory Peak' ]; $m = new Manipulator( 'div' ); $tbl = $m->setCss( [ 'font-family' => 'monospace', 'font-size' => '8px', 'color' => '#333' ] ) ->table ->tableCols( $th ); foreach( $this->_records as $record ) { $fromStart = $record->getAbsoluteResult(); $fromLast = $record->getResult(); if( !$fromLast ) $fromLast = $fromStart; $tr = $tbl->append( 'tr' ); $tr->append( 'th' ) ->setText( $record->getName() ); foreach( [ $fromLast->getTime(), $fromStart->getTime() ] as $time ) { $time = $time * 1000; $tr->append( 'td' ) ->append( 'label[title="'.$time.' ms"]' ) ->setText( StringUtil::timify( $time ) ); } foreach( [ $fromLast->getMemoryUsage(), $fromStart->getMemoryUsage(), $fromLast->getMemoryUsagePeak(), $fromStart->getMemoryUsagePeak(), $fromLast->getRealMemoryUsage(), $fromStart->getRealMemoryUsage(), $fromLast->getRealMemoryUsagePeak(), $fromStart->getRealMemoryUsagePeak() ] as $bytes ) $tr->append( 'td' ) ->append( 'label[title="'.$bytes.' Byte"]' ) ->setText( StringUtil::bytify( $bytes ) ); } $m->find( 'table' )->setCss( [ 'width' => '100%' ] ); $m->find( 'td, th' )->setCss( [ 'border' => '1px solid #ccc' ] ); $m->find( 'td' )->setCss( [ 'text-align' => 'right' ] ); $m->find( 'tr:even, tbody th' )->setCss( [ 'background' => '#efefef' ] ); return $m; }
[ "public", "function", "generateHtml", "(", "$", "withOutput", "=", "false", ")", "{", "$", "th", "=", "[", "'Name/ID'", ",", "'Execution Time'", ",", "'Total Execution Time'", ",", "'Memory'", ",", "'Total Memory'", ",", "'Memory Peak'", ",", "'Avg. Memory Peak'", ",", "'Real Memory'", ",", "'Total Real Memory'", ",", "'Real Memory Peak'", ",", "'Avg. Real Memory Peak'", "]", ";", "$", "m", "=", "new", "Manipulator", "(", "'div'", ")", ";", "$", "tbl", "=", "$", "m", "->", "setCss", "(", "[", "'font-family'", "=>", "'monospace'", ",", "'font-size'", "=>", "'8px'", ",", "'color'", "=>", "'#333'", "]", ")", "->", "table", "->", "tableCols", "(", "$", "th", ")", ";", "foreach", "(", "$", "this", "->", "_records", "as", "$", "record", ")", "{", "$", "fromStart", "=", "$", "record", "->", "getAbsoluteResult", "(", ")", ";", "$", "fromLast", "=", "$", "record", "->", "getResult", "(", ")", ";", "if", "(", "!", "$", "fromLast", ")", "$", "fromLast", "=", "$", "fromStart", ";", "$", "tr", "=", "$", "tbl", "->", "append", "(", "'tr'", ")", ";", "$", "tr", "->", "append", "(", "'th'", ")", "->", "setText", "(", "$", "record", "->", "getName", "(", ")", ")", ";", "foreach", "(", "[", "$", "fromLast", "->", "getTime", "(", ")", ",", "$", "fromStart", "->", "getTime", "(", ")", "]", "as", "$", "time", ")", "{", "$", "time", "=", "$", "time", "*", "1000", ";", "$", "tr", "->", "append", "(", "'td'", ")", "->", "append", "(", "'label[title=\"'", ".", "$", "time", ".", "' ms\"]'", ")", "->", "setText", "(", "StringUtil", "::", "timify", "(", "$", "time", ")", ")", ";", "}", "foreach", "(", "[", "$", "fromLast", "->", "getMemoryUsage", "(", ")", ",", "$", "fromStart", "->", "getMemoryUsage", "(", ")", ",", "$", "fromLast", "->", "getMemoryUsagePeak", "(", ")", ",", "$", "fromStart", "->", "getMemoryUsagePeak", "(", ")", ",", "$", "fromLast", "->", "getRealMemoryUsage", "(", ")", ",", "$", "fromStart", "->", "getRealMemoryUsage", "(", ")", ",", "$", "fromLast", "->", "getRealMemoryUsagePeak", "(", ")", ",", "$", "fromStart", "->", "getRealMemoryUsagePeak", "(", ")", "]", "as", "$", "bytes", ")", "$", "tr", "->", "append", "(", "'td'", ")", "->", "append", "(", "'label[title=\"'", ".", "$", "bytes", ".", "' Byte\"]'", ")", "->", "setText", "(", "StringUtil", "::", "bytify", "(", "$", "bytes", ")", ")", ";", "}", "$", "m", "->", "find", "(", "'table'", ")", "->", "setCss", "(", "[", "'width'", "=>", "'100%'", "]", ")", ";", "$", "m", "->", "find", "(", "'td, th'", ")", "->", "setCss", "(", "[", "'border'", "=>", "'1px solid #ccc'", "]", ")", ";", "$", "m", "->", "find", "(", "'td'", ")", "->", "setCss", "(", "[", "'text-align'", "=>", "'right'", "]", ")", ";", "$", "m", "->", "find", "(", "'tr:even, tbody th'", ")", "->", "setCss", "(", "[", "'background'", "=>", "'#efefef'", "]", ")", ";", "return", "$", "m", ";", "}" ]
@param bool|false $withOutput @return Manipulator
[ "@param", "bool|false", "$withOutput" ]
train
https://github.com/Talesoft/tale-framework/blob/739a7011c6dad409a51c4bcfbcf4b4ffbc8cba49/src/Tale/Debug/Profiler.php#L108-L173
bytic/http
src/Response/ResponseAwareTrait.php
ResponseAwareTrait.getResponse
public function getResponse($autoInit = null) { if (is_bool($autoInit)) { $this->setAutoInitResponse($autoInit); } if ($this->response == null && $this->isAutoInitResponse()) { $this->initResponse(); } return $this->response; }
php
public function getResponse($autoInit = null) { if (is_bool($autoInit)) { $this->setAutoInitResponse($autoInit); } if ($this->response == null && $this->isAutoInitResponse()) { $this->initResponse(); } return $this->response; }
[ "public", "function", "getResponse", "(", "$", "autoInit", "=", "null", ")", "{", "if", "(", "is_bool", "(", "$", "autoInit", ")", ")", "{", "$", "this", "->", "setAutoInitResponse", "(", "$", "autoInit", ")", ";", "}", "if", "(", "$", "this", "->", "response", "==", "null", "&&", "$", "this", "->", "isAutoInitResponse", "(", ")", ")", "{", "$", "this", "->", "initResponse", "(", ")", ";", "}", "return", "$", "this", "->", "response", ";", "}" ]
Get the container. @param bool $autoInit @return Response
[ "Get", "the", "container", "." ]
train
https://github.com/bytic/http/blob/0d22507a8bcf05575d3d1d6c6a87c2026778c47c/src/Response/ResponseAwareTrait.php#L29-L39
anorgan/deployer-common
src/Runner.php
Runner.run
public function run() { foreach ($this->getSteps() as $step) { $this->logger->info('Starting "'.$step->getTitle().'"'); foreach ($this->getServersForStep($step) as $server) { if ($step->isMandatory()) { $server->runCommands(); $this->logger->info('Finished "'.$step->getTitle().'" on "'.$server->getTitle().'"'); } else { try { $server->runCommands(); $this->logger->info('Finished "'.$step->getTitle().'" on "'.$server->getTitle().'"'); } catch (\Exception $e) { $this->logger->info('Failed to run "'.$step->getTitle().'" on "'.$server->getTitle().'"'); } } } } }
php
public function run() { foreach ($this->getSteps() as $step) { $this->logger->info('Starting "'.$step->getTitle().'"'); foreach ($this->getServersForStep($step) as $server) { if ($step->isMandatory()) { $server->runCommands(); $this->logger->info('Finished "'.$step->getTitle().'" on "'.$server->getTitle().'"'); } else { try { $server->runCommands(); $this->logger->info('Finished "'.$step->getTitle().'" on "'.$server->getTitle().'"'); } catch (\Exception $e) { $this->logger->info('Failed to run "'.$step->getTitle().'" on "'.$server->getTitle().'"'); } } } } }
[ "public", "function", "run", "(", ")", "{", "foreach", "(", "$", "this", "->", "getSteps", "(", ")", "as", "$", "step", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Starting \"'", ".", "$", "step", "->", "getTitle", "(", ")", ".", "'\"'", ")", ";", "foreach", "(", "$", "this", "->", "getServersForStep", "(", "$", "step", ")", "as", "$", "server", ")", "{", "if", "(", "$", "step", "->", "isMandatory", "(", ")", ")", "{", "$", "server", "->", "runCommands", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "'Finished \"'", ".", "$", "step", "->", "getTitle", "(", ")", ".", "'\" on \"'", ".", "$", "server", "->", "getTitle", "(", ")", ".", "'\"'", ")", ";", "}", "else", "{", "try", "{", "$", "server", "->", "runCommands", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "'Finished \"'", ".", "$", "step", "->", "getTitle", "(", ")", ".", "'\" on \"'", ".", "$", "server", "->", "getTitle", "(", ")", ".", "'\"'", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Failed to run \"'", ".", "$", "step", "->", "getTitle", "(", ")", ".", "'\" on \"'", ".", "$", "server", "->", "getTitle", "(", ")", ".", "'\"'", ")", ";", "}", "}", "}", "}", "}" ]
Run commands on every server of every step with steps' commands.
[ "Run", "commands", "on", "every", "server", "of", "every", "step", "with", "steps", "commands", "." ]
train
https://github.com/anorgan/deployer-common/blob/8b4bdb6c7ea3f7031aa4ee8eb06a16e49006da6f/src/Runner.php#L38-L57
anorgan/deployer-common
src/Runner.php
Runner.getServersForStep
public function getServersForStep(DeployStep $step) { $servers = $step->getServers(); foreach ($servers as $server) { $server->setLogger($this->logger); $server->setCommands($step->getCommands()); } return $servers; }
php
public function getServersForStep(DeployStep $step) { $servers = $step->getServers(); foreach ($servers as $server) { $server->setLogger($this->logger); $server->setCommands($step->getCommands()); } return $servers; }
[ "public", "function", "getServersForStep", "(", "DeployStep", "$", "step", ")", "{", "$", "servers", "=", "$", "step", "->", "getServers", "(", ")", ";", "foreach", "(", "$", "servers", "as", "$", "server", ")", "{", "$", "server", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "$", "server", "->", "setCommands", "(", "$", "step", "->", "getCommands", "(", ")", ")", ";", "}", "return", "$", "servers", ";", "}" ]
@param DeployStep $step @return AbstractServer[]
[ "@param", "DeployStep", "$step" ]
train
https://github.com/anorgan/deployer-common/blob/8b4bdb6c7ea3f7031aa4ee8eb06a16e49006da6f/src/Runner.php#L72-L81
fond-of/spryker-companies-rest-api
src/FondOfSpryker/Zed/CompaniesRestApi/Communication/Plugin/CompaniesRestApi/CompanyMapperPlugin.php
CompanyMapperPlugin.map
public function map( RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer, CompanyTransfer $companyTransfer ): CompanyTransfer { return $this->getFacade()->mapToCompany($restCompaniesRequestAttributesTransfer, $companyTransfer); }
php
public function map( RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer, CompanyTransfer $companyTransfer ): CompanyTransfer { return $this->getFacade()->mapToCompany($restCompaniesRequestAttributesTransfer, $companyTransfer); }
[ "public", "function", "map", "(", "RestCompaniesRequestAttributesTransfer", "$", "restCompaniesRequestAttributesTransfer", ",", "CompanyTransfer", "$", "companyTransfer", ")", ":", "CompanyTransfer", "{", "return", "$", "this", "->", "getFacade", "(", ")", "->", "mapToCompany", "(", "$", "restCompaniesRequestAttributesTransfer", ",", "$", "companyTransfer", ")", ";", "}" ]
Specification: - Maps rest company request data to company transfer. @api @param \Generated\Shared\Transfer\RestCompaniesRequestAttributesTransfer $restCompaniesRequestAttributesTransfer @param \Generated\Shared\Transfer\CompanyTransfer $companyTransfer @return \Generated\Shared\Transfer\CompanyTransfer
[ "Specification", ":", "-", "Maps", "rest", "company", "request", "data", "to", "company", "transfer", "." ]
train
https://github.com/fond-of/spryker-companies-rest-api/blob/0df688aa37cd6d18f90ac2af0a1cbc39357d94d7/src/FondOfSpryker/Zed/CompaniesRestApi/Communication/Plugin/CompaniesRestApi/CompanyMapperPlugin.php#L26-L31
PenoaksDev/Milky-Framework
src/Milky/Http/View/Compilers/BladeCompiler.php
BladeCompiler.compile
public function compile( $path = null ) { if ( $path ) $this->setPath( $path ); if ( !is_null( $this->cachePath ) ) { $contents = $this->compileString( $this->files->get( $this->getPath() ) ); $this->files->put( $this->getCompiledPath( $this->getPath() ), $contents ); } }
php
public function compile( $path = null ) { if ( $path ) $this->setPath( $path ); if ( !is_null( $this->cachePath ) ) { $contents = $this->compileString( $this->files->get( $this->getPath() ) ); $this->files->put( $this->getCompiledPath( $this->getPath() ), $contents ); } }
[ "public", "function", "compile", "(", "$", "path", "=", "null", ")", "{", "if", "(", "$", "path", ")", "$", "this", "->", "setPath", "(", "$", "path", ")", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "cachePath", ")", ")", "{", "$", "contents", "=", "$", "this", "->", "compileString", "(", "$", "this", "->", "files", "->", "get", "(", "$", "this", "->", "getPath", "(", ")", ")", ")", ";", "$", "this", "->", "files", "->", "put", "(", "$", "this", "->", "getCompiledPath", "(", "$", "this", "->", "getPath", "(", ")", ")", ",", "$", "contents", ")", ";", "}", "}" ]
Compile the view at the given path. @param string $path @return void
[ "Compile", "the", "view", "at", "the", "given", "path", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/View/Compilers/BladeCompiler.php#L107-L117
PenoaksDev/Milky-Framework
src/Milky/Http/View/Compilers/BladeCompiler.php
BladeCompiler.compileString
public function compileString( $value ) { $result = ''; if ( strpos( $value, '@verbatim' ) !== false ) { $value = $this->storeVerbatimBlocks( $value ); } $this->footer = []; // Here we will loop through all of the tokens returned by the Zend lexer and // parse each one into the corresponding valid PHP. We will then have this // template as the correctly rendered PHP that can be rendered natively. foreach ( token_get_all( $value ) as $token ) { $result .= is_array( $token ) ? $this->parseToken( $token ) : $token; } if ( !empty( $this->verbatimBlocks ) ) { $result = $this->restoreVerbatimBlocks( $result ); } // If there are any footer lines that need to get added to a template we will // add them here at the end of the template. This gets used mainly for the // template inheritance via the extends keyword that should be appended. if ( count( $this->footer ) > 0 ) { $result = ltrim( $result, PHP_EOL ) . PHP_EOL . implode( PHP_EOL, array_reverse( $this->footer ) ); } return $result; }
php
public function compileString( $value ) { $result = ''; if ( strpos( $value, '@verbatim' ) !== false ) { $value = $this->storeVerbatimBlocks( $value ); } $this->footer = []; // Here we will loop through all of the tokens returned by the Zend lexer and // parse each one into the corresponding valid PHP. We will then have this // template as the correctly rendered PHP that can be rendered natively. foreach ( token_get_all( $value ) as $token ) { $result .= is_array( $token ) ? $this->parseToken( $token ) : $token; } if ( !empty( $this->verbatimBlocks ) ) { $result = $this->restoreVerbatimBlocks( $result ); } // If there are any footer lines that need to get added to a template we will // add them here at the end of the template. This gets used mainly for the // template inheritance via the extends keyword that should be appended. if ( count( $this->footer ) > 0 ) { $result = ltrim( $result, PHP_EOL ) . PHP_EOL . implode( PHP_EOL, array_reverse( $this->footer ) ); } return $result; }
[ "public", "function", "compileString", "(", "$", "value", ")", "{", "$", "result", "=", "''", ";", "if", "(", "strpos", "(", "$", "value", ",", "'@verbatim'", ")", "!==", "false", ")", "{", "$", "value", "=", "$", "this", "->", "storeVerbatimBlocks", "(", "$", "value", ")", ";", "}", "$", "this", "->", "footer", "=", "[", "]", ";", "// Here we will loop through all of the tokens returned by the Zend lexer and", "// parse each one into the corresponding valid PHP. We will then have this", "// template as the correctly rendered PHP that can be rendered natively.", "foreach", "(", "token_get_all", "(", "$", "value", ")", "as", "$", "token", ")", "{", "$", "result", ".=", "is_array", "(", "$", "token", ")", "?", "$", "this", "->", "parseToken", "(", "$", "token", ")", ":", "$", "token", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "verbatimBlocks", ")", ")", "{", "$", "result", "=", "$", "this", "->", "restoreVerbatimBlocks", "(", "$", "result", ")", ";", "}", "// If there are any footer lines that need to get added to a template we will", "// add them here at the end of the template. This gets used mainly for the", "// template inheritance via the extends keyword that should be appended.", "if", "(", "count", "(", "$", "this", "->", "footer", ")", ">", "0", ")", "{", "$", "result", "=", "ltrim", "(", "$", "result", ",", "PHP_EOL", ")", ".", "PHP_EOL", ".", "implode", "(", "PHP_EOL", ",", "array_reverse", "(", "$", "this", "->", "footer", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Compile the given Blade template contents. @param string $value @return string
[ "Compile", "the", "given", "Blade", "template", "contents", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/View/Compilers/BladeCompiler.php#L146-L179
PenoaksDev/Milky-Framework
src/Milky/Http/View/Compilers/BladeCompiler.php
BladeCompiler.compileInject
protected function compileInject( $expression ) { $segments = $this->parseSegments( $expression, 2 ); return '<?php $' . trim( $segments[0] ) . " = app('" . trim( $segments[1] ) . "'); ?>"; }
php
protected function compileInject( $expression ) { $segments = $this->parseSegments( $expression, 2 ); return '<?php $' . trim( $segments[0] ) . " = app('" . trim( $segments[1] ) . "'); ?>"; }
[ "protected", "function", "compileInject", "(", "$", "expression", ")", "{", "$", "segments", "=", "$", "this", "->", "parseSegments", "(", "$", "expression", ",", "2", ")", ";", "return", "'<?php $'", ".", "trim", "(", "$", "segments", "[", "0", "]", ")", ".", "\" = app('\"", ".", "trim", "(", "$", "segments", "[", "1", "]", ")", ".", "\"'); ?>\"", ";", "}" ]
Compile the inject statements into valid PHP. @param string $expression @return string
[ "Compile", "the", "inject", "statements", "into", "valid", "PHP", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/View/Compilers/BladeCompiler.php#L435-L440
PenoaksDev/Milky-Framework
src/Milky/Http/View/Compilers/BladeCompiler.php
BladeCompiler.parseSegments
protected function parseSegments( $expression, $requiredSegmentCount ) { $segments = explode( ',', preg_replace( "/[ \(\)\\\"\']/", '', $expression ) ); if ( $requiredSegmentCount > count( $segments ) ) throw new FrameworkException( "Blade directive is short the required number of segments of " . $requiredSegmentCount ); return $segments; }
php
protected function parseSegments( $expression, $requiredSegmentCount ) { $segments = explode( ',', preg_replace( "/[ \(\)\\\"\']/", '', $expression ) ); if ( $requiredSegmentCount > count( $segments ) ) throw new FrameworkException( "Blade directive is short the required number of segments of " . $requiredSegmentCount ); return $segments; }
[ "protected", "function", "parseSegments", "(", "$", "expression", ",", "$", "requiredSegmentCount", ")", "{", "$", "segments", "=", "explode", "(", "','", ",", "preg_replace", "(", "\"/[ \\(\\)\\\\\\\"\\']/\"", ",", "''", ",", "$", "expression", ")", ")", ";", "if", "(", "$", "requiredSegmentCount", ">", "count", "(", "$", "segments", ")", ")", "throw", "new", "FrameworkException", "(", "\"Blade directive is short the required number of segments of \"", ".", "$", "requiredSegmentCount", ")", ";", "return", "$", "segments", ";", "}" ]
Parses out a blade directive arguments @param $expression @param $requiredSegmentCount @return array @throws FrameworkException
[ "Parses", "out", "a", "blade", "directive", "arguments" ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/View/Compilers/BladeCompiler.php#L1071-L1079
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.interpreteSpec
private function interpreteSpec() { $this->baseSpec = $this->spec['field']->getBaseSpec(); $this->referenceFields(); if (!$this->fields) { return; } $fieldIndex = $this->spec['field']->getIndexStart(); $prevTag = ''; $this->currentSpec = clone $this->spec; foreach ($this->fields as $this->field) { if ($this->field instanceof File_MARC_Field) { // not for leader // adjust spec to current field repetition $tag = $this->field->getTag(); $fieldIndex = $this->getFieldIndex($prevTag, $tag, $fieldIndex); $this->currentSpec['field']->setIndexStartEnd($fieldIndex, $fieldIndex); $this->baseSpec = $this->currentSpec['field']->getBaseSpec(); } else { $tag = 'LDR'; } /* * Subfield iteration */ if ($this->spec->offsetExists('subfields')) { if ($this->field instanceof File_MARC_Data_Field) { foreach ($this->spec['subfields'] as $currentSubfieldSpec) { if ($_subfields = $this->referenceSubfields($currentSubfieldSpec)) { foreach ($_subfields as $subfieldIndex => $subfield) { $currentSubfieldSpec->setIndexStartEnd($subfieldIndex, $subfieldIndex); /* * Subfield SubSpec validation */ if ($currentSubfieldSpec->offsetExists('subSpecs')) { $valid = $this->iterateSubSpec( $currentSubfieldSpec['subSpecs'], $fieldIndex, $subfieldIndex ); if ($valid) { $this->ref($currentSubfieldSpec, $subfield); } } else { $this->ref($currentSubfieldSpec, $subfield); } } } } // end foreach subfield spec } } elseif ($this->spec->offsetExists('indicator')) { if ($this->field instanceof File_MARC_Data_Field) { /* * Field SubSpec validation */ if ($this->currentSpec['indicator']->offsetExists('subSpecs')) { $valid = $this->iterateSubSpec($this->currentSpec['indicator']['subSpecs'], $fieldIndex); if (!$valid) { $fieldIndex++; $prevTag = $tag; continue; // field subspec must be valid } } $position = (int) $this->currentSpec['indicator']['position']; $this->ref($this->currentSpec['indicator'], $this->field->getIndicator($position)); } } else { /* * Field SubSpec validation */ if ($this->currentSpec['field']->offsetExists('subSpecs')) { $valid = $this->iterateSubSpec($this->currentSpec['field']['subSpecs'], $fieldIndex); if (!$valid) { $fieldIndex++; $prevTag = $tag; continue; // field subspec must be valid } } $this->ref($this->currentSpec['field'], $this->field); } $fieldIndex++; $prevTag = $tag; } // end foreach fields }
php
private function interpreteSpec() { $this->baseSpec = $this->spec['field']->getBaseSpec(); $this->referenceFields(); if (!$this->fields) { return; } $fieldIndex = $this->spec['field']->getIndexStart(); $prevTag = ''; $this->currentSpec = clone $this->spec; foreach ($this->fields as $this->field) { if ($this->field instanceof File_MARC_Field) { // not for leader // adjust spec to current field repetition $tag = $this->field->getTag(); $fieldIndex = $this->getFieldIndex($prevTag, $tag, $fieldIndex); $this->currentSpec['field']->setIndexStartEnd($fieldIndex, $fieldIndex); $this->baseSpec = $this->currentSpec['field']->getBaseSpec(); } else { $tag = 'LDR'; } /* * Subfield iteration */ if ($this->spec->offsetExists('subfields')) { if ($this->field instanceof File_MARC_Data_Field) { foreach ($this->spec['subfields'] as $currentSubfieldSpec) { if ($_subfields = $this->referenceSubfields($currentSubfieldSpec)) { foreach ($_subfields as $subfieldIndex => $subfield) { $currentSubfieldSpec->setIndexStartEnd($subfieldIndex, $subfieldIndex); /* * Subfield SubSpec validation */ if ($currentSubfieldSpec->offsetExists('subSpecs')) { $valid = $this->iterateSubSpec( $currentSubfieldSpec['subSpecs'], $fieldIndex, $subfieldIndex ); if ($valid) { $this->ref($currentSubfieldSpec, $subfield); } } else { $this->ref($currentSubfieldSpec, $subfield); } } } } // end foreach subfield spec } } elseif ($this->spec->offsetExists('indicator')) { if ($this->field instanceof File_MARC_Data_Field) { /* * Field SubSpec validation */ if ($this->currentSpec['indicator']->offsetExists('subSpecs')) { $valid = $this->iterateSubSpec($this->currentSpec['indicator']['subSpecs'], $fieldIndex); if (!$valid) { $fieldIndex++; $prevTag = $tag; continue; // field subspec must be valid } } $position = (int) $this->currentSpec['indicator']['position']; $this->ref($this->currentSpec['indicator'], $this->field->getIndicator($position)); } } else { /* * Field SubSpec validation */ if ($this->currentSpec['field']->offsetExists('subSpecs')) { $valid = $this->iterateSubSpec($this->currentSpec['field']['subSpecs'], $fieldIndex); if (!$valid) { $fieldIndex++; $prevTag = $tag; continue; // field subspec must be valid } } $this->ref($this->currentSpec['field'], $this->field); } $fieldIndex++; $prevTag = $tag; } // end foreach fields }
[ "private", "function", "interpreteSpec", "(", ")", "{", "$", "this", "->", "baseSpec", "=", "$", "this", "->", "spec", "[", "'field'", "]", "->", "getBaseSpec", "(", ")", ";", "$", "this", "->", "referenceFields", "(", ")", ";", "if", "(", "!", "$", "this", "->", "fields", ")", "{", "return", ";", "}", "$", "fieldIndex", "=", "$", "this", "->", "spec", "[", "'field'", "]", "->", "getIndexStart", "(", ")", ";", "$", "prevTag", "=", "''", ";", "$", "this", "->", "currentSpec", "=", "clone", "$", "this", "->", "spec", ";", "foreach", "(", "$", "this", "->", "fields", "as", "$", "this", "->", "field", ")", "{", "if", "(", "$", "this", "->", "field", "instanceof", "File_MARC_Field", ")", "{", "// not for leader", "// adjust spec to current field repetition", "$", "tag", "=", "$", "this", "->", "field", "->", "getTag", "(", ")", ";", "$", "fieldIndex", "=", "$", "this", "->", "getFieldIndex", "(", "$", "prevTag", ",", "$", "tag", ",", "$", "fieldIndex", ")", ";", "$", "this", "->", "currentSpec", "[", "'field'", "]", "->", "setIndexStartEnd", "(", "$", "fieldIndex", ",", "$", "fieldIndex", ")", ";", "$", "this", "->", "baseSpec", "=", "$", "this", "->", "currentSpec", "[", "'field'", "]", "->", "getBaseSpec", "(", ")", ";", "}", "else", "{", "$", "tag", "=", "'LDR'", ";", "}", "/*\n * Subfield iteration\n */", "if", "(", "$", "this", "->", "spec", "->", "offsetExists", "(", "'subfields'", ")", ")", "{", "if", "(", "$", "this", "->", "field", "instanceof", "File_MARC_Data_Field", ")", "{", "foreach", "(", "$", "this", "->", "spec", "[", "'subfields'", "]", "as", "$", "currentSubfieldSpec", ")", "{", "if", "(", "$", "_subfields", "=", "$", "this", "->", "referenceSubfields", "(", "$", "currentSubfieldSpec", ")", ")", "{", "foreach", "(", "$", "_subfields", "as", "$", "subfieldIndex", "=>", "$", "subfield", ")", "{", "$", "currentSubfieldSpec", "->", "setIndexStartEnd", "(", "$", "subfieldIndex", ",", "$", "subfieldIndex", ")", ";", "/*\n * Subfield SubSpec validation\n */", "if", "(", "$", "currentSubfieldSpec", "->", "offsetExists", "(", "'subSpecs'", ")", ")", "{", "$", "valid", "=", "$", "this", "->", "iterateSubSpec", "(", "$", "currentSubfieldSpec", "[", "'subSpecs'", "]", ",", "$", "fieldIndex", ",", "$", "subfieldIndex", ")", ";", "if", "(", "$", "valid", ")", "{", "$", "this", "->", "ref", "(", "$", "currentSubfieldSpec", ",", "$", "subfield", ")", ";", "}", "}", "else", "{", "$", "this", "->", "ref", "(", "$", "currentSubfieldSpec", ",", "$", "subfield", ")", ";", "}", "}", "}", "}", "// end foreach subfield spec", "}", "}", "elseif", "(", "$", "this", "->", "spec", "->", "offsetExists", "(", "'indicator'", ")", ")", "{", "if", "(", "$", "this", "->", "field", "instanceof", "File_MARC_Data_Field", ")", "{", "/*\n * Field SubSpec validation\n */", "if", "(", "$", "this", "->", "currentSpec", "[", "'indicator'", "]", "->", "offsetExists", "(", "'subSpecs'", ")", ")", "{", "$", "valid", "=", "$", "this", "->", "iterateSubSpec", "(", "$", "this", "->", "currentSpec", "[", "'indicator'", "]", "[", "'subSpecs'", "]", ",", "$", "fieldIndex", ")", ";", "if", "(", "!", "$", "valid", ")", "{", "$", "fieldIndex", "++", ";", "$", "prevTag", "=", "$", "tag", ";", "continue", ";", "// field subspec must be valid", "}", "}", "$", "position", "=", "(", "int", ")", "$", "this", "->", "currentSpec", "[", "'indicator'", "]", "[", "'position'", "]", ";", "$", "this", "->", "ref", "(", "$", "this", "->", "currentSpec", "[", "'indicator'", "]", ",", "$", "this", "->", "field", "->", "getIndicator", "(", "$", "position", ")", ")", ";", "}", "}", "else", "{", "/*\n * Field SubSpec validation\n */", "if", "(", "$", "this", "->", "currentSpec", "[", "'field'", "]", "->", "offsetExists", "(", "'subSpecs'", ")", ")", "{", "$", "valid", "=", "$", "this", "->", "iterateSubSpec", "(", "$", "this", "->", "currentSpec", "[", "'field'", "]", "[", "'subSpecs'", "]", ",", "$", "fieldIndex", ")", ";", "if", "(", "!", "$", "valid", ")", "{", "$", "fieldIndex", "++", ";", "$", "prevTag", "=", "$", "tag", ";", "continue", ";", "// field subspec must be valid", "}", "}", "$", "this", "->", "ref", "(", "$", "this", "->", "currentSpec", "[", "'field'", "]", ",", "$", "this", "->", "field", ")", ";", "}", "$", "fieldIndex", "++", ";", "$", "prevTag", "=", "$", "tag", ";", "}", "// end foreach fields", "}" ]
Interpretes the MARCspec to decide what methods to call.
[ "Interpretes", "the", "MARCspec", "to", "decide", "what", "methods", "to", "call", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L85-L168
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.getFieldIndex
private function getFieldIndex($prevTag, $tag, $fieldIndex) { if ($prevTag == $tag or '' == $prevTag) { return $fieldIndex; // iteration of field index will continue } $specTag = $this->currentSpec['field']->getTag(); if (preg_match('/'.$specTag.'/', $tag)) { // not same field tag, but field spec tag matches return $fieldIndex; // iteration of field index will continue } // not same field tag, iteration gets reset return $this->spec['field']->getIndexStart(); }
php
private function getFieldIndex($prevTag, $tag, $fieldIndex) { if ($prevTag == $tag or '' == $prevTag) { return $fieldIndex; // iteration of field index will continue } $specTag = $this->currentSpec['field']->getTag(); if (preg_match('/'.$specTag.'/', $tag)) { // not same field tag, but field spec tag matches return $fieldIndex; // iteration of field index will continue } // not same field tag, iteration gets reset return $this->spec['field']->getIndexStart(); }
[ "private", "function", "getFieldIndex", "(", "$", "prevTag", ",", "$", "tag", ",", "$", "fieldIndex", ")", "{", "if", "(", "$", "prevTag", "==", "$", "tag", "or", "''", "==", "$", "prevTag", ")", "{", "return", "$", "fieldIndex", ";", "// iteration of field index will continue", "}", "$", "specTag", "=", "$", "this", "->", "currentSpec", "[", "'field'", "]", "->", "getTag", "(", ")", ";", "if", "(", "preg_match", "(", "'/'", ".", "$", "specTag", ".", "'/'", ",", "$", "tag", ")", ")", "{", "// not same field tag, but field spec tag matches", "return", "$", "fieldIndex", ";", "// iteration of field index will continue", "}", "// not same field tag, iteration gets reset", "return", "$", "this", "->", "spec", "[", "'field'", "]", "->", "getIndexStart", "(", ")", ";", "}" ]
Get the current field index. @param string $prevTag The previous field tag @param string $tag The current field tag @param int $fieldIndex The current field index @return int $fieldIndex The current field index
[ "Get", "the", "current", "field", "index", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L179-L191
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.iterateSubSpec
private function iterateSubSpec($subSpecs, $fieldIndex, $subfieldIndex = null) { $valid = true; foreach ($subSpecs as $_subSpec) { if (is_array($_subSpec)) { // chained subSpecs (OR) foreach ($_subSpec as $this->currentSubSpec) { $this->setIndexStartEnd($fieldIndex, $subfieldIndex); if ($valid = $this->checkSubSpec()) { break; // at least one of them is true (OR) } } } else { // repeated SubSpecs (AND) $this->currentSubSpec = $_subSpec; $this->setIndexStartEnd($fieldIndex, $subfieldIndex); if (!$valid = $this->checkSubSpec()) { break; // all of them have to be true (AND) } } } return $valid; }
php
private function iterateSubSpec($subSpecs, $fieldIndex, $subfieldIndex = null) { $valid = true; foreach ($subSpecs as $_subSpec) { if (is_array($_subSpec)) { // chained subSpecs (OR) foreach ($_subSpec as $this->currentSubSpec) { $this->setIndexStartEnd($fieldIndex, $subfieldIndex); if ($valid = $this->checkSubSpec()) { break; // at least one of them is true (OR) } } } else { // repeated SubSpecs (AND) $this->currentSubSpec = $_subSpec; $this->setIndexStartEnd($fieldIndex, $subfieldIndex); if (!$valid = $this->checkSubSpec()) { break; // all of them have to be true (AND) } } } return $valid; }
[ "private", "function", "iterateSubSpec", "(", "$", "subSpecs", ",", "$", "fieldIndex", ",", "$", "subfieldIndex", "=", "null", ")", "{", "$", "valid", "=", "true", ";", "foreach", "(", "$", "subSpecs", "as", "$", "_subSpec", ")", "{", "if", "(", "is_array", "(", "$", "_subSpec", ")", ")", "{", "// chained subSpecs (OR)", "foreach", "(", "$", "_subSpec", "as", "$", "this", "->", "currentSubSpec", ")", "{", "$", "this", "->", "setIndexStartEnd", "(", "$", "fieldIndex", ",", "$", "subfieldIndex", ")", ";", "if", "(", "$", "valid", "=", "$", "this", "->", "checkSubSpec", "(", ")", ")", "{", "break", ";", "// at least one of them is true (OR)", "}", "}", "}", "else", "{", "// repeated SubSpecs (AND)", "$", "this", "->", "currentSubSpec", "=", "$", "_subSpec", ";", "$", "this", "->", "setIndexStartEnd", "(", "$", "fieldIndex", ",", "$", "subfieldIndex", ")", ";", "if", "(", "!", "$", "valid", "=", "$", "this", "->", "checkSubSpec", "(", ")", ")", "{", "break", ";", "// all of them have to be true (AND)", "}", "}", "}", "return", "$", "valid", ";", "}" ]
Iterate on subspecs. @param array $subSpecs Array of subspecs @param int $fieldIndex The current field index @param int $subfieldIndex The current subfield index @return bool The validation result
[ "Iterate", "on", "subspecs", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L202-L224
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.setIndexStartEnd
private function setIndexStartEnd($fieldIndex, $subfieldIndex = null) { foreach (['leftSubTerm', 'rightSubTerm'] as $side) { if (!($this->currentSubSpec[$side] instanceof CK\MARCspec\ComparisonStringInterface)) { // only set new index if subspec field tag equals spec field tag!! if ($this->spec['field']['tag'] == $this->currentSubSpec[$side]['field']['tag']) { $this->currentSubSpec[$side]['field']->setIndexStartEnd($fieldIndex, $fieldIndex); if (!is_null($subfieldIndex)) { if ($this->currentSubSpec[$side]->offsetExists('subfields')) { foreach ($this->currentSubSpec[$side]['subfields'] as $subfieldSpec) { $subfieldSpec->setIndexStartEnd($subfieldIndex, $subfieldIndex); } } } } } } }
php
private function setIndexStartEnd($fieldIndex, $subfieldIndex = null) { foreach (['leftSubTerm', 'rightSubTerm'] as $side) { if (!($this->currentSubSpec[$side] instanceof CK\MARCspec\ComparisonStringInterface)) { // only set new index if subspec field tag equals spec field tag!! if ($this->spec['field']['tag'] == $this->currentSubSpec[$side]['field']['tag']) { $this->currentSubSpec[$side]['field']->setIndexStartEnd($fieldIndex, $fieldIndex); if (!is_null($subfieldIndex)) { if ($this->currentSubSpec[$side]->offsetExists('subfields')) { foreach ($this->currentSubSpec[$side]['subfields'] as $subfieldSpec) { $subfieldSpec->setIndexStartEnd($subfieldIndex, $subfieldIndex); } } } } } } }
[ "private", "function", "setIndexStartEnd", "(", "$", "fieldIndex", ",", "$", "subfieldIndex", "=", "null", ")", "{", "foreach", "(", "[", "'leftSubTerm'", ",", "'rightSubTerm'", "]", "as", "$", "side", ")", "{", "if", "(", "!", "(", "$", "this", "->", "currentSubSpec", "[", "$", "side", "]", "instanceof", "CK", "\\", "MARCspec", "\\", "ComparisonStringInterface", ")", ")", "{", "// only set new index if subspec field tag equals spec field tag!!", "if", "(", "$", "this", "->", "spec", "[", "'field'", "]", "[", "'tag'", "]", "==", "$", "this", "->", "currentSubSpec", "[", "$", "side", "]", "[", "'field'", "]", "[", "'tag'", "]", ")", "{", "$", "this", "->", "currentSubSpec", "[", "$", "side", "]", "[", "'field'", "]", "->", "setIndexStartEnd", "(", "$", "fieldIndex", ",", "$", "fieldIndex", ")", ";", "if", "(", "!", "is_null", "(", "$", "subfieldIndex", ")", ")", "{", "if", "(", "$", "this", "->", "currentSubSpec", "[", "$", "side", "]", "->", "offsetExists", "(", "'subfields'", ")", ")", "{", "foreach", "(", "$", "this", "->", "currentSubSpec", "[", "$", "side", "]", "[", "'subfields'", "]", "as", "$", "subfieldSpec", ")", "{", "$", "subfieldSpec", "->", "setIndexStartEnd", "(", "$", "subfieldIndex", ",", "$", "subfieldIndex", ")", ";", "}", "}", "}", "}", "}", "}", "}" ]
Sets the start and end index of the current spec if it's an instance of CK\MARCspec\PositionOrRangeInterface. @param object $spec The current spec @param int $fieldIndex the start/end index to set @param int $subfieldIndex the start/end index to set
[ "Sets", "the", "start", "and", "end", "index", "of", "the", "current", "spec", "if", "it", "s", "an", "instance", "of", "CK", "\\", "MARCspec", "\\", "PositionOrRangeInterface", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L234-L251
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.checkSubSpec
private function checkSubSpec() { $validation = $this->cache->validation($this->currentSubSpec); if (!is_null($validation)) { return $validation; } return $this->validateSubSpec(); }
php
private function checkSubSpec() { $validation = $this->cache->validation($this->currentSubSpec); if (!is_null($validation)) { return $validation; } return $this->validateSubSpec(); }
[ "private", "function", "checkSubSpec", "(", ")", "{", "$", "validation", "=", "$", "this", "->", "cache", "->", "validation", "(", "$", "this", "->", "currentSubSpec", ")", ";", "if", "(", "!", "is_null", "(", "$", "validation", ")", ")", "{", "return", "$", "validation", ";", "}", "return", "$", "this", "->", "validateSubSpec", "(", ")", ";", "}" ]
Checks cache for subspec validation result. Validates SubSpec if it's not in cache. @return bool Validation result
[ "Checks", "cache", "for", "subspec", "validation", "result", ".", "Validates", "SubSpec", "if", "it", "s", "not", "in", "cache", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L259-L267
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.validateSubSpec
private function validateSubSpec() { if ('!' != $this->currentSubSpec['operator'] && '?' != $this->currentSubSpec['operator']) { // skip left subTerm on operators ! and ? if (false === ($this->currentSubSpec['leftSubTerm'] instanceof CK\MARCspec\ComparisonStringInterface)) { $leftSubTermReference = new self( $this->currentSubSpec['leftSubTerm'], $this->record, $this->cache ); if (!$leftSubTerm = $leftSubTermReference->content) { // see 2.3.4 SubSpec validation return $this->cache->validation($this->currentSubSpec, false); } } else { // is a CK\MARCspec\ComparisonStringInterface $leftSubTerm[] = $this->currentSubSpec['leftSubTerm']['comparable']; } } if (false === ($this->currentSubSpec['rightSubTerm'] instanceof CK\MARCspec\ComparisonStringInterface)) { $rightSubTermReference = new self( $this->currentSubSpec['rightSubTerm'], $this->record, $this->cache ); $rightSubTerm = $rightSubTermReference->content; // content maybe an empty array } else { // is a CK\MARCspec\ComparisonStringInterface $rightSubTerm[] = $this->currentSubSpec['rightSubTerm']['comparable']; } $validation = false; switch ($this->currentSubSpec['operator']) { case '=': if (0 < count(array_intersect($leftSubTerm, $rightSubTerm))) { $validation = true; } break; case '!=': if (0 < count(array_diff($leftSubTerm, $rightSubTerm))) { $validation = true; } break; case '~': if (0 < count( array_uintersect( $leftSubTerm, $rightSubTerm, function ($v1, $v2) { if (strpos($v1, $v2) !== false) { return 0; } return -1; } ) ) ) { $validation = true; } break; case '!~': if (0 < count( array_uintersect( $leftSubTerm, $rightSubTerm, function ($v1, $v2) { if (strpos($v1, $v2) === false) { return 0; } return -1; } ) ) ) { $validation = true; } break; case '?': if ($rightSubTerm) { $validation = true; } break; case '!': if (!$rightSubTerm) { $validation = true; } break; } $this->cache->validation($this->currentSubSpec, $validation); return $validation; }
php
private function validateSubSpec() { if ('!' != $this->currentSubSpec['operator'] && '?' != $this->currentSubSpec['operator']) { // skip left subTerm on operators ! and ? if (false === ($this->currentSubSpec['leftSubTerm'] instanceof CK\MARCspec\ComparisonStringInterface)) { $leftSubTermReference = new self( $this->currentSubSpec['leftSubTerm'], $this->record, $this->cache ); if (!$leftSubTerm = $leftSubTermReference->content) { // see 2.3.4 SubSpec validation return $this->cache->validation($this->currentSubSpec, false); } } else { // is a CK\MARCspec\ComparisonStringInterface $leftSubTerm[] = $this->currentSubSpec['leftSubTerm']['comparable']; } } if (false === ($this->currentSubSpec['rightSubTerm'] instanceof CK\MARCspec\ComparisonStringInterface)) { $rightSubTermReference = new self( $this->currentSubSpec['rightSubTerm'], $this->record, $this->cache ); $rightSubTerm = $rightSubTermReference->content; // content maybe an empty array } else { // is a CK\MARCspec\ComparisonStringInterface $rightSubTerm[] = $this->currentSubSpec['rightSubTerm']['comparable']; } $validation = false; switch ($this->currentSubSpec['operator']) { case '=': if (0 < count(array_intersect($leftSubTerm, $rightSubTerm))) { $validation = true; } break; case '!=': if (0 < count(array_diff($leftSubTerm, $rightSubTerm))) { $validation = true; } break; case '~': if (0 < count( array_uintersect( $leftSubTerm, $rightSubTerm, function ($v1, $v2) { if (strpos($v1, $v2) !== false) { return 0; } return -1; } ) ) ) { $validation = true; } break; case '!~': if (0 < count( array_uintersect( $leftSubTerm, $rightSubTerm, function ($v1, $v2) { if (strpos($v1, $v2) === false) { return 0; } return -1; } ) ) ) { $validation = true; } break; case '?': if ($rightSubTerm) { $validation = true; } break; case '!': if (!$rightSubTerm) { $validation = true; } break; } $this->cache->validation($this->currentSubSpec, $validation); return $validation; }
[ "private", "function", "validateSubSpec", "(", ")", "{", "if", "(", "'!'", "!=", "$", "this", "->", "currentSubSpec", "[", "'operator'", "]", "&&", "'?'", "!=", "$", "this", "->", "currentSubSpec", "[", "'operator'", "]", ")", "{", "// skip left subTerm on operators ! and ?", "if", "(", "false", "===", "(", "$", "this", "->", "currentSubSpec", "[", "'leftSubTerm'", "]", "instanceof", "CK", "\\", "MARCspec", "\\", "ComparisonStringInterface", ")", ")", "{", "$", "leftSubTermReference", "=", "new", "self", "(", "$", "this", "->", "currentSubSpec", "[", "'leftSubTerm'", "]", ",", "$", "this", "->", "record", ",", "$", "this", "->", "cache", ")", ";", "if", "(", "!", "$", "leftSubTerm", "=", "$", "leftSubTermReference", "->", "content", ")", "{", "// see 2.3.4 SubSpec validation", "return", "$", "this", "->", "cache", "->", "validation", "(", "$", "this", "->", "currentSubSpec", ",", "false", ")", ";", "}", "}", "else", "{", "// is a CK\\MARCspec\\ComparisonStringInterface", "$", "leftSubTerm", "[", "]", "=", "$", "this", "->", "currentSubSpec", "[", "'leftSubTerm'", "]", "[", "'comparable'", "]", ";", "}", "}", "if", "(", "false", "===", "(", "$", "this", "->", "currentSubSpec", "[", "'rightSubTerm'", "]", "instanceof", "CK", "\\", "MARCspec", "\\", "ComparisonStringInterface", ")", ")", "{", "$", "rightSubTermReference", "=", "new", "self", "(", "$", "this", "->", "currentSubSpec", "[", "'rightSubTerm'", "]", ",", "$", "this", "->", "record", ",", "$", "this", "->", "cache", ")", ";", "$", "rightSubTerm", "=", "$", "rightSubTermReference", "->", "content", ";", "// content maybe an empty array", "}", "else", "{", "// is a CK\\MARCspec\\ComparisonStringInterface", "$", "rightSubTerm", "[", "]", "=", "$", "this", "->", "currentSubSpec", "[", "'rightSubTerm'", "]", "[", "'comparable'", "]", ";", "}", "$", "validation", "=", "false", ";", "switch", "(", "$", "this", "->", "currentSubSpec", "[", "'operator'", "]", ")", "{", "case", "'='", ":", "if", "(", "0", "<", "count", "(", "array_intersect", "(", "$", "leftSubTerm", ",", "$", "rightSubTerm", ")", ")", ")", "{", "$", "validation", "=", "true", ";", "}", "break", ";", "case", "'!='", ":", "if", "(", "0", "<", "count", "(", "array_diff", "(", "$", "leftSubTerm", ",", "$", "rightSubTerm", ")", ")", ")", "{", "$", "validation", "=", "true", ";", "}", "break", ";", "case", "'~'", ":", "if", "(", "0", "<", "count", "(", "array_uintersect", "(", "$", "leftSubTerm", ",", "$", "rightSubTerm", ",", "function", "(", "$", "v1", ",", "$", "v2", ")", "{", "if", "(", "strpos", "(", "$", "v1", ",", "$", "v2", ")", "!==", "false", ")", "{", "return", "0", ";", "}", "return", "-", "1", ";", "}", ")", ")", ")", "{", "$", "validation", "=", "true", ";", "}", "break", ";", "case", "'!~'", ":", "if", "(", "0", "<", "count", "(", "array_uintersect", "(", "$", "leftSubTerm", ",", "$", "rightSubTerm", ",", "function", "(", "$", "v1", ",", "$", "v2", ")", "{", "if", "(", "strpos", "(", "$", "v1", ",", "$", "v2", ")", "===", "false", ")", "{", "return", "0", ";", "}", "return", "-", "1", ";", "}", ")", ")", ")", "{", "$", "validation", "=", "true", ";", "}", "break", ";", "case", "'?'", ":", "if", "(", "$", "rightSubTerm", ")", "{", "$", "validation", "=", "true", ";", "}", "break", ";", "case", "'!'", ":", "if", "(", "!", "$", "rightSubTerm", ")", "{", "$", "validation", "=", "true", ";", "}", "break", ";", "}", "$", "this", "->", "cache", "->", "validation", "(", "$", "this", "->", "currentSubSpec", ",", "$", "validation", ")", ";", "return", "$", "validation", ";", "}" ]
Validates a subSpec. @return bool True if subSpec is valid and false if not
[ "Validates", "a", "subSpec", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L274-L372
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.referenceFieldsByTag
private function referenceFieldsByTag() { $tag = $this->spec['field']['tag']; if ($this->cache->offsetExists($tag)) { return $this->cache[$tag]; } if ('LDR' !== $tag) { $_fieldRef = $this->record->getFields($tag, true); } else { // tag = LDR $_fieldRef[] = $this->record->getLeader(); } $this->cache[$tag] = $_fieldRef; return $_fieldRef; }
php
private function referenceFieldsByTag() { $tag = $this->spec['field']['tag']; if ($this->cache->offsetExists($tag)) { return $this->cache[$tag]; } if ('LDR' !== $tag) { $_fieldRef = $this->record->getFields($tag, true); } else { // tag = LDR $_fieldRef[] = $this->record->getLeader(); } $this->cache[$tag] = $_fieldRef; return $_fieldRef; }
[ "private", "function", "referenceFieldsByTag", "(", ")", "{", "$", "tag", "=", "$", "this", "->", "spec", "[", "'field'", "]", "[", "'tag'", "]", ";", "if", "(", "$", "this", "->", "cache", "->", "offsetExists", "(", "$", "tag", ")", ")", "{", "return", "$", "this", "->", "cache", "[", "$", "tag", "]", ";", "}", "if", "(", "'LDR'", "!==", "$", "tag", ")", "{", "$", "_fieldRef", "=", "$", "this", "->", "record", "->", "getFields", "(", "$", "tag", ",", "true", ")", ";", "}", "else", "{", "// tag = LDR", "$", "_fieldRef", "[", "]", "=", "$", "this", "->", "record", "->", "getLeader", "(", ")", ";", "}", "$", "this", "->", "cache", "[", "$", "tag", "]", "=", "$", "_fieldRef", ";", "return", "$", "_fieldRef", ";", "}" ]
Reference fields by field tag. @return array Array of referred fields
[ "Reference", "fields", "by", "field", "tag", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L379-L397
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.referenceFields
private function referenceFields() { if ($this->fields = $this->cache->getData($this->spec['field'])) { return $this->fields; } if (!$this->fields = $this->referenceFieldsByTag()) { return; } /* * filter by indizes */ if ($_indexRange = $this->getIndexRange($this->spec['field'], count($this->fields))) { $prevTag = ''; $index = 0; foreach ($this->fields as $position => $field) { if (false == ($field instanceof File_MARC_Field)) { continue; } $tag = $field->getTag(); $index = ($prevTag == $tag or '' == $prevTag) ? $index : 0; if (!in_array($index, $_indexRange)) { unset($this->fields[$position]); } $index++; $prevTag = $tag; } } /* * filter for indicator values */ if ($this->spec->offsetExists('indicator')) { foreach ($this->fields as $key => $field) { // only filter by indicators for data fields if (!$field->isDataField()) { // control field have no indicators unset($this->fields[$key]); } } } }
php
private function referenceFields() { if ($this->fields = $this->cache->getData($this->spec['field'])) { return $this->fields; } if (!$this->fields = $this->referenceFieldsByTag()) { return; } /* * filter by indizes */ if ($_indexRange = $this->getIndexRange($this->spec['field'], count($this->fields))) { $prevTag = ''; $index = 0; foreach ($this->fields as $position => $field) { if (false == ($field instanceof File_MARC_Field)) { continue; } $tag = $field->getTag(); $index = ($prevTag == $tag or '' == $prevTag) ? $index : 0; if (!in_array($index, $_indexRange)) { unset($this->fields[$position]); } $index++; $prevTag = $tag; } } /* * filter for indicator values */ if ($this->spec->offsetExists('indicator')) { foreach ($this->fields as $key => $field) { // only filter by indicators for data fields if (!$field->isDataField()) { // control field have no indicators unset($this->fields[$key]); } } } }
[ "private", "function", "referenceFields", "(", ")", "{", "if", "(", "$", "this", "->", "fields", "=", "$", "this", "->", "cache", "->", "getData", "(", "$", "this", "->", "spec", "[", "'field'", "]", ")", ")", "{", "return", "$", "this", "->", "fields", ";", "}", "if", "(", "!", "$", "this", "->", "fields", "=", "$", "this", "->", "referenceFieldsByTag", "(", ")", ")", "{", "return", ";", "}", "/*\n * filter by indizes\n */", "if", "(", "$", "_indexRange", "=", "$", "this", "->", "getIndexRange", "(", "$", "this", "->", "spec", "[", "'field'", "]", ",", "count", "(", "$", "this", "->", "fields", ")", ")", ")", "{", "$", "prevTag", "=", "''", ";", "$", "index", "=", "0", ";", "foreach", "(", "$", "this", "->", "fields", "as", "$", "position", "=>", "$", "field", ")", "{", "if", "(", "false", "==", "(", "$", "field", "instanceof", "File_MARC_Field", ")", ")", "{", "continue", ";", "}", "$", "tag", "=", "$", "field", "->", "getTag", "(", ")", ";", "$", "index", "=", "(", "$", "prevTag", "==", "$", "tag", "or", "''", "==", "$", "prevTag", ")", "?", "$", "index", ":", "0", ";", "if", "(", "!", "in_array", "(", "$", "index", ",", "$", "_indexRange", ")", ")", "{", "unset", "(", "$", "this", "->", "fields", "[", "$", "position", "]", ")", ";", "}", "$", "index", "++", ";", "$", "prevTag", "=", "$", "tag", ";", "}", "}", "/*\n * filter for indicator values\n */", "if", "(", "$", "this", "->", "spec", "->", "offsetExists", "(", "'indicator'", ")", ")", "{", "foreach", "(", "$", "this", "->", "fields", "as", "$", "key", "=>", "$", "field", ")", "{", "// only filter by indicators for data fields", "if", "(", "!", "$", "field", "->", "isDataField", "(", ")", ")", "{", "// control field have no indicators", "unset", "(", "$", "this", "->", "fields", "[", "$", "key", "]", ")", ";", "}", "}", "}", "}" ]
Reference fields. Filter by index and indicator. @return array Array of referenced fields
[ "Reference", "fields", ".", "Filter", "by", "index", "and", "indicator", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L404-L446
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.referenceSubfields
private function referenceSubfields($currentSubfieldSpec) { $baseSubfieldSpec = $this->baseSpec.$currentSubfieldSpec->getBaseSpec(); if ($subfields = $this->cache->getData($this->currentSpec['field'], $currentSubfieldSpec)) { return $subfields; } $_subfields = $this->field->getSubfields($currentSubfieldSpec['tag']); if (!$_subfields) { $this->cache[$baseSubfieldSpec] = []; return []; } /* filter on indizes */ if ($_indexRange = $this->getIndexRange($currentSubfieldSpec, count($_subfields))) { foreach ($_subfields as $sfkey => $item) { if (!in_array($sfkey, $_indexRange) || $item->isEmpty()) { unset($_subfields[$sfkey]); } } } if ($_subfields) { $sf_values = array_values($_subfields); $this->cache[$baseSubfieldSpec] = $sf_values; return $sf_values; } $this->cache[$baseSubfieldSpec] = []; return []; }
php
private function referenceSubfields($currentSubfieldSpec) { $baseSubfieldSpec = $this->baseSpec.$currentSubfieldSpec->getBaseSpec(); if ($subfields = $this->cache->getData($this->currentSpec['field'], $currentSubfieldSpec)) { return $subfields; } $_subfields = $this->field->getSubfields($currentSubfieldSpec['tag']); if (!$_subfields) { $this->cache[$baseSubfieldSpec] = []; return []; } /* filter on indizes */ if ($_indexRange = $this->getIndexRange($currentSubfieldSpec, count($_subfields))) { foreach ($_subfields as $sfkey => $item) { if (!in_array($sfkey, $_indexRange) || $item->isEmpty()) { unset($_subfields[$sfkey]); } } } if ($_subfields) { $sf_values = array_values($_subfields); $this->cache[$baseSubfieldSpec] = $sf_values; return $sf_values; } $this->cache[$baseSubfieldSpec] = []; return []; }
[ "private", "function", "referenceSubfields", "(", "$", "currentSubfieldSpec", ")", "{", "$", "baseSubfieldSpec", "=", "$", "this", "->", "baseSpec", ".", "$", "currentSubfieldSpec", "->", "getBaseSpec", "(", ")", ";", "if", "(", "$", "subfields", "=", "$", "this", "->", "cache", "->", "getData", "(", "$", "this", "->", "currentSpec", "[", "'field'", "]", ",", "$", "currentSubfieldSpec", ")", ")", "{", "return", "$", "subfields", ";", "}", "$", "_subfields", "=", "$", "this", "->", "field", "->", "getSubfields", "(", "$", "currentSubfieldSpec", "[", "'tag'", "]", ")", ";", "if", "(", "!", "$", "_subfields", ")", "{", "$", "this", "->", "cache", "[", "$", "baseSubfieldSpec", "]", "=", "[", "]", ";", "return", "[", "]", ";", "}", "/* filter on indizes */", "if", "(", "$", "_indexRange", "=", "$", "this", "->", "getIndexRange", "(", "$", "currentSubfieldSpec", ",", "count", "(", "$", "_subfields", ")", ")", ")", "{", "foreach", "(", "$", "_subfields", "as", "$", "sfkey", "=>", "$", "item", ")", "{", "if", "(", "!", "in_array", "(", "$", "sfkey", ",", "$", "_indexRange", ")", "||", "$", "item", "->", "isEmpty", "(", ")", ")", "{", "unset", "(", "$", "_subfields", "[", "$", "sfkey", "]", ")", ";", "}", "}", "}", "if", "(", "$", "_subfields", ")", "{", "$", "sf_values", "=", "array_values", "(", "$", "_subfields", ")", ";", "$", "this", "->", "cache", "[", "$", "baseSubfieldSpec", "]", "=", "$", "sf_values", ";", "return", "$", "sf_values", ";", "}", "$", "this", "->", "cache", "[", "$", "baseSubfieldSpec", "]", "=", "[", "]", ";", "return", "[", "]", ";", "}" ]
Reference subfield contents and filter by index. @param SubfieldInterface $currentSubfieldSpec The current subfield spec @return array An array of referenced subfields
[ "Reference", "subfield", "contents", "and", "filter", "by", "index", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L455-L490
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.getIndexRange
private function getIndexRange($spec, $total) { $lastIndex = $total - 1; $indexStart = $spec['indexStart']; $indexEnd = $spec['indexEnd']; if ('#' === $indexStart) { if ('#' === $indexEnd or 0 === $indexEnd) { return [$lastIndex]; } $indexStart = $lastIndex; $indexEnd = $lastIndex - $indexEnd; $indexEnd = (0 > $indexEnd) ? 0 : $indexEnd; } else { if ($lastIndex < $indexStart) { return [$indexStart]; // this will result to no hits } $indexEnd = ('#' === $indexEnd) ? $lastIndex : $indexEnd; if ($indexEnd > $lastIndex) { $indexEnd = $lastIndex; } } return range($indexStart, $indexEnd); }
php
private function getIndexRange($spec, $total) { $lastIndex = $total - 1; $indexStart = $spec['indexStart']; $indexEnd = $spec['indexEnd']; if ('#' === $indexStart) { if ('#' === $indexEnd or 0 === $indexEnd) { return [$lastIndex]; } $indexStart = $lastIndex; $indexEnd = $lastIndex - $indexEnd; $indexEnd = (0 > $indexEnd) ? 0 : $indexEnd; } else { if ($lastIndex < $indexStart) { return [$indexStart]; // this will result to no hits } $indexEnd = ('#' === $indexEnd) ? $lastIndex : $indexEnd; if ($indexEnd > $lastIndex) { $indexEnd = $lastIndex; } } return range($indexStart, $indexEnd); }
[ "private", "function", "getIndexRange", "(", "$", "spec", ",", "$", "total", ")", "{", "$", "lastIndex", "=", "$", "total", "-", "1", ";", "$", "indexStart", "=", "$", "spec", "[", "'indexStart'", "]", ";", "$", "indexEnd", "=", "$", "spec", "[", "'indexEnd'", "]", ";", "if", "(", "'#'", "===", "$", "indexStart", ")", "{", "if", "(", "'#'", "===", "$", "indexEnd", "or", "0", "===", "$", "indexEnd", ")", "{", "return", "[", "$", "lastIndex", "]", ";", "}", "$", "indexStart", "=", "$", "lastIndex", ";", "$", "indexEnd", "=", "$", "lastIndex", "-", "$", "indexEnd", ";", "$", "indexEnd", "=", "(", "0", ">", "$", "indexEnd", ")", "?", "0", ":", "$", "indexEnd", ";", "}", "else", "{", "if", "(", "$", "lastIndex", "<", "$", "indexStart", ")", "{", "return", "[", "$", "indexStart", "]", ";", "// this will result to no hits", "}", "$", "indexEnd", "=", "(", "'#'", "===", "$", "indexEnd", ")", "?", "$", "lastIndex", ":", "$", "indexEnd", ";", "if", "(", "$", "indexEnd", ">", "$", "lastIndex", ")", "{", "$", "indexEnd", "=", "$", "lastIndex", ";", "}", "}", "return", "range", "(", "$", "indexStart", ",", "$", "indexEnd", ")", ";", "}" ]
Calculates a range from indexStart and indexEnd. @param array $spec The spec with possible indizes @param int $total Total count of (sub)fields @return array The range of indizes
[ "Calculates", "a", "range", "from", "indexStart", "and", "indexEnd", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L500-L524
MARCspec/File_MARC_Reference
src/File_MARC_Reference.php
File_MARC_Reference.ref
public function ref($spec, $value) { array_push($this->data, $value); /* * set content */ $value = $this->cache->getContents($spec, [$value]); $this->content = array_merge($this->content, $value); }
php
public function ref($spec, $value) { array_push($this->data, $value); /* * set content */ $value = $this->cache->getContents($spec, [$value]); $this->content = array_merge($this->content, $value); }
[ "public", "function", "ref", "(", "$", "spec", ",", "$", "value", ")", "{", "array_push", "(", "$", "this", "->", "data", ",", "$", "value", ")", ";", "/*\n * set content\n */", "$", "value", "=", "$", "this", "->", "cache", "->", "getContents", "(", "$", "spec", ",", "[", "$", "value", "]", ")", ";", "$", "this", "->", "content", "=", "array_merge", "(", "$", "this", "->", "content", ",", "$", "value", ")", ";", "}" ]
Reference data and set content. @param FieldInterface|SubfieldInterface $spec The corresponding spec @param string|File_MARC_Field|File_MARC_Subfield $value The value to reference
[ "Reference", "data", "and", "set", "content", "." ]
train
https://github.com/MARCspec/File_MARC_Reference/blob/29abbff5bec5e3bcfeeb07ba7bee94cc0a0a7f5e/src/File_MARC_Reference.php#L532-L540
PaulJulio/php-slim-amazon-echo
src/ResponseCard.php
ResponseCard.getAsArray
public function getAsArray() { $a = []; if (isset($this->type)) { $a['type'] = $this->type; } if (isset($this->title)) { $a['title'] = $this->title; } if (isset($this->content)) { $a['content'] = $this->content; } return $a; }
php
public function getAsArray() { $a = []; if (isset($this->type)) { $a['type'] = $this->type; } if (isset($this->title)) { $a['title'] = $this->title; } if (isset($this->content)) { $a['content'] = $this->content; } return $a; }
[ "public", "function", "getAsArray", "(", ")", "{", "$", "a", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "type", ")", ")", "{", "$", "a", "[", "'type'", "]", "=", "$", "this", "->", "type", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "title", ")", ")", "{", "$", "a", "[", "'title'", "]", "=", "$", "this", "->", "title", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "content", ")", ")", "{", "$", "a", "[", "'content'", "]", "=", "$", "this", "->", "content", ";", "}", "return", "$", "a", ";", "}" ]
@return array An array suitable for passing to \PaulJulio\StreamJson\StreamJson
[ "@return", "array" ]
train
https://github.com/PaulJulio/php-slim-amazon-echo/blob/a11a1dd9a085dc8ce519b787bf01ade14c92b4df/src/ResponseCard.php#L42-L54
xZ1mEFx/yii2-base
web/User.php
User.cannot
public function cannot($permissionName, $params = [], $allowCaching = TRUE) { return !$this->can($permissionName, $params, $allowCaching); }
php
public function cannot($permissionName, $params = [], $allowCaching = TRUE) { return !$this->can($permissionName, $params, $allowCaching); }
[ "public", "function", "cannot", "(", "$", "permissionName", ",", "$", "params", "=", "[", "]", ",", "$", "allowCaching", "=", "TRUE", ")", "{", "return", "!", "$", "this", "->", "can", "(", "$", "permissionName", ",", "$", "params", ",", "$", "allowCaching", ")", ";", "}" ]
Checks if the user cannot perform the operation as specified by the given permission. Note that you must configure "authManager" application component in order to use this method. Otherwise it will always return false. @param string|array $permissionName the name(s) of the permission (e.g. "edit post") that needs access check. @param array $params name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user. @param boolean $allowCaching whether to allow caching the result of access check. When this parameter is true (default), if the access check of an operation was performed before, its result will be directly returned when calling this method to check the same operation. If this parameter is false, this method will always call [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this caching is effective only within the same request and only works when `$params = []`. @return boolean whether the user cannot perform the operation as specified by the given permission.
[ "Checks", "if", "the", "user", "cannot", "perform", "the", "operation", "as", "specified", "by", "the", "given", "permission", "." ]
train
https://github.com/xZ1mEFx/yii2-base/blob/f6633c08ccccb7eb5ac000dfae0db26cb2e0a76a/web/User.php#L31-L34
xZ1mEFx/yii2-base
web/User.php
User.can
public function can($permissionName, $params = [], $allowCaching = TRUE) { if (is_array($permissionName)) { foreach (array_unique($permissionName) as $permissionNameItem) { if (parent::can($permissionNameItem, $params, $allowCaching)) { return TRUE; } } return FALSE; } return parent::can($permissionName, $params, $allowCaching); }
php
public function can($permissionName, $params = [], $allowCaching = TRUE) { if (is_array($permissionName)) { foreach (array_unique($permissionName) as $permissionNameItem) { if (parent::can($permissionNameItem, $params, $allowCaching)) { return TRUE; } } return FALSE; } return parent::can($permissionName, $params, $allowCaching); }
[ "public", "function", "can", "(", "$", "permissionName", ",", "$", "params", "=", "[", "]", ",", "$", "allowCaching", "=", "TRUE", ")", "{", "if", "(", "is_array", "(", "$", "permissionName", ")", ")", "{", "foreach", "(", "array_unique", "(", "$", "permissionName", ")", "as", "$", "permissionNameItem", ")", "{", "if", "(", "parent", "::", "can", "(", "$", "permissionNameItem", ",", "$", "params", ",", "$", "allowCaching", ")", ")", "{", "return", "TRUE", ";", "}", "}", "return", "FALSE", ";", "}", "return", "parent", "::", "can", "(", "$", "permissionName", ",", "$", "params", ",", "$", "allowCaching", ")", ";", "}" ]
Checks if the user can perform the operation as specified by the given permission. Note that you must configure "authManager" application component in order to use this method. Otherwise it will always return false. @param string|array $permissionName the name(s) of the permission (e.g. "edit post") that needs access check. @param array $params name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user. @param boolean $allowCaching whether to allow caching the result of access check. When this parameter is true (default), if the access check of an operation was performed before, its result will be directly returned when calling this method to check the same operation. If this parameter is false, this method will always call [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this caching is effective only within the same request and only works when `$params = []`. @return boolean whether the user can perform the operation as specified by the given permission.
[ "Checks", "if", "the", "user", "can", "perform", "the", "operation", "as", "specified", "by", "the", "given", "permission", "." ]
train
https://github.com/xZ1mEFx/yii2-base/blob/f6633c08ccccb7eb5ac000dfae0db26cb2e0a76a/web/User.php#L56-L67
enikeishik/ufoframework
src/Ufo/Core/Config.php
Config.load
public function load(string $configPath, $overwrite = false): void { if (!file_exists($configPath)) { return; } $config = include $configPath; if (!is_array($config) && !is_object($config)) { return; } if (is_object($config)) { $config = get_object_vars($config); } $this->loadArray($config, $overwrite); }
php
public function load(string $configPath, $overwrite = false): void { if (!file_exists($configPath)) { return; } $config = include $configPath; if (!is_array($config) && !is_object($config)) { return; } if (is_object($config)) { $config = get_object_vars($config); } $this->loadArray($config, $overwrite); }
[ "public", "function", "load", "(", "string", "$", "configPath", ",", "$", "overwrite", "=", "false", ")", ":", "void", "{", "if", "(", "!", "file_exists", "(", "$", "configPath", ")", ")", "{", "return", ";", "}", "$", "config", "=", "include", "$", "configPath", ";", "if", "(", "!", "is_array", "(", "$", "config", ")", "&&", "!", "is_object", "(", "$", "config", ")", ")", "{", "return", ";", "}", "if", "(", "is_object", "(", "$", "config", ")", ")", "{", "$", "config", "=", "get_object_vars", "(", "$", "config", ")", ";", "}", "$", "this", "->", "loadArray", "(", "$", "config", ",", "$", "overwrite", ")", ";", "}" ]
Loads configuration from configuration file. @param string $configPath @param bool $overwrite = false
[ "Loads", "configuration", "from", "configuration", "file", "." ]
train
https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Core/Config.php#L162-L175
enikeishik/ufoframework
src/Ufo/Core/Config.php
Config.loadWithDefault
public function loadWithDefault(string $configPath, string $defaultConfigPath): void { if (!file_exists($configPath)) { return; } $configDefault = include $defaultConfigPath; $config = include $configPath; if (!is_array($configDefault) && !is_array($config)) { return; } $this->loadArray(array_merge($configDefault, $config)); }
php
public function loadWithDefault(string $configPath, string $defaultConfigPath): void { if (!file_exists($configPath)) { return; } $configDefault = include $defaultConfigPath; $config = include $configPath; if (!is_array($configDefault) && !is_array($config)) { return; } $this->loadArray(array_merge($configDefault, $config)); }
[ "public", "function", "loadWithDefault", "(", "string", "$", "configPath", ",", "string", "$", "defaultConfigPath", ")", ":", "void", "{", "if", "(", "!", "file_exists", "(", "$", "configPath", ")", ")", "{", "return", ";", "}", "$", "configDefault", "=", "include", "$", "defaultConfigPath", ";", "$", "config", "=", "include", "$", "configPath", ";", "if", "(", "!", "is_array", "(", "$", "configDefault", ")", "&&", "!", "is_array", "(", "$", "config", ")", ")", "{", "return", ";", "}", "$", "this", "->", "loadArray", "(", "array_merge", "(", "$", "configDefault", ",", "$", "config", ")", ")", ";", "}" ]
Loads configuration from configuration file, and from default configuration file. @param string $configPath @param string $defaultConfigPath
[ "Loads", "configuration", "from", "configuration", "file", "and", "from", "default", "configuration", "file", "." ]
train
https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Core/Config.php#L182-L193
enikeishik/ufoframework
src/Ufo/Core/Config.php
Config.loadArray
public function loadArray(array $config, $overwrite = false): void { foreach ($config as $name => $value) { if (!$overwrite && property_exists($this, $name)) { continue; } $this->$name = $value; } }
php
public function loadArray(array $config, $overwrite = false): void { foreach ($config as $name => $value) { if (!$overwrite && property_exists($this, $name)) { continue; } $this->$name = $value; } }
[ "public", "function", "loadArray", "(", "array", "$", "config", ",", "$", "overwrite", "=", "false", ")", ":", "void", "{", "foreach", "(", "$", "config", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "$", "overwrite", "&&", "property_exists", "(", "$", "this", ",", "$", "name", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "$", "name", "=", "$", "value", ";", "}", "}" ]
Loads configuration from array. @param array $config @param bool $overwrite = false
[ "Loads", "configuration", "from", "array", "." ]
train
https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Core/Config.php#L200-L208
enikeishik/ufoframework
src/Ufo/Core/Config.php
Config.loadFromIni
public function loadFromIni(string $iniPath, bool $overwrite = false): void { if (!file_exists($iniPath)) { return; } $iniArr = null; try { $iniArr = parse_ini_file($iniPath, false, INI_SCANNER_TYPED); } catch (\Throwable $e) { } if (!is_array($iniArr)) { return; } $iniArr = array_change_key_case($iniArr, CASE_LOWER); $arr = []; foreach ($iniArr as $name => $value) { $arr[lcfirst(str_replace('_', '', ucwords(str_replace('.', '_', $name), '_')))] = $value; } $this->loadArray($arr, $overwrite); }
php
public function loadFromIni(string $iniPath, bool $overwrite = false): void { if (!file_exists($iniPath)) { return; } $iniArr = null; try { $iniArr = parse_ini_file($iniPath, false, INI_SCANNER_TYPED); } catch (\Throwable $e) { } if (!is_array($iniArr)) { return; } $iniArr = array_change_key_case($iniArr, CASE_LOWER); $arr = []; foreach ($iniArr as $name => $value) { $arr[lcfirst(str_replace('_', '', ucwords(str_replace('.', '_', $name), '_')))] = $value; } $this->loadArray($arr, $overwrite); }
[ "public", "function", "loadFromIni", "(", "string", "$", "iniPath", ",", "bool", "$", "overwrite", "=", "false", ")", ":", "void", "{", "if", "(", "!", "file_exists", "(", "$", "iniPath", ")", ")", "{", "return", ";", "}", "$", "iniArr", "=", "null", ";", "try", "{", "$", "iniArr", "=", "parse_ini_file", "(", "$", "iniPath", ",", "false", ",", "INI_SCANNER_TYPED", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "}", "if", "(", "!", "is_array", "(", "$", "iniArr", ")", ")", "{", "return", ";", "}", "$", "iniArr", "=", "array_change_key_case", "(", "$", "iniArr", ",", "CASE_LOWER", ")", ";", "$", "arr", "=", "[", "]", ";", "foreach", "(", "$", "iniArr", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "arr", "[", "lcfirst", "(", "str_replace", "(", "'_'", ",", "''", ",", "ucwords", "(", "str_replace", "(", "'.'", ",", "'_'", ",", "$", "name", ")", ",", "'_'", ")", ")", ")", "]", "=", "$", "value", ";", "}", "$", "this", "->", "loadArray", "(", "$", "arr", ",", "$", "overwrite", ")", ";", "}" ]
Loads configuration from INI file. @param string $iniPath @param bool $overwrite = false
[ "Loads", "configuration", "from", "INI", "file", "." ]
train
https://github.com/enikeishik/ufoframework/blob/fb44461bcb0506dbc3257724a2281f756594f62f/src/Ufo/Core/Config.php#L215-L237
phossa/phossa-logger
src/Phossa/Logger/LogEntry.php
LogEntry.setLevel
public function setLevel( /*# string */ $level = LogLevel::INFO )/*# : LogEntryInterface */ { // check level LogLevel::getLevelCode($level); // set level $this->level = $level; return $this; }
php
public function setLevel( /*# string */ $level = LogLevel::INFO )/*# : LogEntryInterface */ { // check level LogLevel::getLevelCode($level); // set level $this->level = $level; return $this; }
[ "public", "function", "setLevel", "(", "/*# string */", "$", "level", "=", "LogLevel", "::", "INFO", ")", "/*# : LogEntryInterface */", "{", "// check level", "LogLevel", "::", "getLevelCode", "(", "$", "level", ")", ";", "// set level", "$", "this", "->", "level", "=", "$", "level", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-logger/blob/dfec8a1e6015c66d2aa77134077902fd3d49e41d/src/Phossa/Logger/LogEntry.php#L105-L115
phossa/phossa-logger
src/Phossa/Logger/LogEntry.php
LogEntry.getContext
public function getContext(/*# string */ $name) { if (is_string($name) && isset($this->context[$name])) { return $this->context[$name]; } return null; }
php
public function getContext(/*# string */ $name) { if (is_string($name) && isset($this->context[$name])) { return $this->context[$name]; } return null; }
[ "public", "function", "getContext", "(", "/*# string */", "$", "name", ")", "{", "if", "(", "is_string", "(", "$", "name", ")", "&&", "isset", "(", "$", "this", "->", "context", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "context", "[", "$", "name", "]", ";", "}", "return", "null", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-logger/blob/dfec8a1e6015c66d2aa77134077902fd3d49e41d/src/Phossa/Logger/LogEntry.php#L174-L180
sndsgd/http
src/http/data/decoder/MultipartDataDecoder.php
MultipartDataDecoder.getBoundary
protected function getBoundary() { $pos = strpos($this->contentType, "boundary="); if ($pos === false) { throw new \sndsgd\http\data\DecodeException( "missing value for 'boundary' in content-type header" ); } return "--".substr($this->contentType, $pos + 9); }
php
protected function getBoundary() { $pos = strpos($this->contentType, "boundary="); if ($pos === false) { throw new \sndsgd\http\data\DecodeException( "missing value for 'boundary' in content-type header" ); } return "--".substr($this->contentType, $pos + 9); }
[ "protected", "function", "getBoundary", "(", ")", "{", "$", "pos", "=", "strpos", "(", "$", "this", "->", "contentType", ",", "\"boundary=\"", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "{", "throw", "new", "\\", "sndsgd", "\\", "http", "\\", "data", "\\", "DecodeException", "(", "\"missing value for 'boundary' in content-type header\"", ")", ";", "}", "return", "\"--\"", ".", "substr", "(", "$", "this", "->", "contentType", ",", "$", "pos", "+", "9", ")", ";", "}" ]
Retrieve the parameter boundary from the content type header @return string @throws \sndsgd\http\data\DecodeException If a boundary is not present
[ "Retrieve", "the", "parameter", "boundary", "from", "the", "content", "type", "header" ]
train
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/MultipartDataDecoder.php#L125-L134
sndsgd/http
src/http/data/decoder/MultipartDataDecoder.php
MultipartDataDecoder.fieldsRemain
protected function fieldsRemain() { $bufferlen = strlen($this->buffer); $minlen = strlen($this->lastBoundary); # if the buffer is too short to contain the last boundary # read enough bytes into the buffer to allow for a strpos test if ($bufferlen < $minlen) { if (feof($this->fp)) { fclose($this->fp); throw new \sndsgd\http\data\DecodeException( "Invalid multipart data encountered; ". "end of content was reached before expected" ); } $bytes = fread($this->fp, $this->bytesPerRead); if ($bytes === false) { fclose($this->fp); throw new \RuntimeException( "failed to read $minlen bytes from input stream" ); } $this->buffer .= $bytes; } # if the buffer starts with the last boundary, there are no more fields return (strpos($this->buffer, $this->lastBoundary) !== 0); }
php
protected function fieldsRemain() { $bufferlen = strlen($this->buffer); $minlen = strlen($this->lastBoundary); # if the buffer is too short to contain the last boundary # read enough bytes into the buffer to allow for a strpos test if ($bufferlen < $minlen) { if (feof($this->fp)) { fclose($this->fp); throw new \sndsgd\http\data\DecodeException( "Invalid multipart data encountered; ". "end of content was reached before expected" ); } $bytes = fread($this->fp, $this->bytesPerRead); if ($bytes === false) { fclose($this->fp); throw new \RuntimeException( "failed to read $minlen bytes from input stream" ); } $this->buffer .= $bytes; } # if the buffer starts with the last boundary, there are no more fields return (strpos($this->buffer, $this->lastBoundary) !== 0); }
[ "protected", "function", "fieldsRemain", "(", ")", "{", "$", "bufferlen", "=", "strlen", "(", "$", "this", "->", "buffer", ")", ";", "$", "minlen", "=", "strlen", "(", "$", "this", "->", "lastBoundary", ")", ";", "# if the buffer is too short to contain the last boundary", "# read enough bytes into the buffer to allow for a strpos test", "if", "(", "$", "bufferlen", "<", "$", "minlen", ")", "{", "if", "(", "feof", "(", "$", "this", "->", "fp", ")", ")", "{", "fclose", "(", "$", "this", "->", "fp", ")", ";", "throw", "new", "\\", "sndsgd", "\\", "http", "\\", "data", "\\", "DecodeException", "(", "\"Invalid multipart data encountered; \"", ".", "\"end of content was reached before expected\"", ")", ";", "}", "$", "bytes", "=", "fread", "(", "$", "this", "->", "fp", ",", "$", "this", "->", "bytesPerRead", ")", ";", "if", "(", "$", "bytes", "===", "false", ")", "{", "fclose", "(", "$", "this", "->", "fp", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "\"failed to read $minlen bytes from input stream\"", ")", ";", "}", "$", "this", "->", "buffer", ".=", "$", "bytes", ";", "}", "# if the buffer starts with the last boundary, there are no more fields", "return", "(", "strpos", "(", "$", "this", "->", "buffer", ",", "$", "this", "->", "lastBoundary", ")", "!==", "0", ")", ";", "}" ]
Determine if any more fields remain in the stream @return bool
[ "Determine", "if", "any", "more", "fields", "remain", "in", "the", "stream" ]
train
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/MultipartDataDecoder.php#L141-L170
sndsgd/http
src/http/data/decoder/MultipartDataDecoder.php
MultipartDataDecoder.getFieldHeader
protected function getFieldHeader() { # read the input stream until the empty line after the header $position = $this->readUntil("\r\n\r\n"); # separate the header from the field content # remove the header content from the buffer $header = substr($this->buffer, 0, $position); $this->buffer = substr($this->buffer, $position + 4); $regex = "/content-disposition:[\t ]+?form-data;". "[\t ]+(?:name=\"(.*?)\")?". "(?:;[\t ]+?filename=\"(.*?)\")?/i"; if (preg_match($regex, $header, $matches) !== 1) { fclose($this->fp); throw new \sndsgd\http\data\DecodeException( "Invalid multipart data; 'Content-Disposition' ". "malformed or missing in file field header" ); } # we have no need for the entire match, so we drop it here list( , $name, $filename) = array_pad($matches, 3, ""); # if a filename was in the content disposition # attempt to find its content type in the field header if ($filename !== "") { $regex = "/content-type:[\t ]+?(.*)(?:;|$)/mi"; if (preg_match($regex, $header, $matches) === 1) { $contentType = strtolower($matches[1]); } else { $contentType = ""; } } else { $contentType = ""; } return [$name, $filename, $contentType]; }
php
protected function getFieldHeader() { # read the input stream until the empty line after the header $position = $this->readUntil("\r\n\r\n"); # separate the header from the field content # remove the header content from the buffer $header = substr($this->buffer, 0, $position); $this->buffer = substr($this->buffer, $position + 4); $regex = "/content-disposition:[\t ]+?form-data;". "[\t ]+(?:name=\"(.*?)\")?". "(?:;[\t ]+?filename=\"(.*?)\")?/i"; if (preg_match($regex, $header, $matches) !== 1) { fclose($this->fp); throw new \sndsgd\http\data\DecodeException( "Invalid multipart data; 'Content-Disposition' ". "malformed or missing in file field header" ); } # we have no need for the entire match, so we drop it here list( , $name, $filename) = array_pad($matches, 3, ""); # if a filename was in the content disposition # attempt to find its content type in the field header if ($filename !== "") { $regex = "/content-type:[\t ]+?(.*)(?:;|$)/mi"; if (preg_match($regex, $header, $matches) === 1) { $contentType = strtolower($matches[1]); } else { $contentType = ""; } } else { $contentType = ""; } return [$name, $filename, $contentType]; }
[ "protected", "function", "getFieldHeader", "(", ")", "{", "# read the input stream until the empty line after the header", "$", "position", "=", "$", "this", "->", "readUntil", "(", "\"\\r\\n\\r\\n\"", ")", ";", "# separate the header from the field content", "# remove the header content from the buffer", "$", "header", "=", "substr", "(", "$", "this", "->", "buffer", ",", "0", ",", "$", "position", ")", ";", "$", "this", "->", "buffer", "=", "substr", "(", "$", "this", "->", "buffer", ",", "$", "position", "+", "4", ")", ";", "$", "regex", "=", "\"/content-disposition:[\\t ]+?form-data;\"", ".", "\"[\\t ]+(?:name=\\\"(.*?)\\\")?\"", ".", "\"(?:;[\\t ]+?filename=\\\"(.*?)\\\")?/i\"", ";", "if", "(", "preg_match", "(", "$", "regex", ",", "$", "header", ",", "$", "matches", ")", "!==", "1", ")", "{", "fclose", "(", "$", "this", "->", "fp", ")", ";", "throw", "new", "\\", "sndsgd", "\\", "http", "\\", "data", "\\", "DecodeException", "(", "\"Invalid multipart data; 'Content-Disposition' \"", ".", "\"malformed or missing in file field header\"", ")", ";", "}", "# we have no need for the entire match, so we drop it here", "list", "(", ",", "$", "name", ",", "$", "filename", ")", "=", "array_pad", "(", "$", "matches", ",", "3", ",", "\"\"", ")", ";", "# if a filename was in the content disposition", "# attempt to find its content type in the field header", "if", "(", "$", "filename", "!==", "\"\"", ")", "{", "$", "regex", "=", "\"/content-type:[\\t ]+?(.*)(?:;|$)/mi\"", ";", "if", "(", "preg_match", "(", "$", "regex", ",", "$", "header", ",", "$", "matches", ")", "===", "1", ")", "{", "$", "contentType", "=", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "else", "{", "$", "contentType", "=", "\"\"", ";", "}", "}", "else", "{", "$", "contentType", "=", "\"\"", ";", "}", "return", "[", "$", "name", ",", "$", "filename", ",", "$", "contentType", "]", ";", "}" ]
Read the header values for the current field from the input stream @return array
[ "Read", "the", "header", "values", "for", "the", "current", "field", "from", "the", "input", "stream" ]
train
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/MultipartDataDecoder.php#L198-L238
sndsgd/http
src/http/data/decoder/MultipartDataDecoder.php
MultipartDataDecoder.getValueFromField
private function getValueFromField() { $position = $this->readUntil($this->boundary); # there is always a newline after the value and before the boundary # exclude that newline from the value $value = substr($this->buffer, 0, $position - 2); # update the buffer to exclude the value and the pre boundary newline $this->buffer = substr($this->buffer, $position); return $value; }
php
private function getValueFromField() { $position = $this->readUntil($this->boundary); # there is always a newline after the value and before the boundary # exclude that newline from the value $value = substr($this->buffer, 0, $position - 2); # update the buffer to exclude the value and the pre boundary newline $this->buffer = substr($this->buffer, $position); return $value; }
[ "private", "function", "getValueFromField", "(", ")", "{", "$", "position", "=", "$", "this", "->", "readUntil", "(", "$", "this", "->", "boundary", ")", ";", "# there is always a newline after the value and before the boundary", "# exclude that newline from the value", "$", "value", "=", "substr", "(", "$", "this", "->", "buffer", ",", "0", ",", "$", "position", "-", "2", ")", ";", "# update the buffer to exclude the value and the pre boundary newline", "$", "this", "->", "buffer", "=", "substr", "(", "$", "this", "->", "buffer", ",", "$", "position", ")", ";", "return", "$", "value", ";", "}" ]
Get the value of the current field in the input stream @return string
[ "Get", "the", "value", "of", "the", "current", "field", "in", "the", "input", "stream" ]
train
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/MultipartDataDecoder.php#L245-L257
sndsgd/http
src/http/data/decoder/MultipartDataDecoder.php
MultipartDataDecoder.getFileFromField
protected function getFileFromField( string $name, string $filename, string $unverifiedContentType ) { # create and open a temp file to write the contents to $tempPath = $this->getTempFilePath(); $tempHandle = fopen($tempPath, "w"); if ($tempHandle === false) { fclose($this->fp); $message = \sndsgd\Error::createMessage( "failed to open '$tempPath' for writing" ); throw new \RuntimeException($message); } # number of bytes read from the input stream in the last loop cycle $bytesRead = 0; # the total number of bytes written to the temp file $bytesWritten = 0; # if anything is left over from the previous field, add it to the file if ($this->buffer !== "") { $bytesRead = fwrite($tempHandle, $this->buffer); if ($bytesRead === false) { fclose($this->fp); fclose($tempHandle); throw new \RuntimeException( "fwrite() failed to write to '$tempPath'" ); } $bytesWritten += $bytesRead; } while (($pos = strpos($this->buffer, $this->boundary)) === false) { $this->buffer = fread($this->fp, $this->bytesPerRead); $bytesRead = fwrite($tempHandle, $this->buffer); if ($bytesRead === false) { fclose($this->fp); fclose($tempHandle); throw new \RuntimeException( "fwrite() failed to write to '$tempPath'" ); } $bytesWritten += $bytesRead; } # determine the size of the file based on the boundary position $size = $bytesWritten - $bytesRead + $pos - 2; # trim the excess contents of the local buffer to the object buffer $this->buffer = substr($this->buffer, $pos); # if the uploaded file was empty if ($size < 1) { return $this->fileUploadError( UPLOAD_ERR_NO_FILE, $tempPath, $tempHandle, $filename, $unverifiedContentType, 0 ); } # if the file exceeded the max upload size elseif ($size > $this->maxFileSize) { return $this->fileUploadError( UPLOAD_ERR_INI_SIZE, $tempPath, $tempHandle, $filename, $unverifiedContentType, 0 ); } ftruncate($tempHandle, $size); fclose($tempHandle); return new \sndsgd\http\UploadedFile( $filename, $unverifiedContentType, $size, $tempPath ); }
php
protected function getFileFromField( string $name, string $filename, string $unverifiedContentType ) { # create and open a temp file to write the contents to $tempPath = $this->getTempFilePath(); $tempHandle = fopen($tempPath, "w"); if ($tempHandle === false) { fclose($this->fp); $message = \sndsgd\Error::createMessage( "failed to open '$tempPath' for writing" ); throw new \RuntimeException($message); } # number of bytes read from the input stream in the last loop cycle $bytesRead = 0; # the total number of bytes written to the temp file $bytesWritten = 0; # if anything is left over from the previous field, add it to the file if ($this->buffer !== "") { $bytesRead = fwrite($tempHandle, $this->buffer); if ($bytesRead === false) { fclose($this->fp); fclose($tempHandle); throw new \RuntimeException( "fwrite() failed to write to '$tempPath'" ); } $bytesWritten += $bytesRead; } while (($pos = strpos($this->buffer, $this->boundary)) === false) { $this->buffer = fread($this->fp, $this->bytesPerRead); $bytesRead = fwrite($tempHandle, $this->buffer); if ($bytesRead === false) { fclose($this->fp); fclose($tempHandle); throw new \RuntimeException( "fwrite() failed to write to '$tempPath'" ); } $bytesWritten += $bytesRead; } # determine the size of the file based on the boundary position $size = $bytesWritten - $bytesRead + $pos - 2; # trim the excess contents of the local buffer to the object buffer $this->buffer = substr($this->buffer, $pos); # if the uploaded file was empty if ($size < 1) { return $this->fileUploadError( UPLOAD_ERR_NO_FILE, $tempPath, $tempHandle, $filename, $unverifiedContentType, 0 ); } # if the file exceeded the max upload size elseif ($size > $this->maxFileSize) { return $this->fileUploadError( UPLOAD_ERR_INI_SIZE, $tempPath, $tempHandle, $filename, $unverifiedContentType, 0 ); } ftruncate($tempHandle, $size); fclose($tempHandle); return new \sndsgd\http\UploadedFile( $filename, $unverifiedContentType, $size, $tempPath ); }
[ "protected", "function", "getFileFromField", "(", "string", "$", "name", ",", "string", "$", "filename", ",", "string", "$", "unverifiedContentType", ")", "{", "# create and open a temp file to write the contents to", "$", "tempPath", "=", "$", "this", "->", "getTempFilePath", "(", ")", ";", "$", "tempHandle", "=", "fopen", "(", "$", "tempPath", ",", "\"w\"", ")", ";", "if", "(", "$", "tempHandle", "===", "false", ")", "{", "fclose", "(", "$", "this", "->", "fp", ")", ";", "$", "message", "=", "\\", "sndsgd", "\\", "Error", "::", "createMessage", "(", "\"failed to open '$tempPath' for writing\"", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "$", "message", ")", ";", "}", "# number of bytes read from the input stream in the last loop cycle", "$", "bytesRead", "=", "0", ";", "# the total number of bytes written to the temp file", "$", "bytesWritten", "=", "0", ";", "# if anything is left over from the previous field, add it to the file", "if", "(", "$", "this", "->", "buffer", "!==", "\"\"", ")", "{", "$", "bytesRead", "=", "fwrite", "(", "$", "tempHandle", ",", "$", "this", "->", "buffer", ")", ";", "if", "(", "$", "bytesRead", "===", "false", ")", "{", "fclose", "(", "$", "this", "->", "fp", ")", ";", "fclose", "(", "$", "tempHandle", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "\"fwrite() failed to write to '$tempPath'\"", ")", ";", "}", "$", "bytesWritten", "+=", "$", "bytesRead", ";", "}", "while", "(", "(", "$", "pos", "=", "strpos", "(", "$", "this", "->", "buffer", ",", "$", "this", "->", "boundary", ")", ")", "===", "false", ")", "{", "$", "this", "->", "buffer", "=", "fread", "(", "$", "this", "->", "fp", ",", "$", "this", "->", "bytesPerRead", ")", ";", "$", "bytesRead", "=", "fwrite", "(", "$", "tempHandle", ",", "$", "this", "->", "buffer", ")", ";", "if", "(", "$", "bytesRead", "===", "false", ")", "{", "fclose", "(", "$", "this", "->", "fp", ")", ";", "fclose", "(", "$", "tempHandle", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "\"fwrite() failed to write to '$tempPath'\"", ")", ";", "}", "$", "bytesWritten", "+=", "$", "bytesRead", ";", "}", "# determine the size of the file based on the boundary position", "$", "size", "=", "$", "bytesWritten", "-", "$", "bytesRead", "+", "$", "pos", "-", "2", ";", "# trim the excess contents of the local buffer to the object buffer", "$", "this", "->", "buffer", "=", "substr", "(", "$", "this", "->", "buffer", ",", "$", "pos", ")", ";", "# if the uploaded file was empty", "if", "(", "$", "size", "<", "1", ")", "{", "return", "$", "this", "->", "fileUploadError", "(", "UPLOAD_ERR_NO_FILE", ",", "$", "tempPath", ",", "$", "tempHandle", ",", "$", "filename", ",", "$", "unverifiedContentType", ",", "0", ")", ";", "}", "# if the file exceeded the max upload size", "elseif", "(", "$", "size", ">", "$", "this", "->", "maxFileSize", ")", "{", "return", "$", "this", "->", "fileUploadError", "(", "UPLOAD_ERR_INI_SIZE", ",", "$", "tempPath", ",", "$", "tempHandle", ",", "$", "filename", ",", "$", "unverifiedContentType", ",", "0", ")", ";", "}", "ftruncate", "(", "$", "tempHandle", ",", "$", "size", ")", ";", "fclose", "(", "$", "tempHandle", ")", ";", "return", "new", "\\", "sndsgd", "\\", "http", "\\", "UploadedFile", "(", "$", "filename", ",", "$", "unverifiedContentType", ",", "$", "size", ",", "$", "tempPath", ")", ";", "}" ]
Copy file contents from the input stream to a temp file @param string $name The field name @param string $filename The name of the uploaded file @param string $unverifiedContentType The user provided content type @return \sndsgd\http\UploadedFile
[ "Copy", "file", "contents", "from", "the", "input", "stream", "to", "a", "temp", "file" ]
train
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/MultipartDataDecoder.php#L277-L364
sndsgd/http
src/http/data/decoder/MultipartDataDecoder.php
MultipartDataDecoder.fileUploadError
protected function fileUploadError( int $errorCode, string $tempPath, $tempHandle, string $filename, string $contentType, int $size ): \sndsgd\http\UploadedFile { fclose($tempHandle); if ($tempPath && file_exists($tempPath)) { unlink($tempPath); } return new \sndsgd\http\UploadedFile( $filename, $contentType, $size, "", $errorCode ); }
php
protected function fileUploadError( int $errorCode, string $tempPath, $tempHandle, string $filename, string $contentType, int $size ): \sndsgd\http\UploadedFile { fclose($tempHandle); if ($tempPath && file_exists($tempPath)) { unlink($tempPath); } return new \sndsgd\http\UploadedFile( $filename, $contentType, $size, "", $errorCode ); }
[ "protected", "function", "fileUploadError", "(", "int", "$", "errorCode", ",", "string", "$", "tempPath", ",", "$", "tempHandle", ",", "string", "$", "filename", ",", "string", "$", "contentType", ",", "int", "$", "size", ")", ":", "\\", "sndsgd", "\\", "http", "\\", "UploadedFile", "{", "fclose", "(", "$", "tempHandle", ")", ";", "if", "(", "$", "tempPath", "&&", "file_exists", "(", "$", "tempPath", ")", ")", "{", "unlink", "(", "$", "tempPath", ")", ";", "}", "return", "new", "\\", "sndsgd", "\\", "http", "\\", "UploadedFile", "(", "$", "filename", ",", "$", "contentType", ",", "$", "size", ",", "\"\"", ",", "$", "errorCode", ")", ";", "}" ]
Handle an invalid file upload @param int $errorCode The relevant PHP file upload error @param string $tempPath The absolute path to the temp file @param resource $tempHandle The handle for the temp file @param string $filename The file name as provided by the client @param string $contentType The mime type of the uploaded file @param int $size The bytesize of the uploaded file @return \sndsgd\http\UploadedFile
[ "Handle", "an", "invalid", "file", "upload" ]
train
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/MultipartDataDecoder.php#L377-L398
JamieYnonan/default-property-normalizer
src/Dpn/DefaultPropertyNormalizer.php
DefaultPropertyNormalizer.getAttributeValue
protected function getAttributeValue( $object, $attribute, $format = null, array $context = [] ) { $value = parent::getAttributeValue( $object, $attribute, $format, $context ); if ($value === null && isset($context['default'])) { return $this->getDefaultValue($object, $attribute); } return $value; }
php
protected function getAttributeValue( $object, $attribute, $format = null, array $context = [] ) { $value = parent::getAttributeValue( $object, $attribute, $format, $context ); if ($value === null && isset($context['default'])) { return $this->getDefaultValue($object, $attribute); } return $value; }
[ "protected", "function", "getAttributeValue", "(", "$", "object", ",", "$", "attribute", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "value", "=", "parent", "::", "getAttributeValue", "(", "$", "object", ",", "$", "attribute", ",", "$", "format", ",", "$", "context", ")", ";", "if", "(", "$", "value", "===", "null", "&&", "isset", "(", "$", "context", "[", "'default'", "]", ")", ")", "{", "return", "$", "this", "->", "getDefaultValue", "(", "$", "object", ",", "$", "attribute", ")", ";", "}", "return", "$", "value", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/JamieYnonan/default-property-normalizer/blob/404887827ebda31aaa0d66260d4c7c15a3d285ed/src/Dpn/DefaultPropertyNormalizer.php#L57-L75
JamieYnonan/default-property-normalizer
src/Dpn/DefaultPropertyNormalizer.php
DefaultPropertyNormalizer.setAttributeValue
protected function setAttributeValue( $object, $attribute, $value, $format = null, array $context = [] ) { if (!$this->setAttributeValueBySetter($object, $attribute, $value)) { parent::setAttributeValue($object, $attribute, $value, $format, $context); } }
php
protected function setAttributeValue( $object, $attribute, $value, $format = null, array $context = [] ) { if (!$this->setAttributeValueBySetter($object, $attribute, $value)) { parent::setAttributeValue($object, $attribute, $value, $format, $context); } }
[ "protected", "function", "setAttributeValue", "(", "$", "object", ",", "$", "attribute", ",", "$", "value", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "setAttributeValueBySetter", "(", "$", "object", ",", "$", "attribute", ",", "$", "value", ")", ")", "{", "parent", "::", "setAttributeValue", "(", "$", "object", ",", "$", "attribute", ",", "$", "value", ",", "$", "format", ",", "$", "context", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/JamieYnonan/default-property-normalizer/blob/404887827ebda31aaa0d66260d4c7c15a3d285ed/src/Dpn/DefaultPropertyNormalizer.php#L95-L105
phossa/phossa-config
src/Phossa/Config/Loader/XmlLoader.php
XmlLoader.load
public static function load(/*# string */ $path)/*# : array */ { if (!is_readable($path)) { throw new LogicException( Message::get(Message::CONFIG_LOAD_ERROR, $path), Message::CONFIG_LOAD_ERROR ); } libxml_use_internal_errors(true); $data = simplexml_load_file($path, null, \LIBXML_NOERROR); if (false === $data) { $errors = libxml_get_errors(); $error = array_pop($errors); $message = $error->message; throw new LogicException( $message, Message::CONFIG_FORMAT_ERROR ); } $data = json_decode(json_encode($data), true); return $data; }
php
public static function load(/*# string */ $path)/*# : array */ { if (!is_readable($path)) { throw new LogicException( Message::get(Message::CONFIG_LOAD_ERROR, $path), Message::CONFIG_LOAD_ERROR ); } libxml_use_internal_errors(true); $data = simplexml_load_file($path, null, \LIBXML_NOERROR); if (false === $data) { $errors = libxml_get_errors(); $error = array_pop($errors); $message = $error->message; throw new LogicException( $message, Message::CONFIG_FORMAT_ERROR ); } $data = json_decode(json_encode($data), true); return $data; }
[ "public", "static", "function", "load", "(", "/*# string */", "$", "path", ")", "/*# : array */", "{", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "LogicException", "(", "Message", "::", "get", "(", "Message", "::", "CONFIG_LOAD_ERROR", ",", "$", "path", ")", ",", "Message", "::", "CONFIG_LOAD_ERROR", ")", ";", "}", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "data", "=", "simplexml_load_file", "(", "$", "path", ",", "null", ",", "\\", "LIBXML_NOERROR", ")", ";", "if", "(", "false", "===", "$", "data", ")", "{", "$", "errors", "=", "libxml_get_errors", "(", ")", ";", "$", "error", "=", "array_pop", "(", "$", "errors", ")", ";", "$", "message", "=", "$", "error", "->", "message", ";", "throw", "new", "LogicException", "(", "$", "message", ",", "Message", "::", "CONFIG_FORMAT_ERROR", ")", ";", "}", "$", "data", "=", "json_decode", "(", "json_encode", "(", "$", "data", ")", ",", "true", ")", ";", "return", "$", "data", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-config/blob/fdb90831da06408bb674ab777754e67025604bed/src/Phossa/Config/Loader/XmlLoader.php#L34-L60
siriusSupreme/sirius-support
src/Str.php
Str.replaceFirst
public static function replaceFirst($search, $replace, $subject) { if ($search == '') { return $subject; } $position = mb_strpos($subject, $search); if ($position !== false) { return mb_substr($subject, 0, $position).$replace.mb_substr($subject, $position + mb_strlen($search)); } return $subject; }
php
public static function replaceFirst($search, $replace, $subject) { if ($search == '') { return $subject; } $position = mb_strpos($subject, $search); if ($position !== false) { return mb_substr($subject, 0, $position).$replace.mb_substr($subject, $position + mb_strlen($search)); } return $subject; }
[ "public", "static", "function", "replaceFirst", "(", "$", "search", ",", "$", "replace", ",", "$", "subject", ")", "{", "if", "(", "$", "search", "==", "''", ")", "{", "return", "$", "subject", ";", "}", "$", "position", "=", "mb_strpos", "(", "$", "subject", ",", "$", "search", ")", ";", "if", "(", "$", "position", "!==", "false", ")", "{", "return", "mb_substr", "(", "$", "subject", ",", "0", ",", "$", "position", ")", ".", "$", "replace", ".", "mb_substr", "(", "$", "subject", ",", "$", "position", "+", "mb_strlen", "(", "$", "search", ")", ")", ";", "}", "return", "$", "subject", ";", "}" ]
Replace the first occurrence of a given value in the string. @param string $search @param string $replace @param string $subject @return string
[ "Replace", "the", "first", "occurrence", "of", "a", "given", "value", "in", "the", "string", "." ]
train
https://github.com/siriusSupreme/sirius-support/blob/80436cf8ae7b95d96bb34cd7297be00c77fc1033/src/Str.php#L327-L340
siriusSupreme/sirius-support
src/Str.php
Str.replaceLast
public static function replaceLast($search, $replace, $subject) { $position = mb_strrpos($subject, $search); if ($position !== false) { return mb_substr($subject, 0, $position).$replace.mb_substr($subject, $position + mb_strlen($search)); } return $subject; }
php
public static function replaceLast($search, $replace, $subject) { $position = mb_strrpos($subject, $search); if ($position !== false) { return mb_substr($subject, 0, $position).$replace.mb_substr($subject, $position + mb_strlen($search)); } return $subject; }
[ "public", "static", "function", "replaceLast", "(", "$", "search", ",", "$", "replace", ",", "$", "subject", ")", "{", "$", "position", "=", "mb_strrpos", "(", "$", "subject", ",", "$", "search", ")", ";", "if", "(", "$", "position", "!==", "false", ")", "{", "return", "mb_substr", "(", "$", "subject", ",", "0", ",", "$", "position", ")", ".", "$", "replace", ".", "mb_substr", "(", "$", "subject", ",", "$", "position", "+", "mb_strlen", "(", "$", "search", ")", ")", ";", "}", "return", "$", "subject", ";", "}" ]
Replace the last occurrence of a given value in the string. @param string $search @param string $replace @param string $subject @return string
[ "Replace", "the", "last", "occurrence", "of", "a", "given", "value", "in", "the", "string", "." ]
train
https://github.com/siriusSupreme/sirius-support/blob/80436cf8ae7b95d96bb34cd7297be00c77fc1033/src/Str.php#L350-L359
comodojo/foundation
src/Comodojo/Foundation/Logging/Levels.php
Levels.getLevel
public static function getLevel($level = null) { $level = strtoupper($level); if ( array_key_exists($level, self::$levels) ) return self::$levels[$level]; return self::$levels[self::DEFAULT_LOG_LEVEL]; }
php
public static function getLevel($level = null) { $level = strtoupper($level); if ( array_key_exists($level, self::$levels) ) return self::$levels[$level]; return self::$levels[self::DEFAULT_LOG_LEVEL]; }
[ "public", "static", "function", "getLevel", "(", "$", "level", "=", "null", ")", "{", "$", "level", "=", "strtoupper", "(", "$", "level", ")", ";", "if", "(", "array_key_exists", "(", "$", "level", ",", "self", "::", "$", "levels", ")", ")", "return", "self", "::", "$", "levels", "[", "$", "level", "]", ";", "return", "self", "::", "$", "levels", "[", "self", "::", "DEFAULT_LOG_LEVEL", "]", ";", "}" ]
Map provided log level to level code @param string $level @return integer
[ "Map", "provided", "log", "level", "to", "level", "code" ]
train
https://github.com/comodojo/foundation/blob/21ed690e81763ed9e1ef7721a7eb4fcc0fcefc1a/src/Comodojo/Foundation/Logging/Levels.php#L44-L52
ARCANESOFT/Blog
src/ViewComposers/Front/Widgets/TagsWidgetComposer.php
TagsWidgetComposer.compose
public function compose(View $view) { $tags = Tag::with('posts') ->whereHas('posts', function (Builder $b) { // TODO: Try to export this code with model's scope ? $b->where('is_draft', false) ->where('published_at', '<=', Carbon::now()); }) ->get() ->sortByDesc(function($tag) { return $tag->posts->count(); }); $view->with('tagsWidgetItems', $tags); }
php
public function compose(View $view) { $tags = Tag::with('posts') ->whereHas('posts', function (Builder $b) { // TODO: Try to export this code with model's scope ? $b->where('is_draft', false) ->where('published_at', '<=', Carbon::now()); }) ->get() ->sortByDesc(function($tag) { return $tag->posts->count(); }); $view->with('tagsWidgetItems', $tags); }
[ "public", "function", "compose", "(", "View", "$", "view", ")", "{", "$", "tags", "=", "Tag", "::", "with", "(", "'posts'", ")", "->", "whereHas", "(", "'posts'", ",", "function", "(", "Builder", "$", "b", ")", "{", "// TODO: Try to export this code with model's scope ?", "$", "b", "->", "where", "(", "'is_draft'", ",", "false", ")", "->", "where", "(", "'published_at'", ",", "'<='", ",", "Carbon", "::", "now", "(", ")", ")", ";", "}", ")", "->", "get", "(", ")", "->", "sortByDesc", "(", "function", "(", "$", "tag", ")", "{", "return", "$", "tag", "->", "posts", "->", "count", "(", ")", ";", "}", ")", ";", "$", "view", "->", "with", "(", "'tagsWidgetItems'", ",", "$", "tags", ")", ";", "}" ]
/* ----------------------------------------------------------------- | Main Methods | -----------------------------------------------------------------
[ "/", "*", "-----------------------------------------------------------------", "|", "Main", "Methods", "|", "-----------------------------------------------------------------" ]
train
https://github.com/ARCANESOFT/Blog/blob/2078fdfdcbccda161c02899b9e1f344f011b2859/src/ViewComposers/Front/Widgets/TagsWidgetComposer.php#L30-L44
clippings/phpunit-extensions
src/Assert.php
Assert.assertArrayConstrained
public static function assertArrayConstrained(array $constraints, array $array, $isStrict = true, $message = '') { PHPUnit_Framework_Assert::assertThat($array, self::constrainArray($constraints, $isStrict), $message); }
php
public static function assertArrayConstrained(array $constraints, array $array, $isStrict = true, $message = '') { PHPUnit_Framework_Assert::assertThat($array, self::constrainArray($constraints, $isStrict), $message); }
[ "public", "static", "function", "assertArrayConstrained", "(", "array", "$", "constraints", ",", "array", "$", "array", ",", "$", "isStrict", "=", "true", ",", "$", "message", "=", "''", ")", "{", "PHPUnit_Framework_Assert", "::", "assertThat", "(", "$", "array", ",", "self", "::", "constrainArray", "(", "$", "constraints", ",", "$", "isStrict", ")", ",", "$", "message", ")", ";", "}" ]
Asserts that a condition is true. @param PHPUnit_Framework_Constraint[] $constraints @param array $array @param string $message @throws PHPUnit_Framework_AssertionFailedError
[ "Asserts", "that", "a", "condition", "is", "true", "." ]
train
https://github.com/clippings/phpunit-extensions/blob/d37ce079da85da1aeb3e43c6481d9a802e1e87ee/src/Assert.php#L22-L25
bseddon/XPath20
Iterator/ChildOverDescendantsNodeIterator.php
ChildOverDescendantsNodeIterator.fromParts
public static function fromParts( $context, $nodeTest, $iter ) { $result = new ChildOverDescendantsNodeIterator(); $result->fromChildOverDescendantsNodeIteratorParts( $context, $nodeTest, $iter ); return $result; }
php
public static function fromParts( $context, $nodeTest, $iter ) { $result = new ChildOverDescendantsNodeIterator(); $result->fromChildOverDescendantsNodeIteratorParts( $context, $nodeTest, $iter ); return $result; }
[ "public", "static", "function", "fromParts", "(", "$", "context", ",", "$", "nodeTest", ",", "$", "iter", ")", "{", "$", "result", "=", "new", "ChildOverDescendantsNodeIterator", "(", ")", ";", "$", "result", "->", "fromChildOverDescendantsNodeIteratorParts", "(", "$", "context", ",", "$", "nodeTest", ",", "$", "iter", ")", ";", "return", "$", "result", ";", "}" ]
fromParts @param XPath2Context $context @param array $nodeTest NodeTest[] @param XPath2NodeIterator $iter
[ "fromParts" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Iterator/ChildOverDescendantsNodeIterator.php#L95-L100
bseddon/XPath20
Iterator/ChildOverDescendantsNodeIterator.php
ChildOverDescendantsNodeIterator.fromChildOverDescendantsNodeIteratorParts
protected function fromChildOverDescendantsNodeIteratorParts( $context, $nodeTest, $iter ) { $this->context = $context; $this->nodeTest = $nodeTest; $this->iter = $iter; $this->lastTest = $nodeTest[ count( $nodeTest ) - 1 ]; $this->kind = XPathNodeType::All; if ( isset( $this->lastTest->nameTest ) || ( isset( $this->lastTest->typeTest ) && $this->lastTest->typeTest->GetNodeKind() == XPathNodeType::Element ) ) { $this->kind = XPathNodeType::Element; } }
php
protected function fromChildOverDescendantsNodeIteratorParts( $context, $nodeTest, $iter ) { $this->context = $context; $this->nodeTest = $nodeTest; $this->iter = $iter; $this->lastTest = $nodeTest[ count( $nodeTest ) - 1 ]; $this->kind = XPathNodeType::All; if ( isset( $this->lastTest->nameTest ) || ( isset( $this->lastTest->typeTest ) && $this->lastTest->typeTest->GetNodeKind() == XPathNodeType::Element ) ) { $this->kind = XPathNodeType::Element; } }
[ "protected", "function", "fromChildOverDescendantsNodeIteratorParts", "(", "$", "context", ",", "$", "nodeTest", ",", "$", "iter", ")", "{", "$", "this", "->", "context", "=", "$", "context", ";", "$", "this", "->", "nodeTest", "=", "$", "nodeTest", ";", "$", "this", "->", "iter", "=", "$", "iter", ";", "$", "this", "->", "lastTest", "=", "$", "nodeTest", "[", "count", "(", "$", "nodeTest", ")", "-", "1", "]", ";", "$", "this", "->", "kind", "=", "XPathNodeType", "::", "All", ";", "if", "(", "isset", "(", "$", "this", "->", "lastTest", "->", "nameTest", ")", "||", "(", "isset", "(", "$", "this", "->", "lastTest", "->", "typeTest", ")", "&&", "$", "this", "->", "lastTest", "->", "typeTest", "->", "GetNodeKind", "(", ")", "==", "XPathNodeType", "::", "Element", ")", ")", "{", "$", "this", "->", "kind", "=", "XPathNodeType", "::", "Element", ";", "}", "}" ]
Constructor @param XPath2Context $context @param array $nodeTest NodeTest[] @param XPath2NodeIterator $iter
[ "Constructor" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Iterator/ChildOverDescendantsNodeIterator.php#L108-L119
bseddon/XPath20
Iterator/ChildOverDescendantsNodeIterator.php
ChildOverDescendantsNodeIterator.AssignFrom
private function AssignFrom( $src ) { $this->context = $src->context; $this->nodeTest = $src->nodeTest; $this->iter = $src->iter->CloneInstance(); $this->lastTest = $src->lastTest; $this->kind = $src->kind; }
php
private function AssignFrom( $src ) { $this->context = $src->context; $this->nodeTest = $src->nodeTest; $this->iter = $src->iter->CloneInstance(); $this->lastTest = $src->lastTest; $this->kind = $src->kind; }
[ "private", "function", "AssignFrom", "(", "$", "src", ")", "{", "$", "this", "->", "context", "=", "$", "src", "->", "context", ";", "$", "this", "->", "nodeTest", "=", "$", "src", "->", "nodeTest", ";", "$", "this", "->", "iter", "=", "$", "src", "->", "iter", "->", "CloneInstance", "(", ")", ";", "$", "this", "->", "lastTest", "=", "$", "src", "->", "lastTest", ";", "$", "this", "->", "kind", "=", "$", "src", "->", "kind", ";", "}" ]
Constructor @param ChildOverDescendantsNodeIterator $src
[ "Constructor" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Iterator/ChildOverDescendantsNodeIterator.php#L125-L132
bseddon/XPath20
Iterator/ChildOverDescendantsNodeIterator.php
ChildOverDescendantsNodeIterator.NextItem
protected function NextItem() { MoveNextIter: if ( ! $this->accept ) { if ( ! $this->iter->MoveNext() ) return null; if ( ! $this->iter->getCurrent() instanceof XPathNavigator ) { throw XPath2Exception::withErrorCodeAndParam( "XPTY0019", Resources::XPTY0019, $this->iter->getCurrent()->Value ); } /** * @var XPathNavigator $current */ $current = $this->iter->getCurrent(); if ( is_null( $this->curr ) || ! $this->curr->MoveTo( $current ) ) { $this->curr = $current->CloneInstance(); } $this->sequentialPosition = 0; $this->accept = true; } MoveToFirstChild: if ( $this->curr->MoveToChild( $this->kind ) ) { $this->depth++; goto TestItem; } MoveToNext: if ( $this->depth == 0 ) { $this->accept = false; goto MoveNextIter; } if ( ! $this->curr->MoveToNext( $this->kind ) ) { $this->curr->MoveToParent(); $this->depth--; goto MoveToNext; } TestItem: if ( $this->depth < count( $this->nodeTest ) || ! $this->TestItem( $this->curr, $this->lastTest ) ) goto MoveToFirstChild; if ( is_null( $this->nav ) || ! $this->nav->MoveTo( $this->curr ) ) { $this->nav = $this->curr->CloneInstance(); } for ( $k = count( $this->nodeTest ) - 2; $k >= 0; $k--) { if ( ! ( $this->nav->MoveToParent() && $this->TestItem( $this->nav, $this->nodeTest[ $k ] ) ) ) goto MoveToFirstChild; } $this->sequentialPosition++; return $this->curr; }
php
protected function NextItem() { MoveNextIter: if ( ! $this->accept ) { if ( ! $this->iter->MoveNext() ) return null; if ( ! $this->iter->getCurrent() instanceof XPathNavigator ) { throw XPath2Exception::withErrorCodeAndParam( "XPTY0019", Resources::XPTY0019, $this->iter->getCurrent()->Value ); } /** * @var XPathNavigator $current */ $current = $this->iter->getCurrent(); if ( is_null( $this->curr ) || ! $this->curr->MoveTo( $current ) ) { $this->curr = $current->CloneInstance(); } $this->sequentialPosition = 0; $this->accept = true; } MoveToFirstChild: if ( $this->curr->MoveToChild( $this->kind ) ) { $this->depth++; goto TestItem; } MoveToNext: if ( $this->depth == 0 ) { $this->accept = false; goto MoveNextIter; } if ( ! $this->curr->MoveToNext( $this->kind ) ) { $this->curr->MoveToParent(); $this->depth--; goto MoveToNext; } TestItem: if ( $this->depth < count( $this->nodeTest ) || ! $this->TestItem( $this->curr, $this->lastTest ) ) goto MoveToFirstChild; if ( is_null( $this->nav ) || ! $this->nav->MoveTo( $this->curr ) ) { $this->nav = $this->curr->CloneInstance(); } for ( $k = count( $this->nodeTest ) - 2; $k >= 0; $k--) { if ( ! ( $this->nav->MoveToParent() && $this->TestItem( $this->nav, $this->nodeTest[ $k ] ) ) ) goto MoveToFirstChild; } $this->sequentialPosition++; return $this->curr; }
[ "protected", "function", "NextItem", "(", ")", "{", "MoveNextIter", ":", "if", "(", "!", "$", "this", "->", "accept", ")", "{", "if", "(", "!", "$", "this", "->", "iter", "->", "MoveNext", "(", ")", ")", "return", "null", ";", "if", "(", "!", "$", "this", "->", "iter", "->", "getCurrent", "(", ")", "instanceof", "XPathNavigator", ")", "{", "throw", "XPath2Exception", "::", "withErrorCodeAndParam", "(", "\"XPTY0019\"", ",", "Resources", "::", "XPTY0019", ",", "$", "this", "->", "iter", "->", "getCurrent", "(", ")", "->", "Value", ")", ";", "}", "/**\r\n\t\t\t * @var XPathNavigator $current\r\n\t\t\t */", "$", "current", "=", "$", "this", "->", "iter", "->", "getCurrent", "(", ")", ";", "if", "(", "is_null", "(", "$", "this", "->", "curr", ")", "||", "!", "$", "this", "->", "curr", "->", "MoveTo", "(", "$", "current", ")", ")", "{", "$", "this", "->", "curr", "=", "$", "current", "->", "CloneInstance", "(", ")", ";", "}", "$", "this", "->", "sequentialPosition", "=", "0", ";", "$", "this", "->", "accept", "=", "true", ";", "}", "MoveToFirstChild", ":", "if", "(", "$", "this", "->", "curr", "->", "MoveToChild", "(", "$", "this", "->", "kind", ")", ")", "{", "$", "this", "->", "depth", "++", ";", "goto", "TestItem", ";", "}", "MoveToNext", ":", "if", "(", "$", "this", "->", "depth", "==", "0", ")", "{", "$", "this", "->", "accept", "=", "false", ";", "goto", "MoveNextIter", ";", "}", "if", "(", "!", "$", "this", "->", "curr", "->", "MoveToNext", "(", "$", "this", "->", "kind", ")", ")", "{", "$", "this", "->", "curr", "->", "MoveToParent", "(", ")", ";", "$", "this", "->", "depth", "--", ";", "goto", "MoveToNext", ";", "}", "TestItem", ":", "if", "(", "$", "this", "->", "depth", "<", "count", "(", "$", "this", "->", "nodeTest", ")", "||", "!", "$", "this", "->", "TestItem", "(", "$", "this", "->", "curr", ",", "$", "this", "->", "lastTest", ")", ")", "goto", "MoveToFirstChild", ";", "if", "(", "is_null", "(", "$", "this", "->", "nav", ")", "||", "!", "$", "this", "->", "nav", "->", "MoveTo", "(", "$", "this", "->", "curr", ")", ")", "{", "$", "this", "->", "nav", "=", "$", "this", "->", "curr", "->", "CloneInstance", "(", ")", ";", "}", "for", "(", "$", "k", "=", "count", "(", "$", "this", "->", "nodeTest", ")", "-", "2", ";", "$", "k", ">=", "0", ";", "$", "k", "--", ")", "{", "if", "(", "!", "(", "$", "this", "->", "nav", "->", "MoveToParent", "(", ")", "&&", "$", "this", "->", "TestItem", "(", "$", "this", "->", "nav", ",", "$", "this", "->", "nodeTest", "[", "$", "k", "]", ")", ")", ")", "goto", "MoveToFirstChild", ";", "}", "$", "this", "->", "sequentialPosition", "++", ";", "return", "$", "this", "->", "curr", ";", "}" ]
NextItem @return XPathItem
[ "NextItem" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Iterator/ChildOverDescendantsNodeIterator.php#L216-L285
bseddon/XPath20
Iterator/ChildOverDescendantsNodeIterator.php
ChildOverDescendantsNodeIterator.Reset
public function Reset() { parent::Reset(); $this->nav = null; $this->accept = false; $this->sequentialPosition = 0; $this->depth = 0; $this->iter->Reset(); }
php
public function Reset() { parent::Reset(); $this->nav = null; $this->accept = false; $this->sequentialPosition = 0; $this->depth = 0; $this->iter->Reset(); }
[ "public", "function", "Reset", "(", ")", "{", "parent", "::", "Reset", "(", ")", ";", "$", "this", "->", "nav", "=", "null", ";", "$", "this", "->", "accept", "=", "false", ";", "$", "this", "->", "sequentialPosition", "=", "0", ";", "$", "this", "->", "depth", "=", "0", ";", "$", "this", "->", "iter", "->", "Reset", "(", ")", ";", "}" ]
Allow the iterators to be reset
[ "Allow", "the", "iterators", "to", "be", "reset" ]
train
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Iterator/ChildOverDescendantsNodeIterator.php#L308-L317
fond-of/spryker-company-business-units-rest-api
src/FondOfSpryker/Zed/CompanyBusinessUnitsRestApi/Business/CompanyBusinessUnit/CompanyBusinessUnitReader.php
CompanyBusinessUnitReader.findCompanyBusinessUnitByExternalReference
public function findCompanyBusinessUnitByExternalReference( RestCompanyBusinessUnitsRequestAttributesTransfer $restCompanyBusinessUnitsRequestAttributesTransfer ): RestCompanyBusinessUnitsResponseTransfer { $companyBusinessUnitTransfer = $this->companyBusinessUnitsRestApiRepository->findCompanyBusinessUnitByExternalReference( $restCompanyBusinessUnitsRequestAttributesTransfer->getExternalReference() ); if ($companyBusinessUnitTransfer !== null) { return $this->createCompanyBusinessUnitResponseTransfer($companyBusinessUnitTransfer); } return $this->createCompanyBusinessUnitFailedToLoadErrorResponseTransfer(); }
php
public function findCompanyBusinessUnitByExternalReference( RestCompanyBusinessUnitsRequestAttributesTransfer $restCompanyBusinessUnitsRequestAttributesTransfer ): RestCompanyBusinessUnitsResponseTransfer { $companyBusinessUnitTransfer = $this->companyBusinessUnitsRestApiRepository->findCompanyBusinessUnitByExternalReference( $restCompanyBusinessUnitsRequestAttributesTransfer->getExternalReference() ); if ($companyBusinessUnitTransfer !== null) { return $this->createCompanyBusinessUnitResponseTransfer($companyBusinessUnitTransfer); } return $this->createCompanyBusinessUnitFailedToLoadErrorResponseTransfer(); }
[ "public", "function", "findCompanyBusinessUnitByExternalReference", "(", "RestCompanyBusinessUnitsRequestAttributesTransfer", "$", "restCompanyBusinessUnitsRequestAttributesTransfer", ")", ":", "RestCompanyBusinessUnitsResponseTransfer", "{", "$", "companyBusinessUnitTransfer", "=", "$", "this", "->", "companyBusinessUnitsRestApiRepository", "->", "findCompanyBusinessUnitByExternalReference", "(", "$", "restCompanyBusinessUnitsRequestAttributesTransfer", "->", "getExternalReference", "(", ")", ")", ";", "if", "(", "$", "companyBusinessUnitTransfer", "!==", "null", ")", "{", "return", "$", "this", "->", "createCompanyBusinessUnitResponseTransfer", "(", "$", "companyBusinessUnitTransfer", ")", ";", "}", "return", "$", "this", "->", "createCompanyBusinessUnitFailedToLoadErrorResponseTransfer", "(", ")", ";", "}" ]
@param \Generated\Shared\Transfer\RestCompanyBusinessUnitsRequestAttributesTransfer $restCompanyBusinessUnitsRequestAttributesTransfer @return \Generated\Shared\Transfer\RestCompanyBusinessUnitsResponseTransfer
[ "@param", "\\", "Generated", "\\", "Shared", "\\", "Transfer", "\\", "RestCompanyBusinessUnitsRequestAttributesTransfer", "$restCompanyBusinessUnitsRequestAttributesTransfer" ]
train
https://github.com/fond-of/spryker-company-business-units-rest-api/blob/7393d6064f2618a71f092ecf8c4e62fb73f504bb/src/FondOfSpryker/Zed/CompanyBusinessUnitsRestApi/Business/CompanyBusinessUnit/CompanyBusinessUnitReader.php#L34-L46
fond-of/spryker-company-business-units-rest-api
src/FondOfSpryker/Zed/CompanyBusinessUnitsRestApi/Business/CompanyBusinessUnit/CompanyBusinessUnitReader.php
CompanyBusinessUnitReader.createCompanyBusinessUnitResponseTransfer
protected function createCompanyBusinessUnitResponseTransfer( CompanyBusinessUnitTransfer $companyBusinessUnitTransfer ): RestCompanyBusinessUnitsResponseTransfer { $restCompanyBusinessUnitsResponseAttributesTransfer = new RestCompanyBusinessUnitsResponseAttributesTransfer(); $restCompanyBusinessUnitsResponseAttributesTransfer->fromArray( $companyBusinessUnitTransfer->toArray(), true ); $restCompanyBusinessUnitsResponseTransfer = new RestCompanyBusinessUnitsResponseTransfer(); $restCompanyBusinessUnitsResponseTransfer->setIsSuccess(true) ->setRestCompanyBusinessUnitsResponseAttributes($restCompanyBusinessUnitsResponseAttributesTransfer); return $restCompanyBusinessUnitsResponseTransfer; }
php
protected function createCompanyBusinessUnitResponseTransfer( CompanyBusinessUnitTransfer $companyBusinessUnitTransfer ): RestCompanyBusinessUnitsResponseTransfer { $restCompanyBusinessUnitsResponseAttributesTransfer = new RestCompanyBusinessUnitsResponseAttributesTransfer(); $restCompanyBusinessUnitsResponseAttributesTransfer->fromArray( $companyBusinessUnitTransfer->toArray(), true ); $restCompanyBusinessUnitsResponseTransfer = new RestCompanyBusinessUnitsResponseTransfer(); $restCompanyBusinessUnitsResponseTransfer->setIsSuccess(true) ->setRestCompanyBusinessUnitsResponseAttributes($restCompanyBusinessUnitsResponseAttributesTransfer); return $restCompanyBusinessUnitsResponseTransfer; }
[ "protected", "function", "createCompanyBusinessUnitResponseTransfer", "(", "CompanyBusinessUnitTransfer", "$", "companyBusinessUnitTransfer", ")", ":", "RestCompanyBusinessUnitsResponseTransfer", "{", "$", "restCompanyBusinessUnitsResponseAttributesTransfer", "=", "new", "RestCompanyBusinessUnitsResponseAttributesTransfer", "(", ")", ";", "$", "restCompanyBusinessUnitsResponseAttributesTransfer", "->", "fromArray", "(", "$", "companyBusinessUnitTransfer", "->", "toArray", "(", ")", ",", "true", ")", ";", "$", "restCompanyBusinessUnitsResponseTransfer", "=", "new", "RestCompanyBusinessUnitsResponseTransfer", "(", ")", ";", "$", "restCompanyBusinessUnitsResponseTransfer", "->", "setIsSuccess", "(", "true", ")", "->", "setRestCompanyBusinessUnitsResponseAttributes", "(", "$", "restCompanyBusinessUnitsResponseAttributesTransfer", ")", ";", "return", "$", "restCompanyBusinessUnitsResponseTransfer", ";", "}" ]
@param \Generated\Shared\Transfer\CompanyBusinessUnitTransfer $companyBusinessUnitTransfer @return \Generated\Shared\Transfer\RestCompanyBusinessUnitsResponseTransfer
[ "@param", "\\", "Generated", "\\", "Shared", "\\", "Transfer", "\\", "CompanyBusinessUnitTransfer", "$companyBusinessUnitTransfer" ]
train
https://github.com/fond-of/spryker-company-business-units-rest-api/blob/7393d6064f2618a71f092ecf8c4e62fb73f504bb/src/FondOfSpryker/Zed/CompanyBusinessUnitsRestApi/Business/CompanyBusinessUnit/CompanyBusinessUnitReader.php#L53-L69
intpro/feedback
src/Db/FeedbackQuerier.php
FeedbackQuerier.selectByRef
public function selectByRef(ARef $ref) { $type = $ref->getType(); $type_name = $type->getName(); $id = $ref->getId(); $table = $this->getTable($type); $query = new QueryBuilder(DB::table($table)); $query->where($table.'.name', '=', $type_name); if($id > 0) { $query->where($table.'.id', '=', $id); } return $query; }
php
public function selectByRef(ARef $ref) { $type = $ref->getType(); $type_name = $type->getName(); $id = $ref->getId(); $table = $this->getTable($type); $query = new QueryBuilder(DB::table($table)); $query->where($table.'.name', '=', $type_name); if($id > 0) { $query->where($table.'.id', '=', $id); } return $query; }
[ "public", "function", "selectByRef", "(", "ARef", "$", "ref", ")", "{", "$", "type", "=", "$", "ref", "->", "getType", "(", ")", ";", "$", "type_name", "=", "$", "type", "->", "getName", "(", ")", ";", "$", "id", "=", "$", "ref", "->", "getId", "(", ")", ";", "$", "table", "=", "$", "this", "->", "getTable", "(", "$", "type", ")", ";", "$", "query", "=", "new", "QueryBuilder", "(", "DB", "::", "table", "(", "$", "table", ")", ")", ";", "$", "query", "->", "where", "(", "$", "table", ".", "'.name'", ",", "'='", ",", "$", "type_name", ")", ";", "if", "(", "$", "id", ">", "0", ")", "{", "$", "query", "->", "where", "(", "$", "table", ".", "'.id'", ",", "'='", ",", "$", "id", ")", ";", "}", "return", "$", "query", ";", "}" ]
@param \Interpro\Core\Contracts\Ref\ARef $ref @return \Interpro\Extractor\Db\QueryBuilder
[ "@param", "\\", "Interpro", "\\", "Core", "\\", "Contracts", "\\", "Ref", "\\", "ARef", "$ref" ]
train
https://github.com/intpro/feedback/blob/394845e13b6464936a3d0435128dd85d9494a267/src/Db/FeedbackQuerier.php#L74-L91
intpro/feedback
src/Db/FeedbackQuerier.php
FeedbackQuerier.selectByUnit
public function selectByUnit(SelectionUnit $selectionUnit) { $type = $selectionUnit->getType(); $entity_name = $type->getName(); $model_table = $this->getTable($type); $self_fields = ['id,from,subject,to,username,email,body,mailed,host,port,encryption,report,password,domain']; //Группировка путей с общими отрезками //------------------------------------------------------------- $join_fields = $selectionUnit->getJoinFieldsPaths(); $join_array = ['sub_levels' => [], 'full_field_names' => [], 'value_level' => false];//первый уровень - соединение с главным запросом + пути к полям по уровням foreach($join_fields as $field) { if (in_array($field, $self_fields)) { continue; } $curr_level_array = & $join_array; $field_array = explode('.', $field); $full_field_name = str_replace('.', '_', $field); $curr_level_array['full_field_names'][] = $full_field_name; foreach($field_array as $field_name) { if(!array_key_exists($field_name, $curr_level_array['sub_levels'])) { $curr_level_array['sub_levels'][$field_name] = ['sub_levels' => [], 'full_field_names' => [], 'value_level' => false]; } $curr_level_array = &$curr_level_array['sub_levels'][$field_name]; $curr_level_array['full_field_names'][] = $full_field_name; } $curr_level_array['value_level'] = true;//В конце всегда должно стоять поле скалярного типа } //------------------------------------------------------------- //В главном запросе можно пользоваться биндингом, а в подзапросах нельзя, так как порядок параметров будет сбиваться параметрами подзапросов $main_query = new QueryBuilder(DB::table($model_table)); $main_query->where($model_table.'.name', '=', $entity_name); $get_fields = [ $model_table.'.name' ]; if($model_table === 'fbforms') { $get_fields[] = $model_table.'.from'; $get_fields[] = $model_table.'.to'; $get_fields[] = $model_table.'.subject'; $get_fields[] = $model_table.'.username'; $get_fields[] = $model_table.'.password'; $get_fields[] = $model_table.'.host'; $get_fields[] = $model_table.'.port'; $get_fields[] = $model_table.'.encryption'; } elseif($model_table === 'fbmails') { $get_fields[] = $model_table.'.id'; $get_fields[] = $model_table.'.form_name'; $get_fields[] = $model_table.'.from'; $get_fields[] = $model_table.'.subject'; $get_fields[] = $model_table.'.to'; $get_fields[] = $model_table.'.username'; $get_fields[] = $model_table.'.email'; $get_fields[] = $model_table.'.body'; $get_fields[] = $model_table.'.mailed'; $get_fields[] = $model_table.'.host'; $get_fields[] = $model_table.'.port'; $get_fields[] = $model_table.'.encryption'; $get_fields[] = $model_table.'.report'; $get_fields[] = $model_table.'.updated_at'; $get_fields[] = $model_table.'.created_at'; } elseif($model_table === 'fbmailtos') { $get_fields[] = $model_table.'.id'; $get_fields[] = $model_table.'.form_name'; $get_fields[] = $model_table.'.to'; } elseif($model_table === 'fbacs') { $get_fields[] = $model_table.'.id'; $get_fields[] = $model_table.'.domain'; $get_fields[] = $model_table.'.host'; $get_fields[] = $model_table.'.port'; $get_fields[] = $model_table.'.encryption'; } //Сначала подсоединяем все, кроме slug, title, sorter, show //$field - путь к полю разделенный точками foreach($join_array['sub_levels'] as $level0_field_name => $sub_array) { $Field = $type->getField($level0_field_name); $join_q = $this->joinMediator->externalJoin($Field, $sub_array); $main_query->leftJoin(DB::raw('('.$join_q->toSql().') AS '.$level0_field_name.'_table'), function($join) use ($level0_field_name, $model_table) { $join->on($model_table.'.name', '=', $level0_field_name.'_table.entity_name'); $join->on($model_table.'.id', '=', $level0_field_name.'_table.entity_id'); }); //$main_query->addBinding($join_q->getBindings()); $get_fields = array_merge($get_fields, $sub_array['full_field_names']); } //Применим все параметры условия и сортировки выборки к запросу: $selectionUnit->apply($main_query); $main_query->select($get_fields); return $main_query; }
php
public function selectByUnit(SelectionUnit $selectionUnit) { $type = $selectionUnit->getType(); $entity_name = $type->getName(); $model_table = $this->getTable($type); $self_fields = ['id,from,subject,to,username,email,body,mailed,host,port,encryption,report,password,domain']; //Группировка путей с общими отрезками //------------------------------------------------------------- $join_fields = $selectionUnit->getJoinFieldsPaths(); $join_array = ['sub_levels' => [], 'full_field_names' => [], 'value_level' => false];//первый уровень - соединение с главным запросом + пути к полям по уровням foreach($join_fields as $field) { if (in_array($field, $self_fields)) { continue; } $curr_level_array = & $join_array; $field_array = explode('.', $field); $full_field_name = str_replace('.', '_', $field); $curr_level_array['full_field_names'][] = $full_field_name; foreach($field_array as $field_name) { if(!array_key_exists($field_name, $curr_level_array['sub_levels'])) { $curr_level_array['sub_levels'][$field_name] = ['sub_levels' => [], 'full_field_names' => [], 'value_level' => false]; } $curr_level_array = &$curr_level_array['sub_levels'][$field_name]; $curr_level_array['full_field_names'][] = $full_field_name; } $curr_level_array['value_level'] = true;//В конце всегда должно стоять поле скалярного типа } //------------------------------------------------------------- //В главном запросе можно пользоваться биндингом, а в подзапросах нельзя, так как порядок параметров будет сбиваться параметрами подзапросов $main_query = new QueryBuilder(DB::table($model_table)); $main_query->where($model_table.'.name', '=', $entity_name); $get_fields = [ $model_table.'.name' ]; if($model_table === 'fbforms') { $get_fields[] = $model_table.'.from'; $get_fields[] = $model_table.'.to'; $get_fields[] = $model_table.'.subject'; $get_fields[] = $model_table.'.username'; $get_fields[] = $model_table.'.password'; $get_fields[] = $model_table.'.host'; $get_fields[] = $model_table.'.port'; $get_fields[] = $model_table.'.encryption'; } elseif($model_table === 'fbmails') { $get_fields[] = $model_table.'.id'; $get_fields[] = $model_table.'.form_name'; $get_fields[] = $model_table.'.from'; $get_fields[] = $model_table.'.subject'; $get_fields[] = $model_table.'.to'; $get_fields[] = $model_table.'.username'; $get_fields[] = $model_table.'.email'; $get_fields[] = $model_table.'.body'; $get_fields[] = $model_table.'.mailed'; $get_fields[] = $model_table.'.host'; $get_fields[] = $model_table.'.port'; $get_fields[] = $model_table.'.encryption'; $get_fields[] = $model_table.'.report'; $get_fields[] = $model_table.'.updated_at'; $get_fields[] = $model_table.'.created_at'; } elseif($model_table === 'fbmailtos') { $get_fields[] = $model_table.'.id'; $get_fields[] = $model_table.'.form_name'; $get_fields[] = $model_table.'.to'; } elseif($model_table === 'fbacs') { $get_fields[] = $model_table.'.id'; $get_fields[] = $model_table.'.domain'; $get_fields[] = $model_table.'.host'; $get_fields[] = $model_table.'.port'; $get_fields[] = $model_table.'.encryption'; } //Сначала подсоединяем все, кроме slug, title, sorter, show //$field - путь к полю разделенный точками foreach($join_array['sub_levels'] as $level0_field_name => $sub_array) { $Field = $type->getField($level0_field_name); $join_q = $this->joinMediator->externalJoin($Field, $sub_array); $main_query->leftJoin(DB::raw('('.$join_q->toSql().') AS '.$level0_field_name.'_table'), function($join) use ($level0_field_name, $model_table) { $join->on($model_table.'.name', '=', $level0_field_name.'_table.entity_name'); $join->on($model_table.'.id', '=', $level0_field_name.'_table.entity_id'); }); //$main_query->addBinding($join_q->getBindings()); $get_fields = array_merge($get_fields, $sub_array['full_field_names']); } //Применим все параметры условия и сортировки выборки к запросу: $selectionUnit->apply($main_query); $main_query->select($get_fields); return $main_query; }
[ "public", "function", "selectByUnit", "(", "SelectionUnit", "$", "selectionUnit", ")", "{", "$", "type", "=", "$", "selectionUnit", "->", "getType", "(", ")", ";", "$", "entity_name", "=", "$", "type", "->", "getName", "(", ")", ";", "$", "model_table", "=", "$", "this", "->", "getTable", "(", "$", "type", ")", ";", "$", "self_fields", "=", "[", "'id,from,subject,to,username,email,body,mailed,host,port,encryption,report,password,domain'", "]", ";", "//Группировка путей с общими отрезками", "//-------------------------------------------------------------", "$", "join_fields", "=", "$", "selectionUnit", "->", "getJoinFieldsPaths", "(", ")", ";", "$", "join_array", "=", "[", "'sub_levels'", "=>", "[", "]", ",", "'full_field_names'", "=>", "[", "]", ",", "'value_level'", "=>", "false", "]", ";", "//первый уровень - соединение с главным запросом + пути к полям по уровням", "foreach", "(", "$", "join_fields", "as", "$", "field", ")", "{", "if", "(", "in_array", "(", "$", "field", ",", "$", "self_fields", ")", ")", "{", "continue", ";", "}", "$", "curr_level_array", "=", "&", "$", "join_array", ";", "$", "field_array", "=", "explode", "(", "'.'", ",", "$", "field", ")", ";", "$", "full_field_name", "=", "str_replace", "(", "'.'", ",", "'_'", ",", "$", "field", ")", ";", "$", "curr_level_array", "[", "'full_field_names'", "]", "[", "]", "=", "$", "full_field_name", ";", "foreach", "(", "$", "field_array", "as", "$", "field_name", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "field_name", ",", "$", "curr_level_array", "[", "'sub_levels'", "]", ")", ")", "{", "$", "curr_level_array", "[", "'sub_levels'", "]", "[", "$", "field_name", "]", "=", "[", "'sub_levels'", "=>", "[", "]", ",", "'full_field_names'", "=>", "[", "]", ",", "'value_level'", "=>", "false", "]", ";", "}", "$", "curr_level_array", "=", "&", "$", "curr_level_array", "[", "'sub_levels'", "]", "[", "$", "field_name", "]", ";", "$", "curr_level_array", "[", "'full_field_names'", "]", "[", "]", "=", "$", "full_field_name", ";", "}", "$", "curr_level_array", "[", "'value_level'", "]", "=", "true", ";", "//В конце всегда должно стоять поле скалярного типа", "}", "//-------------------------------------------------------------", "//В главном запросе можно пользоваться биндингом, а в подзапросах нельзя, так как порядок параметров будет сбиваться параметрами подзапросов", "$", "main_query", "=", "new", "QueryBuilder", "(", "DB", "::", "table", "(", "$", "model_table", ")", ")", ";", "$", "main_query", "->", "where", "(", "$", "model_table", ".", "'.name'", ",", "'='", ",", "$", "entity_name", ")", ";", "$", "get_fields", "=", "[", "$", "model_table", ".", "'.name'", "]", ";", "if", "(", "$", "model_table", "===", "'fbforms'", ")", "{", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.from'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.to'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.subject'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.username'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.password'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.host'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.port'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.encryption'", ";", "}", "elseif", "(", "$", "model_table", "===", "'fbmails'", ")", "{", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.id'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.form_name'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.from'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.subject'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.to'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.username'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.email'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.body'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.mailed'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.host'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.port'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.encryption'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.report'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.updated_at'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.created_at'", ";", "}", "elseif", "(", "$", "model_table", "===", "'fbmailtos'", ")", "{", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.id'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.form_name'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.to'", ";", "}", "elseif", "(", "$", "model_table", "===", "'fbacs'", ")", "{", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.id'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.domain'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.host'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.port'", ";", "$", "get_fields", "[", "]", "=", "$", "model_table", ".", "'.encryption'", ";", "}", "//Сначала подсоединяем все, кроме slug, title, sorter, show", "//$field - путь к полю разделенный точками", "foreach", "(", "$", "join_array", "[", "'sub_levels'", "]", "as", "$", "level0_field_name", "=>", "$", "sub_array", ")", "{", "$", "Field", "=", "$", "type", "->", "getField", "(", "$", "level0_field_name", ")", ";", "$", "join_q", "=", "$", "this", "->", "joinMediator", "->", "externalJoin", "(", "$", "Field", ",", "$", "sub_array", ")", ";", "$", "main_query", "->", "leftJoin", "(", "DB", "::", "raw", "(", "'('", ".", "$", "join_q", "->", "toSql", "(", ")", ".", "') AS '", ".", "$", "level0_field_name", ".", "'_table'", ")", ",", "function", "(", "$", "join", ")", "use", "(", "$", "level0_field_name", ",", "$", "model_table", ")", "{", "$", "join", "->", "on", "(", "$", "model_table", ".", "'.name'", ",", "'='", ",", "$", "level0_field_name", ".", "'_table.entity_name'", ")", ";", "$", "join", "->", "on", "(", "$", "model_table", ".", "'.id'", ",", "'='", ",", "$", "level0_field_name", ".", "'_table.entity_id'", ")", ";", "}", ")", ";", "//$main_query->addBinding($join_q->getBindings());", "$", "get_fields", "=", "array_merge", "(", "$", "get_fields", ",", "$", "sub_array", "[", "'full_field_names'", "]", ")", ";", "}", "//Применим все параметры условия и сортировки выборки к запросу:", "$", "selectionUnit", "->", "apply", "(", "$", "main_query", ")", ";", "$", "main_query", "->", "select", "(", "$", "get_fields", ")", ";", "return", "$", "main_query", ";", "}" ]
@param SelectionUnit $selectionUnit @return \Interpro\Extractor\Db\QueryBuilder @throws \Interpro\QS\Exception\QSException
[ "@param", "SelectionUnit", "$selectionUnit" ]
train
https://github.com/intpro/feedback/blob/394845e13b6464936a3d0435128dd85d9494a267/src/Db/FeedbackQuerier.php#L99-L221
PatrolServer/patrolsdk-php
lib/PatrolModel.php
PatrolModel._get
protected function _get($url, $parameters = null, $scopes = [], $class = null) { $client = new HttpClient($this->patrol, 'get', $url, $parameters); $client->setScopes($scopes); $data = $client->response(); if (isset($data['error'])) { $this->_error($data); } $data = $data['data']; $callee = $class ? $class : get_called_class(); return Util::parseResponseToPatrolObject($this->patrol, $data, $callee, $this->defaults); }
php
protected function _get($url, $parameters = null, $scopes = [], $class = null) { $client = new HttpClient($this->patrol, 'get', $url, $parameters); $client->setScopes($scopes); $data = $client->response(); if (isset($data['error'])) { $this->_error($data); } $data = $data['data']; $callee = $class ? $class : get_called_class(); return Util::parseResponseToPatrolObject($this->patrol, $data, $callee, $this->defaults); }
[ "protected", "function", "_get", "(", "$", "url", ",", "$", "parameters", "=", "null", ",", "$", "scopes", "=", "[", "]", ",", "$", "class", "=", "null", ")", "{", "$", "client", "=", "new", "HttpClient", "(", "$", "this", "->", "patrol", ",", "'get'", ",", "$", "url", ",", "$", "parameters", ")", ";", "$", "client", "->", "setScopes", "(", "$", "scopes", ")", ";", "$", "data", "=", "$", "client", "->", "response", "(", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'error'", "]", ")", ")", "{", "$", "this", "->", "_error", "(", "$", "data", ")", ";", "}", "$", "data", "=", "$", "data", "[", "'data'", "]", ";", "$", "callee", "=", "$", "class", "?", "$", "class", ":", "get_called_class", "(", ")", ";", "return", "Util", "::", "parseResponseToPatrolObject", "(", "$", "this", "->", "patrol", ",", "$", "data", ",", "$", "callee", ",", "$", "this", "->", "defaults", ")", ";", "}" ]
Perform a GET request based on this model @param string $url @param array $parameters @param array $scopes @param string $class The class type where the result should be casted to @return PatrolSdk\Model
[ "Perform", "a", "GET", "request", "based", "on", "this", "model" ]
train
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/PatrolModel.php#L32-L47
PatrolServer/patrolsdk-php
lib/PatrolModel.php
PatrolModel._post
protected function _post($url, $data = [], $class = null) { $client = new HttpClient($this->patrol, 'post', $url, $data); $data = $client->response(); if (isset($data['error'])) { $this->_error($data); } if (!isset($data['data'])) { return $data; } $data = $data['data']; $callee = $class ? $class : get_called_class(); return Util::parseResponseToPatrolObject($this->patrol, $data, $callee, $this->defaults); }
php
protected function _post($url, $data = [], $class = null) { $client = new HttpClient($this->patrol, 'post', $url, $data); $data = $client->response(); if (isset($data['error'])) { $this->_error($data); } if (!isset($data['data'])) { return $data; } $data = $data['data']; $callee = $class ? $class : get_called_class(); return Util::parseResponseToPatrolObject($this->patrol, $data, $callee, $this->defaults); }
[ "protected", "function", "_post", "(", "$", "url", ",", "$", "data", "=", "[", "]", ",", "$", "class", "=", "null", ")", "{", "$", "client", "=", "new", "HttpClient", "(", "$", "this", "->", "patrol", ",", "'post'", ",", "$", "url", ",", "$", "data", ")", ";", "$", "data", "=", "$", "client", "->", "response", "(", ")", ";", "if", "(", "isset", "(", "$", "data", "[", "'error'", "]", ")", ")", "{", "$", "this", "->", "_error", "(", "$", "data", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "'data'", "]", ")", ")", "{", "return", "$", "data", ";", "}", "$", "data", "=", "$", "data", "[", "'data'", "]", ";", "$", "callee", "=", "$", "class", "?", "$", "class", ":", "get_called_class", "(", ")", ";", "return", "Util", "::", "parseResponseToPatrolObject", "(", "$", "this", "->", "patrol", ",", "$", "data", ",", "$", "callee", ",", "$", "this", "->", "defaults", ")", ";", "}" ]
Perform a POST request based on this model @param string $url @param array $data @param string $class The class type where the result should be casted to @return PatrolSdk\Model
[ "Perform", "a", "POST", "request", "based", "on", "this", "model" ]
train
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/PatrolModel.php#L58-L75
MatiasNAmendola/slimpower-slim
src/Middleware/Json/View.php
View.render
public function render($status = 200, $data = null) { $app = $this->app; $status = \intval($status); if ($this->dataWrapper) { $response[$this->dataWrapper] = $this->all(); } else { $response = $this->all(); } if (!$this->dataOnly) { //append error bool if ($status < 400) { if ($this->metaWrapper) { $response[$this->metaWrapper]['error'] = false; } else { $response['error'] = false; } } else { if ($this->metaWrapper) { $response[$this->metaWrapper]['error'] = true; } else { $response['error'] = true; } } //append status code if ($app->config(Config::Status)) { if ($this->metaWrapper) { $response[$this->metaWrapper]['status'] = $status; } else { $response['status'] = $status; } } //add flash messages if (isset($this->data->flash) && \is_object($this->data->flash)) { // if (isset($response['flash']) && \is_object($response['flash'])) { $flash = $this->data->flash->getMessages(); if ($this->dataWrapper) { unset($response[$this->dataWrapper]['flash']); } else { unset($response['flash']); } if (count($flash)) { if ($this->metaWrapper) { $response[$this->metaWrapper]['flash'] = $flash; } else { $response['flash'] = $flash; } } } } else { unset($response['flash'], $response['status'], $response['error']); } $app->response()->status($status); $app->response()->header('Content-Type', $this->contentType); $jsonp_callback = $app->request->get('callback', null); /** * Bitmask consisting of <b>JSON_HEX_QUOT</b>, * <b>JSON_HEX_TAG</b>, * <b>JSON_HEX_AMP</b>, * <b>JSON_HEX_APOS</b>, * <b>JSON_NUMERIC_CHECK</b>, * <b>JSON_PRETTY_PRINT</b>, * <b>JSON_UNESCAPED_SLASHES</b>, * <b>JSON_FORCE_OBJECT</b>, * <b>JSON_UNESCAPED_UNICODE</b>. * The behaviour of these constants is described on * the JSON constants page. * @var int */ $encodingOptions = $app->config(Config::JsonEncodeOptions); if ($jsonp_callback !== null) { $body = $jsonp_callback . '(' . json_encode($response, $encodingOptions) . ')'; } else { $body = json_encode($response, $encodingOptions); } if ($status == 404) { return $body; } else { $app->response()->body($body); } }
php
public function render($status = 200, $data = null) { $app = $this->app; $status = \intval($status); if ($this->dataWrapper) { $response[$this->dataWrapper] = $this->all(); } else { $response = $this->all(); } if (!$this->dataOnly) { //append error bool if ($status < 400) { if ($this->metaWrapper) { $response[$this->metaWrapper]['error'] = false; } else { $response['error'] = false; } } else { if ($this->metaWrapper) { $response[$this->metaWrapper]['error'] = true; } else { $response['error'] = true; } } //append status code if ($app->config(Config::Status)) { if ($this->metaWrapper) { $response[$this->metaWrapper]['status'] = $status; } else { $response['status'] = $status; } } //add flash messages if (isset($this->data->flash) && \is_object($this->data->flash)) { // if (isset($response['flash']) && \is_object($response['flash'])) { $flash = $this->data->flash->getMessages(); if ($this->dataWrapper) { unset($response[$this->dataWrapper]['flash']); } else { unset($response['flash']); } if (count($flash)) { if ($this->metaWrapper) { $response[$this->metaWrapper]['flash'] = $flash; } else { $response['flash'] = $flash; } } } } else { unset($response['flash'], $response['status'], $response['error']); } $app->response()->status($status); $app->response()->header('Content-Type', $this->contentType); $jsonp_callback = $app->request->get('callback', null); /** * Bitmask consisting of <b>JSON_HEX_QUOT</b>, * <b>JSON_HEX_TAG</b>, * <b>JSON_HEX_AMP</b>, * <b>JSON_HEX_APOS</b>, * <b>JSON_NUMERIC_CHECK</b>, * <b>JSON_PRETTY_PRINT</b>, * <b>JSON_UNESCAPED_SLASHES</b>, * <b>JSON_FORCE_OBJECT</b>, * <b>JSON_UNESCAPED_UNICODE</b>. * The behaviour of these constants is described on * the JSON constants page. * @var int */ $encodingOptions = $app->config(Config::JsonEncodeOptions); if ($jsonp_callback !== null) { $body = $jsonp_callback . '(' . json_encode($response, $encodingOptions) . ')'; } else { $body = json_encode($response, $encodingOptions); } if ($status == 404) { return $body; } else { $app->response()->body($body); } }
[ "public", "function", "render", "(", "$", "status", "=", "200", ",", "$", "data", "=", "null", ")", "{", "$", "app", "=", "$", "this", "->", "app", ";", "$", "status", "=", "\\", "intval", "(", "$", "status", ")", ";", "if", "(", "$", "this", "->", "dataWrapper", ")", "{", "$", "response", "[", "$", "this", "->", "dataWrapper", "]", "=", "$", "this", "->", "all", "(", ")", ";", "}", "else", "{", "$", "response", "=", "$", "this", "->", "all", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "dataOnly", ")", "{", "//append error bool\r", "if", "(", "$", "status", "<", "400", ")", "{", "if", "(", "$", "this", "->", "metaWrapper", ")", "{", "$", "response", "[", "$", "this", "->", "metaWrapper", "]", "[", "'error'", "]", "=", "false", ";", "}", "else", "{", "$", "response", "[", "'error'", "]", "=", "false", ";", "}", "}", "else", "{", "if", "(", "$", "this", "->", "metaWrapper", ")", "{", "$", "response", "[", "$", "this", "->", "metaWrapper", "]", "[", "'error'", "]", "=", "true", ";", "}", "else", "{", "$", "response", "[", "'error'", "]", "=", "true", ";", "}", "}", "//append status code\r", "if", "(", "$", "app", "->", "config", "(", "Config", "::", "Status", ")", ")", "{", "if", "(", "$", "this", "->", "metaWrapper", ")", "{", "$", "response", "[", "$", "this", "->", "metaWrapper", "]", "[", "'status'", "]", "=", "$", "status", ";", "}", "else", "{", "$", "response", "[", "'status'", "]", "=", "$", "status", ";", "}", "}", "//add flash messages\r", "if", "(", "isset", "(", "$", "this", "->", "data", "->", "flash", ")", "&&", "\\", "is_object", "(", "$", "this", "->", "data", "->", "flash", ")", ")", "{", "// if (isset($response['flash']) && \\is_object($response['flash'])) {\r", "$", "flash", "=", "$", "this", "->", "data", "->", "flash", "->", "getMessages", "(", ")", ";", "if", "(", "$", "this", "->", "dataWrapper", ")", "{", "unset", "(", "$", "response", "[", "$", "this", "->", "dataWrapper", "]", "[", "'flash'", "]", ")", ";", "}", "else", "{", "unset", "(", "$", "response", "[", "'flash'", "]", ")", ";", "}", "if", "(", "count", "(", "$", "flash", ")", ")", "{", "if", "(", "$", "this", "->", "metaWrapper", ")", "{", "$", "response", "[", "$", "this", "->", "metaWrapper", "]", "[", "'flash'", "]", "=", "$", "flash", ";", "}", "else", "{", "$", "response", "[", "'flash'", "]", "=", "$", "flash", ";", "}", "}", "}", "}", "else", "{", "unset", "(", "$", "response", "[", "'flash'", "]", ",", "$", "response", "[", "'status'", "]", ",", "$", "response", "[", "'error'", "]", ")", ";", "}", "$", "app", "->", "response", "(", ")", "->", "status", "(", "$", "status", ")", ";", "$", "app", "->", "response", "(", ")", "->", "header", "(", "'Content-Type'", ",", "$", "this", "->", "contentType", ")", ";", "$", "jsonp_callback", "=", "$", "app", "->", "request", "->", "get", "(", "'callback'", ",", "null", ")", ";", "/**\r\n * Bitmask consisting of <b>JSON_HEX_QUOT</b>,\r\n * <b>JSON_HEX_TAG</b>,\r\n * <b>JSON_HEX_AMP</b>,\r\n * <b>JSON_HEX_APOS</b>,\r\n * <b>JSON_NUMERIC_CHECK</b>,\r\n * <b>JSON_PRETTY_PRINT</b>,\r\n * <b>JSON_UNESCAPED_SLASHES</b>,\r\n * <b>JSON_FORCE_OBJECT</b>,\r\n * <b>JSON_UNESCAPED_UNICODE</b>.\r\n * The behaviour of these constants is described on\r\n * the JSON constants page.\r\n * @var int\r\n */", "$", "encodingOptions", "=", "$", "app", "->", "config", "(", "Config", "::", "JsonEncodeOptions", ")", ";", "if", "(", "$", "jsonp_callback", "!==", "null", ")", "{", "$", "body", "=", "$", "jsonp_callback", ".", "'('", ".", "json_encode", "(", "$", "response", ",", "$", "encodingOptions", ")", ".", "')'", ";", "}", "else", "{", "$", "body", "=", "json_encode", "(", "$", "response", ",", "$", "encodingOptions", ")", ";", "}", "if", "(", "$", "status", "==", "404", ")", "{", "return", "$", "body", ";", "}", "else", "{", "$", "app", "->", "response", "(", ")", "->", "body", "(", "$", "body", ")", ";", "}", "}" ]
Render @param int|string $status (optional) @param array|null $data (optional) @return void
[ "Render" ]
train
https://github.com/MatiasNAmendola/slimpower-slim/blob/c78ebbd4124d75ec82fe19b6dd62504da097fd15/src/Middleware/Json/View.php#L90-L182
tonis-io-legacy/tonis
src/Http/Response.php
Response.redirectToRoute
public function redirectToRoute($route, array $params = [], $permanent = false) { $map = $this->app()->getRouteMap(); $url = $map->assemble($route, $params); return $this->redirect($url, $permanent); }
php
public function redirectToRoute($route, array $params = [], $permanent = false) { $map = $this->app()->getRouteMap(); $url = $map->assemble($route, $params); return $this->redirect($url, $permanent); }
[ "public", "function", "redirectToRoute", "(", "$", "route", ",", "array", "$", "params", "=", "[", "]", ",", "$", "permanent", "=", "false", ")", "{", "$", "map", "=", "$", "this", "->", "app", "(", ")", "->", "getRouteMap", "(", ")", ";", "$", "url", "=", "$", "map", "->", "assemble", "(", "$", "route", ",", "$", "params", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "url", ",", "$", "permanent", ")", ";", "}" ]
Redirects to a named route. @see \Tonis\Http\Response::redirect() @param string $route @param array $params @param bool|false $permanent @return ResponseInterface
[ "Redirects", "to", "a", "named", "route", "." ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L60-L66
tonis-io-legacy/tonis
src/Http/Response.php
Response.jsonp
public function jsonp($input, $callback) { return $this ->withHeader('Content-Type', 'application/javascript') ->write(sprintf('%s(%s);', $callback, json_encode($input))); }
php
public function jsonp($input, $callback) { return $this ->withHeader('Content-Type', 'application/javascript') ->write(sprintf('%s(%s);', $callback, json_encode($input))); }
[ "public", "function", "jsonp", "(", "$", "input", ",", "$", "callback", ")", "{", "return", "$", "this", "->", "withHeader", "(", "'Content-Type'", ",", "'application/javascript'", ")", "->", "write", "(", "sprintf", "(", "'%s(%s);'", ",", "$", "callback", ",", "json_encode", "(", "$", "input", ")", ")", ")", ";", "}" ]
Encodes the input as JSONP and sets the Content-Type header to application/javascript. @param mixed $input @param string $callback @return self
[ "Encodes", "the", "input", "as", "JSONP", "and", "sets", "the", "Content", "-", "Type", "header", "to", "application", "/", "javascript", "." ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L88-L93
tonis-io-legacy/tonis
src/Http/Response.php
Response.render
public function render($template, array $params = []) { return $this->write($this->app->getView()->render($template, $params)); }
php
public function render($template, array $params = []) { return $this->write($this->app->getView()->render($template, $params)); }
[ "public", "function", "render", "(", "$", "template", ",", "array", "$", "params", "=", "[", "]", ")", "{", "return", "$", "this", "->", "write", "(", "$", "this", "->", "app", "->", "getView", "(", ")", "->", "render", "(", "$", "template", ",", "$", "params", ")", ")", ";", "}" ]
Attempts to render the `$template` with `$params` using the ViewManager. If a strategy is not available then the Tonis fallback strategy is used. @param string $template @param array $params @return string
[ "Attempts", "to", "render", "the", "$template", "with", "$params", "using", "the", "ViewManager", ".", "If", "a", "strategy", "is", "not", "available", "then", "the", "Tonis", "fallback", "strategy", "is", "used", "." ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L103-L106
tonis-io-legacy/tonis
src/Http/Response.php
Response.withHeader
public function withHeader($name, $value) { return new self($this->app, $this->decorated->withHeader($name, $value)); }
php
public function withHeader($name, $value) { return new self($this->app, $this->decorated->withHeader($name, $value)); }
[ "public", "function", "withHeader", "(", "$", "name", ",", "$", "value", ")", "{", "return", "new", "self", "(", "$", "this", "->", "app", ",", "$", "this", "->", "decorated", "->", "withHeader", "(", "$", "name", ",", "$", "value", ")", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L159-L162
tonis-io-legacy/tonis
src/Http/Response.php
Response.withAddedHeader
public function withAddedHeader($name, $value) { return new self($this->app, $this->decorated->withAddedHeader($name, $value)); }
php
public function withAddedHeader($name, $value) { return new self($this->app, $this->decorated->withAddedHeader($name, $value)); }
[ "public", "function", "withAddedHeader", "(", "$", "name", ",", "$", "value", ")", "{", "return", "new", "self", "(", "$", "this", "->", "app", ",", "$", "this", "->", "decorated", "->", "withAddedHeader", "(", "$", "name", ",", "$", "value", ")", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L167-L170
tonis-io-legacy/tonis
src/Http/Response.php
Response.withBody
public function withBody(StreamInterface $body) { return new self($this->app, $this->decorated->withBody($body)); }
php
public function withBody(StreamInterface $body) { return new self($this->app, $this->decorated->withBody($body)); }
[ "public", "function", "withBody", "(", "StreamInterface", "$", "body", ")", "{", "return", "new", "self", "(", "$", "this", "->", "app", ",", "$", "this", "->", "decorated", "->", "withBody", "(", "$", "body", ")", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L191-L194
tonis-io-legacy/tonis
src/Http/Response.php
Response.withStatus
public function withStatus($code, $reasonPhrase = '') { return new self($this->app, $this->decorated->withStatus($code, $reasonPhrase)); }
php
public function withStatus($code, $reasonPhrase = '') { return new self($this->app, $this->decorated->withStatus($code, $reasonPhrase)); }
[ "public", "function", "withStatus", "(", "$", "code", ",", "$", "reasonPhrase", "=", "''", ")", "{", "return", "new", "self", "(", "$", "this", "->", "app", ",", "$", "this", "->", "decorated", "->", "withStatus", "(", "$", "code", ",", "$", "reasonPhrase", ")", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/tonis-io-legacy/tonis/blob/8371a277a94232433d882aaf37a85cd469daf501/src/Http/Response.php#L207-L210
PenoaksDev/Milky-Framework
src/Milky/Mail/TransportManager.php
TransportManager.createSmtpDriver
protected function createSmtpDriver() { $config = Config::get( 'mail' ); // The Swift SMTP transport instance will allow us to use any SMTP backend // for delivering mail such as Sendgrid, Amazon SES, or a custom server // a developer has available. We will just pass this configured host. $transport = SmtpTransport::newInstance( $config['host'], $config['port'] ); if ( isset( $config['encryption'] ) ) $transport->setEncryption( $config['encryption'] ); // Once we have the transport we will check for the presence of a username // and password. If we have it we will set the credentials on the Swift // transporter instance so that we'll properly authenticate delivery. if ( isset( $config['username'] ) ) { $transport->setUsername( $config['username'] ); $transport->setPassword( $config['password'] ); } if ( isset( $config['stream'] ) ) $transport->setStreamOptions( $config['stream'] ); return $transport; }
php
protected function createSmtpDriver() { $config = Config::get( 'mail' ); // The Swift SMTP transport instance will allow us to use any SMTP backend // for delivering mail such as Sendgrid, Amazon SES, or a custom server // a developer has available. We will just pass this configured host. $transport = SmtpTransport::newInstance( $config['host'], $config['port'] ); if ( isset( $config['encryption'] ) ) $transport->setEncryption( $config['encryption'] ); // Once we have the transport we will check for the presence of a username // and password. If we have it we will set the credentials on the Swift // transporter instance so that we'll properly authenticate delivery. if ( isset( $config['username'] ) ) { $transport->setUsername( $config['username'] ); $transport->setPassword( $config['password'] ); } if ( isset( $config['stream'] ) ) $transport->setStreamOptions( $config['stream'] ); return $transport; }
[ "protected", "function", "createSmtpDriver", "(", ")", "{", "$", "config", "=", "Config", "::", "get", "(", "'mail'", ")", ";", "// The Swift SMTP transport instance will allow us to use any SMTP backend", "// for delivering mail such as Sendgrid, Amazon SES, or a custom server", "// a developer has available. We will just pass this configured host.", "$", "transport", "=", "SmtpTransport", "::", "newInstance", "(", "$", "config", "[", "'host'", "]", ",", "$", "config", "[", "'port'", "]", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'encryption'", "]", ")", ")", "$", "transport", "->", "setEncryption", "(", "$", "config", "[", "'encryption'", "]", ")", ";", "// Once we have the transport we will check for the presence of a username", "// and password. If we have it we will set the credentials on the Swift", "// transporter instance so that we'll properly authenticate delivery.", "if", "(", "isset", "(", "$", "config", "[", "'username'", "]", ")", ")", "{", "$", "transport", "->", "setUsername", "(", "$", "config", "[", "'username'", "]", ")", ";", "$", "transport", "->", "setPassword", "(", "$", "config", "[", "'password'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'stream'", "]", ")", ")", "$", "transport", "->", "setStreamOptions", "(", "$", "config", "[", "'stream'", "]", ")", ";", "return", "$", "transport", ";", "}" ]
Create an instance of the SMTP Swift Transport driver. @return \Swift_SmtpTransport
[ "Create", "an", "instance", "of", "the", "SMTP", "Swift", "Transport", "driver", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Mail/TransportManager.php#L33-L58
PenoaksDev/Milky-Framework
src/Milky/Mail/TransportManager.php
TransportManager.createSesDriver
protected function createSesDriver() { $config = Config::get( 'services.ses' ); $config += [ 'version' => 'latest', 'service' => 'email', ]; if ( $config['key'] && $config['secret'] ) { $config['credentials'] = Arr::only( $config, ['key', 'secret'] ); } return new SesTransport( new SesClient( $config ) ); }
php
protected function createSesDriver() { $config = Config::get( 'services.ses' ); $config += [ 'version' => 'latest', 'service' => 'email', ]; if ( $config['key'] && $config['secret'] ) { $config['credentials'] = Arr::only( $config, ['key', 'secret'] ); } return new SesTransport( new SesClient( $config ) ); }
[ "protected", "function", "createSesDriver", "(", ")", "{", "$", "config", "=", "Config", "::", "get", "(", "'services.ses'", ")", ";", "$", "config", "+=", "[", "'version'", "=>", "'latest'", ",", "'service'", "=>", "'email'", ",", "]", ";", "if", "(", "$", "config", "[", "'key'", "]", "&&", "$", "config", "[", "'secret'", "]", ")", "{", "$", "config", "[", "'credentials'", "]", "=", "Arr", "::", "only", "(", "$", "config", ",", "[", "'key'", ",", "'secret'", "]", ")", ";", "}", "return", "new", "SesTransport", "(", "new", "SesClient", "(", "$", "config", ")", ")", ";", "}" ]
Create an instance of the Amazon SES Swift Transport driver. @return SesTransport
[ "Create", "an", "instance", "of", "the", "Amazon", "SES", "Swift", "Transport", "driver", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Mail/TransportManager.php#L77-L92
PenoaksDev/Milky-Framework
src/Milky/Mail/TransportManager.php
TransportManager.createMailgunDriver
protected function createMailgunDriver() { $config = Config::get( 'services.mailgun', [] ); return new MailgunTransport( $this->getHttpClient( $config ), $config['secret'], $config['domain'] ); }
php
protected function createMailgunDriver() { $config = Config::get( 'services.mailgun', [] ); return new MailgunTransport( $this->getHttpClient( $config ), $config['secret'], $config['domain'] ); }
[ "protected", "function", "createMailgunDriver", "(", ")", "{", "$", "config", "=", "Config", "::", "get", "(", "'services.mailgun'", ",", "[", "]", ")", ";", "return", "new", "MailgunTransport", "(", "$", "this", "->", "getHttpClient", "(", "$", "config", ")", ",", "$", "config", "[", "'secret'", "]", ",", "$", "config", "[", "'domain'", "]", ")", ";", "}" ]
Create an instance of the Mailgun Swift Transport driver. @return MailgunTransport
[ "Create", "an", "instance", "of", "the", "Mailgun", "Swift", "Transport", "driver", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Mail/TransportManager.php#L109-L114
PenoaksDev/Milky-Framework
src/Milky/Mail/TransportManager.php
TransportManager.createSparkPostDriver
protected function createSparkPostDriver() { $config = Config::get( 'services.sparkpost', [] ); return new SparkPostTransport( $this->getHttpClient( $config ), $config['secret'], Arr::get( $config, 'options', [] ) ); }
php
protected function createSparkPostDriver() { $config = Config::get( 'services.sparkpost', [] ); return new SparkPostTransport( $this->getHttpClient( $config ), $config['secret'], Arr::get( $config, 'options', [] ) ); }
[ "protected", "function", "createSparkPostDriver", "(", ")", "{", "$", "config", "=", "Config", "::", "get", "(", "'services.sparkpost'", ",", "[", "]", ")", ";", "return", "new", "SparkPostTransport", "(", "$", "this", "->", "getHttpClient", "(", "$", "config", ")", ",", "$", "config", "[", "'secret'", "]", ",", "Arr", "::", "get", "(", "$", "config", ",", "'options'", ",", "[", "]", ")", ")", ";", "}" ]
Create an instance of the SparkPost Swift Transport driver. @return SparkPostTransport
[ "Create", "an", "instance", "of", "the", "SparkPost", "Swift", "Transport", "driver", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Mail/TransportManager.php#L133-L138
PenoaksDev/Milky-Framework
src/Milky/Mail/TransportManager.php
TransportManager.getHttpClient
protected function getHttpClient( $config ) { $guzzleConfig = Arr::get( $config, 'guzzle', [] ); return new HttpClient( Arr::add( $guzzleConfig, 'connect_timeout', 60 ) ); }
php
protected function getHttpClient( $config ) { $guzzleConfig = Arr::get( $config, 'guzzle', [] ); return new HttpClient( Arr::add( $guzzleConfig, 'connect_timeout', 60 ) ); }
[ "protected", "function", "getHttpClient", "(", "$", "config", ")", "{", "$", "guzzleConfig", "=", "Arr", "::", "get", "(", "$", "config", ",", "'guzzle'", ",", "[", "]", ")", ";", "return", "new", "HttpClient", "(", "Arr", "::", "add", "(", "$", "guzzleConfig", ",", "'connect_timeout'", ",", "60", ")", ")", ";", "}" ]
Get a fresh Guzzle HTTP client instance. @param array $config @return HttpClient
[ "Get", "a", "fresh", "Guzzle", "HTTP", "client", "instance", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Mail/TransportManager.php#L156-L161
pluf/tenant
src/Tenant/Views/Resource.php
Tenant_Views_Resource.download
public function download($request, $match) { // GET data $resource = Pluf_Shortcuts_GetObjectOr404('Tenant_Resource', $match['modelId']); // Do $resource->downloads += 1; $resource->update(); return new Pluf_HTTP_Response_File($resource->getAbsloutPath(), $resource->mime_type); }
php
public function download($request, $match) { // GET data $resource = Pluf_Shortcuts_GetObjectOr404('Tenant_Resource', $match['modelId']); // Do $resource->downloads += 1; $resource->update(); return new Pluf_HTTP_Response_File($resource->getAbsloutPath(), $resource->mime_type); }
[ "public", "function", "download", "(", "$", "request", ",", "$", "match", ")", "{", "// GET data", "$", "resource", "=", "Pluf_Shortcuts_GetObjectOr404", "(", "'Tenant_Resource'", ",", "$", "match", "[", "'modelId'", "]", ")", ";", "// Do", "$", "resource", "->", "downloads", "+=", "1", ";", "$", "resource", "->", "update", "(", ")", ";", "return", "new", "Pluf_HTTP_Response_File", "(", "$", "resource", "->", "getAbsloutPath", "(", ")", ",", "$", "resource", "->", "mime_type", ")", ";", "}" ]
Download a resource @param Pluf_HTTP_Request $request @param array $match @return Pluf_HTTP_Response_File
[ "Download", "a", "resource" ]
train
https://github.com/pluf/tenant/blob/a06359c52b9a257b5a0a186264e8770acfc54b73/src/Tenant/Views/Resource.php#L37-L45
pluf/tenant
src/Tenant/Views/Resource.php
Tenant_Views_Resource.updateFile
public function updateFile($request, $match) { // Get data $resource = Pluf_Shortcuts_GetObjectOr404('Tenant_Resource', $match['modelId']); // Do action if (array_key_exists('file', $request->FILES)) { $extra = array( 'model' => $resource ); $form = new Tenant_Form_ResourceUpdate(array_merge($request->REQUEST, $request->FILES), $extra); $resource = $form->save(); return $resource; } else { $myfile = fopen($resource->getAbsloutPath(), "w") or die("Unable to open file!"); $entityBody = file_get_contents('php://input', 'r'); fwrite($myfile, $entityBody); fclose($myfile); $resource->update(); } return $resource; }
php
public function updateFile($request, $match) { // Get data $resource = Pluf_Shortcuts_GetObjectOr404('Tenant_Resource', $match['modelId']); // Do action if (array_key_exists('file', $request->FILES)) { $extra = array( 'model' => $resource ); $form = new Tenant_Form_ResourceUpdate(array_merge($request->REQUEST, $request->FILES), $extra); $resource = $form->save(); return $resource; } else { $myfile = fopen($resource->getAbsloutPath(), "w") or die("Unable to open file!"); $entityBody = file_get_contents('php://input', 'r'); fwrite($myfile, $entityBody); fclose($myfile); $resource->update(); } return $resource; }
[ "public", "function", "updateFile", "(", "$", "request", ",", "$", "match", ")", "{", "// Get data", "$", "resource", "=", "Pluf_Shortcuts_GetObjectOr404", "(", "'Tenant_Resource'", ",", "$", "match", "[", "'modelId'", "]", ")", ";", "// Do action", "if", "(", "array_key_exists", "(", "'file'", ",", "$", "request", "->", "FILES", ")", ")", "{", "$", "extra", "=", "array", "(", "'model'", "=>", "$", "resource", ")", ";", "$", "form", "=", "new", "Tenant_Form_ResourceUpdate", "(", "array_merge", "(", "$", "request", "->", "REQUEST", ",", "$", "request", "->", "FILES", ")", ",", "$", "extra", ")", ";", "$", "resource", "=", "$", "form", "->", "save", "(", ")", ";", "return", "$", "resource", ";", "}", "else", "{", "$", "myfile", "=", "fopen", "(", "$", "resource", "->", "getAbsloutPath", "(", ")", ",", "\"w\"", ")", "or", "die", "(", "\"Unable to open file!\"", ")", ";", "$", "entityBody", "=", "file_get_contents", "(", "'php://input'", ",", "'r'", ")", ";", "fwrite", "(", "$", "myfile", ",", "$", "entityBody", ")", ";", "fclose", "(", "$", "myfile", ")", ";", "$", "resource", "->", "update", "(", ")", ";", "}", "return", "$", "resource", ";", "}" ]
Upload a file as content @param Pluf_HTTP_Request $request @param array $match @return Pluf_HTTP_Response_Json|object
[ "Upload", "a", "file", "as", "content" ]
train
https://github.com/pluf/tenant/blob/a06359c52b9a257b5a0a186264e8770acfc54b73/src/Tenant/Views/Resource.php#L54-L74
hiqdev/minii-caching
src/ApcCache.php
ApcCache.setValues
protected function setValues($data, $duration) { $result = apc_store($data, null, $duration); return is_array($result) ? array_keys($result) : []; }
php
protected function setValues($data, $duration) { $result = apc_store($data, null, $duration); return is_array($result) ? array_keys($result) : []; }
[ "protected", "function", "setValues", "(", "$", "data", ",", "$", "duration", ")", "{", "$", "result", "=", "apc_store", "(", "$", "data", ",", "null", ",", "$", "duration", ")", ";", "return", "is_array", "(", "$", "result", ")", "?", "array_keys", "(", "$", "result", ")", ":", "[", "]", ";", "}" ]
Stores multiple key-value pairs in cache. @param array $data array where key corresponds to cache key while value @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire. @return array array of failed keys
[ "Stores", "multiple", "key", "-", "value", "pairs", "in", "cache", "." ]
train
https://github.com/hiqdev/minii-caching/blob/04c3f810a4af43b53855ee9c5e3ef6455080b538/src/ApcCache.php#L82-L86
hiqdev/minii-caching
src/ApcCache.php
ApcCache.addValues
protected function addValues($data, $duration) { $result = apc_add($data, null, $duration); return is_array($result) ? array_keys($result) : []; }
php
protected function addValues($data, $duration) { $result = apc_add($data, null, $duration); return is_array($result) ? array_keys($result) : []; }
[ "protected", "function", "addValues", "(", "$", "data", ",", "$", "duration", ")", "{", "$", "result", "=", "apc_add", "(", "$", "data", ",", "null", ",", "$", "duration", ")", ";", "return", "is_array", "(", "$", "result", ")", "?", "array_keys", "(", "$", "result", ")", ":", "[", "]", ";", "}" ]
Adds multiple key-value pairs to cache. @param array $data array where key corresponds to cache key while value is the value stored @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire. @return array array of failed keys
[ "Adds", "multiple", "key", "-", "value", "pairs", "to", "cache", "." ]
train
https://github.com/hiqdev/minii-caching/blob/04c3f810a4af43b53855ee9c5e3ef6455080b538/src/ApcCache.php#L107-L111
rutger-speksnijder/restphp
src/RestPHP/Response/ResponseFactory.php
ResponseFactory.build
public function build($type, $data, $hypertextRoutes = []) { if (!isset($this->types[$type])) { throw new \Exception("Unknown response type."); } return new $this->types[$type]($data, $hypertextRoutes); }
php
public function build($type, $data, $hypertextRoutes = []) { if (!isset($this->types[$type])) { throw new \Exception("Unknown response type."); } return new $this->types[$type]($data, $hypertextRoutes); }
[ "public", "function", "build", "(", "$", "type", ",", "$", "data", ",", "$", "hypertextRoutes", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "types", "[", "$", "type", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Unknown response type.\"", ")", ";", "}", "return", "new", "$", "this", "->", "types", "[", "$", "type", "]", "(", "$", "data", ",", "$", "hypertextRoutes", ")", ";", "}" ]
Builds the response object. @param string $type The type of response to build. @param mixed $data The response data. @param optional array $hypertextRoutes An array of hypertext routes. @throws Exception Throws an exception for unknown response types. @return \RestPHP\Response The created object.
[ "Builds", "the", "response", "object", "." ]
train
https://github.com/rutger-speksnijder/restphp/blob/326a7c0d79b266bbdd8a27ff1c8021caf9d28a3d/src/RestPHP/Response/ResponseFactory.php#L52-L58
TeaLabs/collections
src/Collection.php
Collection.default
public function default($key, $default = null) { if($this->has($key)) return $this->get($key); $this->put($key, $default); return $default; }
php
public function default($key, $default = null) { if($this->has($key)) return $this->get($key); $this->put($key, $default); return $default; }
[ "public", "function", "default", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "key", ")", ")", "return", "$", "this", "->", "get", "(", "$", "key", ")", ";", "$", "this", "->", "put", "(", "$", "key", ",", "$", "default", ")", ";", "return", "$", "default", ";", "}" ]
If key is in the collection, return its value. If not, insert key with the given default as value and return default. @param string $key @param mixed $default @return mixed
[ "If", "key", "is", "in", "the", "collection", "return", "its", "value", ".", "If", "not", "insert", "key", "with", "the", "given", "default", "as", "value", "and", "return", "default", "." ]
train
https://github.com/TeaLabs/collections/blob/5d8885b2799791c0bcbff4e6cbacddb270b4288e/src/Collection.php#L30-L38
TeaLabs/collections
src/Collection.php
Collection.has
public function has($keys, $any = false) { foreach ($this->getArrayableItems($keys) as $key) { $exists = $this->offsetExists($key); if(($any && $exists) || (!$any && !$exists)) return $exists; } return $any ? false : true; }
php
public function has($keys, $any = false) { foreach ($this->getArrayableItems($keys) as $key) { $exists = $this->offsetExists($key); if(($any && $exists) || (!$any && !$exists)) return $exists; } return $any ? false : true; }
[ "public", "function", "has", "(", "$", "keys", ",", "$", "any", "=", "false", ")", "{", "foreach", "(", "$", "this", "->", "getArrayableItems", "(", "$", "keys", ")", "as", "$", "key", ")", "{", "$", "exists", "=", "$", "this", "->", "offsetExists", "(", "$", "key", ")", ";", "if", "(", "(", "$", "any", "&&", "$", "exists", ")", "||", "(", "!", "$", "any", "&&", "!", "$", "exists", ")", ")", "return", "$", "exists", ";", "}", "return", "$", "any", "?", "false", ":", "true", ";", "}" ]
Determine if all or any of the given items exists in the collection by key. $keys can be a single item key or an iterable of keys. If $keys is an iterable and $any is false or not given, will return true if all keys in $keys are exist in the collection and false otherwise. If $keys is an iterable and $any is true, will return true if at least one of the keys in $key exists in the collection and false otherwise. @param mixed|iterable $keys @param bool $any @return bool
[ "Determine", "if", "all", "or", "any", "of", "the", "given", "items", "exists", "in", "the", "collection", "by", "key", ".", "$keys", "can", "be", "a", "single", "item", "key", "or", "an", "iterable", "of", "keys", ".", "If", "$keys", "is", "an", "iterable", "and", "$any", "is", "false", "or", "not", "given", "will", "return", "true", "if", "all", "keys", "in", "$keys", "are", "exist", "in", "the", "collection", "and", "false", "otherwise", ".", "If", "$keys", "is", "an", "iterable", "and", "$any", "is", "true", "will", "return", "true", "if", "at", "least", "one", "of", "the", "keys", "in", "$key", "exists", "in", "the", "collection", "and", "false", "otherwise", "." ]
train
https://github.com/TeaLabs/collections/blob/5d8885b2799791c0bcbff4e6cbacddb270b4288e/src/Collection.php#L84-L92
TeaLabs/collections
src/Collection.php
Collection.update
public function update($items, $recursive = false) { $items = $this->getArrayableItems($items); if($recursive) $this->items = array_replace_recursive($this->items, $items); else $this->items = array_replace($this->items, $items); return $this; }
php
public function update($items, $recursive = false) { $items = $this->getArrayableItems($items); if($recursive) $this->items = array_replace_recursive($this->items, $items); else $this->items = array_replace($this->items, $items); return $this; }
[ "public", "function", "update", "(", "$", "items", ",", "$", "recursive", "=", "false", ")", "{", "$", "items", "=", "$", "this", "->", "getArrayableItems", "(", "$", "items", ")", ";", "if", "(", "$", "recursive", ")", "$", "this", "->", "items", "=", "array_replace_recursive", "(", "$", "this", "->", "items", ",", "$", "items", ")", ";", "else", "$", "this", "->", "items", "=", "array_replace", "(", "$", "this", "->", "items", ",", "$", "items", ")", ";", "return", "$", "this", ";", "}" ]
Update the collection with another collection of items. If an item in the collection also exists in the new $items, it's value will be replaced by the value in the new $items. If an item exists in the new $items but not in the collection, it will be added to the collection as well. @see \Tea\Collections\Collection::replace() @uses array_replace() when $recursive is false (default). @uses array_replace_recursive() when $recursive is true. @param mixed $items @param bool $recursive @return $this
[ "Update", "the", "collection", "with", "another", "collection", "of", "items", ".", "If", "an", "item", "in", "the", "collection", "also", "exists", "in", "the", "new", "$items", "it", "s", "value", "will", "be", "replaced", "by", "the", "value", "in", "the", "new", "$items", ".", "If", "an", "item", "exists", "in", "the", "new", "$items", "but", "not", "in", "the", "collection", "it", "will", "be", "added", "to", "the", "collection", "as", "well", "." ]
train
https://github.com/TeaLabs/collections/blob/5d8885b2799791c0bcbff4e6cbacddb270b4288e/src/Collection.php#L125-L135
stevenliebregt/crispysystem
src/Database/Model.php
Model.showTables
public function showTables() { $sql = 'SHOW TABLES'; $query = $this->pdo->prepare($sql); $query->execute(); return $query->fetchAll(PDO::FETCH_ASSOC); }
php
public function showTables() { $sql = 'SHOW TABLES'; $query = $this->pdo->prepare($sql); $query->execute(); return $query->fetchAll(PDO::FETCH_ASSOC); }
[ "public", "function", "showTables", "(", ")", "{", "$", "sql", "=", "'SHOW TABLES'", ";", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "$", "query", "->", "execute", "(", ")", ";", "return", "$", "query", "->", "fetchAll", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "}" ]
Run a `SHOW TABLES` query and return the results @return array Result of the `SHOW TABLES` query @since 1.1.4
[ "Run", "a", "SHOW", "TABLES", "query", "and", "return", "the", "results" ]
train
https://github.com/stevenliebregt/crispysystem/blob/06547dae100dae1023a93ec903f2d2abacce9aec/src/Database/Model.php#L56-L63
stevenliebregt/crispysystem
src/Database/Model.php
Model.getAll
public function getAll() { $fields = implode(', ', $this->fields); $sql = 'SELECT ' . $fields . ' FROM ' . $this->table; $query = $this->pdo->prepare($sql); $query->execute(); return $query->fetchAll(PDO::FETCH_ASSOC); }
php
public function getAll() { $fields = implode(', ', $this->fields); $sql = 'SELECT ' . $fields . ' FROM ' . $this->table; $query = $this->pdo->prepare($sql); $query->execute(); return $query->fetchAll(PDO::FETCH_ASSOC); }
[ "public", "function", "getAll", "(", ")", "{", "$", "fields", "=", "implode", "(", "', '", ",", "$", "this", "->", "fields", ")", ";", "$", "sql", "=", "'SELECT '", ".", "$", "fields", ".", "' FROM '", ".", "$", "this", "->", "table", ";", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "$", "query", "->", "execute", "(", ")", ";", "return", "$", "query", "->", "fetchAll", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "}" ]
Run a SELECT all query @return array Query result @since 1.1.4
[ "Run", "a", "SELECT", "all", "query" ]
train
https://github.com/stevenliebregt/crispysystem/blob/06547dae100dae1023a93ec903f2d2abacce9aec/src/Database/Model.php#L70-L78
stevenliebregt/crispysystem
src/Database/Model.php
Model.getOneById
public function getOneById($id) { $id = (string)$id; $fields = implode(', ', $this->fields); $sql = 'SELECT ' . $fields . ' FROM ' . $this->table . ' WHERE ' . $this->table . '.id = :id'; $query = $this->pdo->prepare($sql); $query->bindParam(':id', $id); $query->execute(); return $query->fetch(PDO::FETCH_ASSOC); }
php
public function getOneById($id) { $id = (string)$id; $fields = implode(', ', $this->fields); $sql = 'SELECT ' . $fields . ' FROM ' . $this->table . ' WHERE ' . $this->table . '.id = :id'; $query = $this->pdo->prepare($sql); $query->bindParam(':id', $id); $query->execute(); return $query->fetch(PDO::FETCH_ASSOC); }
[ "public", "function", "getOneById", "(", "$", "id", ")", "{", "$", "id", "=", "(", "string", ")", "$", "id", ";", "$", "fields", "=", "implode", "(", "', '", ",", "$", "this", "->", "fields", ")", ";", "$", "sql", "=", "'SELECT '", ".", "$", "fields", ".", "' FROM '", ".", "$", "this", "->", "table", ".", "' WHERE '", ".", "$", "this", "->", "table", ".", "'.id = :id'", ";", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "$", "query", "->", "bindParam", "(", "':id'", ",", "$", "id", ")", ";", "$", "query", "->", "execute", "(", ")", ";", "return", "$", "query", "->", "fetch", "(", "PDO", "::", "FETCH_ASSOC", ")", ";", "}" ]
Run a SELECT query by ID @param int|string $id The id of the record you want to retrieve @return mixed Query result @since 1.1.4
[ "Run", "a", "SELECT", "query", "by", "ID" ]
train
https://github.com/stevenliebregt/crispysystem/blob/06547dae100dae1023a93ec903f2d2abacce9aec/src/Database/Model.php#L86-L97
stevenliebregt/crispysystem
src/Database/Model.php
Model.insert
public function insert(array $values) : int { $fields = $this->fields; array_shift($fields); $sql = 'INSERT INTO `' . $this->table . '` (' . implode(', ', $fields) . ') VALUES (:' . implode(', :', $fields) . ')'; $query = $this->pdo->prepare($sql); foreach ($values as $key => &$value) { $query->bindParam(':' . $fields[$key], $value); } $query->execute(); return $this->pdo->lastInsertId(); }
php
public function insert(array $values) : int { $fields = $this->fields; array_shift($fields); $sql = 'INSERT INTO `' . $this->table . '` (' . implode(', ', $fields) . ') VALUES (:' . implode(', :', $fields) . ')'; $query = $this->pdo->prepare($sql); foreach ($values as $key => &$value) { $query->bindParam(':' . $fields[$key], $value); } $query->execute(); return $this->pdo->lastInsertId(); }
[ "public", "function", "insert", "(", "array", "$", "values", ")", ":", "int", "{", "$", "fields", "=", "$", "this", "->", "fields", ";", "array_shift", "(", "$", "fields", ")", ";", "$", "sql", "=", "'INSERT INTO `'", ".", "$", "this", "->", "table", ".", "'` ('", ".", "implode", "(", "', '", ",", "$", "fields", ")", ".", "') VALUES (:'", ".", "implode", "(", "', :'", ",", "$", "fields", ")", ".", "')'", ";", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "foreach", "(", "$", "values", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "$", "query", "->", "bindParam", "(", "':'", ".", "$", "fields", "[", "$", "key", "]", ",", "$", "value", ")", ";", "}", "$", "query", "->", "execute", "(", ")", ";", "return", "$", "this", "->", "pdo", "->", "lastInsertId", "(", ")", ";", "}" ]
Insert a new record in the database @param array $values Values to insert, except id, since it is expected to be AUTO_INCREMENT @return int Return the last inserted id @since 1.1.4
[ "Insert", "a", "new", "record", "in", "the", "database" ]
train
https://github.com/stevenliebregt/crispysystem/blob/06547dae100dae1023a93ec903f2d2abacce9aec/src/Database/Model.php#L105-L118
stevenliebregt/crispysystem
src/Database/Model.php
Model.updateById
public function updateById($id, array $values) : int { $sql = 'UPDATE `' . $this->table . '` SET '; foreach ($values as $key => $value) { $sql .= $key . '=:' . $key . ', '; } $sql = substr($sql, 0, -2); $sql .= ' WHERE '; // Assign id(s) if (is_array($id)) { $i = 0; foreach ($id as $_id) { if ($i === 0) { $sql .= ' id=:id' . $i; } else { $sql .= ' OR id=:id' . $i; } $i++; } $query = $this->pdo->prepare($sql); for ($j = 0; $j < 0; $j++) { $query->bindParam(':id' . $j, $id[$j]); } } else { $sql .= 'id=:id'; $query = $this->pdo->prepare($sql); $query->bindParam(':id', $id); } // Assign values foreach ($values as $key => &$value) { $query->bindParam(':' . $key, $value); } $query->execute(); return $query->rowCount(); }
php
public function updateById($id, array $values) : int { $sql = 'UPDATE `' . $this->table . '` SET '; foreach ($values as $key => $value) { $sql .= $key . '=:' . $key . ', '; } $sql = substr($sql, 0, -2); $sql .= ' WHERE '; // Assign id(s) if (is_array($id)) { $i = 0; foreach ($id as $_id) { if ($i === 0) { $sql .= ' id=:id' . $i; } else { $sql .= ' OR id=:id' . $i; } $i++; } $query = $this->pdo->prepare($sql); for ($j = 0; $j < 0; $j++) { $query->bindParam(':id' . $j, $id[$j]); } } else { $sql .= 'id=:id'; $query = $this->pdo->prepare($sql); $query->bindParam(':id', $id); } // Assign values foreach ($values as $key => &$value) { $query->bindParam(':' . $key, $value); } $query->execute(); return $query->rowCount(); }
[ "public", "function", "updateById", "(", "$", "id", ",", "array", "$", "values", ")", ":", "int", "{", "$", "sql", "=", "'UPDATE `'", ".", "$", "this", "->", "table", ".", "'` SET '", ";", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "sql", ".=", "$", "key", ".", "'=:'", ".", "$", "key", ".", "', '", ";", "}", "$", "sql", "=", "substr", "(", "$", "sql", ",", "0", ",", "-", "2", ")", ";", "$", "sql", ".=", "' WHERE '", ";", "// Assign id(s)", "if", "(", "is_array", "(", "$", "id", ")", ")", "{", "$", "i", "=", "0", ";", "foreach", "(", "$", "id", "as", "$", "_id", ")", "{", "if", "(", "$", "i", "===", "0", ")", "{", "$", "sql", ".=", "' id=:id'", ".", "$", "i", ";", "}", "else", "{", "$", "sql", ".=", "' OR id=:id'", ".", "$", "i", ";", "}", "$", "i", "++", ";", "}", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "0", ";", "$", "j", "++", ")", "{", "$", "query", "->", "bindParam", "(", "':id'", ".", "$", "j", ",", "$", "id", "[", "$", "j", "]", ")", ";", "}", "}", "else", "{", "$", "sql", ".=", "'id=:id'", ";", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "$", "query", "->", "bindParam", "(", "':id'", ",", "$", "id", ")", ";", "}", "// Assign values", "foreach", "(", "$", "values", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "$", "query", "->", "bindParam", "(", "':'", ".", "$", "key", ",", "$", "value", ")", ";", "}", "$", "query", "->", "execute", "(", ")", ";", "return", "$", "query", "->", "rowCount", "(", ")", ";", "}" ]
Update a record @param string|array $id The id(s) to update @param array $values Values to update, key = field, value = value @return int The amount of rows affected by the query @since 1.1.4
[ "Update", "a", "record" ]
train
https://github.com/stevenliebregt/crispysystem/blob/06547dae100dae1023a93ec903f2d2abacce9aec/src/Database/Model.php#L127-L167
stevenliebregt/crispysystem
src/Database/Model.php
Model.deleteById
public function deleteById($id) : int { $sql = 'DELETE FROM `' . $this->table . '` WHERE '; // Assign ids if (is_array($id)) { $i = 0; foreach ($id as $_id) { if ($i === 0) { $sql .= ' id=:id' . $i; } else { $sql .= ' OR id=:id' . $i; } $i++; } $query = $this->pdo->prepare($sql); for ($j = 0; $j < 0; $j++) { $query->bindParam(':id' . $j, $id[$j]); } } else { $sql .= 'id=:id'; $query = $this->pdo->prepare($sql); $query->bindParam(':id', $id); } $query->execute(); return $query->rowCount(); }
php
public function deleteById($id) : int { $sql = 'DELETE FROM `' . $this->table . '` WHERE '; // Assign ids if (is_array($id)) { $i = 0; foreach ($id as $_id) { if ($i === 0) { $sql .= ' id=:id' . $i; } else { $sql .= ' OR id=:id' . $i; } $i++; } $query = $this->pdo->prepare($sql); for ($j = 0; $j < 0; $j++) { $query->bindParam(':id' . $j, $id[$j]); } } else { $sql .= 'id=:id'; $query = $this->pdo->prepare($sql); $query->bindParam(':id', $id); } $query->execute(); return $query->rowCount(); }
[ "public", "function", "deleteById", "(", "$", "id", ")", ":", "int", "{", "$", "sql", "=", "'DELETE FROM `'", ".", "$", "this", "->", "table", ".", "'` WHERE '", ";", "// Assign ids", "if", "(", "is_array", "(", "$", "id", ")", ")", "{", "$", "i", "=", "0", ";", "foreach", "(", "$", "id", "as", "$", "_id", ")", "{", "if", "(", "$", "i", "===", "0", ")", "{", "$", "sql", ".=", "' id=:id'", ".", "$", "i", ";", "}", "else", "{", "$", "sql", ".=", "' OR id=:id'", ".", "$", "i", ";", "}", "$", "i", "++", ";", "}", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "0", ";", "$", "j", "++", ")", "{", "$", "query", "->", "bindParam", "(", "':id'", ".", "$", "j", ",", "$", "id", "[", "$", "j", "]", ")", ";", "}", "}", "else", "{", "$", "sql", ".=", "'id=:id'", ";", "$", "query", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "sql", ")", ";", "$", "query", "->", "bindParam", "(", "':id'", ",", "$", "id", ")", ";", "}", "$", "query", "->", "execute", "(", ")", ";", "return", "$", "query", "->", "rowCount", "(", ")", ";", "}" ]
Run a DELETE query @param string|array $id Id(s) to delete @return int Return affected rows @since 1.1.4
[ "Run", "a", "DELETE", "query" ]
train
https://github.com/stevenliebregt/crispysystem/blob/06547dae100dae1023a93ec903f2d2abacce9aec/src/Database/Model.php#L175-L203
Wedeto/FileFormats
src/XML/Reader.php
Reader.readFile
public function readFile(string $file_name) { $reader = new XMLReader; $reader->open($file_name); $data = $this->toArray($reader); $reader->close(); return $data; }
php
public function readFile(string $file_name) { $reader = new XMLReader; $reader->open($file_name); $data = $this->toArray($reader); $reader->close(); return $data; }
[ "public", "function", "readFile", "(", "string", "$", "file_name", ")", "{", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "open", "(", "$", "file_name", ")", ";", "$", "data", "=", "$", "this", "->", "toArray", "(", "$", "reader", ")", ";", "$", "reader", "->", "close", "(", ")", ";", "return", "$", "data", ";", "}" ]
Read a XML file into an array @param string $filename The file to read @return array The array representation of the XML Data
[ "Read", "a", "XML", "file", "into", "an", "array" ]
train
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/XML/Reader.php#L42-L51
Wedeto/FileFormats
src/XML/Reader.php
Reader.readString
public function readString(string $data) { $reader = new XMLReader; $reader->XML($data); $contents = $this->toArray($reader); $reader->close(); return $contents; }
php
public function readString(string $data) { $reader = new XMLReader; $reader->XML($data); $contents = $this->toArray($reader); $reader->close(); return $contents; }
[ "public", "function", "readString", "(", "string", "$", "data", ")", "{", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "XML", "(", "$", "data", ")", ";", "$", "contents", "=", "$", "this", "->", "toArray", "(", "$", "reader", ")", ";", "$", "reader", "->", "close", "(", ")", ";", "return", "$", "contents", ";", "}" ]
Read XML Data from a string @param string $data The data to read @return array the array representation of the XML data
[ "Read", "XML", "Data", "from", "a", "string" ]
train
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/XML/Reader.php#L59-L68
Wedeto/FileFormats
src/XML/Reader.php
Reader.parseTree
public function parseTree(XMLReader $reader) { libxml_use_internal_errors(true); $root = new XMLNode; $cur = null; $read_anything = false; while ($reader->read()) { $read_anything = true; if ($reader->nodeType === XMLReader::ELEMENT) { if ($cur === null) { $root->name = $reader->name; $cur = $root; } else { $node = new XMLNode; $node->name = $reader->name; $node->parent = $cur; $cur->children[] = $node; $cur = $node; } if ($reader->hasAttributes) { while ($reader->moveToNextAttribute()) { $node = new XMLNode; $node->name = $reader->name; $node->content = $reader->value; $cur->attributes[] = $node; } } } else if ($reader->nodeType === XMLReader::END_ELEMENT) { $cur = $cur->parent; } else if ($reader->nodeType === XMLReader::TEXT) { $cur->content = $reader->value; } } try { foreach (libxml_get_errors() as $error) throw new XMLException($error); } finally { libxml_clear_errors(); } return $root; }
php
public function parseTree(XMLReader $reader) { libxml_use_internal_errors(true); $root = new XMLNode; $cur = null; $read_anything = false; while ($reader->read()) { $read_anything = true; if ($reader->nodeType === XMLReader::ELEMENT) { if ($cur === null) { $root->name = $reader->name; $cur = $root; } else { $node = new XMLNode; $node->name = $reader->name; $node->parent = $cur; $cur->children[] = $node; $cur = $node; } if ($reader->hasAttributes) { while ($reader->moveToNextAttribute()) { $node = new XMLNode; $node->name = $reader->name; $node->content = $reader->value; $cur->attributes[] = $node; } } } else if ($reader->nodeType === XMLReader::END_ELEMENT) { $cur = $cur->parent; } else if ($reader->nodeType === XMLReader::TEXT) { $cur->content = $reader->value; } } try { foreach (libxml_get_errors() as $error) throw new XMLException($error); } finally { libxml_clear_errors(); } return $root; }
[ "public", "function", "parseTree", "(", "XMLReader", "$", "reader", ")", "{", "libxml_use_internal_errors", "(", "true", ")", ";", "$", "root", "=", "new", "XMLNode", ";", "$", "cur", "=", "null", ";", "$", "read_anything", "=", "false", ";", "while", "(", "$", "reader", "->", "read", "(", ")", ")", "{", "$", "read_anything", "=", "true", ";", "if", "(", "$", "reader", "->", "nodeType", "===", "XMLReader", "::", "ELEMENT", ")", "{", "if", "(", "$", "cur", "===", "null", ")", "{", "$", "root", "->", "name", "=", "$", "reader", "->", "name", ";", "$", "cur", "=", "$", "root", ";", "}", "else", "{", "$", "node", "=", "new", "XMLNode", ";", "$", "node", "->", "name", "=", "$", "reader", "->", "name", ";", "$", "node", "->", "parent", "=", "$", "cur", ";", "$", "cur", "->", "children", "[", "]", "=", "$", "node", ";", "$", "cur", "=", "$", "node", ";", "}", "if", "(", "$", "reader", "->", "hasAttributes", ")", "{", "while", "(", "$", "reader", "->", "moveToNextAttribute", "(", ")", ")", "{", "$", "node", "=", "new", "XMLNode", ";", "$", "node", "->", "name", "=", "$", "reader", "->", "name", ";", "$", "node", "->", "content", "=", "$", "reader", "->", "value", ";", "$", "cur", "->", "attributes", "[", "]", "=", "$", "node", ";", "}", "}", "}", "else", "if", "(", "$", "reader", "->", "nodeType", "===", "XMLReader", "::", "END_ELEMENT", ")", "{", "$", "cur", "=", "$", "cur", "->", "parent", ";", "}", "else", "if", "(", "$", "reader", "->", "nodeType", "===", "XMLReader", "::", "TEXT", ")", "{", "$", "cur", "->", "content", "=", "$", "reader", "->", "value", ";", "}", "}", "try", "{", "foreach", "(", "libxml_get_errors", "(", ")", "as", "$", "error", ")", "throw", "new", "XMLException", "(", "$", "error", ")", ";", "}", "finally", "{", "libxml_clear_errors", "(", ")", ";", "}", "return", "$", "root", ";", "}" ]
Parse the XML into an array. This will add all nodes and attributes to a tree of XML nodes. This is only basic XML flattening, for full-blown XML support be sure to use a more fully featured solution like SimpleXML @param XMLReader $reader The reader reading the XML @return XMLNode The root node
[ "Parse", "the", "XML", "into", "an", "array", ".", "This", "will", "add", "all", "nodes", "and", "attributes", "to", "a", "tree", "of", "XML", "nodes", ".", "This", "is", "only", "basic", "XML", "flattening", "for", "full", "-", "blown", "XML", "support", "be", "sure", "to", "use", "a", "more", "fully", "featured", "solution", "like", "SimpleXML" ]
train
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/XML/Reader.php#L93-L152
ciims/ciims-modules-api
ApiModule.php
ApiModule.init
public function init() { // Autoload the models and components directory $this->setImport(array( 'api.models.*', 'api.components.*', )); // Disable layout rendering $this->layout = false; // Disable logging for the API foreach(Yii::app()->log->routes as $k=>$v) { if (get_class($v) == 'CWebLogRoute' || get_class($v) == "CProfileLogRoute") Yii::app()->log->routes[$k]->enabled = false; } // Set default components and routes Yii::app()->setComponents(array( 'errorHandler' => array( 'errorAction' => 'api/default/error', ), 'messages' => array( 'class' => 'cii.components.CiiPHPMessageSource', 'basePath' => Yii::getPathOfAlias('application.modules.api') ) )); }
php
public function init() { // Autoload the models and components directory $this->setImport(array( 'api.models.*', 'api.components.*', )); // Disable layout rendering $this->layout = false; // Disable logging for the API foreach(Yii::app()->log->routes as $k=>$v) { if (get_class($v) == 'CWebLogRoute' || get_class($v) == "CProfileLogRoute") Yii::app()->log->routes[$k]->enabled = false; } // Set default components and routes Yii::app()->setComponents(array( 'errorHandler' => array( 'errorAction' => 'api/default/error', ), 'messages' => array( 'class' => 'cii.components.CiiPHPMessageSource', 'basePath' => Yii::getPathOfAlias('application.modules.api') ) )); }
[ "public", "function", "init", "(", ")", "{", "// Autoload the models and components directory \r", "$", "this", "->", "setImport", "(", "array", "(", "'api.models.*'", ",", "'api.components.*'", ",", ")", ")", ";", "// Disable layout rendering\r", "$", "this", "->", "layout", "=", "false", ";", "// Disable logging for the API\r", "foreach", "(", "Yii", "::", "app", "(", ")", "->", "log", "->", "routes", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "get_class", "(", "$", "v", ")", "==", "'CWebLogRoute'", "||", "get_class", "(", "$", "v", ")", "==", "\"CProfileLogRoute\"", ")", "Yii", "::", "app", "(", ")", "->", "log", "->", "routes", "[", "$", "k", "]", "->", "enabled", "=", "false", ";", "}", "// Set default components and routes\r", "Yii", "::", "app", "(", ")", "->", "setComponents", "(", "array", "(", "'errorHandler'", "=>", "array", "(", "'errorAction'", "=>", "'api/default/error'", ",", ")", ",", "'messages'", "=>", "array", "(", "'class'", "=>", "'cii.components.CiiPHPMessageSource'", ",", "'basePath'", "=>", "Yii", "::", "getPathOfAlias", "(", "'application.modules.api'", ")", ")", ")", ")", ";", "}" ]
Yii Init method Implements basic configuration for module
[ "Yii", "Init", "method", "Implements", "basic", "configuration", "for", "module" ]
train
https://github.com/ciims/ciims-modules-api/blob/4351855328da0b112ac27bde7e7e07e212be8689/ApiModule.php#L24-L52
MatiasNAmendola/slimpower-auth-core
src/Abstracts/AuthenticationMiddleware.php
AuthenticationMiddleware.call
public function call() { /* If rules say we should not authenticate call next and return. */ if (false === $this->shouldAuthenticate()) { $this->next->call(); return; } $this->checkSecure(); $freePass = $this->hasFreePass(); /* If userdata cannot be found return with 401 Unauthorized. */ if ((false === $this->data = $this->fetchData()) && !$freePass) { $this->callError(); return; } if (false === $this->data && $freePass) { $this->next->call(); return; } /* Check if user authenticates. */ $authenticator = $this->options["authenticator"]; if (false === $authenticator($this->data)) { $this->error = $authenticator->getError(); $this->callError(); return; } $this->app->userData = $authenticator->getData(); if (!$this->customValidation()) { $this->callError(); return; } /* If callback returns false return with 401 Unauthorized. */ if (is_callable($this->options["callback"])) { $params = $this->getParams(); if (false === $this->options["callback"]($params)) { $this->error = new Error(); $this->error->setDescription("Callback returned false"); $this->callError(); return; } } /* Everything ok, call next middleware. */ $this->next->call(); }
php
public function call() { /* If rules say we should not authenticate call next and return. */ if (false === $this->shouldAuthenticate()) { $this->next->call(); return; } $this->checkSecure(); $freePass = $this->hasFreePass(); /* If userdata cannot be found return with 401 Unauthorized. */ if ((false === $this->data = $this->fetchData()) && !$freePass) { $this->callError(); return; } if (false === $this->data && $freePass) { $this->next->call(); return; } /* Check if user authenticates. */ $authenticator = $this->options["authenticator"]; if (false === $authenticator($this->data)) { $this->error = $authenticator->getError(); $this->callError(); return; } $this->app->userData = $authenticator->getData(); if (!$this->customValidation()) { $this->callError(); return; } /* If callback returns false return with 401 Unauthorized. */ if (is_callable($this->options["callback"])) { $params = $this->getParams(); if (false === $this->options["callback"]($params)) { $this->error = new Error(); $this->error->setDescription("Callback returned false"); $this->callError(); return; } } /* Everything ok, call next middleware. */ $this->next->call(); }
[ "public", "function", "call", "(", ")", "{", "/* If rules say we should not authenticate call next and return. */", "if", "(", "false", "===", "$", "this", "->", "shouldAuthenticate", "(", ")", ")", "{", "$", "this", "->", "next", "->", "call", "(", ")", ";", "return", ";", "}", "$", "this", "->", "checkSecure", "(", ")", ";", "$", "freePass", "=", "$", "this", "->", "hasFreePass", "(", ")", ";", "/* If userdata cannot be found return with 401 Unauthorized. */", "if", "(", "(", "false", "===", "$", "this", "->", "data", "=", "$", "this", "->", "fetchData", "(", ")", ")", "&&", "!", "$", "freePass", ")", "{", "$", "this", "->", "callError", "(", ")", ";", "return", ";", "}", "if", "(", "false", "===", "$", "this", "->", "data", "&&", "$", "freePass", ")", "{", "$", "this", "->", "next", "->", "call", "(", ")", ";", "return", ";", "}", "/* Check if user authenticates. */", "$", "authenticator", "=", "$", "this", "->", "options", "[", "\"authenticator\"", "]", ";", "if", "(", "false", "===", "$", "authenticator", "(", "$", "this", "->", "data", ")", ")", "{", "$", "this", "->", "error", "=", "$", "authenticator", "->", "getError", "(", ")", ";", "$", "this", "->", "callError", "(", ")", ";", "return", ";", "}", "$", "this", "->", "app", "->", "userData", "=", "$", "authenticator", "->", "getData", "(", ")", ";", "if", "(", "!", "$", "this", "->", "customValidation", "(", ")", ")", "{", "$", "this", "->", "callError", "(", ")", ";", "return", ";", "}", "/* If callback returns false return with 401 Unauthorized. */", "if", "(", "is_callable", "(", "$", "this", "->", "options", "[", "\"callback\"", "]", ")", ")", "{", "$", "params", "=", "$", "this", "->", "getParams", "(", ")", ";", "if", "(", "false", "===", "$", "this", "->", "options", "[", "\"callback\"", "]", "(", "$", "params", ")", ")", "{", "$", "this", "->", "error", "=", "new", "Error", "(", ")", ";", "$", "this", "->", "error", "->", "setDescription", "(", "\"Callback returned false\"", ")", ";", "$", "this", "->", "callError", "(", ")", ";", "return", ";", "}", "}", "/* Everything ok, call next middleware. */", "$", "this", "->", "next", "->", "call", "(", ")", ";", "}" ]
Call the middleware
[ "Call", "the", "middleware" ]
train
https://github.com/MatiasNAmendola/slimpower-auth-core/blob/550ab85d871de8451cb242eaa17f4041ff320b7c/src/Abstracts/AuthenticationMiddleware.php#L132-L183
MatiasNAmendola/slimpower-auth-core
src/Abstracts/AuthenticationMiddleware.php
AuthenticationMiddleware.checkSecure
private function checkSecure() { $environment = $this->app->environment; $scheme = $environment["slim.url_scheme"]; if ("https" !== $scheme && true === $this->options["secure"]) { if (!in_array($environment["SERVER_NAME"], $this->options["relaxed"])) { $message = sprintf( "Insecure use of middleware over %s denied by configuration.", strtoupper($scheme) ); throw new \RuntimeException($message); } } }
php
private function checkSecure() { $environment = $this->app->environment; $scheme = $environment["slim.url_scheme"]; if ("https" !== $scheme && true === $this->options["secure"]) { if (!in_array($environment["SERVER_NAME"], $this->options["relaxed"])) { $message = sprintf( "Insecure use of middleware over %s denied by configuration.", strtoupper($scheme) ); throw new \RuntimeException($message); } } }
[ "private", "function", "checkSecure", "(", ")", "{", "$", "environment", "=", "$", "this", "->", "app", "->", "environment", ";", "$", "scheme", "=", "$", "environment", "[", "\"slim.url_scheme\"", "]", ";", "if", "(", "\"https\"", "!==", "$", "scheme", "&&", "true", "===", "$", "this", "->", "options", "[", "\"secure\"", "]", ")", "{", "if", "(", "!", "in_array", "(", "$", "environment", "[", "\"SERVER_NAME\"", "]", ",", "$", "this", "->", "options", "[", "\"relaxed\"", "]", ")", ")", "{", "$", "message", "=", "sprintf", "(", "\"Insecure use of middleware over %s denied by configuration.\"", ",", "strtoupper", "(", "$", "scheme", ")", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "$", "message", ")", ";", "}", "}", "}" ]
HTTP allowed only if secure is false or server is in relaxed array. @throws \RuntimeException
[ "HTTP", "allowed", "only", "if", "secure", "is", "false", "or", "server", "is", "in", "relaxed", "array", "." ]
train
https://github.com/MatiasNAmendola/slimpower-auth-core/blob/550ab85d871de8451cb242eaa17f4041ff320b7c/src/Abstracts/AuthenticationMiddleware.php#L193-L205
MatiasNAmendola/slimpower-auth-core
src/Abstracts/AuthenticationMiddleware.php
AuthenticationMiddleware.hydrate
private function hydrate($data = array()) { foreach ($data as $key => $value) { $method = "set" . ucfirst($key); if (method_exists($this, $method)) { call_user_func(array($this, $method), $value); } } }
php
private function hydrate($data = array()) { foreach ($data as $key => $value) { $method = "set" . ucfirst($key); if (method_exists($this, $method)) { call_user_func(array($this, $method), $value); } } }
[ "private", "function", "hydrate", "(", "$", "data", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "method", "=", "\"set\"", ".", "ucfirst", "(", "$", "key", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", ")", ")", "{", "call_user_func", "(", "array", "(", "$", "this", ",", "$", "method", ")", ",", "$", "value", ")", ";", "}", "}", "}" ]
Hydate options from given array @param array $data Array of options. @return self
[ "Hydate", "options", "from", "given", "array" ]
train
https://github.com/MatiasNAmendola/slimpower-auth-core/blob/550ab85d871de8451cb242eaa17f4041ff320b7c/src/Abstracts/AuthenticationMiddleware.php#L230-L237
MatiasNAmendola/slimpower-auth-core
src/Abstracts/AuthenticationMiddleware.php
AuthenticationMiddleware.callError
public function callError() { if (!($this->error instanceof Error)) { $this->error = new Error(); } $status = $this->error->getStatus(); $this->app->response->status($status); if (is_callable($this->options["error"])) { $this->options["error"]($this->error); } }
php
public function callError() { if (!($this->error instanceof Error)) { $this->error = new Error(); } $status = $this->error->getStatus(); $this->app->response->status($status); if (is_callable($this->options["error"])) { $this->options["error"]($this->error); } }
[ "public", "function", "callError", "(", ")", "{", "if", "(", "!", "(", "$", "this", "->", "error", "instanceof", "Error", ")", ")", "{", "$", "this", "->", "error", "=", "new", "Error", "(", ")", ";", "}", "$", "status", "=", "$", "this", "->", "error", "->", "getStatus", "(", ")", ";", "$", "this", "->", "app", "->", "response", "->", "status", "(", "$", "status", ")", ";", "if", "(", "is_callable", "(", "$", "this", "->", "options", "[", "\"error\"", "]", ")", ")", "{", "$", "this", "->", "options", "[", "\"error\"", "]", "(", "$", "this", "->", "error", ")", ";", "}", "}" ]
Call the error handler if it exists @return void
[ "Call", "the", "error", "handler", "if", "it", "exists" ]
train
https://github.com/MatiasNAmendola/slimpower-auth-core/blob/550ab85d871de8451cb242eaa17f4041ff320b7c/src/Abstracts/AuthenticationMiddleware.php#L259-L270
MatiasNAmendola/slimpower-auth-core
src/Abstracts/AuthenticationMiddleware.php
AuthenticationMiddleware.setRules
public function setRules(array $rules) { /* Clear the stack */ unset($this->rules); $this->rules = new \SplStack; /* Add the rules */ foreach ($rules as $callable) { $this->addRule($callable); } return $this; }
php
public function setRules(array $rules) { /* Clear the stack */ unset($this->rules); $this->rules = new \SplStack; /* Add the rules */ foreach ($rules as $callable) { $this->addRule($callable); } return $this; }
[ "public", "function", "setRules", "(", "array", "$", "rules", ")", "{", "/* Clear the stack */", "unset", "(", "$", "this", "->", "rules", ")", ";", "$", "this", "->", "rules", "=", "new", "\\", "SplStack", ";", "/* Add the rules */", "foreach", "(", "$", "rules", "as", "$", "callable", ")", "{", "$", "this", "->", "addRule", "(", "$", "callable", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set all rules in the stack @return self
[ "Set", "all", "rules", "in", "the", "stack" ]
train
https://github.com/MatiasNAmendola/slimpower-auth-core/blob/550ab85d871de8451cb242eaa17f4041ff320b7c/src/Abstracts/AuthenticationMiddleware.php#L413-L424
SandratraRM/mora-core
src/cli/Mora_cli.php
Mora_cli.execController
private static function execController($controller,$action,$args){ $controller = new $controller(); $controller->doAction($action,$args); }
php
private static function execController($controller,$action,$args){ $controller = new $controller(); $controller->doAction($action,$args); }
[ "private", "static", "function", "execController", "(", "$", "controller", ",", "$", "action", ",", "$", "args", ")", "{", "$", "controller", "=", "new", "$", "controller", "(", ")", ";", "$", "controller", "->", "doAction", "(", "$", "action", ",", "$", "args", ")", ";", "}" ]
execController @param Controller $controller @param string $action @param array $ags @return void
[ "execController" ]
train
https://github.com/SandratraRM/mora-core/blob/9cd8e16e4b619798a51dc2ac66ddd8d22caf7baa/src/cli/Mora_cli.php#L60-L63
theopera/framework
src/Component/Http/ParameterBag.php
ParameterBag.add
public function add(string $key, $value, bool $override = false) { if (!$override && $this->exists($key)) { return; } $this->parameters[$key] = $value; }
php
public function add(string $key, $value, bool $override = false) { if (!$override && $this->exists($key)) { return; } $this->parameters[$key] = $value; }
[ "public", "function", "add", "(", "string", "$", "key", ",", "$", "value", ",", "bool", "$", "override", "=", "false", ")", "{", "if", "(", "!", "$", "override", "&&", "$", "this", "->", "exists", "(", "$", "key", ")", ")", "{", "return", ";", "}", "$", "this", "->", "parameters", "[", "$", "key", "]", "=", "$", "value", ";", "}" ]
Add a parameter to the bag @param string $key @param mixed $value
[ "Add", "a", "parameter", "to", "the", "bag" ]
train
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/Http/ParameterBag.php#L57-L64
theopera/framework
src/Component/Http/ParameterBag.php
ParameterBag.get
public function get(string $key, $default = null) { if ($this->exists($key)) { return $this->parameters[$key]; } return $default; }
php
public function get(string $key, $default = null) { if ($this->exists($key)) { return $this->parameters[$key]; } return $default; }
[ "public", "function", "get", "(", "string", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "this", "->", "exists", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "parameters", "[", "$", "key", "]", ";", "}", "return", "$", "default", ";", "}" ]
Get the value of a parameter of it does not exits the default value will be returned @param string $key @param mixed $default @return mixed
[ "Get", "the", "value", "of", "a", "parameter", "of", "it", "does", "not", "exits", "the", "default", "value", "will", "be", "returned" ]
train
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/Http/ParameterBag.php#L75-L82
theopera/framework
src/Component/Http/ParameterBag.php
ParameterBag.getString
public function getString(string $key, string $default = null) : string { return (string) $this->get($key, $default); }
php
public function getString(string $key, string $default = null) : string { return (string) $this->get($key, $default); }
[ "public", "function", "getString", "(", "string", "$", "key", ",", "string", "$", "default", "=", "null", ")", ":", "string", "{", "return", "(", "string", ")", "$", "this", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "}" ]
Get the value of a parameter of it does not exits the default value will be returned @param string $key @param string $default @return string
[ "Get", "the", "value", "of", "a", "parameter", "of", "it", "does", "not", "exits", "the", "default", "value", "will", "be", "returned" ]
train
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/Http/ParameterBag.php#L93-L96
theopera/framework
src/Component/Http/ParameterBag.php
ParameterBag.getBool
public function getBool(string $key, bool $default = null) : bool { if ($this->getString($key) === 'true') { return true; } if ($this->getString($key) === 'false') { return false; } return (bool) $this->get($key, $default); }
php
public function getBool(string $key, bool $default = null) : bool { if ($this->getString($key) === 'true') { return true; } if ($this->getString($key) === 'false') { return false; } return (bool) $this->get($key, $default); }
[ "public", "function", "getBool", "(", "string", "$", "key", ",", "bool", "$", "default", "=", "null", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "getString", "(", "$", "key", ")", "===", "'true'", ")", "{", "return", "true", ";", "}", "if", "(", "$", "this", "->", "getString", "(", "$", "key", ")", "===", "'false'", ")", "{", "return", "false", ";", "}", "return", "(", "bool", ")", "$", "this", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "}" ]
Get the value of a parameter of it does not exits the default value will be returned @param string $key @param bool|null $default @return bool
[ "Get", "the", "value", "of", "a", "parameter", "of", "it", "does", "not", "exits", "the", "default", "value", "will", "be", "returned" ]
train
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/Http/ParameterBag.php#L106-L117
theopera/framework
src/Component/Http/ParameterBag.php
ParameterBag.getInt
public function getInt(string $key, int $default = null) : int { return (int) $this->get($key, $default); }
php
public function getInt(string $key, int $default = null) : int { return (int) $this->get($key, $default); }
[ "public", "function", "getInt", "(", "string", "$", "key", ",", "int", "$", "default", "=", "null", ")", ":", "int", "{", "return", "(", "int", ")", "$", "this", "->", "get", "(", "$", "key", ",", "$", "default", ")", ";", "}" ]
Get the value of a parameter of it does not exits the default value will be returned @param string $key @param int|null $default @return int
[ "Get", "the", "value", "of", "a", "parameter", "of", "it", "does", "not", "exits", "the", "default", "value", "will", "be", "returned" ]
train
https://github.com/theopera/framework/blob/fa6165d3891a310faa580c81dee49a63c150c711/src/Component/Http/ParameterBag.php#L127-L130
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Upload/Driver/Upyun.php
Upyun.save
public function save($file, $replace = true) { $header['Content-Type'] = $file['type']; $header['Content-MD5'] = $file['md5']; $header['Mkdir'] = 'true'; $resource = fopen($file['tmp_name'], 'r'); $save = $this->rootPath . $file['savepath'] . $file['savename']; $data = $this->request($save, 'PUT', $header, $resource); return false === $data ? false : true; }
php
public function save($file, $replace = true) { $header['Content-Type'] = $file['type']; $header['Content-MD5'] = $file['md5']; $header['Mkdir'] = 'true'; $resource = fopen($file['tmp_name'], 'r'); $save = $this->rootPath . $file['savepath'] . $file['savename']; $data = $this->request($save, 'PUT', $header, $resource); return false === $data ? false : true; }
[ "public", "function", "save", "(", "$", "file", ",", "$", "replace", "=", "true", ")", "{", "$", "header", "[", "'Content-Type'", "]", "=", "$", "file", "[", "'type'", "]", ";", "$", "header", "[", "'Content-MD5'", "]", "=", "$", "file", "[", "'md5'", "]", ";", "$", "header", "[", "'Mkdir'", "]", "=", "'true'", ";", "$", "resource", "=", "fopen", "(", "$", "file", "[", "'tmp_name'", "]", ",", "'r'", ")", ";", "$", "save", "=", "$", "this", "->", "rootPath", ".", "$", "file", "[", "'savepath'", "]", ".", "$", "file", "[", "'savename'", "]", ";", "$", "data", "=", "$", "this", "->", "request", "(", "$", "save", ",", "'PUT'", ",", "$", "header", ",", "$", "resource", ")", ";", "return", "false", "===", "$", "data", "?", "false", ":", "true", ";", "}" ]
保存指定文件 @param array $file 保存的文件信息 @param boolean $replace 同名文件是否覆盖 @return boolean 保存状态,true-成功,false-失败
[ "保存指定文件" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Upload/Driver/Upyun.php#L79-L88