repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
datasift/datasift-php
lib/DataSift/User.php
DataSift_User.get
public function get($endpoint, $params = array(), $headers = array()) { $res = call_user_func( array($this->_api_client, 'call'), $this, $endpoint, 'get', array(), $headers, $this->getUserAgent(), $params ); $this->_rate_limit = $res['rate_limit']; $this->_rate_limit_remaining = $res['rate_limit_remaining']; return $this->handleResponse($res); }
php
public function get($endpoint, $params = array(), $headers = array()) { $res = call_user_func( array($this->_api_client, 'call'), $this, $endpoint, 'get', array(), $headers, $this->getUserAgent(), $params ); $this->_rate_limit = $res['rate_limit']; $this->_rate_limit_remaining = $res['rate_limit_remaining']; return $this->handleResponse($res); }
[ "public", "function", "get", "(", "$", "endpoint", ",", "$", "params", "=", "array", "(", ")", ",", "$", "headers", "=", "array", "(", ")", ")", "{", "$", "res", "=", "call_user_func", "(", "array", "(", "$", "this", "->", "_api_client", ",", "'call'", ")", ",", "$", "this", ",", "$", "endpoint", ",", "'get'", ",", "array", "(", ")", ",", "$", "headers", ",", "$", "this", "->", "getUserAgent", "(", ")", ",", "$", "params", ")", ";", "$", "this", "->", "_rate_limit", "=", "$", "res", "[", "'rate_limit'", "]", ";", "$", "this", "->", "_rate_limit_remaining", "=", "$", "res", "[", "'rate_limit_remaining'", "]", ";", "return", "$", "this", "->", "handleResponse", "(", "$", "res", ")", ";", "}" ]
Make a GET call to a DataSift API endpoint. @param string $endpoint The endpoint of the API call. @param array $params The parameters to be passed along with the request. @return array The response from the server. @throws DataSift_Exception_APIError @throws DataSift_Exception_RateLimitExceeded
[ "Make", "a", "GET", "call", "to", "a", "DataSift", "API", "endpoint", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/User.php#L611-L628
EcomDev/phpspec-magento-di-adapter
src/GeneratorWrapper.php
GeneratorWrapper.supports
public function supports($className) { return (strpos($className, ucfirst($this->classSuffix)) === strlen($className) - strlen($this->classSuffix)); }
php
public function supports($className) { return (strpos($className, ucfirst($this->classSuffix)) === strlen($className) - strlen($this->classSuffix)); }
[ "public", "function", "supports", "(", "$", "className", ")", "{", "return", "(", "strpos", "(", "$", "className", ",", "ucfirst", "(", "$", "this", "->", "classSuffix", ")", ")", "===", "strlen", "(", "$", "className", ")", "-", "strlen", "(", "$", "this", "->", "classSuffix", ")", ")", ";", "}" ]
Returns true if class has been generated @param string $className @return bool
[ "Returns", "true", "if", "class", "has", "been", "generated" ]
train
https://github.com/EcomDev/phpspec-magento-di-adapter/blob/b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37/src/GeneratorWrapper.php#L45-L48
EcomDev/phpspec-magento-di-adapter
src/GeneratorWrapper.php
GeneratorWrapper.createGenerator
public function createGenerator($className) { $factory = $this->generatorFactory; $sourceClass = rtrim(substr($className, 0, strpos($className, ucfirst($this->classSuffix))), '\\'); $entityGenerator = $factory($sourceClass, $className); return $entityGenerator; }
php
public function createGenerator($className) { $factory = $this->generatorFactory; $sourceClass = rtrim(substr($className, 0, strpos($className, ucfirst($this->classSuffix))), '\\'); $entityGenerator = $factory($sourceClass, $className); return $entityGenerator; }
[ "public", "function", "createGenerator", "(", "$", "className", ")", "{", "$", "factory", "=", "$", "this", "->", "generatorFactory", ";", "$", "sourceClass", "=", "rtrim", "(", "substr", "(", "$", "className", ",", "0", ",", "strpos", "(", "$", "className", ",", "ucfirst", "(", "$", "this", "->", "classSuffix", ")", ")", ")", ",", "'\\\\'", ")", ";", "$", "entityGenerator", "=", "$", "factory", "(", "$", "sourceClass", ",", "$", "className", ")", ";", "return", "$", "entityGenerator", ";", "}" ]
Creates a generator @param string $className @return EntityAbstract
[ "Creates", "a", "generator" ]
train
https://github.com/EcomDev/phpspec-magento-di-adapter/blob/b39f6f0afbb837dbf0eb4c71e6cdb318b8c9de37/src/GeneratorWrapper.php#L69-L75
verschoof/bunq-api
src/Resource/MonetaryAccountResource.php
MonetaryAccountResource.listMonetaryAccounts
public function listMonetaryAccounts($userId) { $monetaryAccounts = $this->client->get($this->getResourceEndpoint($userId)); return $monetaryAccounts; }
php
public function listMonetaryAccounts($userId) { $monetaryAccounts = $this->client->get($this->getResourceEndpoint($userId)); return $monetaryAccounts; }
[ "public", "function", "listMonetaryAccounts", "(", "$", "userId", ")", "{", "$", "monetaryAccounts", "=", "$", "this", "->", "client", "->", "get", "(", "$", "this", "->", "getResourceEndpoint", "(", "$", "userId", ")", ")", ";", "return", "$", "monetaryAccounts", ";", "}" ]
Lists all the Monetary accounts for the current user. @param integer $userId @return array
[ "Lists", "all", "the", "Monetary", "accounts", "for", "the", "current", "user", "." ]
train
https://github.com/verschoof/bunq-api/blob/df9aa19f384275f4f0deb26de0cb5e5f8b45ffcd/src/Resource/MonetaryAccountResource.php#L29-L34
verschoof/bunq-api
src/Resource/MonetaryAccountResource.php
MonetaryAccountResource.getMonetaryAccount
public function getMonetaryAccount($userId, $id) { $monetaryAccount = $this->client->get($this->getResourceEndpoint($userId) . '/' . (int)$id); return $monetaryAccount['Response'][0]['MonetaryAccountBank']; }
php
public function getMonetaryAccount($userId, $id) { $monetaryAccount = $this->client->get($this->getResourceEndpoint($userId) . '/' . (int)$id); return $monetaryAccount['Response'][0]['MonetaryAccountBank']; }
[ "public", "function", "getMonetaryAccount", "(", "$", "userId", ",", "$", "id", ")", "{", "$", "monetaryAccount", "=", "$", "this", "->", "client", "->", "get", "(", "$", "this", "->", "getResourceEndpoint", "(", "$", "userId", ")", ".", "'/'", ".", "(", "int", ")", "$", "id", ")", ";", "return", "$", "monetaryAccount", "[", "'Response'", "]", "[", "0", "]", "[", "'MonetaryAccountBank'", "]", ";", "}" ]
Gets a Monetary Account by its identifier. @param integer $userId @param integer $id @return array
[ "Gets", "a", "Monetary", "Account", "by", "its", "identifier", "." ]
train
https://github.com/verschoof/bunq-api/blob/df9aa19f384275f4f0deb26de0cb5e5f8b45ffcd/src/Resource/MonetaryAccountResource.php#L44-L49
yosmanyga/resource
src/Yosmanyga/Resource/Cacher/Checker/DirectoryVersionChecker.php
DirectoryVersionChecker.add
public function add(Resource $resource) { $this->storer->add( $this->calculateDirVersion($resource), $resource ); }
php
public function add(Resource $resource) { $this->storer->add( $this->calculateDirVersion($resource), $resource ); }
[ "public", "function", "add", "(", "Resource", "$", "resource", ")", "{", "$", "this", "->", "storer", "->", "add", "(", "$", "this", "->", "calculateDirVersion", "(", "$", "resource", ")", ",", "$", "resource", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Cacher/Checker/DirectoryVersionChecker.php#L46-L52
BugBuster1701/banner
classes/ModuleBannerLog.php
ModuleBannerLog.writeLog
public static function writeLog($method,$line,$value) { if ($method == '## START ##') { if (!isset($GLOBALS['banner']['debug']['first'])) { if ((bool)$GLOBALS['banner']['debug']['tag'] || (bool)$GLOBALS['banner']['debug']['helper'] || (bool)$GLOBALS['banner']['debug']['image'] || (bool)$GLOBALS['banner']['debug']['referrer'] ) { $arrUniqid = trimsplit('.', uniqid('c0n7a0',true) ); $GLOBALS['banner']['debug']['first'] = $arrUniqid[1]; log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$method,$line,$value),'banner_debug.log'); return ; } return ; } else { return ; } } $arrNamespace = trimsplit('::', $method); $arrClass = trimsplit('\\', $arrNamespace[0]); $vclass = $arrClass[2]; // class that will write the log if (is_array($value)) { $value = print_r($value,true); } switch ($vclass) { case "ModuleBannerTag": if ($GLOBALS['banner']['debug']['tag']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; case "BannerHelper": if ($GLOBALS['banner']['debug']['helper']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; case "BannerImage": if ($GLOBALS['banner']['debug']['image']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; case "BannerReferrer": if ($GLOBALS['banner']['debug']['referrer']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; default: log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$method,$line,'('.$vclass.')'.$value),'banner_debug.log'); break; } return ; }
php
public static function writeLog($method,$line,$value) { if ($method == '## START ##') { if (!isset($GLOBALS['banner']['debug']['first'])) { if ((bool)$GLOBALS['banner']['debug']['tag'] || (bool)$GLOBALS['banner']['debug']['helper'] || (bool)$GLOBALS['banner']['debug']['image'] || (bool)$GLOBALS['banner']['debug']['referrer'] ) { $arrUniqid = trimsplit('.', uniqid('c0n7a0',true) ); $GLOBALS['banner']['debug']['first'] = $arrUniqid[1]; log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$method,$line,$value),'banner_debug.log'); return ; } return ; } else { return ; } } $arrNamespace = trimsplit('::', $method); $arrClass = trimsplit('\\', $arrNamespace[0]); $vclass = $arrClass[2]; // class that will write the log if (is_array($value)) { $value = print_r($value,true); } switch ($vclass) { case "ModuleBannerTag": if ($GLOBALS['banner']['debug']['tag']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; case "BannerHelper": if ($GLOBALS['banner']['debug']['helper']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; case "BannerImage": if ($GLOBALS['banner']['debug']['image']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; case "BannerReferrer": if ($GLOBALS['banner']['debug']['referrer']) { log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$vclass.'::'.$arrNamespace[1],$line,$value),'banner_debug.log'); } break; default: log_message(sprintf('[%s] [%s] [%s] %s',$GLOBALS['banner']['debug']['first'],$method,$line,'('.$vclass.')'.$value),'banner_debug.log'); break; } return ; }
[ "public", "static", "function", "writeLog", "(", "$", "method", ",", "$", "line", ",", "$", "value", ")", "{", "if", "(", "$", "method", "==", "'## START ##'", ")", "{", "if", "(", "!", "isset", "(", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ")", ")", "{", "if", "(", "(", "bool", ")", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'tag'", "]", "||", "(", "bool", ")", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'helper'", "]", "||", "(", "bool", ")", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'image'", "]", "||", "(", "bool", ")", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'referrer'", "]", ")", "{", "$", "arrUniqid", "=", "trimsplit", "(", "'.'", ",", "uniqid", "(", "'c0n7a0'", ",", "true", ")", ")", ";", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", "=", "$", "arrUniqid", "[", "1", "]", ";", "log_message", "(", "sprintf", "(", "'[%s] [%s] [%s] %s'", ",", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ",", "$", "method", ",", "$", "line", ",", "$", "value", ")", ",", "'banner_debug.log'", ")", ";", "return", ";", "}", "return", ";", "}", "else", "{", "return", ";", "}", "}", "$", "arrNamespace", "=", "trimsplit", "(", "'::'", ",", "$", "method", ")", ";", "$", "arrClass", "=", "trimsplit", "(", "'\\\\'", ",", "$", "arrNamespace", "[", "0", "]", ")", ";", "$", "vclass", "=", "$", "arrClass", "[", "2", "]", ";", "// class that will write the log", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "print_r", "(", "$", "value", ",", "true", ")", ";", "}", "switch", "(", "$", "vclass", ")", "{", "case", "\"ModuleBannerTag\"", ":", "if", "(", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'tag'", "]", ")", "{", "log_message", "(", "sprintf", "(", "'[%s] [%s] [%s] %s'", ",", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ",", "$", "vclass", ".", "'::'", ".", "$", "arrNamespace", "[", "1", "]", ",", "$", "line", ",", "$", "value", ")", ",", "'banner_debug.log'", ")", ";", "}", "break", ";", "case", "\"BannerHelper\"", ":", "if", "(", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'helper'", "]", ")", "{", "log_message", "(", "sprintf", "(", "'[%s] [%s] [%s] %s'", ",", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ",", "$", "vclass", ".", "'::'", ".", "$", "arrNamespace", "[", "1", "]", ",", "$", "line", ",", "$", "value", ")", ",", "'banner_debug.log'", ")", ";", "}", "break", ";", "case", "\"BannerImage\"", ":", "if", "(", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'image'", "]", ")", "{", "log_message", "(", "sprintf", "(", "'[%s] [%s] [%s] %s'", ",", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ",", "$", "vclass", ".", "'::'", ".", "$", "arrNamespace", "[", "1", "]", ",", "$", "line", ",", "$", "value", ")", ",", "'banner_debug.log'", ")", ";", "}", "break", ";", "case", "\"BannerReferrer\"", ":", "if", "(", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'referrer'", "]", ")", "{", "log_message", "(", "sprintf", "(", "'[%s] [%s] [%s] %s'", ",", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ",", "$", "vclass", ".", "'::'", ".", "$", "arrNamespace", "[", "1", "]", ",", "$", "line", ",", "$", "value", ")", ",", "'banner_debug.log'", ")", ";", "}", "break", ";", "default", ":", "log_message", "(", "sprintf", "(", "'[%s] [%s] [%s] %s'", ",", "$", "GLOBALS", "[", "'banner'", "]", "[", "'debug'", "]", "[", "'first'", "]", ",", "$", "method", ",", "$", "line", ",", "'('", ".", "$", "vclass", ".", "')'", ".", "$", "value", ")", ",", "'banner_debug.log'", ")", ";", "break", ";", "}", "return", ";", "}" ]
Write in log file, if debug is enabled @param string $method @param integer $line
[ "Write", "in", "log", "file", "if", "debug", "is", "enabled" ]
train
https://github.com/BugBuster1701/banner/blob/3ffac36837923194ab0ebaf308c0b23a3684b005/classes/ModuleBannerLog.php#L33-L98
huasituo/hstcms
src/Console/Generators/MakeApiCommand.php
MakeApiCommand.stepOne
private function stepOne() { $t = $this->option('t'); $apps = hst_api_app(); if($t === 'add') { $this->container['name'] = $this->ask('Please enter the name:'); $this->comment('You have provided the following manifest information:'); $this->comment('Name: '.$this->container['name']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { $appid = $this->creatAppId(); $secret = $this->creatSecret(); $vData = [ 'name'=>$this->container['name'], 'appid'=>$appid, 'secret'=>$secret, 'addtimes'=>hst_time(), 'edittimes'=>hst_time(), 'status'=>0 ]; $apps[$appid] = $vData; $this->saveCache($apps); ApiModel::insert($vData); $this->info('Add Success'); } } else if($t === 'edit') { $this->container['appid'] = $this->ask('Please enter the appid:'); $this->container['name'] = $this->ask('Please enter the name:'); $this->comment('You have provided the following manifest information:'); $this->comment('AppId: '.$this->container['appid']); $this->comment('Name: '.$this->container['name']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { if(!isset($apps[$this->container['appid']])) { $this->Error('Edit Error'); return true; } $apps[$this->container['appid']]['name'] = $this->container['name']; $apps[$this->container['appid']]['edittimes'] = hst_time(); $this->saveCache($apps); ApiModel::where('appid', $this->container['appid'])->update([ 'name'=>$this->container['name'], 'edittimes'=>$apps[$this->container['appid']]['edittimes'] ]); $this->info('Edit Success'); } } else if($t === 'status') { $s = (int)$this->option('s'); $this->container['appid'] = $this->ask('Please enter the appid:'); $this->comment('You have provided the following manifest information:'); $this->comment('AppId: '.$this->container['appid']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { if(!isset($apps[$this->container['appid']])) { $this->Error('Edit Error'); return true; } $apps[$this->container['appid']]['status'] = $s; $apps[$this->container['appid']]['edittimes'] = hst_time(); $this->saveCache($apps); ApiModel::where('appid', $this->container['appid'])->update([ 'status'=>$s, 'edittimes'=>$apps[$this->container['appid']]['edittimes'] ]); $this->info('Edit Success'); } } else if($t === 'delete') { $this->container['appid'] = $this->ask('Please enter the appid:'); $this->comment('You have provided the following manifest information:'); $this->comment('AppId: '.$this->container['appid']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { unset($apps[$this->container['appid']]); $this->saveCache($apps); ApiModel::where('appid', $this->container['appid'])->delete(); $this->info('Delete Success'); } } else if($t === 'clear') { if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { $this->saveCache([]); ApiModel::where('id', '>', 0)->delete(); $this->info('Clear Success'); } } else { $headers = ['Name', 'AppId', 'Secret', 'AddTimes', 'EditTimes', 'Status']; $this->table($headers, $apps); } return true; }
php
private function stepOne() { $t = $this->option('t'); $apps = hst_api_app(); if($t === 'add') { $this->container['name'] = $this->ask('Please enter the name:'); $this->comment('You have provided the following manifest information:'); $this->comment('Name: '.$this->container['name']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { $appid = $this->creatAppId(); $secret = $this->creatSecret(); $vData = [ 'name'=>$this->container['name'], 'appid'=>$appid, 'secret'=>$secret, 'addtimes'=>hst_time(), 'edittimes'=>hst_time(), 'status'=>0 ]; $apps[$appid] = $vData; $this->saveCache($apps); ApiModel::insert($vData); $this->info('Add Success'); } } else if($t === 'edit') { $this->container['appid'] = $this->ask('Please enter the appid:'); $this->container['name'] = $this->ask('Please enter the name:'); $this->comment('You have provided the following manifest information:'); $this->comment('AppId: '.$this->container['appid']); $this->comment('Name: '.$this->container['name']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { if(!isset($apps[$this->container['appid']])) { $this->Error('Edit Error'); return true; } $apps[$this->container['appid']]['name'] = $this->container['name']; $apps[$this->container['appid']]['edittimes'] = hst_time(); $this->saveCache($apps); ApiModel::where('appid', $this->container['appid'])->update([ 'name'=>$this->container['name'], 'edittimes'=>$apps[$this->container['appid']]['edittimes'] ]); $this->info('Edit Success'); } } else if($t === 'status') { $s = (int)$this->option('s'); $this->container['appid'] = $this->ask('Please enter the appid:'); $this->comment('You have provided the following manifest information:'); $this->comment('AppId: '.$this->container['appid']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { if(!isset($apps[$this->container['appid']])) { $this->Error('Edit Error'); return true; } $apps[$this->container['appid']]['status'] = $s; $apps[$this->container['appid']]['edittimes'] = hst_time(); $this->saveCache($apps); ApiModel::where('appid', $this->container['appid'])->update([ 'status'=>$s, 'edittimes'=>$apps[$this->container['appid']]['edittimes'] ]); $this->info('Edit Success'); } } else if($t === 'delete') { $this->container['appid'] = $this->ask('Please enter the appid:'); $this->comment('You have provided the following manifest information:'); $this->comment('AppId: '.$this->container['appid']); if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { unset($apps[$this->container['appid']]); $this->saveCache($apps); ApiModel::where('appid', $this->container['appid'])->delete(); $this->info('Delete Success'); } } else if($t === 'clear') { if ($this->confirm('If the provided information is correct, type "yes" to generate.')) { $this->saveCache([]); ApiModel::where('id', '>', 0)->delete(); $this->info('Clear Success'); } } else { $headers = ['Name', 'AppId', 'Secret', 'AddTimes', 'EditTimes', 'Status']; $this->table($headers, $apps); } return true; }
[ "private", "function", "stepOne", "(", ")", "{", "$", "t", "=", "$", "this", "->", "option", "(", "'t'", ")", ";", "$", "apps", "=", "hst_api_app", "(", ")", ";", "if", "(", "$", "t", "===", "'add'", ")", "{", "$", "this", "->", "container", "[", "'name'", "]", "=", "$", "this", "->", "ask", "(", "'Please enter the name:'", ")", ";", "$", "this", "->", "comment", "(", "'You have provided the following manifest information:'", ")", ";", "$", "this", "->", "comment", "(", "'Name: '", ".", "$", "this", "->", "container", "[", "'name'", "]", ")", ";", "if", "(", "$", "this", "->", "confirm", "(", "'If the provided information is correct, type \"yes\" to generate.'", ")", ")", "{", "$", "appid", "=", "$", "this", "->", "creatAppId", "(", ")", ";", "$", "secret", "=", "$", "this", "->", "creatSecret", "(", ")", ";", "$", "vData", "=", "[", "'name'", "=>", "$", "this", "->", "container", "[", "'name'", "]", ",", "'appid'", "=>", "$", "appid", ",", "'secret'", "=>", "$", "secret", ",", "'addtimes'", "=>", "hst_time", "(", ")", ",", "'edittimes'", "=>", "hst_time", "(", ")", ",", "'status'", "=>", "0", "]", ";", "$", "apps", "[", "$", "appid", "]", "=", "$", "vData", ";", "$", "this", "->", "saveCache", "(", "$", "apps", ")", ";", "ApiModel", "::", "insert", "(", "$", "vData", ")", ";", "$", "this", "->", "info", "(", "'Add Success'", ")", ";", "}", "}", "else", "if", "(", "$", "t", "===", "'edit'", ")", "{", "$", "this", "->", "container", "[", "'appid'", "]", "=", "$", "this", "->", "ask", "(", "'Please enter the appid:'", ")", ";", "$", "this", "->", "container", "[", "'name'", "]", "=", "$", "this", "->", "ask", "(", "'Please enter the name:'", ")", ";", "$", "this", "->", "comment", "(", "'You have provided the following manifest information:'", ")", ";", "$", "this", "->", "comment", "(", "'AppId: '", ".", "$", "this", "->", "container", "[", "'appid'", "]", ")", ";", "$", "this", "->", "comment", "(", "'Name: '", ".", "$", "this", "->", "container", "[", "'name'", "]", ")", ";", "if", "(", "$", "this", "->", "confirm", "(", "'If the provided information is correct, type \"yes\" to generate.'", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", ")", ")", "{", "$", "this", "->", "Error", "(", "'Edit Error'", ")", ";", "return", "true", ";", "}", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", "[", "'name'", "]", "=", "$", "this", "->", "container", "[", "'name'", "]", ";", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", "[", "'edittimes'", "]", "=", "hst_time", "(", ")", ";", "$", "this", "->", "saveCache", "(", "$", "apps", ")", ";", "ApiModel", "::", "where", "(", "'appid'", ",", "$", "this", "->", "container", "[", "'appid'", "]", ")", "->", "update", "(", "[", "'name'", "=>", "$", "this", "->", "container", "[", "'name'", "]", ",", "'edittimes'", "=>", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", "[", "'edittimes'", "]", "]", ")", ";", "$", "this", "->", "info", "(", "'Edit Success'", ")", ";", "}", "}", "else", "if", "(", "$", "t", "===", "'status'", ")", "{", "$", "s", "=", "(", "int", ")", "$", "this", "->", "option", "(", "'s'", ")", ";", "$", "this", "->", "container", "[", "'appid'", "]", "=", "$", "this", "->", "ask", "(", "'Please enter the appid:'", ")", ";", "$", "this", "->", "comment", "(", "'You have provided the following manifest information:'", ")", ";", "$", "this", "->", "comment", "(", "'AppId: '", ".", "$", "this", "->", "container", "[", "'appid'", "]", ")", ";", "if", "(", "$", "this", "->", "confirm", "(", "'If the provided information is correct, type \"yes\" to generate.'", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", ")", ")", "{", "$", "this", "->", "Error", "(", "'Edit Error'", ")", ";", "return", "true", ";", "}", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", "[", "'status'", "]", "=", "$", "s", ";", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", "[", "'edittimes'", "]", "=", "hst_time", "(", ")", ";", "$", "this", "->", "saveCache", "(", "$", "apps", ")", ";", "ApiModel", "::", "where", "(", "'appid'", ",", "$", "this", "->", "container", "[", "'appid'", "]", ")", "->", "update", "(", "[", "'status'", "=>", "$", "s", ",", "'edittimes'", "=>", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", "[", "'edittimes'", "]", "]", ")", ";", "$", "this", "->", "info", "(", "'Edit Success'", ")", ";", "}", "}", "else", "if", "(", "$", "t", "===", "'delete'", ")", "{", "$", "this", "->", "container", "[", "'appid'", "]", "=", "$", "this", "->", "ask", "(", "'Please enter the appid:'", ")", ";", "$", "this", "->", "comment", "(", "'You have provided the following manifest information:'", ")", ";", "$", "this", "->", "comment", "(", "'AppId: '", ".", "$", "this", "->", "container", "[", "'appid'", "]", ")", ";", "if", "(", "$", "this", "->", "confirm", "(", "'If the provided information is correct, type \"yes\" to generate.'", ")", ")", "{", "unset", "(", "$", "apps", "[", "$", "this", "->", "container", "[", "'appid'", "]", "]", ")", ";", "$", "this", "->", "saveCache", "(", "$", "apps", ")", ";", "ApiModel", "::", "where", "(", "'appid'", ",", "$", "this", "->", "container", "[", "'appid'", "]", ")", "->", "delete", "(", ")", ";", "$", "this", "->", "info", "(", "'Delete Success'", ")", ";", "}", "}", "else", "if", "(", "$", "t", "===", "'clear'", ")", "{", "if", "(", "$", "this", "->", "confirm", "(", "'If the provided information is correct, type \"yes\" to generate.'", ")", ")", "{", "$", "this", "->", "saveCache", "(", "[", "]", ")", ";", "ApiModel", "::", "where", "(", "'id'", ",", "'>'", ",", "0", ")", "->", "delete", "(", ")", ";", "$", "this", "->", "info", "(", "'Clear Success'", ")", ";", "}", "}", "else", "{", "$", "headers", "=", "[", "'Name'", ",", "'AppId'", ",", "'Secret'", ",", "'AddTimes'", ",", "'EditTimes'", ",", "'Status'", "]", ";", "$", "this", "->", "table", "(", "$", "headers", ",", "$", "apps", ")", ";", "}", "return", "true", ";", "}" ]
Step 1: Configure module manifest. @return mixed
[ "Step", "1", ":", "Configure", "module", "manifest", "." ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Console/Generators/MakeApiCommand.php#L105-L189
weavephp/weave
src/Router/Router.php
Router.run
protected function run(Request $request) { if (!$this->routesConfigured) { $this->adaptor->configureRoutes($this->routeProvider); $this->routesConfigured = true; } $handler = $this->adaptor->route($request); if ($handler === false) { return $this->chain($request); } // Setup any remaining chained parts of the dispatch for future dispatch $request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler)); // Resolve the handler into something callable $dispatchable = $this->resolver->resolve($handler, $resolutionType); $parameters = [ $dispatchable, $resolutionType, DispatchAdaptorInterface::SOURCE_ROUTER, $request ]; $response = $this->getResponseObject(); if ($response !== null) { $parameters[] = $response; } return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request); }
php
protected function run(Request $request) { if (!$this->routesConfigured) { $this->adaptor->configureRoutes($this->routeProvider); $this->routesConfigured = true; } $handler = $this->adaptor->route($request); if ($handler === false) { return $this->chain($request); } // Setup any remaining chained parts of the dispatch for future dispatch $request = $request->withAttribute('dispatch.handler', $this->resolver->shift($handler)); // Resolve the handler into something callable $dispatchable = $this->resolver->resolve($handler, $resolutionType); $parameters = [ $dispatchable, $resolutionType, DispatchAdaptorInterface::SOURCE_ROUTER, $request ]; $response = $this->getResponseObject(); if ($response !== null) { $parameters[] = $response; } return $this->dispatcher->dispatch(...$parameters) ?: $this->chain($request); }
[ "protected", "function", "run", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "routesConfigured", ")", "{", "$", "this", "->", "adaptor", "->", "configureRoutes", "(", "$", "this", "->", "routeProvider", ")", ";", "$", "this", "->", "routesConfigured", "=", "true", ";", "}", "$", "handler", "=", "$", "this", "->", "adaptor", "->", "route", "(", "$", "request", ")", ";", "if", "(", "$", "handler", "===", "false", ")", "{", "return", "$", "this", "->", "chain", "(", "$", "request", ")", ";", "}", "// Setup any remaining chained parts of the dispatch for future dispatch", "$", "request", "=", "$", "request", "->", "withAttribute", "(", "'dispatch.handler'", ",", "$", "this", "->", "resolver", "->", "shift", "(", "$", "handler", ")", ")", ";", "// Resolve the handler into something callable", "$", "dispatchable", "=", "$", "this", "->", "resolver", "->", "resolve", "(", "$", "handler", ",", "$", "resolutionType", ")", ";", "$", "parameters", "=", "[", "$", "dispatchable", ",", "$", "resolutionType", ",", "DispatchAdaptorInterface", "::", "SOURCE_ROUTER", ",", "$", "request", "]", ";", "$", "response", "=", "$", "this", "->", "getResponseObject", "(", ")", ";", "if", "(", "$", "response", "!==", "null", ")", "{", "$", "parameters", "[", "]", "=", "$", "response", ";", "}", "return", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "...", "$", "parameters", ")", "?", ":", "$", "this", "->", "chain", "(", "$", "request", ")", ";", "}" ]
Configure and then attempt to route and dispatch for the supplied Request. @param Request $request The request to route. @return Response
[ "Configure", "and", "then", "attempt", "to", "route", "and", "dispatch", "for", "the", "supplied", "Request", "." ]
train
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Router/Router.php#L82-L112
acasademont/wurfl
WURFL/Storage/Base.php
WURFL_Storage_Base.setCacheStorage
public function setCacheStorage(WURFL_Storage_Base $cache) { if (!$this->supportsSecondaryCaching()) { throw new WURFL_Storage_Exception("The storage provider ".get_class($cache)." cannot be used as a cache for ".get_class($this)); } $this->cache = $cache; }
php
public function setCacheStorage(WURFL_Storage_Base $cache) { if (!$this->supportsSecondaryCaching()) { throw new WURFL_Storage_Exception("The storage provider ".get_class($cache)." cannot be used as a cache for ".get_class($this)); } $this->cache = $cache; }
[ "public", "function", "setCacheStorage", "(", "WURFL_Storage_Base", "$", "cache", ")", "{", "if", "(", "!", "$", "this", "->", "supportsSecondaryCaching", "(", ")", ")", "{", "throw", "new", "WURFL_Storage_Exception", "(", "\"The storage provider \"", ".", "get_class", "(", "$", "cache", ")", ".", "\" cannot be used as a cache for \"", ".", "get_class", "(", "$", "this", ")", ")", ";", "}", "$", "this", "->", "cache", "=", "$", "cache", ";", "}" ]
Sets the cache provider for the persistence provider; this is used to cache data in a volatile storage system like APC in front of a slow persistence provider like the filesystem. @param WURFL_Storage_Base $cache
[ "Sets", "the", "cache", "provider", "for", "the", "persistence", "provider", ";", "this", "is", "used", "to", "cache", "data", "in", "a", "volatile", "storage", "system", "like", "APC", "in", "front", "of", "a", "slow", "persistence", "provider", "like", "the", "filesystem", "." ]
train
https://github.com/acasademont/wurfl/blob/0f4fb6e06b452ba95ad1d15e7d8226d0974b60c2/WURFL/Storage/Base.php#L129-L135
acasademont/wurfl
WURFL/Storage/Base.php
WURFL_Storage_Base.setWURFLLoaded
public function setWURFLLoaded($loaded = true) { $this->save(self::WURFL_LOADED, $loaded); $this->cacheSave(self::WURFL_LOADED, new StorageObject($loaded, 0)); }
php
public function setWURFLLoaded($loaded = true) { $this->save(self::WURFL_LOADED, $loaded); $this->cacheSave(self::WURFL_LOADED, new StorageObject($loaded, 0)); }
[ "public", "function", "setWURFLLoaded", "(", "$", "loaded", "=", "true", ")", "{", "$", "this", "->", "save", "(", "self", "::", "WURFL_LOADED", ",", "$", "loaded", ")", ";", "$", "this", "->", "cacheSave", "(", "self", "::", "WURFL_LOADED", ",", "new", "StorageObject", "(", "$", "loaded", ",", "0", ")", ")", ";", "}" ]
Sets the WURFL Loaded flag @param bool $loaded
[ "Sets", "the", "WURFL", "Loaded", "flag" ]
train
https://github.com/acasademont/wurfl/blob/0f4fb6e06b452ba95ad1d15e7d8226d0974b60c2/WURFL/Storage/Base.php#L182-L186
movoin/one-swoole
src/Console/Command.php
Command.status
public function status(string $message, string $status, string $decorateStyle = 'info', string $decorate = '*') { $this->output->writeln( sprintf( ' <%s>%s</> %s %s', $decorateStyle, $decorate, str_pad($message, 36), $status ) ); }
php
public function status(string $message, string $status, string $decorateStyle = 'info', string $decorate = '*') { $this->output->writeln( sprintf( ' <%s>%s</> %s %s', $decorateStyle, $decorate, str_pad($message, 36), $status ) ); }
[ "public", "function", "status", "(", "string", "$", "message", ",", "string", "$", "status", ",", "string", "$", "decorateStyle", "=", "'info'", ",", "string", "$", "decorate", "=", "'*'", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "sprintf", "(", "' <%s>%s</> %s %s'", ",", "$", "decorateStyle", ",", "$", "decorate", ",", "str_pad", "(", "$", "message", ",", "36", ")", ",", "$", "status", ")", ")", ";", "}" ]
输出列表项目 @param string $message @param string $status @param string $decorateStyle @param string $decorate
[ "输出列表项目" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Console/Command.php#L40-L51
movoin/one-swoole
src/Console/Command.php
Command.initialize
protected function initialize(InputInterface $input, OutputInterface $output) { $styles = [ // --------------------------------------- // Style => [ Color, BgColor, Options ] // --------------------------------------- 'title' => [ 'white', null, ['bold'] ], 'info' => [ 'cyan' ], 'warn' => [ 'yellow', null, ['bold'] ], 'erro' => [ 'red', null, ['bold'] ], 'success' => [ 'green' ], 'failure' => [ 'yellow' ], 'label' => [ 'cyan', null, ['underscore'] ], 'comment' => [ 'white', null, ['reverse'] ], 'highlight' => [ 'yellow' ], ]; foreach ($styles as $name => $style) { $output->getFormatter()->setStyle( $name, Reflection::newInstance( OutputFormatterStyle::class, $style ) ); } $this->output = new OutputStyle($input, $output); }
php
protected function initialize(InputInterface $input, OutputInterface $output) { $styles = [ // --------------------------------------- // Style => [ Color, BgColor, Options ] // --------------------------------------- 'title' => [ 'white', null, ['bold'] ], 'info' => [ 'cyan' ], 'warn' => [ 'yellow', null, ['bold'] ], 'erro' => [ 'red', null, ['bold'] ], 'success' => [ 'green' ], 'failure' => [ 'yellow' ], 'label' => [ 'cyan', null, ['underscore'] ], 'comment' => [ 'white', null, ['reverse'] ], 'highlight' => [ 'yellow' ], ]; foreach ($styles as $name => $style) { $output->getFormatter()->setStyle( $name, Reflection::newInstance( OutputFormatterStyle::class, $style ) ); } $this->output = new OutputStyle($input, $output); }
[ "protected", "function", "initialize", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "styles", "=", "[", "// ---------------------------------------", "// Style => [ Color, BgColor, Options ]", "// ---------------------------------------", "'title'", "=>", "[", "'white'", ",", "null", ",", "[", "'bold'", "]", "]", ",", "'info'", "=>", "[", "'cyan'", "]", ",", "'warn'", "=>", "[", "'yellow'", ",", "null", ",", "[", "'bold'", "]", "]", ",", "'erro'", "=>", "[", "'red'", ",", "null", ",", "[", "'bold'", "]", "]", ",", "'success'", "=>", "[", "'green'", "]", ",", "'failure'", "=>", "[", "'yellow'", "]", ",", "'label'", "=>", "[", "'cyan'", ",", "null", ",", "[", "'underscore'", "]", "]", ",", "'comment'", "=>", "[", "'white'", ",", "null", ",", "[", "'reverse'", "]", "]", ",", "'highlight'", "=>", "[", "'yellow'", "]", ",", "]", ";", "foreach", "(", "$", "styles", "as", "$", "name", "=>", "$", "style", ")", "{", "$", "output", "->", "getFormatter", "(", ")", "->", "setStyle", "(", "$", "name", ",", "Reflection", "::", "newInstance", "(", "OutputFormatterStyle", "::", "class", ",", "$", "style", ")", ")", ";", "}", "$", "this", "->", "output", "=", "new", "OutputStyle", "(", "$", "input", ",", "$", "output", ")", ";", "}" ]
初始化 @param \Symfony\Component\Console\Input\InputInterface $input @param \Symfony\Component\Console\Output\OutputInterface $output
[ "初始化" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Console/Command.php#L72-L100
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.find
public function find($id, $projections = array(), $options = array()) { if (null !== ($object = parent::find($id, $projections, $options))) { $data = []; if ($this->getStreamProjection($projections)) { $data["stream"] = $this->bucket->openDownloadStream($object->getId()); } $this->hydrator->hydrate($object, $data, true); return $object; } }
php
public function find($id, $projections = array(), $options = array()) { if (null !== ($object = parent::find($id, $projections, $options))) { $data = []; if ($this->getStreamProjection($projections)) { $data["stream"] = $this->bucket->openDownloadStream($object->getId()); } $this->hydrator->hydrate($object, $data, true); return $object; } }
[ "public", "function", "find", "(", "$", "id", ",", "$", "projections", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "null", "!==", "(", "$", "object", "=", "parent", "::", "find", "(", "$", "id", ",", "$", "projections", ",", "$", "options", ")", ")", ")", "{", "$", "data", "=", "[", "]", ";", "if", "(", "$", "this", "->", "getStreamProjection", "(", "$", "projections", ")", ")", "{", "$", "data", "[", "\"stream\"", "]", "=", "$", "this", "->", "bucket", "->", "openDownloadStream", "(", "$", "object", "->", "getId", "(", ")", ")", ";", "}", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "object", ",", "$", "data", ",", "true", ")", ";", "return", "$", "object", ";", "}", "}" ]
Find document by ID Options : * readOnly : boolean - When false, flush will not update object @see MongoDB\Operation\FindOne::__construct for more option @param mixed $id Id of the document @param array $projections Projection of the query @param array $options Options for the query @return object|null
[ "Find", "document", "by", "ID" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L87-L97
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.findAll
public function findAll($projections = array(), $sorts = array(), $options = array()) { $options = $this->createOption($projections, $sorts, $options); if (!isset($options['iterator']) || $options['iterator'] === false) { $objects = parent::findAll($projections, $sorts, $options); foreach ($objects as $object) { if ($this->getStreamProjection($projections)) { $data["stream"] = $this->bucket->openDownloadStream($object->getId()); } $this->hydrator->hydrate($object, $data, true); } return $objects; } else { if (!is_string($options['iterator'])) { $options['iterator'] = GridFSDocumentIterator::class; } return parent::findAll($projections, $sorts, $options); } }
php
public function findAll($projections = array(), $sorts = array(), $options = array()) { $options = $this->createOption($projections, $sorts, $options); if (!isset($options['iterator']) || $options['iterator'] === false) { $objects = parent::findAll($projections, $sorts, $options); foreach ($objects as $object) { if ($this->getStreamProjection($projections)) { $data["stream"] = $this->bucket->openDownloadStream($object->getId()); } $this->hydrator->hydrate($object, $data, true); } return $objects; } else { if (!is_string($options['iterator'])) { $options['iterator'] = GridFSDocumentIterator::class; } return parent::findAll($projections, $sorts, $options); } }
[ "public", "function", "findAll", "(", "$", "projections", "=", "array", "(", ")", ",", "$", "sorts", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "options", "=", "$", "this", "->", "createOption", "(", "$", "projections", ",", "$", "sorts", ",", "$", "options", ")", ";", "if", "(", "!", "isset", "(", "$", "options", "[", "'iterator'", "]", ")", "||", "$", "options", "[", "'iterator'", "]", "===", "false", ")", "{", "$", "objects", "=", "parent", "::", "findAll", "(", "$", "projections", ",", "$", "sorts", ",", "$", "options", ")", ";", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "if", "(", "$", "this", "->", "getStreamProjection", "(", "$", "projections", ")", ")", "{", "$", "data", "[", "\"stream\"", "]", "=", "$", "this", "->", "bucket", "->", "openDownloadStream", "(", "$", "object", "->", "getId", "(", ")", ")", ";", "}", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "object", ",", "$", "data", ",", "true", ")", ";", "}", "return", "$", "objects", ";", "}", "else", "{", "if", "(", "!", "is_string", "(", "$", "options", "[", "'iterator'", "]", ")", ")", "{", "$", "options", "[", "'iterator'", "]", "=", "GridFSDocumentIterator", "::", "class", ";", "}", "return", "parent", "::", "findAll", "(", "$", "projections", ",", "$", "sorts", ",", "$", "options", ")", ";", "}", "}" ]
Get all documents of collection Options : * readOnly : boolean - When false, flush will not update object * iterator : boolean|string - Return DocumentIterator if true (or specified class if is string) @see MongoDB\Operation\Find::__construct for more option @param array $projections Projection of the query @param array $sorts Sorts specification @param array $options Options for the query @param array $options @return void
[ "Get", "all", "documents", "of", "collection" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L113-L131
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.findOneBy
public function findOneBy($filters = array(), $projections = array(), $sorts = array(), $options = array()) { $object = parent::findOneBy($filters, $projections, $sorts, $options); if (isset($object)) { $data = []; if ($this->getStreamProjection($projections)) { $data["stream"] = $this->bucket->openDownloadStream($object->getId()); $this->hydrator->hydrate($object, $data, true); } return $object; } }
php
public function findOneBy($filters = array(), $projections = array(), $sorts = array(), $options = array()) { $object = parent::findOneBy($filters, $projections, $sorts, $options); if (isset($object)) { $data = []; if ($this->getStreamProjection($projections)) { $data["stream"] = $this->bucket->openDownloadStream($object->getId()); $this->hydrator->hydrate($object, $data, true); } return $object; } }
[ "public", "function", "findOneBy", "(", "$", "filters", "=", "array", "(", ")", ",", "$", "projections", "=", "array", "(", ")", ",", "$", "sorts", "=", "array", "(", ")", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "object", "=", "parent", "::", "findOneBy", "(", "$", "filters", ",", "$", "projections", ",", "$", "sorts", ",", "$", "options", ")", ";", "if", "(", "isset", "(", "$", "object", ")", ")", "{", "$", "data", "=", "[", "]", ";", "if", "(", "$", "this", "->", "getStreamProjection", "(", "$", "projections", ")", ")", "{", "$", "data", "[", "\"stream\"", "]", "=", "$", "this", "->", "bucket", "->", "openDownloadStream", "(", "$", "object", "->", "getId", "(", ")", ")", ";", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "object", ",", "$", "data", ",", "true", ")", ";", "}", "return", "$", "object", ";", "}", "}" ]
Get first document which match the query Options : * readOnly : boolean - When false, flush will not update object @see MongoDB\Operation\Find::__construct for more option @param array $filters Filters @param array $projections Projection of the query @param array $sorts Sorts specification @param array $options Options for the query @param array $options @return void
[ "Get", "first", "document", "which", "match", "the", "query" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L183-L195
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.cacheObject
public function cacheObject($object) { if (is_object($object)) { $unhyd = $this->hydrator->unhydrate($object); unset($unhyd["stream"]); $this->objectCache->save(spl_object_hash($object), $unhyd); } }
php
public function cacheObject($object) { if (is_object($object)) { $unhyd = $this->hydrator->unhydrate($object); unset($unhyd["stream"]); $this->objectCache->save(spl_object_hash($object), $unhyd); } }
[ "public", "function", "cacheObject", "(", "$", "object", ")", "{", "if", "(", "is_object", "(", "$", "object", ")", ")", "{", "$", "unhyd", "=", "$", "this", "->", "hydrator", "->", "unhydrate", "(", "$", "object", ")", ";", "unset", "(", "$", "unhyd", "[", "\"stream\"", "]", ")", ";", "$", "this", "->", "objectCache", "->", "save", "(", "spl_object_hash", "(", "$", "object", ")", ",", "$", "unhyd", ")", ";", "}", "}" ]
Store object in cache to see changes @param object $object Object to cache @return void
[ "Store", "object", "in", "cache", "to", "see", "changes" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L242-L249
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.insertOne
public function insertOne($document, $options = []) { $objectDatas = $this->hydrator->unhydrate($document); $stream = $objectDatas["stream"]; unset($objectDatas["stream"]); if (!isset($objectDatas["filename"])) { $filename = stream_get_meta_data($stream)["uri"]; } else { $filename = $objectDatas["filename"]; } unset($objectDatas["filename"]); $id = $this->bucket->uploadFromStream($filename, $stream, $objectDatas); $data['_id'] = $id; $data["stream"] = $this->bucket->openDownloadStream($data['_id']); $this->hydrator->hydrate($document, $data, true); $this->documentManager->setObjectState($document, ObjectManager::OBJ_MANAGED); $this->cacheObject($document); return true; }
php
public function insertOne($document, $options = []) { $objectDatas = $this->hydrator->unhydrate($document); $stream = $objectDatas["stream"]; unset($objectDatas["stream"]); if (!isset($objectDatas["filename"])) { $filename = stream_get_meta_data($stream)["uri"]; } else { $filename = $objectDatas["filename"]; } unset($objectDatas["filename"]); $id = $this->bucket->uploadFromStream($filename, $stream, $objectDatas); $data['_id'] = $id; $data["stream"] = $this->bucket->openDownloadStream($data['_id']); $this->hydrator->hydrate($document, $data, true); $this->documentManager->setObjectState($document, ObjectManager::OBJ_MANAGED); $this->cacheObject($document); return true; }
[ "public", "function", "insertOne", "(", "$", "document", ",", "$", "options", "=", "[", "]", ")", "{", "$", "objectDatas", "=", "$", "this", "->", "hydrator", "->", "unhydrate", "(", "$", "document", ")", ";", "$", "stream", "=", "$", "objectDatas", "[", "\"stream\"", "]", ";", "unset", "(", "$", "objectDatas", "[", "\"stream\"", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "objectDatas", "[", "\"filename\"", "]", ")", ")", "{", "$", "filename", "=", "stream_get_meta_data", "(", "$", "stream", ")", "[", "\"uri\"", "]", ";", "}", "else", "{", "$", "filename", "=", "$", "objectDatas", "[", "\"filename\"", "]", ";", "}", "unset", "(", "$", "objectDatas", "[", "\"filename\"", "]", ")", ";", "$", "id", "=", "$", "this", "->", "bucket", "->", "uploadFromStream", "(", "$", "filename", ",", "$", "stream", ",", "$", "objectDatas", ")", ";", "$", "data", "[", "'_id'", "]", "=", "$", "id", ";", "$", "data", "[", "\"stream\"", "]", "=", "$", "this", "->", "bucket", "->", "openDownloadStream", "(", "$", "data", "[", "'_id'", "]", ")", ";", "$", "this", "->", "hydrator", "->", "hydrate", "(", "$", "document", ",", "$", "data", ",", "true", ")", ";", "$", "this", "->", "documentManager", "->", "setObjectState", "(", "$", "document", ",", "ObjectManager", "::", "OBJ_MANAGED", ")", ";", "$", "this", "->", "cacheObject", "(", "$", "document", ")", ";", "return", "true", ";", "}" ]
Insert a GridFS document @param object $document Document to insert @param array $options Useless, just for Repository compatibility @return boolean
[ "Insert", "a", "GridFS", "document" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L269-L294
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.insertMany
public function insertMany($documents, $options = []) { foreach ($documents as $document) { if (!$this->insertOne($document)) { return false; } } return true; }
php
public function insertMany($documents, $options = []) { foreach ($documents as $document) { if (!$this->insertOne($document)) { return false; } } return true; }
[ "public", "function", "insertMany", "(", "$", "documents", ",", "$", "options", "=", "[", "]", ")", "{", "foreach", "(", "$", "documents", "as", "$", "document", ")", "{", "if", "(", "!", "$", "this", "->", "insertOne", "(", "$", "document", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Insert multiple GridFS documents @param array $documents Documents to insert @param array $options Useless, just for Repository compatibility @return boolean
[ "Insert", "multiple", "GridFS", "documents" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L303-L312
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.deleteOne
public function deleteOne($document, $options = []) { $unhydratedObject = $this->hydrator->unhydrate($document); $id = $unhydratedObject["_id"]; $this->bucket->delete($id); $this->documentManager->removeObject($document); }
php
public function deleteOne($document, $options = []) { $unhydratedObject = $this->hydrator->unhydrate($document); $id = $unhydratedObject["_id"]; $this->bucket->delete($id); $this->documentManager->removeObject($document); }
[ "public", "function", "deleteOne", "(", "$", "document", ",", "$", "options", "=", "[", "]", ")", "{", "$", "unhydratedObject", "=", "$", "this", "->", "hydrator", "->", "unhydrate", "(", "$", "document", ")", ";", "$", "id", "=", "$", "unhydratedObject", "[", "\"_id\"", "]", ";", "$", "this", "->", "bucket", "->", "delete", "(", "$", "id", ")", ";", "$", "this", "->", "documentManager", "->", "removeObject", "(", "$", "document", ")", ";", "}" ]
Delete a document form gr @param object|array $document Document or query to delete @param array $options Useless, just for Repository compatibility @return void
[ "Delete", "a", "document", "form", "gr" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L321-L329
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.getUpdateQuery
public function getUpdateQuery($document) { $updateQuery = []; $old = $this->uncacheObject($document); $new = $this->hydrator->unhydrate($document); unset($new["stream"]); return $this->updateQueryCreator->createUpdateQuery($old, $new); }
php
public function getUpdateQuery($document) { $updateQuery = []; $old = $this->uncacheObject($document); $new = $this->hydrator->unhydrate($document); unset($new["stream"]); return $this->updateQueryCreator->createUpdateQuery($old, $new); }
[ "public", "function", "getUpdateQuery", "(", "$", "document", ")", "{", "$", "updateQuery", "=", "[", "]", ";", "$", "old", "=", "$", "this", "->", "uncacheObject", "(", "$", "document", ")", ";", "$", "new", "=", "$", "this", "->", "hydrator", "->", "unhydrate", "(", "$", "document", ")", ";", "unset", "(", "$", "new", "[", "\"stream\"", "]", ")", ";", "return", "$", "this", "->", "updateQueryCreator", "->", "createUpdateQuery", "(", "$", "old", ",", "$", "new", ")", ";", "}" ]
Create the update query from object diff @param object $document The document that the update query will match @return array
[ "Create", "the", "update", "query", "from", "object", "diff" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L349-L357
JoffreyPoreeCoding/MongoDB-ODM
src/GridFS/Repository.php
Repository.getStreamProjection
private function getStreamProjection($projections) { if (isset($projections['stream'])) { return $projections['stream']; } elseif (empty($projections)) { return true; } else { if (isset($projections['_id'])) { unset($projections['_id']); } return reset($projections) ? false : true; } }
php
private function getStreamProjection($projections) { if (isset($projections['stream'])) { return $projections['stream']; } elseif (empty($projections)) { return true; } else { if (isset($projections['_id'])) { unset($projections['_id']); } return reset($projections) ? false : true; } }
[ "private", "function", "getStreamProjection", "(", "$", "projections", ")", "{", "if", "(", "isset", "(", "$", "projections", "[", "'stream'", "]", ")", ")", "{", "return", "$", "projections", "[", "'stream'", "]", ";", "}", "elseif", "(", "empty", "(", "$", "projections", ")", ")", "{", "return", "true", ";", "}", "else", "{", "if", "(", "isset", "(", "$", "projections", "[", "'_id'", "]", ")", ")", "{", "unset", "(", "$", "projections", "[", "'_id'", "]", ")", ";", "}", "return", "reset", "(", "$", "projections", ")", "?", "false", ":", "true", ";", "}", "}" ]
Get the stream projection @param array $projections Projection of query @return boolean
[ "Get", "the", "stream", "projection" ]
train
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/GridFS/Repository.php#L365-L377
FrenchFrogs/framework
src/Core/Panel.php
Panel.setPanel
public function setPanel(FrenchFrogs\Panel\Panel\Panel $panel) { $this->panel = $panel; return $this; }
php
public function setPanel(FrenchFrogs\Panel\Panel\Panel $panel) { $this->panel = $panel; return $this; }
[ "public", "function", "setPanel", "(", "FrenchFrogs", "\\", "Panel", "\\", "Panel", "\\", "Panel", "$", "panel", ")", "{", "$", "this", "->", "panel", "=", "$", "panel", ";", "return", "$", "this", ";", "}" ]
Setter for $panel Attribute @param \FrenchFrogs\Panel\Panel\Panel $panel @return $this
[ "Setter", "for", "$panel", "Attribute" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Core/Panel.php#L23-L27
FrenchFrogs/framework
src/Core/Panel.php
Panel.useDefaultPanel
public function useDefaultPanel($title = '') { /** @var $panel \FrenchFrogs\Panel\Panel\Panel */ $panel = configurator()->get('panel.class'); $panel = new $panel; $panel->setTitle(strval($title)); return $this->setPanel($panel); }
php
public function useDefaultPanel($title = '') { /** @var $panel \FrenchFrogs\Panel\Panel\Panel */ $panel = configurator()->get('panel.class'); $panel = new $panel; $panel->setTitle(strval($title)); return $this->setPanel($panel); }
[ "public", "function", "useDefaultPanel", "(", "$", "title", "=", "''", ")", "{", "/** @var $panel \\FrenchFrogs\\Panel\\Panel\\Panel */", "$", "panel", "=", "configurator", "(", ")", "->", "get", "(", "'panel.class'", ")", ";", "$", "panel", "=", "new", "$", "panel", ";", "$", "panel", "->", "setTitle", "(", "strval", "(", "$", "title", ")", ")", ";", "return", "$", "this", "->", "setPanel", "(", "$", "panel", ")", ";", "}" ]
Set default panel @param string $title @return $this
[ "Set", "default", "panel" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Core/Panel.php#L35-L44
e0ipso/drupal-unit-autoload
src/Discovery/PathFinderCore.php
PathFinderCore.find
public function find($seed) { $seed = realpath($seed); $directory = is_dir($seed) ? $seed : dirname($seed); // Starting at the directory containing the seed path, we go one directory // up and up and up until we reach the Drupal root. do { if ($this->isDrupalRoot($directory)) { return $directory . $this->path; } } while ($directory = $this->getParentDirectory($directory)); // @codeCoverageIgnoreStart // If we have not returned, that means that the Drupal core directory could // not be found. throw new ClassLoaderException(sprintf('Drupal core directory could not be found as a parent of: %s.', $seed)); // @codeCoverageIgnoreEnd }
php
public function find($seed) { $seed = realpath($seed); $directory = is_dir($seed) ? $seed : dirname($seed); // Starting at the directory containing the seed path, we go one directory // up and up and up until we reach the Drupal root. do { if ($this->isDrupalRoot($directory)) { return $directory . $this->path; } } while ($directory = $this->getParentDirectory($directory)); // @codeCoverageIgnoreStart // If we have not returned, that means that the Drupal core directory could // not be found. throw new ClassLoaderException(sprintf('Drupal core directory could not be found as a parent of: %s.', $seed)); // @codeCoverageIgnoreEnd }
[ "public", "function", "find", "(", "$", "seed", ")", "{", "$", "seed", "=", "realpath", "(", "$", "seed", ")", ";", "$", "directory", "=", "is_dir", "(", "$", "seed", ")", "?", "$", "seed", ":", "dirname", "(", "$", "seed", ")", ";", "// Starting at the directory containing the seed path, we go one directory", "// up and up and up until we reach the Drupal root.", "do", "{", "if", "(", "$", "this", "->", "isDrupalRoot", "(", "$", "directory", ")", ")", "{", "return", "$", "directory", ".", "$", "this", "->", "path", ";", "}", "}", "while", "(", "$", "directory", "=", "$", "this", "->", "getParentDirectory", "(", "$", "directory", ")", ")", ";", "// @codeCoverageIgnoreStart", "// If we have not returned, that means that the Drupal core directory could", "// not be found.", "throw", "new", "ClassLoaderException", "(", "sprintf", "(", "'Drupal core directory could not be found as a parent of: %s.'", ",", "$", "seed", ")", ")", ";", "// @codeCoverageIgnoreEnd", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/e0ipso/drupal-unit-autoload/blob/7ce147b269c7333eca31e2cd04b736d6274b9cbf/src/Discovery/PathFinderCore.php#L17-L34
e0ipso/drupal-unit-autoload
src/Discovery/PathFinderCore.php
PathFinderCore.isDrupalRoot
protected function isDrupalRoot($directory) { if (!empty($directory) && is_dir($directory) && file_exists($directory . DIRECTORY_SEPARATOR . '/index.php')) { // Drupal 7 root. // We check for the presence of 'modules/field/field.module' to differentiate this from a D6 site return (file_exists($directory . DIRECTORY_SEPARATOR . 'includes/common.inc') && file_exists($directory . DIRECTORY_SEPARATOR . 'misc/drupal.js') && file_exists($directory . DIRECTORY_SEPARATOR . 'modules/field/field.module')); } return FALSE; }
php
protected function isDrupalRoot($directory) { if (!empty($directory) && is_dir($directory) && file_exists($directory . DIRECTORY_SEPARATOR . '/index.php')) { // Drupal 7 root. // We check for the presence of 'modules/field/field.module' to differentiate this from a D6 site return (file_exists($directory . DIRECTORY_SEPARATOR . 'includes/common.inc') && file_exists($directory . DIRECTORY_SEPARATOR . 'misc/drupal.js') && file_exists($directory . DIRECTORY_SEPARATOR . 'modules/field/field.module')); } return FALSE; }
[ "protected", "function", "isDrupalRoot", "(", "$", "directory", ")", "{", "if", "(", "!", "empty", "(", "$", "directory", ")", "&&", "is_dir", "(", "$", "directory", ")", "&&", "file_exists", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "'/index.php'", ")", ")", "{", "// Drupal 7 root.", "// We check for the presence of 'modules/field/field.module' to differentiate this from a D6 site", "return", "(", "file_exists", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "'includes/common.inc'", ")", "&&", "file_exists", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "'misc/drupal.js'", ")", "&&", "file_exists", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "'modules/field/field.module'", ")", ")", ";", "}", "return", "FALSE", ";", "}" ]
Checks if the passed directory is the Drupal root. @param string $directory The directory path. @return bool TRUE if the passed directory is the Drupal root.
[ "Checks", "if", "the", "passed", "directory", "is", "the", "Drupal", "root", "." ]
train
https://github.com/e0ipso/drupal-unit-autoload/blob/7ce147b269c7333eca31e2cd04b736d6274b9cbf/src/Discovery/PathFinderCore.php#L45-L54
jasny/router
src/Router/Runner/PhpScript.php
PhpScript.run
public function run(ServerRequestInterface $request, ResponseInterface $response) { $route = $request->getAttribute('route'); $file = !empty($route->file) ? ltrim($route->file, '/') : ''; if ($file[0] === '~' || strpos($file, '..') !== false) { trigger_error("Won't route to '$file': '~', '..' are not allowed in filename", E_USER_NOTICE); return $this->notFound($request, $response); } if (!file_exists($file)) { trigger_error("Failed to route using '$file': File doesn't exist", E_USER_NOTICE); return $this->notFound($request, $response); } $result = $this->includeScript($file, $request, $response); return $result === true || $result === 1 ? $response : $result; }
php
public function run(ServerRequestInterface $request, ResponseInterface $response) { $route = $request->getAttribute('route'); $file = !empty($route->file) ? ltrim($route->file, '/') : ''; if ($file[0] === '~' || strpos($file, '..') !== false) { trigger_error("Won't route to '$file': '~', '..' are not allowed in filename", E_USER_NOTICE); return $this->notFound($request, $response); } if (!file_exists($file)) { trigger_error("Failed to route using '$file': File doesn't exist", E_USER_NOTICE); return $this->notFound($request, $response); } $result = $this->includeScript($file, $request, $response); return $result === true || $result === 1 ? $response : $result; }
[ "public", "function", "run", "(", "ServerRequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "route", "=", "$", "request", "->", "getAttribute", "(", "'route'", ")", ";", "$", "file", "=", "!", "empty", "(", "$", "route", "->", "file", ")", "?", "ltrim", "(", "$", "route", "->", "file", ",", "'/'", ")", ":", "''", ";", "if", "(", "$", "file", "[", "0", "]", "===", "'~'", "||", "strpos", "(", "$", "file", ",", "'..'", ")", "!==", "false", ")", "{", "trigger_error", "(", "\"Won't route to '$file': '~', '..' are not allowed in filename\"", ",", "E_USER_NOTICE", ")", ";", "return", "$", "this", "->", "notFound", "(", "$", "request", ",", "$", "response", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "trigger_error", "(", "\"Failed to route using '$file': File doesn't exist\"", ",", "E_USER_NOTICE", ")", ";", "return", "$", "this", "->", "notFound", "(", "$", "request", ",", "$", "response", ")", ";", "}", "$", "result", "=", "$", "this", "->", "includeScript", "(", "$", "file", ",", "$", "request", ",", "$", "response", ")", ";", "return", "$", "result", "===", "true", "||", "$", "result", "===", "1", "?", "$", "response", ":", "$", "result", ";", "}" ]
Route to a file @param ServerRequestInterface $request @param ResponseInterface $response @return ResponseInterface|mixed
[ "Route", "to", "a", "file" ]
train
https://github.com/jasny/router/blob/4c776665ba343150b442c21893946e3d54190896/src/Router/Runner/PhpScript.php#L35-L53
webignition/website-rss-feed-finder
src/WebsiteRssFeedFinder.php
WebsiteRssFeedFinder.getLinkHref
private function getLinkHref(string $type): array { if (empty($this->feedUris[$type])) { $this->findFeedUrls(); } return array_values($this->feedUris[$type]); }
php
private function getLinkHref(string $type): array { if (empty($this->feedUris[$type])) { $this->findFeedUrls(); } return array_values($this->feedUris[$type]); }
[ "private", "function", "getLinkHref", "(", "string", "$", "type", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "feedUris", "[", "$", "type", "]", ")", ")", "{", "$", "this", "->", "findFeedUrls", "(", ")", ";", "}", "return", "array_values", "(", "$", "this", "->", "feedUris", "[", "$", "type", "]", ")", ";", "}" ]
@param string $type @return UriInterface[]
[ "@param", "string", "$type" ]
train
https://github.com/webignition/website-rss-feed-finder/blob/ec4a78937d7b81f450e20fc170e07786e1f4e857/src/WebsiteRssFeedFinder.php#L93-L100
Srokap/code_review
classes/CodeReview/Config.php
Config.elggExtract
private function elggExtract($key, array $array, $default = null, $strict = true) { if (!is_array($array)) { return $default; } if ($strict) { return (isset($array[$key])) ? $array[$key] : $default; } else { return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default; } }
php
private function elggExtract($key, array $array, $default = null, $strict = true) { if (!is_array($array)) { return $default; } if ($strict) { return (isset($array[$key])) ? $array[$key] : $default; } else { return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default; } }
[ "private", "function", "elggExtract", "(", "$", "key", ",", "array", "$", "array", ",", "$", "default", "=", "null", ",", "$", "strict", "=", "true", ")", "{", "if", "(", "!", "is_array", "(", "$", "array", ")", ")", "{", "return", "$", "default", ";", "}", "if", "(", "$", "strict", ")", "{", "return", "(", "isset", "(", "$", "array", "[", "$", "key", "]", ")", ")", "?", "$", "array", "[", "$", "key", "]", ":", "$", "default", ";", "}", "else", "{", "return", "(", "isset", "(", "$", "array", "[", "$", "key", "]", ")", "&&", "!", "empty", "(", "$", "array", "[", "$", "key", "]", ")", ")", "?", "$", "array", "[", "$", "key", "]", ":", "$", "default", ";", "}", "}" ]
@param $key @param array $array @param null $default @param bool $strict @return null Function is a part of Elgg framework with following license: Copyright (c) 2013. See COPYRIGHT.txt http://elgg.org/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[ "@param", "$key", "@param", "array", "$array", "@param", "null", "$default", "@param", "bool", "$strict", "@return", "null" ]
train
https://github.com/Srokap/code_review/blob/c79c619f99279cf15713b118ae19b0ef017db362/classes/CodeReview/Config.php#L146-L156
activecollab/databasestructure
src/Field/Composite/IsArchivedField.php
IsArchivedField.onAddedToType
public function onAddedToType(TypeInterface &$type) { parent::onAddedToType($type); $type->addTrait(IsArchivedInterface::class, IsArchivedInterfaceImplementation::class)->serialize($this->getName()); }
php
public function onAddedToType(TypeInterface &$type) { parent::onAddedToType($type); $type->addTrait(IsArchivedInterface::class, IsArchivedInterfaceImplementation::class)->serialize($this->getName()); }
[ "public", "function", "onAddedToType", "(", "TypeInterface", "&", "$", "type", ")", "{", "parent", "::", "onAddedToType", "(", "$", "type", ")", ";", "$", "type", "->", "addTrait", "(", "IsArchivedInterface", "::", "class", ",", "IsArchivedInterfaceImplementation", "::", "class", ")", "->", "serialize", "(", "$", "this", "->", "getName", "(", ")", ")", ";", "}" ]
Method that is called when field is added to a type. @param TypeInterface $type
[ "Method", "that", "is", "called", "when", "field", "is", "added", "to", "a", "type", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Field/Composite/IsArchivedField.php#L83-L88
FrenchFrogs/framework
src/Form/Element/Select.php
Select.setDependOn
public function setDependOn($selector, $url) { return $this->addAttribute('data-parent-url', $url) ->addAttribute('data-parent-selector', $selector) ->addAttribute('data-populate', function(Element $element){ return $element->getValue(); }) ->addClass('select-remote'); }
php
public function setDependOn($selector, $url) { return $this->addAttribute('data-parent-url', $url) ->addAttribute('data-parent-selector', $selector) ->addAttribute('data-populate', function(Element $element){ return $element->getValue(); }) ->addClass('select-remote'); }
[ "public", "function", "setDependOn", "(", "$", "selector", ",", "$", "url", ")", "{", "return", "$", "this", "->", "addAttribute", "(", "'data-parent-url'", ",", "$", "url", ")", "->", "addAttribute", "(", "'data-parent-selector'", ",", "$", "selector", ")", "->", "addAttribute", "(", "'data-populate'", ",", "function", "(", "Element", "$", "element", ")", "{", "return", "$", "element", "->", "getValue", "(", ")", ";", "}", ")", "->", "addClass", "(", "'select-remote'", ")", ";", "}" ]
Set Options from parent selection @param $selector @param $url @return $this
[ "Set", "Options", "from", "parent", "selection" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Form/Element/Select.php#L135-L143
ericpoe/haystack
src/HArray.php
HArray.toHString
public function toHString($glue = '') { if (empty($this->arr)) { return new HString(); } $str = new ArrayToString($this->arr, $glue); return new HString($str->toString()); }
php
public function toHString($glue = '') { if (empty($this->arr)) { return new HString(); } $str = new ArrayToString($this->arr, $glue); return new HString($str->toString()); }
[ "public", "function", "toHString", "(", "$", "glue", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "arr", ")", ")", "{", "return", "new", "HString", "(", ")", ";", "}", "$", "str", "=", "new", "ArrayToString", "(", "$", "this", "->", "arr", ",", "$", "glue", ")", ";", "return", "new", "HString", "(", "$", "str", "->", "toString", "(", ")", ")", ";", "}" ]
Alias to PHP function `implode` @param string $glue - defaults to an empty string @return HString
[ "Alias", "to", "PHP", "function", "implode" ]
train
https://github.com/ericpoe/haystack/blob/92c9ec4698fd013c1465efa6d49bc844a5869be0/src/HArray.php#L61-L69
ericpoe/haystack
src/HArray.php
HArray.insert
public function insert($value, $key = null) { $answer = new HArrayInsert($this); return new static($answer->insert($value, $key)); }
php
public function insert($value, $key = null) { $answer = new HArrayInsert($this); return new static($answer->insert($value, $key)); }
[ "public", "function", "insert", "(", "$", "value", ",", "$", "key", "=", "null", ")", "{", "$", "answer", "=", "new", "HArrayInsert", "(", "$", "this", ")", ";", "return", "new", "static", "(", "$", "answer", "->", "insert", "(", "$", "value", ",", "$", "key", ")", ")", ";", "}" ]
@inheritdoc @param mixed $value @param int|null $key @return HArray @throws \InvalidArgumentException
[ "@inheritdoc" ]
train
https://github.com/ericpoe/haystack/blob/92c9ec4698fd013c1465efa6d49bc844a5869be0/src/HArray.php#L117-L121
ericpoe/haystack
src/HArray.php
HArray.slice
public function slice($start, $length = null) { $answer = new HArraySlice($this); return new static($answer->slice($start, $length)); }
php
public function slice($start, $length = null) { $answer = new HArraySlice($this); return new static($answer->slice($start, $length)); }
[ "public", "function", "slice", "(", "$", "start", ",", "$", "length", "=", "null", ")", "{", "$", "answer", "=", "new", "HArraySlice", "(", "$", "this", ")", ";", "return", "new", "static", "(", "$", "answer", "->", "slice", "(", "$", "start", ",", "$", "length", ")", ")", ";", "}" ]
@inheritdoc @param int $start @param int $length @return HArray @throws \InvalidArgumentException
[ "@inheritdoc" ]
train
https://github.com/ericpoe/haystack/blob/92c9ec4698fd013c1465efa6d49bc844a5869be0/src/HArray.php#L144-L148
ericpoe/haystack
src/HArray.php
HArray.map
public function map(callable $func) { $containers = array_slice(func_get_args(), 1); // remove `$func` if (empty($containers)) { return new static((new HaystackMap($this))->map($func)); } return new static((new HaystackMap($this))->map($func, $containers)); }
php
public function map(callable $func) { $containers = array_slice(func_get_args(), 1); // remove `$func` if (empty($containers)) { return new static((new HaystackMap($this))->map($func)); } return new static((new HaystackMap($this))->map($func, $containers)); }
[ "public", "function", "map", "(", "callable", "$", "func", ")", "{", "$", "containers", "=", "array_slice", "(", "func_get_args", "(", ")", ",", "1", ")", ";", "// remove `$func`", "if", "(", "empty", "(", "$", "containers", ")", ")", "{", "return", "new", "static", "(", "(", "new", "HaystackMap", "(", "$", "this", ")", ")", "->", "map", "(", "$", "func", ")", ")", ";", "}", "return", "new", "static", "(", "(", "new", "HaystackMap", "(", "$", "this", ")", ")", "->", "map", "(", "$", "func", ",", "$", "containers", ")", ")", ";", "}" ]
@inheritdoc @param callable $func @return HArray
[ "@inheritdoc" ]
train
https://github.com/ericpoe/haystack/blob/92c9ec4698fd013c1465efa6d49bc844a5869be0/src/HArray.php#L156-L165
ericpoe/haystack
src/HArray.php
HArray.filter
public function filter(callable $func = null, $flag = null) { $answer = new Filter($this); return new static($answer->filter($func, $flag)); }
php
public function filter(callable $func = null, $flag = null) { $answer = new Filter($this); return new static($answer->filter($func, $flag)); }
[ "public", "function", "filter", "(", "callable", "$", "func", "=", "null", ",", "$", "flag", "=", "null", ")", "{", "$", "answer", "=", "new", "Filter", "(", "$", "this", ")", ";", "return", "new", "static", "(", "$", "answer", "->", "filter", "(", "$", "func", ",", "$", "flag", ")", ")", ";", "}" ]
@inheritdoc @param callable $func - If no callback is supplied, all entries of container equal to FALSE will be removed. @param null $flag - Flag determining what arguments are sent to callback - USE_KEY - pass key as the only argument to callback instead of the value - USE_BOTH - pass both value and key as arguments to callback instead of the value @return HArray @throws \InvalidArgumentException
[ "@inheritdoc" ]
train
https://github.com/ericpoe/haystack/blob/92c9ec4698fd013c1465efa6d49bc844a5869be0/src/HArray.php#L192-L196
ericpoe/haystack
src/HArray.php
HArray.reduce
public function reduce(callable $func, $initial = null) { $answer = new HaystackReduce($this->arr); return $answer->reduce($func, $initial); }
php
public function reduce(callable $func, $initial = null) { $answer = new HaystackReduce($this->arr); return $answer->reduce($func, $initial); }
[ "public", "function", "reduce", "(", "callable", "$", "func", ",", "$", "initial", "=", "null", ")", "{", "$", "answer", "=", "new", "HaystackReduce", "(", "$", "this", "->", "arr", ")", ";", "return", "$", "answer", "->", "reduce", "(", "$", "func", ",", "$", "initial", ")", ";", "}" ]
@inheritdoc @param callable $func @param mixed|null $initial @return bool|float|int|HString|HArray
[ "@inheritdoc" ]
train
https://github.com/ericpoe/haystack/blob/92c9ec4698fd013c1465efa6d49bc844a5869be0/src/HArray.php#L205-L209
acasademont/wurfl
WURFL/Handlers/FirefoxOSHandler.php
WURFL_Handlers_FirefoxOSHandler.getFirefoxOSVersion
public static function getFirefoxOSVersion($ua) { // Find Firefox Browser/Gecko version if (preg_match('#\brv:(\d+\.\d+)#', $ua, $matches) && array_key_exists($matches[1], self::$firefoxOSMap)) { return self::$firefoxOSMap[$matches[1]]; } // Set appropriate default values if not in OS mapping if (strpos($ua, 'Tablet') !== false) { // Firefox OS 1.3 is the lowest version of Firefox OS to have a tablet WURFL ID return "1.3"; } return "1.0"; }
php
public static function getFirefoxOSVersion($ua) { // Find Firefox Browser/Gecko version if (preg_match('#\brv:(\d+\.\d+)#', $ua, $matches) && array_key_exists($matches[1], self::$firefoxOSMap)) { return self::$firefoxOSMap[$matches[1]]; } // Set appropriate default values if not in OS mapping if (strpos($ua, 'Tablet') !== false) { // Firefox OS 1.3 is the lowest version of Firefox OS to have a tablet WURFL ID return "1.3"; } return "1.0"; }
[ "public", "static", "function", "getFirefoxOSVersion", "(", "$", "ua", ")", "{", "// Find Firefox Browser/Gecko version", "if", "(", "preg_match", "(", "'#\\brv:(\\d+\\.\\d+)#'", ",", "$", "ua", ",", "$", "matches", ")", "&&", "array_key_exists", "(", "$", "matches", "[", "1", "]", ",", "self", "::", "$", "firefoxOSMap", ")", ")", "{", "return", "self", "::", "$", "firefoxOSMap", "[", "$", "matches", "[", "1", "]", "]", ";", "}", "// Set appropriate default values if not in OS mapping", "if", "(", "strpos", "(", "$", "ua", ",", "'Tablet'", ")", "!==", "false", ")", "{", "// Firefox OS 1.3 is the lowest version of Firefox OS to have a tablet WURFL ID", "return", "\"1.3\"", ";", "}", "return", "\"1.0\"", ";", "}" ]
Function to extract Firefox OS version from Gecko/Firefox Browser version in the User-Agent
[ "Function", "to", "extract", "Firefox", "OS", "version", "from", "Gecko", "/", "Firefox", "Browser", "version", "in", "the", "User", "-", "Agent" ]
train
https://github.com/acasademont/wurfl/blob/0f4fb6e06b452ba95ad1d15e7d8226d0974b60c2/WURFL/Handlers/FirefoxOSHandler.php#L110-L124
crossjoin/Css
src/Crossjoin/Css/Format/Rule/AtFontFace/FontFaceRule.php
FontFaceRule.addDeclaration
public function addDeclaration(DeclarationAbstract $declaration) { if ($declaration instanceof FontFaceDeclaration) { $this->declarations[] = $declaration; } else { throw new \InvalidArgumentException( "Invalid declaration instance. Instance of 'FontFaceDeclaration' expected." ); } return $this; }
php
public function addDeclaration(DeclarationAbstract $declaration) { if ($declaration instanceof FontFaceDeclaration) { $this->declarations[] = $declaration; } else { throw new \InvalidArgumentException( "Invalid declaration instance. Instance of 'FontFaceDeclaration' expected." ); } return $this; }
[ "public", "function", "addDeclaration", "(", "DeclarationAbstract", "$", "declaration", ")", "{", "if", "(", "$", "declaration", "instanceof", "FontFaceDeclaration", ")", "{", "$", "this", "->", "declarations", "[", "]", "=", "$", "declaration", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid declaration instance. Instance of 'FontFaceDeclaration' expected.\"", ")", ";", "}", "return", "$", "this", ";", "}" ]
Adds a declaration to the rule. @param FontFaceDeclaration $declaration @return $this
[ "Adds", "a", "declaration", "to", "the", "rule", "." ]
train
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/AtFontFace/FontFaceRule.php#L36-L47
FrenchFrogs/framework
src/Table/Table/Pagination.php
Pagination.paginate
public function paginate(array $params) { // page if (isset($params[$this->getParamPage()])) { $this->setPage($params[$this->getParamPage()]); } return $this; }
php
public function paginate(array $params) { // page if (isset($params[$this->getParamPage()])) { $this->setPage($params[$this->getParamPage()]); } return $this; }
[ "public", "function", "paginate", "(", "array", "$", "params", ")", "{", "// page", "if", "(", "isset", "(", "$", "params", "[", "$", "this", "->", "getParamPage", "(", ")", "]", ")", ")", "{", "$", "this", "->", "setPage", "(", "$", "params", "[", "$", "this", "->", "getParamPage", "(", ")", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Fast pagination setup @param array $params @return $this
[ "Fast", "pagination", "setup" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Table/Table/Pagination.php#L213-L222
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.getTreeSelectList
public function getTreeSelectList(array $list, $root = 0) { $list = ArrayHelper::listToTree($list, $this->pkField, $this->parentField, '_child', $root); $list = $this->_toFormatTree($list, 0); return $this->buildTreeOptionsToArray($list); }
php
public function getTreeSelectList(array $list, $root = 0) { $list = ArrayHelper::listToTree($list, $this->pkField, $this->parentField, '_child', $root); $list = $this->_toFormatTree($list, 0); return $this->buildTreeOptionsToArray($list); }
[ "public", "function", "getTreeSelectList", "(", "array", "$", "list", ",", "$", "root", "=", "0", ")", "{", "$", "list", "=", "ArrayHelper", "::", "listToTree", "(", "$", "list", ",", "$", "this", "->", "pkField", ",", "$", "this", "->", "parentField", ",", "'_child'", ",", "$", "root", ")", ";", "$", "list", "=", "$", "this", "->", "_toFormatTree", "(", "$", "list", ",", "0", ")", ";", "return", "$", "this", "->", "buildTreeOptionsToArray", "(", "$", "list", ")", ";", "}" ]
获取树型下拉菜单选项列表 @param array $list 菜单数据 @param integer $root 顶级菜单数值,默认为`0`,表示显示到最顶级菜单 @return array
[ "获取树型下拉菜单选项列表" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L102-L108
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.buildTreeOptionsToArray
protected function buildTreeOptionsToArray($list) { $found = false; $options = []; // 模型数据存在时,排除自身选项 /** @var self $model */ $model = !empty($this->owner->{$this->pkField}) ? $this->owner : null; foreach ($list as $row) { if ($model != null) { // 排除自身选项 if ($model[$this->showPkField] == $row[$this->showPkField]) { $model->level = $row['level']; $found = true; continue; } // 排除归属自身的子类选项 if ($found) { if ($row['level'] > $model->level) { continue; } else { $found = false; } } } $options[$row[$this->showPkField]] = $row[$this->showTitleField]; } return $options; }
php
protected function buildTreeOptionsToArray($list) { $found = false; $options = []; // 模型数据存在时,排除自身选项 /** @var self $model */ $model = !empty($this->owner->{$this->pkField}) ? $this->owner : null; foreach ($list as $row) { if ($model != null) { // 排除自身选项 if ($model[$this->showPkField] == $row[$this->showPkField]) { $model->level = $row['level']; $found = true; continue; } // 排除归属自身的子类选项 if ($found) { if ($row['level'] > $model->level) { continue; } else { $found = false; } } } $options[$row[$this->showPkField]] = $row[$this->showTitleField]; } return $options; }
[ "protected", "function", "buildTreeOptionsToArray", "(", "$", "list", ")", "{", "$", "found", "=", "false", ";", "$", "options", "=", "[", "]", ";", "// 模型数据存在时,排除自身选项", "/** @var self $model */", "$", "model", "=", "!", "empty", "(", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "pkField", "}", ")", "?", "$", "this", "->", "owner", ":", "null", ";", "foreach", "(", "$", "list", "as", "$", "row", ")", "{", "if", "(", "$", "model", "!=", "null", ")", "{", "// 排除自身选项", "if", "(", "$", "model", "[", "$", "this", "->", "showPkField", "]", "==", "$", "row", "[", "$", "this", "->", "showPkField", "]", ")", "{", "$", "model", "->", "level", "=", "$", "row", "[", "'level'", "]", ";", "$", "found", "=", "true", ";", "continue", ";", "}", "// 排除归属自身的子类选项", "if", "(", "$", "found", ")", "{", "if", "(", "$", "row", "[", "'level'", "]", ">", "$", "model", "->", "level", ")", "{", "continue", ";", "}", "else", "{", "$", "found", "=", "false", ";", "}", "}", "}", "$", "options", "[", "$", "row", "[", "$", "this", "->", "showPkField", "]", "]", "=", "$", "row", "[", "$", "this", "->", "showTitleField", "]", ";", "}", "return", "$", "options", ";", "}" ]
生成树型下拉选项数据 @param array $list 菜单数据 @return array
[ "生成树型下拉选项数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L117-L146
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior._toFormatTree
private function _toFormatTree($list, $level = 0) { $formatTree = []; foreach ($list as $val) { $tmp_str = str_repeat($this->tabSize, $level); $tmp_str .= "└&nbsp;"; $val['level'] = intval($level); $val[$this->showTitleField] = $level == 0 ? $val[$this->showTitleField] : $tmp_str . $val[$this->showTitleField]; if (!array_key_exists('_child', $val)) { array_push($formatTree, $val); } else { $tmp_ary = $val['_child']; unset($val['_child']); array_push($formatTree, $val); $formatTree = array_merge($formatTree, $this->_toFormatTree($tmp_ary, $level + 1)); } } return $formatTree; }
php
private function _toFormatTree($list, $level = 0) { $formatTree = []; foreach ($list as $val) { $tmp_str = str_repeat($this->tabSize, $level); $tmp_str .= "└&nbsp;"; $val['level'] = intval($level); $val[$this->showTitleField] = $level == 0 ? $val[$this->showTitleField] : $tmp_str . $val[$this->showTitleField]; if (!array_key_exists('_child', $val)) { array_push($formatTree, $val); } else { $tmp_ary = $val['_child']; unset($val['_child']); array_push($formatTree, $val); $formatTree = array_merge($formatTree, $this->_toFormatTree($tmp_ary, $level + 1)); } } return $formatTree; }
[ "private", "function", "_toFormatTree", "(", "$", "list", ",", "$", "level", "=", "0", ")", "{", "$", "formatTree", "=", "[", "]", ";", "foreach", "(", "$", "list", "as", "$", "val", ")", "{", "$", "tmp_str", "=", "str_repeat", "(", "$", "this", "->", "tabSize", ",", "$", "level", ")", ";", "$", "tmp_str", ".=", "\"└&nbsp;\";", "", "$", "val", "[", "'level'", "]", "=", "intval", "(", "$", "level", ")", ";", "$", "val", "[", "$", "this", "->", "showTitleField", "]", "=", "$", "level", "==", "0", "?", "$", "val", "[", "$", "this", "->", "showTitleField", "]", ":", "$", "tmp_str", ".", "$", "val", "[", "$", "this", "->", "showTitleField", "]", ";", "if", "(", "!", "array_key_exists", "(", "'_child'", ",", "$", "val", ")", ")", "{", "array_push", "(", "$", "formatTree", ",", "$", "val", ")", ";", "}", "else", "{", "$", "tmp_ary", "=", "$", "val", "[", "'_child'", "]", ";", "unset", "(", "$", "val", "[", "'_child'", "]", ")", ";", "array_push", "(", "$", "formatTree", ",", "$", "val", ")", ";", "$", "formatTree", "=", "array_merge", "(", "$", "formatTree", ",", "$", "this", "->", "_toFormatTree", "(", "$", "tmp_ary", ",", "$", "level", "+", "1", ")", ")", ";", "}", "}", "return", "$", "formatTree", ";", "}" ]
格式化菜单列表数据 @param array $list @param integer $level @return array
[ "格式化菜单列表数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L156-L176
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.getBreadcrumbs
public function getBreadcrumbs($currentPid = 0, $defaultLabel = '列表', $url = '', $urlParams = [], $appendToTop = [], $append = []) { /** @var \yii\db\ActiveRecord $model */ $model = $this->owner; // 顶级面包屑 $breadcrumbs[] = $defaultLabel; // 非顶级数据则获取该值的所有父级数据 if (!empty($currentPid)) { if ($model->{$this->pkField} == $currentPid) { $self = $model; } else { /** @var self $self 当前`$currentPid`的模型数据 */ $self = $model::find()->select([ $this->pkField, $this->showTitleField, $this->parentField, ])->where([$this->pkField => $currentPid])->one(); } // 当前模型数据的所有父级数据 $parentIds = $self->getParentIds(); if (!empty($parentIds)) { $parents = $model::find()->select([ $this->pkField, $this->showTitleField, $this->parentField, ])->where([ $this->pkField => $parentIds, ])->asArray()->all(); $parents = ArrayHelper::listToTree($parents, $this->pkField, $this->parentField, '_child'); // 所有的父级面包屑 $breadcrumbs = ArrayHelper::merge($breadcrumbs, $this->_toFormatBreadcrumbs($parents)); } // 包含自身面包屑 $breadcrumbs[$self->{$this->pkField}] = $self->{$this->showTitleField}; } // 格式化面包屑 foreach ($breadcrumbs as $id => &$title) { $arr = []; $arr['label'] = $title; if ($currentPid != $id || $append) { $arr['url'][] = $url; $arr['url'][$this->breadcrumbParentParam] = $id ?: null; if ($urlParams) { $arr['url'] = ArrayHelper::merge($urlParams, $arr['url']); } } $title = $arr; } // 添加自定义面包屑在已有面包屑后面 if ($append) { $breadcrumbs = ArrayHelper::merge($breadcrumbs, $append); } // 添加自定义面包屑在所有面包屑前端 if ($appendToTop) { $breadcrumbs = ArrayHelper::merge($appendToTop, $breadcrumbs); } return $breadcrumbs; }
php
public function getBreadcrumbs($currentPid = 0, $defaultLabel = '列表', $url = '', $urlParams = [], $appendToTop = [], $append = []) { /** @var \yii\db\ActiveRecord $model */ $model = $this->owner; // 顶级面包屑 $breadcrumbs[] = $defaultLabel; // 非顶级数据则获取该值的所有父级数据 if (!empty($currentPid)) { if ($model->{$this->pkField} == $currentPid) { $self = $model; } else { /** @var self $self 当前`$currentPid`的模型数据 */ $self = $model::find()->select([ $this->pkField, $this->showTitleField, $this->parentField, ])->where([$this->pkField => $currentPid])->one(); } // 当前模型数据的所有父级数据 $parentIds = $self->getParentIds(); if (!empty($parentIds)) { $parents = $model::find()->select([ $this->pkField, $this->showTitleField, $this->parentField, ])->where([ $this->pkField => $parentIds, ])->asArray()->all(); $parents = ArrayHelper::listToTree($parents, $this->pkField, $this->parentField, '_child'); // 所有的父级面包屑 $breadcrumbs = ArrayHelper::merge($breadcrumbs, $this->_toFormatBreadcrumbs($parents)); } // 包含自身面包屑 $breadcrumbs[$self->{$this->pkField}] = $self->{$this->showTitleField}; } // 格式化面包屑 foreach ($breadcrumbs as $id => &$title) { $arr = []; $arr['label'] = $title; if ($currentPid != $id || $append) { $arr['url'][] = $url; $arr['url'][$this->breadcrumbParentParam] = $id ?: null; if ($urlParams) { $arr['url'] = ArrayHelper::merge($urlParams, $arr['url']); } } $title = $arr; } // 添加自定义面包屑在已有面包屑后面 if ($append) { $breadcrumbs = ArrayHelper::merge($breadcrumbs, $append); } // 添加自定义面包屑在所有面包屑前端 if ($appendToTop) { $breadcrumbs = ArrayHelper::merge($appendToTop, $breadcrumbs); } return $breadcrumbs; }
[ "public", "function", "getBreadcrumbs", "(", "$", "currentPid", "=", "0", ",", "$", "defaultLabel", "=", "'列表', $u", "r", " ", "= '", ",", "$u", "r", "P", "arams = [", ",", "$", "a", "p", "e", "ndToTop = [", ",", "$", "a", "p", "e", "nd = [", ")", "", "", "", "{", "/** @var \\yii\\db\\ActiveRecord $model */", "$", "model", "=", "$", "this", "->", "owner", ";", "// 顶级面包屑", "$", "breadcrumbs", "[", "]", "=", "$", "defaultLabel", ";", "// 非顶级数据则获取该值的所有父级数据", "if", "(", "!", "empty", "(", "$", "currentPid", ")", ")", "{", "if", "(", "$", "model", "->", "{", "$", "this", "->", "pkField", "}", "==", "$", "currentPid", ")", "{", "$", "self", "=", "$", "model", ";", "}", "else", "{", "/** @var self $self 当前`$currentPid`的模型数据 */", "$", "self", "=", "$", "model", "::", "find", "(", ")", "->", "select", "(", "[", "$", "this", "->", "pkField", ",", "$", "this", "->", "showTitleField", ",", "$", "this", "->", "parentField", ",", "]", ")", "->", "where", "(", "[", "$", "this", "->", "pkField", "=>", "$", "currentPid", "]", ")", "->", "one", "(", ")", ";", "}", "// 当前模型数据的所有父级数据", "$", "parentIds", "=", "$", "self", "->", "getParentIds", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "parentIds", ")", ")", "{", "$", "parents", "=", "$", "model", "::", "find", "(", ")", "->", "select", "(", "[", "$", "this", "->", "pkField", ",", "$", "this", "->", "showTitleField", ",", "$", "this", "->", "parentField", ",", "]", ")", "->", "where", "(", "[", "$", "this", "->", "pkField", "=>", "$", "parentIds", ",", "]", ")", "->", "asArray", "(", ")", "->", "all", "(", ")", ";", "$", "parents", "=", "ArrayHelper", "::", "listToTree", "(", "$", "parents", ",", "$", "this", "->", "pkField", ",", "$", "this", "->", "parentField", ",", "'_child'", ")", ";", "// 所有的父级面包屑", "$", "breadcrumbs", "=", "ArrayHelper", "::", "merge", "(", "$", "breadcrumbs", ",", "$", "this", "->", "_toFormatBreadcrumbs", "(", "$", "parents", ")", ")", ";", "}", "// 包含自身面包屑", "$", "breadcrumbs", "[", "$", "self", "->", "{", "$", "this", "->", "pkField", "}", "]", "=", "$", "self", "->", "{", "$", "this", "->", "showTitleField", "}", ";", "}", "// 格式化面包屑", "foreach", "(", "$", "breadcrumbs", "as", "$", "id", "=>", "&", "$", "title", ")", "{", "$", "arr", "=", "[", "]", ";", "$", "arr", "[", "'label'", "]", "=", "$", "title", ";", "if", "(", "$", "currentPid", "!=", "$", "id", "||", "$", "append", ")", "{", "$", "arr", "[", "'url'", "]", "[", "]", "=", "$", "url", ";", "$", "arr", "[", "'url'", "]", "[", "$", "this", "->", "breadcrumbParentParam", "]", "=", "$", "id", "?", ":", "null", ";", "if", "(", "$", "urlParams", ")", "{", "$", "arr", "[", "'url'", "]", "=", "ArrayHelper", "::", "merge", "(", "$", "urlParams", ",", "$", "arr", "[", "'url'", "]", ")", ";", "}", "}", "$", "title", "=", "$", "arr", ";", "}", "// 添加自定义面包屑在已有面包屑后面", "if", "(", "$", "append", ")", "{", "$", "breadcrumbs", "=", "ArrayHelper", "::", "merge", "(", "$", "breadcrumbs", ",", "$", "append", ")", ";", "}", "// 添加自定义面包屑在所有面包屑前端", "if", "(", "$", "appendToTop", ")", "{", "$", "breadcrumbs", "=", "ArrayHelper", "::", "merge", "(", "$", "appendToTop", ",", "$", "breadcrumbs", ")", ";", "}", "return", "$", "breadcrumbs", ";", "}" ]
获取面包屑导航 @param int $currentPid 当前父级ID @param string $defaultLabel 默认的顶级面包屑标题 @param string $url 面包屑基础url @param array $urlParams 面包屑url参数 @param array $appendToTop 自定义添加面包屑在所有数据之前 @param array $append 添加自定义面包屑在已有面包屑后面 @return array ['label', 'url']
[ "获取面包屑导航" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L190-L252
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior._toFormatBreadcrumbs
private function _toFormatBreadcrumbs($list) { $format = []; foreach ($list as $val) { $format[$val[$this->pkField]] = $val[$this->showTitleField]; if (array_key_exists('_child', $val)) { $format = ArrayHelper::merge($format, $this->_toFormatBreadcrumbs($val['_child'])); } } return $format; }
php
private function _toFormatBreadcrumbs($list) { $format = []; foreach ($list as $val) { $format[$val[$this->pkField]] = $val[$this->showTitleField]; if (array_key_exists('_child', $val)) { $format = ArrayHelper::merge($format, $this->_toFormatBreadcrumbs($val['_child'])); } } return $format; }
[ "private", "function", "_toFormatBreadcrumbs", "(", "$", "list", ")", "{", "$", "format", "=", "[", "]", ";", "foreach", "(", "$", "list", "as", "$", "val", ")", "{", "$", "format", "[", "$", "val", "[", "$", "this", "->", "pkField", "]", "]", "=", "$", "val", "[", "$", "this", "->", "showTitleField", "]", ";", "if", "(", "array_key_exists", "(", "'_child'", ",", "$", "val", ")", ")", "{", "$", "format", "=", "ArrayHelper", "::", "merge", "(", "$", "format", ",", "$", "this", "->", "_toFormatBreadcrumbs", "(", "$", "val", "[", "'_child'", "]", ")", ")", ";", "}", "}", "return", "$", "format", ";", "}" ]
格式化面包屑导航数据 @param array $list @return array
[ "格式化面包屑导航数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L261-L272
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.getParentIds
public function getParentIds($rootId = 0) { if ($this->_parentIds === null) { // 增加对模型内置[[getAll()]]方法的支持,可避免多次查询数据库,优化性能 if ($this->owner->hasMethod('getAll')) { $this->_parentIds = $this->getParentIdsInternal($rootId); } else { $this->_parentIds = Tree::getParentIds($this->owner, 0, $this->pkField, $this->parentField, $rootId); } } return $this->_parentIds; }
php
public function getParentIds($rootId = 0) { if ($this->_parentIds === null) { // 增加对模型内置[[getAll()]]方法的支持,可避免多次查询数据库,优化性能 if ($this->owner->hasMethod('getAll')) { $this->_parentIds = $this->getParentIdsInternal($rootId); } else { $this->_parentIds = Tree::getParentIds($this->owner, 0, $this->pkField, $this->parentField, $rootId); } } return $this->_parentIds; }
[ "public", "function", "getParentIds", "(", "$", "rootId", "=", "0", ")", "{", "if", "(", "$", "this", "->", "_parentIds", "===", "null", ")", "{", "// 增加对模型内置[[getAll()]]方法的支持,可避免多次查询数据库,优化性能", "if", "(", "$", "this", "->", "owner", "->", "hasMethod", "(", "'getAll'", ")", ")", "{", "$", "this", "->", "_parentIds", "=", "$", "this", "->", "getParentIdsInternal", "(", "$", "rootId", ")", ";", "}", "else", "{", "$", "this", "->", "_parentIds", "=", "Tree", "::", "getParentIds", "(", "$", "this", "->", "owner", ",", "0", ",", "$", "this", "->", "pkField", ",", "$", "this", "->", "parentField", ",", "$", "rootId", ")", ";", "}", "}", "return", "$", "this", "->", "_parentIds", ";", "}" ]
获取当前模型所有父级ID数据 @param integer $rootId 顶级ID,默认为`0`,返回的父级ID数据获取到此顶级ID后则停止获取 @return array @throws NotFoundHttpException @throws InvalidConfigException
[ "获取当前模型所有父级ID数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L288-L300
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.getParentIdsInternal
protected function getParentIdsInternal($rootId) { $model = $this->owner; if (empty($model->{$this->pkField})) { $method = __METHOD__ . '()'; throw new NotFoundHttpException("{$model->className()}()必须先通过`{$this->pkField}`主键获取相关数据后才能执行操作:{$method}"); } $_parentIds = []; $all = $this->owner->getAll(); while (!empty($model)) { $model[$this->parentField] = (int)$model[$this->parentField]; if ($model[$this->parentField] !== $rootId) { array_unshift($_parentIds, $model[$this->parentField]); $model = ArrayHelper::listSearch($all, [ $this->pkField => $model[$this->parentField], ]); $model = isset($model[0]) ? $model[0] : []; } else { $model = []; } } return $_parentIds; }
php
protected function getParentIdsInternal($rootId) { $model = $this->owner; if (empty($model->{$this->pkField})) { $method = __METHOD__ . '()'; throw new NotFoundHttpException("{$model->className()}()必须先通过`{$this->pkField}`主键获取相关数据后才能执行操作:{$method}"); } $_parentIds = []; $all = $this->owner->getAll(); while (!empty($model)) { $model[$this->parentField] = (int)$model[$this->parentField]; if ($model[$this->parentField] !== $rootId) { array_unshift($_parentIds, $model[$this->parentField]); $model = ArrayHelper::listSearch($all, [ $this->pkField => $model[$this->parentField], ]); $model = isset($model[0]) ? $model[0] : []; } else { $model = []; } } return $_parentIds; }
[ "protected", "function", "getParentIdsInternal", "(", "$", "rootId", ")", "{", "$", "model", "=", "$", "this", "->", "owner", ";", "if", "(", "empty", "(", "$", "model", "->", "{", "$", "this", "->", "pkField", "}", ")", ")", "{", "$", "method", "=", "__METHOD__", ".", "'()'", ";", "throw", "new", "NotFoundHttpException", "(", "\"{$model->className()}()必须先通过`{$this->pkField}`主键获取相关数据后才能执行操作:{$method}\");", "", "", "}", "$", "_parentIds", "=", "[", "]", ";", "$", "all", "=", "$", "this", "->", "owner", "->", "getAll", "(", ")", ";", "while", "(", "!", "empty", "(", "$", "model", ")", ")", "{", "$", "model", "[", "$", "this", "->", "parentField", "]", "=", "(", "int", ")", "$", "model", "[", "$", "this", "->", "parentField", "]", ";", "if", "(", "$", "model", "[", "$", "this", "->", "parentField", "]", "!==", "$", "rootId", ")", "{", "array_unshift", "(", "$", "_parentIds", ",", "$", "model", "[", "$", "this", "->", "parentField", "]", ")", ";", "$", "model", "=", "ArrayHelper", "::", "listSearch", "(", "$", "all", ",", "[", "$", "this", "->", "pkField", "=>", "$", "model", "[", "$", "this", "->", "parentField", "]", ",", "]", ")", ";", "$", "model", "=", "isset", "(", "$", "model", "[", "0", "]", ")", "?", "$", "model", "[", "0", "]", ":", "[", "]", ";", "}", "else", "{", "$", "model", "=", "[", "]", ";", "}", "}", "return", "$", "_parentIds", ";", "}" ]
获取缓存内的所有父级ID数据 @param integer $rootId 顶级ID,默认为`0`,返回的父级ID数据获取到此顶级ID后则停止获取 @return array @throws NotFoundHttpException
[ "获取缓存内的所有父级ID数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L310-L334
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.getChildrenIds
public function getChildrenIds() { if ($this->_childrenIds === null) { // 增加对模型内置[[getAll()]]方法的支持,可避免多次查询数据库,优化性能 if ($this->owner->hasMethod('getAll')) { $this->_childrenIds = $this->getChildrenIdsInternal(); } else { $this->_childrenIds = Tree::getChildrenIds($this->owner, 0, $this->pkField, $this->parentField); } } return $this->_childrenIds; }
php
public function getChildrenIds() { if ($this->_childrenIds === null) { // 增加对模型内置[[getAll()]]方法的支持,可避免多次查询数据库,优化性能 if ($this->owner->hasMethod('getAll')) { $this->_childrenIds = $this->getChildrenIdsInternal(); } else { $this->_childrenIds = Tree::getChildrenIds($this->owner, 0, $this->pkField, $this->parentField); } } return $this->_childrenIds; }
[ "public", "function", "getChildrenIds", "(", ")", "{", "if", "(", "$", "this", "->", "_childrenIds", "===", "null", ")", "{", "// 增加对模型内置[[getAll()]]方法的支持,可避免多次查询数据库,优化性能", "if", "(", "$", "this", "->", "owner", "->", "hasMethod", "(", "'getAll'", ")", ")", "{", "$", "this", "->", "_childrenIds", "=", "$", "this", "->", "getChildrenIdsInternal", "(", ")", ";", "}", "else", "{", "$", "this", "->", "_childrenIds", "=", "Tree", "::", "getChildrenIds", "(", "$", "this", "->", "owner", ",", "0", ",", "$", "this", "->", "pkField", ",", "$", "this", "->", "parentField", ")", ";", "}", "}", "return", "$", "this", "->", "_childrenIds", ";", "}" ]
获取当前模型所有子类ID数据 @return array @throws \yii\base\InvalidConfigException @throws \yii\web\NotFoundHttpException
[ "获取当前模型所有子类ID数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L348-L360
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.getChildrenIdsInternal
protected function getChildrenIdsInternal() { if (empty($this->owner->{$this->pkField})) { $method = __METHOD__ . '()'; throw new NotFoundHttpException("{$this->owner->className()}()必须先通过`{$this->pkField}`主键获取相关数据后才能执行操作:{$method}"); } $_childrenIds = []; if (method_exists($this, 'getAll')) { $all = $this->owner->getAll(); if ($all) { $children = ArrayHelper::listSearch($all, [ $this->parentField => $this->owner->{$this->pkField}, ]); while (count($children) > 0) { $first = array_shift($children); $_childrenIds[] = (int)$first[$this->pkField]; $next = ArrayHelper::listSearch($all, [ $this->parentField => $first[$this->pkField], ]); if (count($next) > 0) { $children = array_merge($children, $next); } } } } return $_childrenIds; }
php
protected function getChildrenIdsInternal() { if (empty($this->owner->{$this->pkField})) { $method = __METHOD__ . '()'; throw new NotFoundHttpException("{$this->owner->className()}()必须先通过`{$this->pkField}`主键获取相关数据后才能执行操作:{$method}"); } $_childrenIds = []; if (method_exists($this, 'getAll')) { $all = $this->owner->getAll(); if ($all) { $children = ArrayHelper::listSearch($all, [ $this->parentField => $this->owner->{$this->pkField}, ]); while (count($children) > 0) { $first = array_shift($children); $_childrenIds[] = (int)$first[$this->pkField]; $next = ArrayHelper::listSearch($all, [ $this->parentField => $first[$this->pkField], ]); if (count($next) > 0) { $children = array_merge($children, $next); } } } } return $_childrenIds; }
[ "protected", "function", "getChildrenIdsInternal", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "pkField", "}", ")", ")", "{", "$", "method", "=", "__METHOD__", ".", "'()'", ";", "throw", "new", "NotFoundHttpException", "(", "\"{$this->owner->className()}()必须先通过`{$this->pkField}`主键获取相关数据后才能执行操作:{$method}\");", "", "", "}", "$", "_childrenIds", "=", "[", "]", ";", "if", "(", "method_exists", "(", "$", "this", ",", "'getAll'", ")", ")", "{", "$", "all", "=", "$", "this", "->", "owner", "->", "getAll", "(", ")", ";", "if", "(", "$", "all", ")", "{", "$", "children", "=", "ArrayHelper", "::", "listSearch", "(", "$", "all", ",", "[", "$", "this", "->", "parentField", "=>", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "pkField", "}", ",", "]", ")", ";", "while", "(", "count", "(", "$", "children", ")", ">", "0", ")", "{", "$", "first", "=", "array_shift", "(", "$", "children", ")", ";", "$", "_childrenIds", "[", "]", "=", "(", "int", ")", "$", "first", "[", "$", "this", "->", "pkField", "]", ";", "$", "next", "=", "ArrayHelper", "::", "listSearch", "(", "$", "all", ",", "[", "$", "this", "->", "parentField", "=>", "$", "first", "[", "$", "this", "->", "pkField", "]", ",", "]", ")", ";", "if", "(", "count", "(", "$", "next", ")", ">", "0", ")", "{", "$", "children", "=", "array_merge", "(", "$", "children", ",", "$", "next", ")", ";", "}", "}", "}", "}", "return", "$", "_childrenIds", ";", "}" ]
获取缓存内的所有子类ID数据 @return array @throws NotFoundHttpException
[ "获取缓存内的所有子类ID数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L368-L397
Wonail/wocenter
behaviors/TreeBehavior.php
TreeBehavior.hasChildren
public function hasChildren($event) { if (!empty($this->getChildrenIds())) { $this->owner->message = '删除该数据前请删除或转移其下的子级数据'; $event->isValid = false; } }
php
public function hasChildren($event) { if (!empty($this->getChildrenIds())) { $this->owner->message = '删除该数据前请删除或转移其下的子级数据'; $event->isValid = false; } }
[ "public", "function", "hasChildren", "(", "$", "event", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "getChildrenIds", "(", ")", ")", ")", "{", "$", "this", "->", "owner", "->", "message", "=", "'删除该数据前请删除或转移其下的子级数据';", "", "$", "event", "->", "isValid", "=", "false", ";", "}", "}" ]
检测当前模型是否拥有子类数据 @param ModelEvent $event
[ "检测当前模型是否拥有子类数据" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/behaviors/TreeBehavior.php#L414-L420
huasituo/hstcms
src/Http/Middleware/ApiService.php
ApiService.handle
public function handle(Request $request, Closure $next) { $appid = $request->headers->get('appid') ? $request->headers->get('appid') : $request->get('appid'); if(!$appid) { return $this->message('Appid does not exist', '-1'); } $apps = hst_api_app(); if(!isset($apps[$appid]) || !$apps[$appid]) { return $this->message('Appid does not exist', '-2'); } $app = $apps[$appid]; if($app && $app['status']) { return $this->message('Appid A suspension of use', '-3'); } if(config('hstcms.apiSign')) { $sign = $request->get('sign'); if(!$sign) { return $this->message('Sign Error', '-4'); } $all = $request->all(); $checkSign = false; $HstcmsSign = new HstcmsSign(); $checkSign = $HstcmsSign->verifySign($all, $app['secret']); if(!$checkSign) { return $this->message('Sign Error', '-5'); } } $request->attributes->add(['apiAppInfo'=>$app]); //添加参数 return $next($request); }
php
public function handle(Request $request, Closure $next) { $appid = $request->headers->get('appid') ? $request->headers->get('appid') : $request->get('appid'); if(!$appid) { return $this->message('Appid does not exist', '-1'); } $apps = hst_api_app(); if(!isset($apps[$appid]) || !$apps[$appid]) { return $this->message('Appid does not exist', '-2'); } $app = $apps[$appid]; if($app && $app['status']) { return $this->message('Appid A suspension of use', '-3'); } if(config('hstcms.apiSign')) { $sign = $request->get('sign'); if(!$sign) { return $this->message('Sign Error', '-4'); } $all = $request->all(); $checkSign = false; $HstcmsSign = new HstcmsSign(); $checkSign = $HstcmsSign->verifySign($all, $app['secret']); if(!$checkSign) { return $this->message('Sign Error', '-5'); } } $request->attributes->add(['apiAppInfo'=>$app]); //添加参数 return $next($request); }
[ "public", "function", "handle", "(", "Request", "$", "request", ",", "Closure", "$", "next", ")", "{", "$", "appid", "=", "$", "request", "->", "headers", "->", "get", "(", "'appid'", ")", "?", "$", "request", "->", "headers", "->", "get", "(", "'appid'", ")", ":", "$", "request", "->", "get", "(", "'appid'", ")", ";", "if", "(", "!", "$", "appid", ")", "{", "return", "$", "this", "->", "message", "(", "'Appid does not exist'", ",", "'-1'", ")", ";", "}", "$", "apps", "=", "hst_api_app", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "apps", "[", "$", "appid", "]", ")", "||", "!", "$", "apps", "[", "$", "appid", "]", ")", "{", "return", "$", "this", "->", "message", "(", "'Appid does not exist'", ",", "'-2'", ")", ";", "}", "$", "app", "=", "$", "apps", "[", "$", "appid", "]", ";", "if", "(", "$", "app", "&&", "$", "app", "[", "'status'", "]", ")", "{", "return", "$", "this", "->", "message", "(", "'Appid A suspension of use'", ",", "'-3'", ")", ";", "}", "if", "(", "config", "(", "'hstcms.apiSign'", ")", ")", "{", "$", "sign", "=", "$", "request", "->", "get", "(", "'sign'", ")", ";", "if", "(", "!", "$", "sign", ")", "{", "return", "$", "this", "->", "message", "(", "'Sign Error'", ",", "'-4'", ")", ";", "}", "$", "all", "=", "$", "request", "->", "all", "(", ")", ";", "$", "checkSign", "=", "false", ";", "$", "HstcmsSign", "=", "new", "HstcmsSign", "(", ")", ";", "$", "checkSign", "=", "$", "HstcmsSign", "->", "verifySign", "(", "$", "all", ",", "$", "app", "[", "'secret'", "]", ")", ";", "if", "(", "!", "$", "checkSign", ")", "{", "return", "$", "this", "->", "message", "(", "'Sign Error'", ",", "'-5'", ")", ";", "}", "}", "$", "request", "->", "attributes", "->", "add", "(", "[", "'apiAppInfo'", "=>", "$", "app", "]", ")", ";", "//添加参数", "return", "$", "next", "(", "$", "request", ")", ";", "}" ]
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Http/Middleware/ApiService.php#L26-L55
stubbles/stubbles-webapp-core
src/main/php/WebApp.php
WebApp.run
public function run(): SendableResponse { $request = WebRequest::fromRawSource(); $response = new WebResponse($request); if ($response->isFixed()) { return $response; // http version of request not supported } try { $requestUri = $request->uri(); } catch (MalformedUri $mue) { $response->status()->badRequest(); return $response; } $this->configureRouting($this->routing); $uriResource = $this->routing->findResource($requestUri, $request->method()); if ($this->switchToHttps($request, $uriResource)) { $response->redirect($uriResource->httpsUri()); return $response; } try { if (!$uriResource->negotiateMimeType($request, $response)) { return $response; } $this->sessionHandshake($request, $response); if ($uriResource->applyPreInterceptors($request, $response)) { $response->write($uriResource->resolve($request, $response)); $uriResource->applyPostInterceptors($request, $response); } } catch (\Exception $e) { $this->injector->getInstance(ExceptionLogger::class)->log($e); $response->write($response->internalServerError($e->getMessage())); } return $response; }
php
public function run(): SendableResponse { $request = WebRequest::fromRawSource(); $response = new WebResponse($request); if ($response->isFixed()) { return $response; // http version of request not supported } try { $requestUri = $request->uri(); } catch (MalformedUri $mue) { $response->status()->badRequest(); return $response; } $this->configureRouting($this->routing); $uriResource = $this->routing->findResource($requestUri, $request->method()); if ($this->switchToHttps($request, $uriResource)) { $response->redirect($uriResource->httpsUri()); return $response; } try { if (!$uriResource->negotiateMimeType($request, $response)) { return $response; } $this->sessionHandshake($request, $response); if ($uriResource->applyPreInterceptors($request, $response)) { $response->write($uriResource->resolve($request, $response)); $uriResource->applyPostInterceptors($request, $response); } } catch (\Exception $e) { $this->injector->getInstance(ExceptionLogger::class)->log($e); $response->write($response->internalServerError($e->getMessage())); } return $response; }
[ "public", "function", "run", "(", ")", ":", "SendableResponse", "{", "$", "request", "=", "WebRequest", "::", "fromRawSource", "(", ")", ";", "$", "response", "=", "new", "WebResponse", "(", "$", "request", ")", ";", "if", "(", "$", "response", "->", "isFixed", "(", ")", ")", "{", "return", "$", "response", ";", "// http version of request not supported", "}", "try", "{", "$", "requestUri", "=", "$", "request", "->", "uri", "(", ")", ";", "}", "catch", "(", "MalformedUri", "$", "mue", ")", "{", "$", "response", "->", "status", "(", ")", "->", "badRequest", "(", ")", ";", "return", "$", "response", ";", "}", "$", "this", "->", "configureRouting", "(", "$", "this", "->", "routing", ")", ";", "$", "uriResource", "=", "$", "this", "->", "routing", "->", "findResource", "(", "$", "requestUri", ",", "$", "request", "->", "method", "(", ")", ")", ";", "if", "(", "$", "this", "->", "switchToHttps", "(", "$", "request", ",", "$", "uriResource", ")", ")", "{", "$", "response", "->", "redirect", "(", "$", "uriResource", "->", "httpsUri", "(", ")", ")", ";", "return", "$", "response", ";", "}", "try", "{", "if", "(", "!", "$", "uriResource", "->", "negotiateMimeType", "(", "$", "request", ",", "$", "response", ")", ")", "{", "return", "$", "response", ";", "}", "$", "this", "->", "sessionHandshake", "(", "$", "request", ",", "$", "response", ")", ";", "if", "(", "$", "uriResource", "->", "applyPreInterceptors", "(", "$", "request", ",", "$", "response", ")", ")", "{", "$", "response", "->", "write", "(", "$", "uriResource", "->", "resolve", "(", "$", "request", ",", "$", "response", ")", ")", ";", "$", "uriResource", "->", "applyPostInterceptors", "(", "$", "request", ",", "$", "response", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "injector", "->", "getInstance", "(", "ExceptionLogger", "::", "class", ")", "->", "log", "(", "$", "e", ")", ";", "$", "response", "->", "write", "(", "$", "response", "->", "internalServerError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ")", ";", "}", "return", "$", "response", ";", "}" ]
runs the application but does not send the response @return \stubbles\webapp\response\SendableResponse
[ "runs", "the", "application", "but", "does", "not", "send", "the", "response" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/WebApp.php#L58-L96
stubbles/stubbles-webapp-core
src/main/php/WebApp.php
WebApp.sessionHandshake
private function sessionHandshake(Request $request, Response $response) { $session = $this->createSession($request, $response); if (null !== $session) { $this->injector->setSession( $request->attachSession($session), Session::class ); } }
php
private function sessionHandshake(Request $request, Response $response) { $session = $this->createSession($request, $response); if (null !== $session) { $this->injector->setSession( $request->attachSession($session), Session::class ); } }
[ "private", "function", "sessionHandshake", "(", "Request", "$", "request", ",", "Response", "$", "response", ")", "{", "$", "session", "=", "$", "this", "->", "createSession", "(", "$", "request", ",", "$", "response", ")", ";", "if", "(", "null", "!==", "$", "session", ")", "{", "$", "this", "->", "injector", "->", "setSession", "(", "$", "request", "->", "attachSession", "(", "$", "session", ")", ",", "Session", "::", "class", ")", ";", "}", "}" ]
ensures session is present when created @param \stubbles\webapp\Request $request @param \stubbles\webapp\Response $response
[ "ensures", "session", "is", "present", "when", "created" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/WebApp.php#L104-L113
stubbles/stubbles-webapp-core
src/main/php/WebApp.php
WebApp.switchToHttps
protected function switchToHttps(Request $request, UriResource $uriResource): bool { return !$request->isSsl() && $uriResource->requiresHttps(); }
php
protected function switchToHttps(Request $request, UriResource $uriResource): bool { return !$request->isSsl() && $uriResource->requiresHttps(); }
[ "protected", "function", "switchToHttps", "(", "Request", "$", "request", ",", "UriResource", "$", "uriResource", ")", ":", "bool", "{", "return", "!", "$", "request", "->", "isSsl", "(", ")", "&&", "$", "uriResource", "->", "requiresHttps", "(", ")", ";", "}" ]
checks whether a switch to https must be made @param \stubbles\webapp\Request $request @param \stubbles\webapp\routing\UriResource $uriResource @return bool
[ "checks", "whether", "a", "switch", "to", "https", "must", "be", "made" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/WebApp.php#L135-L138
harp-orm/query
src/Compiler/Compiler.php
Compiler.humanize
public static function humanize($sql, array $parameters) { $parameters = array_map(__NAMESPACE__.'\Compiler::quoteValue', $parameters); return preg_replace_callback('/\?/', function () use (& $parameters) { return current(each($parameters)); }, $sql); }
php
public static function humanize($sql, array $parameters) { $parameters = array_map(__NAMESPACE__.'\Compiler::quoteValue', $parameters); return preg_replace_callback('/\?/', function () use (& $parameters) { return current(each($parameters)); }, $sql); }
[ "public", "static", "function", "humanize", "(", "$", "sql", ",", "array", "$", "parameters", ")", "{", "$", "parameters", "=", "array_map", "(", "__NAMESPACE__", ".", "'\\Compiler::quoteValue'", ",", "$", "parameters", ")", ";", "return", "preg_replace_callback", "(", "'/\\?/'", ",", "function", "(", ")", "use", "(", "&", "$", "parameters", ")", "{", "return", "current", "(", "each", "(", "$", "parameters", ")", ")", ";", "}", ",", "$", "sql", ")", ";", "}" ]
Replace placeholders with parameters @param string $sql @param array $parameters @return string
[ "Replace", "placeholders", "with", "parameters" ]
train
https://github.com/harp-orm/query/blob/98ce2468a0a31fe15ed3692bad32547bf6dbe41a/src/Compiler/Compiler.php#L127-L134
harp-orm/query
src/Compiler/Compiler.php
Compiler.parameters
public static function parameters(array $items) { $parameters = array(); $items = array_filter(Arr::flatten($items)); foreach ($items as $item) { $itemParams = $item->getParameters(); if ($itemParams !== null) { $parameters []= $itemParams; } } return Arr::flatten($parameters); }
php
public static function parameters(array $items) { $parameters = array(); $items = array_filter(Arr::flatten($items)); foreach ($items as $item) { $itemParams = $item->getParameters(); if ($itemParams !== null) { $parameters []= $itemParams; } } return Arr::flatten($parameters); }
[ "public", "static", "function", "parameters", "(", "array", "$", "items", ")", "{", "$", "parameters", "=", "array", "(", ")", ";", "$", "items", "=", "array_filter", "(", "Arr", "::", "flatten", "(", "$", "items", ")", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "itemParams", "=", "$", "item", "->", "getParameters", "(", ")", ";", "if", "(", "$", "itemParams", "!==", "null", ")", "{", "$", "parameters", "[", "]", "=", "$", "itemParams", ";", "}", "}", "return", "Arr", "::", "flatten", "(", "$", "parameters", ")", ";", "}" ]
Get parameters from Parametrised objects @param array $items @return array
[ "Get", "parameters", "from", "Parametrised", "objects" ]
train
https://github.com/harp-orm/query/blob/98ce2468a0a31fe15ed3692bad32547bf6dbe41a/src/Compiler/Compiler.php#L157-L171
RinkAttendant6/JsonI18n
src/ResourceBuilder.php
ResourceBuilder.fromString
public static function fromString(string $input, string $locale): Resource { $data = json_decode($input, true); if (json_last_error() !== \JSON_ERROR_NONE) { if (function_exists('json_last_error_msg')) { throw new \InvalidArgumentException(json_last_error_msg(), json_last_error()); } throw new \InvalidArgumentException("Error parsing JSON.", json_last_error()); } return static::fromArray($data, $locale); }
php
public static function fromString(string $input, string $locale): Resource { $data = json_decode($input, true); if (json_last_error() !== \JSON_ERROR_NONE) { if (function_exists('json_last_error_msg')) { throw new \InvalidArgumentException(json_last_error_msg(), json_last_error()); } throw new \InvalidArgumentException("Error parsing JSON.", json_last_error()); } return static::fromArray($data, $locale); }
[ "public", "static", "function", "fromString", "(", "string", "$", "input", ",", "string", "$", "locale", ")", ":", "Resource", "{", "$", "data", "=", "json_decode", "(", "$", "input", ",", "true", ")", ";", "if", "(", "json_last_error", "(", ")", "!==", "\\", "JSON_ERROR_NONE", ")", "{", "if", "(", "function_exists", "(", "'json_last_error_msg'", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "json_last_error_msg", "(", ")", ",", "json_last_error", "(", ")", ")", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Error parsing JSON.\"", ",", "json_last_error", "(", ")", ")", ";", "}", "return", "static", "::", "fromArray", "(", "$", "data", ",", "$", "locale", ")", ";", "}" ]
Creates a Resource from a JSON string @param string $input The JSON object @param string $locale The locale @return Resource
[ "Creates", "a", "Resource", "from", "a", "JSON", "string" ]
train
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/ResourceBuilder.php#L31-L42
RinkAttendant6/JsonI18n
src/ResourceBuilder.php
ResourceBuilder.fromFile
public static function fromFile(string $file, string $locale): Resource { if (!is_file($file)) { throw new \InvalidArgumentException("$file is not a file"); } $contents = file_get_contents($file); if ($contents === false) { throw new \RuntimeException("Error reading file at $file."); } return static::fromString($contents, $locale); }
php
public static function fromFile(string $file, string $locale): Resource { if (!is_file($file)) { throw new \InvalidArgumentException("$file is not a file"); } $contents = file_get_contents($file); if ($contents === false) { throw new \RuntimeException("Error reading file at $file."); } return static::fromString($contents, $locale); }
[ "public", "static", "function", "fromFile", "(", "string", "$", "file", ",", "string", "$", "locale", ")", ":", "Resource", "{", "if", "(", "!", "is_file", "(", "$", "file", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"$file is not a file\"", ")", ";", "}", "$", "contents", "=", "file_get_contents", "(", "$", "file", ")", ";", "if", "(", "$", "contents", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Error reading file at $file.\"", ")", ";", "}", "return", "static", "::", "fromString", "(", "$", "contents", ",", "$", "locale", ")", ";", "}" ]
Creates a Resource from a file @param string $file The path to the file @param string $locale The locale @return Resource
[ "Creates", "a", "Resource", "from", "a", "file" ]
train
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/ResourceBuilder.php#L50-L63
o2system/html
src/Dom/XPath.php
XPath.query
public function query($expression, \DOMNode $context = null, $registerNodeNS = null) { if (strpos($expression, '/') === false) { $expression = $this->fetchExpression($expression); } return new Lists\Nodes(parent::query($expression, $context)); }
php
public function query($expression, \DOMNode $context = null, $registerNodeNS = null) { if (strpos($expression, '/') === false) { $expression = $this->fetchExpression($expression); } return new Lists\Nodes(parent::query($expression, $context)); }
[ "public", "function", "query", "(", "$", "expression", ",", "\\", "DOMNode", "$", "context", "=", "null", ",", "$", "registerNodeNS", "=", "null", ")", "{", "if", "(", "strpos", "(", "$", "expression", ",", "'/'", ")", "===", "false", ")", "{", "$", "expression", "=", "$", "this", "->", "fetchExpression", "(", "$", "expression", ")", ";", "}", "return", "new", "Lists", "\\", "Nodes", "(", "parent", "::", "query", "(", "$", "expression", ",", "$", "context", ")", ")", ";", "}" ]
XPath::query Evaluates the given XPath expression. @see http://php.net/manual/en/domxpath.query.php @param string $expression <p> The XPath expression to execute. </p> @param \DOMNode $context [optional] <p> The optional node context can be specified for doing relative XPath queries. By default, the queries are relative to the root element. </p> @return Nodes a DOMNodeList containing all nodes matching the given XPath expression. Any expression which do not return nodes will return an empty DOMNodeList. @since 5.0
[ "XPath", "::", "query" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L59-L66
o2system/html
src/Dom/XPath.php
XPath.fetchExpression
private function fetchExpression($expression) { $selectors = explode(',', $expression); $paths = []; foreach ($selectors as $selector) { $selector = trim($selector); if (array_key_exists($selector, $this->compiledExpressions)) { $paths[] = $this->compiledExpressions[ $selector ]; continue; } $this->compiledExpressions[ $selector ] = $this->fetchCssExpression($selector); $paths[] = $this->compiledExpressions[ $selector ]; } return implode('|', $paths); }
php
private function fetchExpression($expression) { $selectors = explode(',', $expression); $paths = []; foreach ($selectors as $selector) { $selector = trim($selector); if (array_key_exists($selector, $this->compiledExpressions)) { $paths[] = $this->compiledExpressions[ $selector ]; continue; } $this->compiledExpressions[ $selector ] = $this->fetchCssExpression($selector); $paths[] = $this->compiledExpressions[ $selector ]; } return implode('|', $paths); }
[ "private", "function", "fetchExpression", "(", "$", "expression", ")", "{", "$", "selectors", "=", "explode", "(", "','", ",", "$", "expression", ")", ";", "$", "paths", "=", "[", "]", ";", "foreach", "(", "$", "selectors", "as", "$", "selector", ")", "{", "$", "selector", "=", "trim", "(", "$", "selector", ")", ";", "if", "(", "array_key_exists", "(", "$", "selector", ",", "$", "this", "->", "compiledExpressions", ")", ")", "{", "$", "paths", "[", "]", "=", "$", "this", "->", "compiledExpressions", "[", "$", "selector", "]", ";", "continue", ";", "}", "$", "this", "->", "compiledExpressions", "[", "$", "selector", "]", "=", "$", "this", "->", "fetchCssExpression", "(", "$", "selector", ")", ";", "$", "paths", "[", "]", "=", "$", "this", "->", "compiledExpressions", "[", "$", "selector", "]", ";", "}", "return", "implode", "(", "'|'", ",", "$", "paths", ")", ";", "}" ]
XPath::fetchExpression @param string $expression @return string
[ "XPath", "::", "fetchExpression" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L77-L97
o2system/html
src/Dom/XPath.php
XPath.fetchCssExpression
private function fetchCssExpression($selector, $prefix = '//') { $pos = strrpos($selector, '::'); if ($pos !== false) { $property = substr($selector, $pos + 2); $property = $this->fetchCssProperty($property); $property = $this->parseCssProperty($property[ 'name' ], $property[ 'args' ]); $selector = substr($selector, 0, $pos); } if (substr($selector, 0, 1) === '>') { $prefix = '/'; $selector = ltrim($selector, '> '); } $segments = $this->getSelectorSegments($selector); $expression = ''; while (count($segments) > 0) { $expression .= $this->generateExpression($segments, $prefix); $selector = trim(substr($selector, strlen($segments[ 'selector' ]))); $prefix = isset($segments[ 'rel' ]) ? '/' : '//'; if ($selector === '') { break; } $segments = $this->getSelectorSegments($selector); } if (isset($property)) { $expression = $expression . '/' . $property; } return $expression; }
php
private function fetchCssExpression($selector, $prefix = '//') { $pos = strrpos($selector, '::'); if ($pos !== false) { $property = substr($selector, $pos + 2); $property = $this->fetchCssProperty($property); $property = $this->parseCssProperty($property[ 'name' ], $property[ 'args' ]); $selector = substr($selector, 0, $pos); } if (substr($selector, 0, 1) === '>') { $prefix = '/'; $selector = ltrim($selector, '> '); } $segments = $this->getSelectorSegments($selector); $expression = ''; while (count($segments) > 0) { $expression .= $this->generateExpression($segments, $prefix); $selector = trim(substr($selector, strlen($segments[ 'selector' ]))); $prefix = isset($segments[ 'rel' ]) ? '/' : '//'; if ($selector === '') { break; } $segments = $this->getSelectorSegments($selector); } if (isset($property)) { $expression = $expression . '/' . $property; } return $expression; }
[ "private", "function", "fetchCssExpression", "(", "$", "selector", ",", "$", "prefix", "=", "'//'", ")", "{", "$", "pos", "=", "strrpos", "(", "$", "selector", ",", "'::'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "$", "property", "=", "substr", "(", "$", "selector", ",", "$", "pos", "+", "2", ")", ";", "$", "property", "=", "$", "this", "->", "fetchCssProperty", "(", "$", "property", ")", ";", "$", "property", "=", "$", "this", "->", "parseCssProperty", "(", "$", "property", "[", "'name'", "]", ",", "$", "property", "[", "'args'", "]", ")", ";", "$", "selector", "=", "substr", "(", "$", "selector", ",", "0", ",", "$", "pos", ")", ";", "}", "if", "(", "substr", "(", "$", "selector", ",", "0", ",", "1", ")", "===", "'>'", ")", "{", "$", "prefix", "=", "'/'", ";", "$", "selector", "=", "ltrim", "(", "$", "selector", ",", "'> '", ")", ";", "}", "$", "segments", "=", "$", "this", "->", "getSelectorSegments", "(", "$", "selector", ")", ";", "$", "expression", "=", "''", ";", "while", "(", "count", "(", "$", "segments", ")", ">", "0", ")", "{", "$", "expression", ".=", "$", "this", "->", "generateExpression", "(", "$", "segments", ",", "$", "prefix", ")", ";", "$", "selector", "=", "trim", "(", "substr", "(", "$", "selector", ",", "strlen", "(", "$", "segments", "[", "'selector'", "]", ")", ")", ")", ";", "$", "prefix", "=", "isset", "(", "$", "segments", "[", "'rel'", "]", ")", "?", "'/'", ":", "'//'", ";", "if", "(", "$", "selector", "===", "''", ")", "{", "break", ";", "}", "$", "segments", "=", "$", "this", "->", "getSelectorSegments", "(", "$", "selector", ")", ";", "}", "if", "(", "isset", "(", "$", "property", ")", ")", "{", "$", "expression", "=", "$", "expression", ".", "'/'", ".", "$", "property", ";", "}", "return", "$", "expression", ";", "}" ]
XPath::fetchCssExpression Converts a CSS selector into an XPath expression. @param string $selector A CSS selector @param string $prefix Specifies the nesting of nodes @return string XPath expression
[ "XPath", "::", "fetchCssExpression" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L111-L150
o2system/html
src/Dom/XPath.php
XPath.fetchCssProperty
protected function fetchCssProperty($property) { $name = '(?P<name>[\w\-]*)'; $args = '(?:\((?P<args>[^\)]+)\))'; $regexp = '/(?:' . $name . $args . '?)?/is'; if (preg_match($regexp, $property, $segments)) { $result = []; $result[ 'name' ] = $segments[ 'name' ]; $result[ 'args' ] = isset($segments[ 'args' ]) ? explode('|', $segments[ 'args' ]) : []; return $result; } throw new RuntimeException('Invalid selector'); }
php
protected function fetchCssProperty($property) { $name = '(?P<name>[\w\-]*)'; $args = '(?:\((?P<args>[^\)]+)\))'; $regexp = '/(?:' . $name . $args . '?)?/is'; if (preg_match($regexp, $property, $segments)) { $result = []; $result[ 'name' ] = $segments[ 'name' ]; $result[ 'args' ] = isset($segments[ 'args' ]) ? explode('|', $segments[ 'args' ]) : []; return $result; } throw new RuntimeException('Invalid selector'); }
[ "protected", "function", "fetchCssProperty", "(", "$", "property", ")", "{", "$", "name", "=", "'(?P<name>[\\w\\-]*)'", ";", "$", "args", "=", "'(?:\\((?P<args>[^\\)]+)\\))'", ";", "$", "regexp", "=", "'/(?:'", ".", "$", "name", ".", "$", "args", ".", "'?)?/is'", ";", "if", "(", "preg_match", "(", "$", "regexp", ",", "$", "property", ",", "$", "segments", ")", ")", "{", "$", "result", "=", "[", "]", ";", "$", "result", "[", "'name'", "]", "=", "$", "segments", "[", "'name'", "]", ";", "$", "result", "[", "'args'", "]", "=", "isset", "(", "$", "segments", "[", "'args'", "]", ")", "?", "explode", "(", "'|'", ",", "$", "segments", "[", "'args'", "]", ")", ":", "[", "]", ";", "return", "$", "result", ";", "}", "throw", "new", "RuntimeException", "(", "'Invalid selector'", ")", ";", "}" ]
XPath::fetchCssProperty @param $property @return array
[ "XPath", "::", "fetchCssProperty" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L161-L177
o2system/html
src/Dom/XPath.php
XPath.parseCssProperty
protected function parseCssProperty($name, $args = []) { if ($name === 'text') { return 'text()'; } if ($name === 'attr') { $attributes = []; foreach ($args as $attribute) { $attributes[] = sprintf('name() = "%s"', $attribute); } return sprintf('@*[%s]', implode(' or ', $attributes)); } throw new RuntimeException('HTML_E_INVALID_CSS_PROPERTY'); }
php
protected function parseCssProperty($name, $args = []) { if ($name === 'text') { return 'text()'; } if ($name === 'attr') { $attributes = []; foreach ($args as $attribute) { $attributes[] = sprintf('name() = "%s"', $attribute); } return sprintf('@*[%s]', implode(' or ', $attributes)); } throw new RuntimeException('HTML_E_INVALID_CSS_PROPERTY'); }
[ "protected", "function", "parseCssProperty", "(", "$", "name", ",", "$", "args", "=", "[", "]", ")", "{", "if", "(", "$", "name", "===", "'text'", ")", "{", "return", "'text()'", ";", "}", "if", "(", "$", "name", "===", "'attr'", ")", "{", "$", "attributes", "=", "[", "]", ";", "foreach", "(", "$", "args", "as", "$", "attribute", ")", "{", "$", "attributes", "[", "]", "=", "sprintf", "(", "'name() = \"%s\"'", ",", "$", "attribute", ")", ";", "}", "return", "sprintf", "(", "'@*[%s]'", ",", "implode", "(", "' or '", ",", "$", "attributes", ")", ")", ";", "}", "throw", "new", "RuntimeException", "(", "'HTML_E_INVALID_CSS_PROPERTY'", ")", ";", "}" ]
XPath::parseCssProperty @param string $name @param array $args @return string
[ "XPath", "::", "parseCssProperty" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L189-L206
o2system/html
src/Dom/XPath.php
XPath.generateExpression
private function generateExpression($segments, $prefix = '//') { $tagName = isset($segments[ 'tag' ]) ? $segments[ 'tag' ] : '*'; $attributes = []; // if the id attribute specified if (isset($segments[ 'id' ])) { $attributes[] = sprintf('@id="%s"', $segments[ 'id' ]); } // if the class attribute specified if (isset($segments[ 'classes' ])) { foreach ($segments[ 'classes' ] as $class) { $attributes[] = sprintf('contains(concat(" ", normalize-space(@class), " "), " %s ")', $class); } } // if the attributes specified if (isset($segments[ 'attributes' ])) { foreach ($segments[ 'attributes' ] as $name => $value) { $attributes[] = $this->fetchCssAttributeSelector($name, $value); } } // if the pseudo class specified if (isset($segments[ 'pseudo' ])) { $expression = isset($segments[ 'expr' ]) ? trim($segments[ 'expr' ]) : ''; $parameters = explode(',', $expression); $attributes[] = $this->fetchCssPseudoSelector($segments[ 'pseudo' ], $parameters, $tagName); } if (count($attributes) === 0 and ! isset($segments[ 'tag' ])) { throw new InvalidArgumentException( 'The array of segments should contain the name of the tag or at least one attribute' ); } $xpath = $prefix . $tagName; if ($count = count($attributes)) { $xpath .= ($count > 1) ? sprintf('[(%s)]', implode(') and (', $attributes)) : sprintf( '[%s]', $attributes[ 0 ] ); } return $xpath; }
php
private function generateExpression($segments, $prefix = '//') { $tagName = isset($segments[ 'tag' ]) ? $segments[ 'tag' ] : '*'; $attributes = []; // if the id attribute specified if (isset($segments[ 'id' ])) { $attributes[] = sprintf('@id="%s"', $segments[ 'id' ]); } // if the class attribute specified if (isset($segments[ 'classes' ])) { foreach ($segments[ 'classes' ] as $class) { $attributes[] = sprintf('contains(concat(" ", normalize-space(@class), " "), " %s ")', $class); } } // if the attributes specified if (isset($segments[ 'attributes' ])) { foreach ($segments[ 'attributes' ] as $name => $value) { $attributes[] = $this->fetchCssAttributeSelector($name, $value); } } // if the pseudo class specified if (isset($segments[ 'pseudo' ])) { $expression = isset($segments[ 'expr' ]) ? trim($segments[ 'expr' ]) : ''; $parameters = explode(',', $expression); $attributes[] = $this->fetchCssPseudoSelector($segments[ 'pseudo' ], $parameters, $tagName); } if (count($attributes) === 0 and ! isset($segments[ 'tag' ])) { throw new InvalidArgumentException( 'The array of segments should contain the name of the tag or at least one attribute' ); } $xpath = $prefix . $tagName; if ($count = count($attributes)) { $xpath .= ($count > 1) ? sprintf('[(%s)]', implode(') and (', $attributes)) : sprintf( '[%s]', $attributes[ 0 ] ); } return $xpath; }
[ "private", "function", "generateExpression", "(", "$", "segments", ",", "$", "prefix", "=", "'//'", ")", "{", "$", "tagName", "=", "isset", "(", "$", "segments", "[", "'tag'", "]", ")", "?", "$", "segments", "[", "'tag'", "]", ":", "'*'", ";", "$", "attributes", "=", "[", "]", ";", "// if the id attribute specified\r", "if", "(", "isset", "(", "$", "segments", "[", "'id'", "]", ")", ")", "{", "$", "attributes", "[", "]", "=", "sprintf", "(", "'@id=\"%s\"'", ",", "$", "segments", "[", "'id'", "]", ")", ";", "}", "// if the class attribute specified\r", "if", "(", "isset", "(", "$", "segments", "[", "'classes'", "]", ")", ")", "{", "foreach", "(", "$", "segments", "[", "'classes'", "]", "as", "$", "class", ")", "{", "$", "attributes", "[", "]", "=", "sprintf", "(", "'contains(concat(\" \", normalize-space(@class), \" \"), \" %s \")'", ",", "$", "class", ")", ";", "}", "}", "// if the attributes specified\r", "if", "(", "isset", "(", "$", "segments", "[", "'attributes'", "]", ")", ")", "{", "foreach", "(", "$", "segments", "[", "'attributes'", "]", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "attributes", "[", "]", "=", "$", "this", "->", "fetchCssAttributeSelector", "(", "$", "name", ",", "$", "value", ")", ";", "}", "}", "// if the pseudo class specified\r", "if", "(", "isset", "(", "$", "segments", "[", "'pseudo'", "]", ")", ")", "{", "$", "expression", "=", "isset", "(", "$", "segments", "[", "'expr'", "]", ")", "?", "trim", "(", "$", "segments", "[", "'expr'", "]", ")", ":", "''", ";", "$", "parameters", "=", "explode", "(", "','", ",", "$", "expression", ")", ";", "$", "attributes", "[", "]", "=", "$", "this", "->", "fetchCssPseudoSelector", "(", "$", "segments", "[", "'pseudo'", "]", ",", "$", "parameters", ",", "$", "tagName", ")", ";", "}", "if", "(", "count", "(", "$", "attributes", ")", "===", "0", "and", "!", "isset", "(", "$", "segments", "[", "'tag'", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The array of segments should contain the name of the tag or at least one attribute'", ")", ";", "}", "$", "xpath", "=", "$", "prefix", ".", "$", "tagName", ";", "if", "(", "$", "count", "=", "count", "(", "$", "attributes", ")", ")", "{", "$", "xpath", ".=", "(", "$", "count", ">", "1", ")", "?", "sprintf", "(", "'[(%s)]'", ",", "implode", "(", "') and ('", ",", "$", "attributes", ")", ")", ":", "sprintf", "(", "'[%s]'", ",", "$", "attributes", "[", "0", "]", ")", ";", "}", "return", "$", "xpath", ";", "}" ]
XPath::generateExpression @param array $segments @param string $prefix Specifies the nesting of nodes @return string XPath expression @throws InvalidArgumentException if you neither specify tag name nor attributes
[ "XPath", "::", "generateExpression" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L313-L365
o2system/html
src/Dom/XPath.php
XPath.fetchCssAttributeSelector
protected function fetchCssAttributeSelector($name, $value) { // if the attribute name starts with ^ // example: *[^data-] if (substr($name, 0, 1) === '^') { $xpath = sprintf('@*[starts-with(name(), "%s")]', substr($name, 1)); return $value === null ? $xpath : sprintf('%s="%s"', $xpath, $value); } // if the attribute name starts with ! // example: input[!disabled] if (substr($name, 0, 1) === '!') { $xpath = sprintf('not(@%s)', substr($name, 1)); return $xpath; } switch (substr($name, -1)) { case '^': $xpath = sprintf('starts-with(@%s, "%s")', substr($name, 0, -1), $value); break; case '$': $xpath = sprintf('ends-with(@%s, "%s")', substr($name, 0, -1), $value); break; case '*': $xpath = sprintf('contains(@%s, "%s")', substr($name, 0, -1), $value); break; case '!': $xpath = sprintf('not(@%s="%s")', substr($name, 0, -1), $value); break; case '~': $xpath = sprintf( 'contains(concat(" ", normalize-space(@%s), " "), " %s ")', substr($name, 0, -1), $value ); break; default: // if specified only the attribute name $xpath = $value === null ? '@' . $name : sprintf('@%s="%s"', $name, $value); break; } return $xpath; }
php
protected function fetchCssAttributeSelector($name, $value) { // if the attribute name starts with ^ // example: *[^data-] if (substr($name, 0, 1) === '^') { $xpath = sprintf('@*[starts-with(name(), "%s")]', substr($name, 1)); return $value === null ? $xpath : sprintf('%s="%s"', $xpath, $value); } // if the attribute name starts with ! // example: input[!disabled] if (substr($name, 0, 1) === '!') { $xpath = sprintf('not(@%s)', substr($name, 1)); return $xpath; } switch (substr($name, -1)) { case '^': $xpath = sprintf('starts-with(@%s, "%s")', substr($name, 0, -1), $value); break; case '$': $xpath = sprintf('ends-with(@%s, "%s")', substr($name, 0, -1), $value); break; case '*': $xpath = sprintf('contains(@%s, "%s")', substr($name, 0, -1), $value); break; case '!': $xpath = sprintf('not(@%s="%s")', substr($name, 0, -1), $value); break; case '~': $xpath = sprintf( 'contains(concat(" ", normalize-space(@%s), " "), " %s ")', substr($name, 0, -1), $value ); break; default: // if specified only the attribute name $xpath = $value === null ? '@' . $name : sprintf('@%s="%s"', $name, $value); break; } return $xpath; }
[ "protected", "function", "fetchCssAttributeSelector", "(", "$", "name", ",", "$", "value", ")", "{", "// if the attribute name starts with ^\r", "// example: *[^data-]\r", "if", "(", "substr", "(", "$", "name", ",", "0", ",", "1", ")", "===", "'^'", ")", "{", "$", "xpath", "=", "sprintf", "(", "'@*[starts-with(name(), \"%s\")]'", ",", "substr", "(", "$", "name", ",", "1", ")", ")", ";", "return", "$", "value", "===", "null", "?", "$", "xpath", ":", "sprintf", "(", "'%s=\"%s\"'", ",", "$", "xpath", ",", "$", "value", ")", ";", "}", "// if the attribute name starts with !\r", "// example: input[!disabled]\r", "if", "(", "substr", "(", "$", "name", ",", "0", ",", "1", ")", "===", "'!'", ")", "{", "$", "xpath", "=", "sprintf", "(", "'not(@%s)'", ",", "substr", "(", "$", "name", ",", "1", ")", ")", ";", "return", "$", "xpath", ";", "}", "switch", "(", "substr", "(", "$", "name", ",", "-", "1", ")", ")", "{", "case", "'^'", ":", "$", "xpath", "=", "sprintf", "(", "'starts-with(@%s, \"%s\")'", ",", "substr", "(", "$", "name", ",", "0", ",", "-", "1", ")", ",", "$", "value", ")", ";", "break", ";", "case", "'$'", ":", "$", "xpath", "=", "sprintf", "(", "'ends-with(@%s, \"%s\")'", ",", "substr", "(", "$", "name", ",", "0", ",", "-", "1", ")", ",", "$", "value", ")", ";", "break", ";", "case", "'*'", ":", "$", "xpath", "=", "sprintf", "(", "'contains(@%s, \"%s\")'", ",", "substr", "(", "$", "name", ",", "0", ",", "-", "1", ")", ",", "$", "value", ")", ";", "break", ";", "case", "'!'", ":", "$", "xpath", "=", "sprintf", "(", "'not(@%s=\"%s\")'", ",", "substr", "(", "$", "name", ",", "0", ",", "-", "1", ")", ",", "$", "value", ")", ";", "break", ";", "case", "'~'", ":", "$", "xpath", "=", "sprintf", "(", "'contains(concat(\" \", normalize-space(@%s), \" \"), \" %s \")'", ",", "substr", "(", "$", "name", ",", "0", ",", "-", "1", ")", ",", "$", "value", ")", ";", "break", ";", "default", ":", "// if specified only the attribute name\r", "$", "xpath", "=", "$", "value", "===", "null", "?", "'@'", ".", "$", "name", ":", "sprintf", "(", "'@%s=\"%s\"'", ",", "$", "name", ",", "$", "value", ")", ";", "break", ";", "}", "return", "$", "xpath", ";", "}" ]
XPath::fetchCssAttributeSelector @param string $name The attribute name @param string $value The attribute value @return string
[ "XPath", "::", "fetchCssAttributeSelector" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L377-L422
o2system/html
src/Dom/XPath.php
XPath.fetchCssPseudoSelector
protected function fetchCssPseudoSelector($pseudo, $parameters = [], &$tagName) { switch ($pseudo) { case 'first-child': return 'position() = 1'; break; case 'last-child': return 'position() = last()'; break; case 'nth-child': $xpath = sprintf( '(name()="%s") and (%s)', $tagName, $this->fetchCssPseudoNthSelector($parameters[ 0 ]) ); $tagName = '*'; return $xpath; break; case 'contains': $string = trim($parameters[ 0 ], ' \'"'); $caseSensitive = isset($parameters[ 1 ]) and (trim($parameters[ 1 ]) === 'true'); return $this->fetchCssPseudoContainsSelector($string, $caseSensitive); break; case 'has': return $this->fetchCssExpression($parameters[ 0 ], './/'); break; case 'not': return sprintf('not($this->%s)', $this->fetchCssExpression($parameters[ 0 ], '')); break; case 'nth-of-type': return $this->fetchCssPseudoNthSelector($parameters[ 0 ]); break; case 'empty': return 'count(descendant::*) = 0'; break; case 'not-empty': return 'count(descendant::*) > 0'; break; } throw new RuntimeException('Invalid selector: unknown pseudo-class'); }
php
protected function fetchCssPseudoSelector($pseudo, $parameters = [], &$tagName) { switch ($pseudo) { case 'first-child': return 'position() = 1'; break; case 'last-child': return 'position() = last()'; break; case 'nth-child': $xpath = sprintf( '(name()="%s") and (%s)', $tagName, $this->fetchCssPseudoNthSelector($parameters[ 0 ]) ); $tagName = '*'; return $xpath; break; case 'contains': $string = trim($parameters[ 0 ], ' \'"'); $caseSensitive = isset($parameters[ 1 ]) and (trim($parameters[ 1 ]) === 'true'); return $this->fetchCssPseudoContainsSelector($string, $caseSensitive); break; case 'has': return $this->fetchCssExpression($parameters[ 0 ], './/'); break; case 'not': return sprintf('not($this->%s)', $this->fetchCssExpression($parameters[ 0 ], '')); break; case 'nth-of-type': return $this->fetchCssPseudoNthSelector($parameters[ 0 ]); break; case 'empty': return 'count(descendant::*) = 0'; break; case 'not-empty': return 'count(descendant::*) > 0'; break; } throw new RuntimeException('Invalid selector: unknown pseudo-class'); }
[ "protected", "function", "fetchCssPseudoSelector", "(", "$", "pseudo", ",", "$", "parameters", "=", "[", "]", ",", "&", "$", "tagName", ")", "{", "switch", "(", "$", "pseudo", ")", "{", "case", "'first-child'", ":", "return", "'position() = 1'", ";", "break", ";", "case", "'last-child'", ":", "return", "'position() = last()'", ";", "break", ";", "case", "'nth-child'", ":", "$", "xpath", "=", "sprintf", "(", "'(name()=\"%s\") and (%s)'", ",", "$", "tagName", ",", "$", "this", "->", "fetchCssPseudoNthSelector", "(", "$", "parameters", "[", "0", "]", ")", ")", ";", "$", "tagName", "=", "'*'", ";", "return", "$", "xpath", ";", "break", ";", "case", "'contains'", ":", "$", "string", "=", "trim", "(", "$", "parameters", "[", "0", "]", ",", "' \\'\"'", ")", ";", "$", "caseSensitive", "=", "isset", "(", "$", "parameters", "[", "1", "]", ")", "and", "(", "trim", "(", "$", "parameters", "[", "1", "]", ")", "===", "'true'", ")", ";", "return", "$", "this", "->", "fetchCssPseudoContainsSelector", "(", "$", "string", ",", "$", "caseSensitive", ")", ";", "break", ";", "case", "'has'", ":", "return", "$", "this", "->", "fetchCssExpression", "(", "$", "parameters", "[", "0", "]", ",", "'.//'", ")", ";", "break", ";", "case", "'not'", ":", "return", "sprintf", "(", "'not($this->%s)'", ",", "$", "this", "->", "fetchCssExpression", "(", "$", "parameters", "[", "0", "]", ",", "''", ")", ")", ";", "break", ";", "case", "'nth-of-type'", ":", "return", "$", "this", "->", "fetchCssPseudoNthSelector", "(", "$", "parameters", "[", "0", "]", ")", ";", "break", ";", "case", "'empty'", ":", "return", "'count(descendant::*) = 0'", ";", "break", ";", "case", "'not-empty'", ":", "return", "'count(descendant::*) > 0'", ";", "break", ";", "}", "throw", "new", "RuntimeException", "(", "'Invalid selector: unknown pseudo-class'", ")", ";", "}" ]
XPath::fetchCssPseudoSelector Converts a CSS pseudo-class into an XPath expression. @param string $pseudo Pseudo-class @param array $parameters @param string $tagName @return string @throws \RuntimeException if passed an unknown pseudo-class
[ "XPath", "::", "fetchCssPseudoSelector" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L439-L482
o2system/html
src/Dom/XPath.php
XPath.fetchCssPseudoNthSelector
protected function fetchCssPseudoNthSelector($expression) { if ($expression === '') { throw new RuntimeException( 'Invalid selector: nth-child (or nth-last-child) expression must not be empty' ); } if ($expression === 'odd') { return 'position() mod 2 = 1 and position() >= 1'; } if ($expression === 'even') { return 'position() mod 2 = 0 and position() >= 0'; } if (is_numeric($expression)) { return sprintf('position() = %d', $expression); } if (preg_match("/^(?P<mul>[0-9]?n)(?:(?P<sign>\+|\-)(?P<pos>[0-9]+))?$/is", $expression, $segments)) { if (isset($segments[ 'mul' ])) { $multiplier = $segments[ 'mul' ] === 'n' ? 1 : trim($segments[ 'mul' ], 'n'); $sign = (isset($segments[ 'sign' ]) and $segments[ 'sign' ] === '+') ? '-' : '+'; $position = isset($segments[ 'pos' ]) ? $segments[ 'pos' ] : 0; return sprintf( '(position() %s %d) mod %d = 0 and position() >= %d', $sign, $position, $multiplier, $position ); } } throw new RuntimeException('Invalid selector: invalid nth-child expression'); }
php
protected function fetchCssPseudoNthSelector($expression) { if ($expression === '') { throw new RuntimeException( 'Invalid selector: nth-child (or nth-last-child) expression must not be empty' ); } if ($expression === 'odd') { return 'position() mod 2 = 1 and position() >= 1'; } if ($expression === 'even') { return 'position() mod 2 = 0 and position() >= 0'; } if (is_numeric($expression)) { return sprintf('position() = %d', $expression); } if (preg_match("/^(?P<mul>[0-9]?n)(?:(?P<sign>\+|\-)(?P<pos>[0-9]+))?$/is", $expression, $segments)) { if (isset($segments[ 'mul' ])) { $multiplier = $segments[ 'mul' ] === 'n' ? 1 : trim($segments[ 'mul' ], 'n'); $sign = (isset($segments[ 'sign' ]) and $segments[ 'sign' ] === '+') ? '-' : '+'; $position = isset($segments[ 'pos' ]) ? $segments[ 'pos' ] : 0; return sprintf( '(position() %s %d) mod %d = 0 and position() >= %d', $sign, $position, $multiplier, $position ); } } throw new RuntimeException('Invalid selector: invalid nth-child expression'); }
[ "protected", "function", "fetchCssPseudoNthSelector", "(", "$", "expression", ")", "{", "if", "(", "$", "expression", "===", "''", ")", "{", "throw", "new", "RuntimeException", "(", "'Invalid selector: nth-child (or nth-last-child) expression must not be empty'", ")", ";", "}", "if", "(", "$", "expression", "===", "'odd'", ")", "{", "return", "'position() mod 2 = 1 and position() >= 1'", ";", "}", "if", "(", "$", "expression", "===", "'even'", ")", "{", "return", "'position() mod 2 = 0 and position() >= 0'", ";", "}", "if", "(", "is_numeric", "(", "$", "expression", ")", ")", "{", "return", "sprintf", "(", "'position() = %d'", ",", "$", "expression", ")", ";", "}", "if", "(", "preg_match", "(", "\"/^(?P<mul>[0-9]?n)(?:(?P<sign>\\+|\\-)(?P<pos>[0-9]+))?$/is\"", ",", "$", "expression", ",", "$", "segments", ")", ")", "{", "if", "(", "isset", "(", "$", "segments", "[", "'mul'", "]", ")", ")", "{", "$", "multiplier", "=", "$", "segments", "[", "'mul'", "]", "===", "'n'", "?", "1", ":", "trim", "(", "$", "segments", "[", "'mul'", "]", ",", "'n'", ")", ";", "$", "sign", "=", "(", "isset", "(", "$", "segments", "[", "'sign'", "]", ")", "and", "$", "segments", "[", "'sign'", "]", "===", "'+'", ")", "?", "'-'", ":", "'+'", ";", "$", "position", "=", "isset", "(", "$", "segments", "[", "'pos'", "]", ")", "?", "$", "segments", "[", "'pos'", "]", ":", "0", ";", "return", "sprintf", "(", "'(position() %s %d) mod %d = 0 and position() >= %d'", ",", "$", "sign", ",", "$", "position", ",", "$", "multiplier", ",", "$", "position", ")", ";", "}", "}", "throw", "new", "RuntimeException", "(", "'Invalid selector: invalid nth-child expression'", ")", ";", "}" ]
XPath::fetchCssPseudoNthSelector Converts nth-expression into an XPath expression. @param string $expression nth-expression @return string @throws \RuntimeException if passed nth-child is empty @throws \RuntimeException if passed an unknown nth-child expression
[ "XPath", "::", "fetchCssPseudoNthSelector" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L498-L535
o2system/html
src/Dom/XPath.php
XPath.fetchCssPseudoContainsSelector
protected function fetchCssPseudoContainsSelector($string, $caseSensitive = false) { if ($caseSensitive) { return sprintf('text() = "%s"', $string); } if (function_exists('mb_strtolower')) { return sprintf( 'php:functionString("mb_strtolower", .) = php:functionString("mb_strtolower", "%s")', $string ); } else { return sprintf('php:functionString("strtolower", .) = php:functionString("strtolower", "%s")', $string); } }
php
protected function fetchCssPseudoContainsSelector($string, $caseSensitive = false) { if ($caseSensitive) { return sprintf('text() = "%s"', $string); } if (function_exists('mb_strtolower')) { return sprintf( 'php:functionString("mb_strtolower", .) = php:functionString("mb_strtolower", "%s")', $string ); } else { return sprintf('php:functionString("strtolower", .) = php:functionString("strtolower", "%s")', $string); } }
[ "protected", "function", "fetchCssPseudoContainsSelector", "(", "$", "string", ",", "$", "caseSensitive", "=", "false", ")", "{", "if", "(", "$", "caseSensitive", ")", "{", "return", "sprintf", "(", "'text() = \"%s\"'", ",", "$", "string", ")", ";", "}", "if", "(", "function_exists", "(", "'mb_strtolower'", ")", ")", "{", "return", "sprintf", "(", "'php:functionString(\"mb_strtolower\", .) = php:functionString(\"mb_strtolower\", \"%s\")'", ",", "$", "string", ")", ";", "}", "else", "{", "return", "sprintf", "(", "'php:functionString(\"strtolower\", .) = php:functionString(\"strtolower\", \"%s\")'", ",", "$", "string", ")", ";", "}", "}" ]
XPath::fetchCssPseudoContainsSelector @param string $string @param bool $caseSensitive @return string
[ "XPath", "::", "fetchCssPseudoContainsSelector" ]
train
https://github.com/o2system/html/blob/b7336fb45d42603ce1064b25572a05d495887670/src/Dom/XPath.php#L547-L561
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.addBindingType
public function addBindingType(BindingType $type) { if (isset($this->keysByTypeName[$type->getName()])) { throw DuplicateTypeException::forTypeName($type->getName()); } $key = $this->nextKey++; $this->keysByTypeName[$type->getName()] = $key; // Use integer keys to reduce storage space // (compared to fully-qualified class names) $this->typesByKey[$key] = $type; $this->store->set('::keysByTypeName', $this->keysByTypeName); $this->store->set('::nextKey', $this->nextKey); $this->store->set('t:'.$key, $type); }
php
public function addBindingType(BindingType $type) { if (isset($this->keysByTypeName[$type->getName()])) { throw DuplicateTypeException::forTypeName($type->getName()); } $key = $this->nextKey++; $this->keysByTypeName[$type->getName()] = $key; // Use integer keys to reduce storage space // (compared to fully-qualified class names) $this->typesByKey[$key] = $type; $this->store->set('::keysByTypeName', $this->keysByTypeName); $this->store->set('::nextKey', $this->nextKey); $this->store->set('t:'.$key, $type); }
[ "public", "function", "addBindingType", "(", "BindingType", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "type", "->", "getName", "(", ")", "]", ")", ")", "{", "throw", "DuplicateTypeException", "::", "forTypeName", "(", "$", "type", "->", "getName", "(", ")", ")", ";", "}", "$", "key", "=", "$", "this", "->", "nextKey", "++", ";", "$", "this", "->", "keysByTypeName", "[", "$", "type", "->", "getName", "(", ")", "]", "=", "$", "key", ";", "// Use integer keys to reduce storage space", "// (compared to fully-qualified class names)", "$", "this", "->", "typesByKey", "[", "$", "key", "]", "=", "$", "type", ";", "$", "this", "->", "store", "->", "set", "(", "'::keysByTypeName'", ",", "$", "this", "->", "keysByTypeName", ")", ";", "$", "this", "->", "store", "->", "set", "(", "'::nextKey'", ",", "$", "this", "->", "nextKey", ")", ";", "$", "this", "->", "store", "->", "set", "(", "'t:'", ".", "$", "key", ",", "$", "type", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L98-L115
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.removeBindingType
public function removeBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (!isset($this->keysByTypeName[$typeName])) { return; } $key = $this->keysByTypeName[$typeName]; unset( $this->keysByTypeName[$typeName], $this->typesByKey[$key], $this->bindingsByKey[$key] ); $this->store->remove('t:'.$key); $this->store->remove('b:'.$key); $this->store->set('::keysByTypeName', $this->keysByTypeName); }
php
public function removeBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (!isset($this->keysByTypeName[$typeName])) { return; } $key = $this->keysByTypeName[$typeName]; unset( $this->keysByTypeName[$typeName], $this->typesByKey[$key], $this->bindingsByKey[$key] ); $this->store->remove('t:'.$key); $this->store->remove('b:'.$key); $this->store->set('::keysByTypeName', $this->keysByTypeName); }
[ "public", "function", "removeBindingType", "(", "$", "typeName", ")", "{", "Assert", "::", "stringNotEmpty", "(", "$", "typeName", ",", "'The type class must be a non-empty string. Got: %s'", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ")", ")", "{", "return", ";", "}", "$", "key", "=", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ";", "unset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ",", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ",", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ";", "$", "this", "->", "store", "->", "remove", "(", "'t:'", ".", "$", "key", ")", ";", "$", "this", "->", "store", "->", "remove", "(", "'b:'", ".", "$", "key", ")", ";", "$", "this", "->", "store", "->", "set", "(", "'::keysByTypeName'", ",", "$", "this", "->", "keysByTypeName", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L120-L139
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.removeBindingTypes
public function removeBindingTypes() { $this->keysByTypeName = array(); $this->typesByKey = array(); $this->bindingsByKey = array(); $this->nextKey = 0; $this->store->clear(); }
php
public function removeBindingTypes() { $this->keysByTypeName = array(); $this->typesByKey = array(); $this->bindingsByKey = array(); $this->nextKey = 0; $this->store->clear(); }
[ "public", "function", "removeBindingTypes", "(", ")", "{", "$", "this", "->", "keysByTypeName", "=", "array", "(", ")", ";", "$", "this", "->", "typesByKey", "=", "array", "(", ")", ";", "$", "this", "->", "bindingsByKey", "=", "array", "(", ")", ";", "$", "this", "->", "nextKey", "=", "0", ";", "$", "this", "->", "store", "->", "clear", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L144-L152
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.getBindingType
public function getBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (!isset($this->keysByTypeName[$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->keysByTypeName[$typeName]; if (!isset($this->typesByKey[$key])) { $this->typesByKey[$key] = $this->store->get('t:'.$key); } return $this->typesByKey[$key]; }
php
public function getBindingType($typeName) { Assert::stringNotEmpty($typeName, 'The type class must be a non-empty string. Got: %s'); if (!isset($this->keysByTypeName[$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->keysByTypeName[$typeName]; if (!isset($this->typesByKey[$key])) { $this->typesByKey[$key] = $this->store->get('t:'.$key); } return $this->typesByKey[$key]; }
[ "public", "function", "getBindingType", "(", "$", "typeName", ")", "{", "Assert", "::", "stringNotEmpty", "(", "$", "typeName", ",", "'The type class must be a non-empty string. Got: %s'", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ")", ")", "{", "throw", "NoSuchTypeException", "::", "forTypeName", "(", "$", "typeName", ")", ";", "}", "$", "key", "=", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "typesByKey", "[", "$", "key", "]", "=", "$", "this", "->", "store", "->", "get", "(", "'t:'", ".", "$", "key", ")", ";", "}", "return", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L167-L182
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.getBindingTypes
public function getBindingTypes() { $keysToFetch = array(); foreach ($this->keysByTypeName as $key) { if (!isset($this->typesByKey[$key])) { $keysToFetch[] = 't:'.$key; } } $types = $this->store->getMultiple($keysToFetch); foreach ($types as $prefixedKey => $type) { $this->typesByKey[substr($prefixedKey, 2)] = $type; } ksort($this->typesByKey); return $this->typesByKey; }
php
public function getBindingTypes() { $keysToFetch = array(); foreach ($this->keysByTypeName as $key) { if (!isset($this->typesByKey[$key])) { $keysToFetch[] = 't:'.$key; } } $types = $this->store->getMultiple($keysToFetch); foreach ($types as $prefixedKey => $type) { $this->typesByKey[substr($prefixedKey, 2)] = $type; } ksort($this->typesByKey); return $this->typesByKey; }
[ "public", "function", "getBindingTypes", "(", ")", "{", "$", "keysToFetch", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "keysByTypeName", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "typesByKey", "[", "$", "key", "]", ")", ")", "{", "$", "keysToFetch", "[", "]", "=", "'t:'", ".", "$", "key", ";", "}", "}", "$", "types", "=", "$", "this", "->", "store", "->", "getMultiple", "(", "$", "keysToFetch", ")", ";", "foreach", "(", "$", "types", "as", "$", "prefixedKey", "=>", "$", "type", ")", "{", "$", "this", "->", "typesByKey", "[", "substr", "(", "$", "prefixedKey", ",", "2", ")", "]", "=", "$", "type", ";", "}", "ksort", "(", "$", "this", "->", "typesByKey", ")", ";", "return", "$", "this", "->", "typesByKey", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L195-L214
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.addBinding
public function addBinding(Binding $binding) { $typeName = $binding->getTypeName(); if (!isset($this->keysByTypeName[$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->keysByTypeName[$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } $this->initializeBinding($binding); $this->bindingsByKey[$key][] = $binding; $this->store->set('b:'.$key, $this->bindingsByKey[$key]); }
php
public function addBinding(Binding $binding) { $typeName = $binding->getTypeName(); if (!isset($this->keysByTypeName[$typeName])) { throw NoSuchTypeException::forTypeName($typeName); } $key = $this->keysByTypeName[$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } $this->initializeBinding($binding); $this->bindingsByKey[$key][] = $binding; $this->store->set('b:'.$key, $this->bindingsByKey[$key]); }
[ "public", "function", "addBinding", "(", "Binding", "$", "binding", ")", "{", "$", "typeName", "=", "$", "binding", "->", "getTypeName", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ")", ")", "{", "throw", "NoSuchTypeException", "::", "forTypeName", "(", "$", "typeName", ")", ";", "}", "$", "key", "=", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ")", ";", "}", "$", "this", "->", "initializeBinding", "(", "$", "binding", ")", ";", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "[", "]", "=", "$", "binding", ";", "$", "this", "->", "store", "->", "set", "(", "'b:'", ".", "$", "key", ",", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L219-L238
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.getBindings
public function getBindings() { $this->loadAllBindings(); $bindings = array(); foreach ($this->bindingsByKey as $bindingsForKey) { $bindings = array_merge($bindings, $bindingsForKey); } return $bindings; }
php
public function getBindings() { $this->loadAllBindings(); $bindings = array(); foreach ($this->bindingsByKey as $bindingsForKey) { $bindings = array_merge($bindings, $bindingsForKey); } return $bindings; }
[ "public", "function", "getBindings", "(", ")", "{", "$", "this", "->", "loadAllBindings", "(", ")", ";", "$", "bindings", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "bindingsByKey", "as", "$", "bindingsForKey", ")", "{", "$", "bindings", "=", "array_merge", "(", "$", "bindings", ",", "$", "bindingsForKey", ")", ";", "}", "return", "$", "bindings", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L269-L280
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.removeAllBindings
protected function removeAllBindings() { $this->bindingsByKey = array(); // Iterate $keysByTypeName which does not contain duplicate keys foreach ($this->keysByTypeName as $key) { $this->store->remove('b:'.$key); } }
php
protected function removeAllBindings() { $this->bindingsByKey = array(); // Iterate $keysByTypeName which does not contain duplicate keys foreach ($this->keysByTypeName as $key) { $this->store->remove('b:'.$key); } }
[ "protected", "function", "removeAllBindings", "(", ")", "{", "$", "this", "->", "bindingsByKey", "=", "array", "(", ")", ";", "// Iterate $keysByTypeName which does not contain duplicate keys", "foreach", "(", "$", "this", "->", "keysByTypeName", "as", "$", "key", ")", "{", "$", "this", "->", "store", "->", "remove", "(", "'b:'", ".", "$", "key", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L285-L293
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.removeBindingsThatMatch
protected function removeBindingsThatMatch(Expression $expr) { $this->loadAllBindings(); foreach ($this->bindingsByKey as $key => $bindingsForKey) { foreach ($bindingsForKey as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } // Reindex array $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); } }
php
protected function removeBindingsThatMatch(Expression $expr) { $this->loadAllBindings(); foreach ($this->bindingsByKey as $key => $bindingsForKey) { foreach ($bindingsForKey as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } // Reindex array $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); } }
[ "protected", "function", "removeBindingsThatMatch", "(", "Expression", "$", "expr", ")", "{", "$", "this", "->", "loadAllBindings", "(", ")", ";", "foreach", "(", "$", "this", "->", "bindingsByKey", "as", "$", "key", "=>", "$", "bindingsForKey", ")", "{", "foreach", "(", "$", "bindingsForKey", "as", "$", "i", "=>", "$", "binding", ")", "{", "if", "(", "$", "expr", "->", "evaluate", "(", "$", "binding", ")", ")", "{", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "[", "$", "i", "]", ")", ";", "}", "}", "// Reindex array", "$", "this", "->", "reindexBindingsForKey", "(", "$", "key", ")", ";", "$", "this", "->", "syncBindingsForKey", "(", "$", "key", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L298-L314
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.removeBindingsWithTypeName
protected function removeBindingsWithTypeName($typeName) { if (!isset($this->keysByTypeName[$typeName])) { return; } $key = $this->keysByTypeName[$typeName]; if (!isset($this->bindingsByKey[$key])) { // no initialize, since we're removing this anyway $this->loadBindingsForKey($key, false); } unset($this->bindingsByKey[$key]); $this->store->remove('b:'.$key); }
php
protected function removeBindingsWithTypeName($typeName) { if (!isset($this->keysByTypeName[$typeName])) { return; } $key = $this->keysByTypeName[$typeName]; if (!isset($this->bindingsByKey[$key])) { // no initialize, since we're removing this anyway $this->loadBindingsForKey($key, false); } unset($this->bindingsByKey[$key]); $this->store->remove('b:'.$key); }
[ "protected", "function", "removeBindingsWithTypeName", "(", "$", "typeName", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ")", ")", "{", "return", ";", "}", "$", "key", "=", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "// no initialize, since we're removing this anyway", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ",", "false", ")", ";", "}", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ";", "$", "this", "->", "store", "->", "remove", "(", "'b:'", ".", "$", "key", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L319-L335
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.removeBindingsWithTypeNameThatMatch
protected function removeBindingsWithTypeNameThatMatch($typeName, Expression $expr) { if (!isset($this->keysByTypeName[$typeName])) { return; } $key = $this->keysByTypeName[$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } foreach ($this->bindingsByKey[$key] as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); }
php
protected function removeBindingsWithTypeNameThatMatch($typeName, Expression $expr) { if (!isset($this->keysByTypeName[$typeName])) { return; } $key = $this->keysByTypeName[$typeName]; if (!isset($this->bindingsByKey[$key])) { $this->loadBindingsForKey($key); } foreach ($this->bindingsByKey[$key] as $i => $binding) { if ($expr->evaluate($binding)) { unset($this->bindingsByKey[$key][$i]); } } $this->reindexBindingsForKey($key); $this->syncBindingsForKey($key); }
[ "protected", "function", "removeBindingsWithTypeNameThatMatch", "(", "$", "typeName", ",", "Expression", "$", "expr", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ")", ")", "{", "return", ";", "}", "$", "key", "=", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "loadBindingsForKey", "(", "$", "key", ")", ";", "}", "foreach", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "as", "$", "i", "=>", "$", "binding", ")", "{", "if", "(", "$", "expr", "->", "evaluate", "(", "$", "binding", ")", ")", "{", "unset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", "[", "$", "i", "]", ")", ";", "}", "}", "$", "this", "->", "reindexBindingsForKey", "(", "$", "key", ")", ";", "$", "this", "->", "syncBindingsForKey", "(", "$", "key", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L340-L360
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.hasAnyBinding
protected function hasAnyBinding() { // First check loaded keys if (count($this->bindingsByKey) > 0) { return true; } // Next check unloaded keys foreach ($this->keysByTypeName as $key) { if ($this->store->exists('b:'.$key)) { return true; } } return false; }
php
protected function hasAnyBinding() { // First check loaded keys if (count($this->bindingsByKey) > 0) { return true; } // Next check unloaded keys foreach ($this->keysByTypeName as $key) { if ($this->store->exists('b:'.$key)) { return true; } } return false; }
[ "protected", "function", "hasAnyBinding", "(", ")", "{", "// First check loaded keys", "if", "(", "count", "(", "$", "this", "->", "bindingsByKey", ")", ">", "0", ")", "{", "return", "true", ";", "}", "// Next check unloaded keys", "foreach", "(", "$", "this", "->", "keysByTypeName", "as", "$", "key", ")", "{", "if", "(", "$", "this", "->", "store", "->", "exists", "(", "'b:'", ".", "$", "key", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L365-L380
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.hasBindingsThatMatch
protected function hasBindingsThatMatch(Expression $expr) { $this->loadAllBindings(); foreach ($this->bindingsByKey as $bindingsForKey) { foreach ($bindingsForKey as $binding) { if ($expr->evaluate($binding)) { return true; } } } return false; }
php
protected function hasBindingsThatMatch(Expression $expr) { $this->loadAllBindings(); foreach ($this->bindingsByKey as $bindingsForKey) { foreach ($bindingsForKey as $binding) { if ($expr->evaluate($binding)) { return true; } } } return false; }
[ "protected", "function", "hasBindingsThatMatch", "(", "Expression", "$", "expr", ")", "{", "$", "this", "->", "loadAllBindings", "(", ")", ";", "foreach", "(", "$", "this", "->", "bindingsByKey", "as", "$", "bindingsForKey", ")", "{", "foreach", "(", "$", "bindingsForKey", "as", "$", "binding", ")", "{", "if", "(", "$", "expr", "->", "evaluate", "(", "$", "binding", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L385-L398
puli/discovery
src/KeyValueStoreDiscovery.php
KeyValueStoreDiscovery.hasBindingsWithTypeName
protected function hasBindingsWithTypeName($typeName) { if (!isset($this->keysByTypeName[$typeName])) { return false; } $key = $this->keysByTypeName[$typeName]; return isset($this->bindingsByKey[$key]) || $this->store->exists('b:'.$key); }
php
protected function hasBindingsWithTypeName($typeName) { if (!isset($this->keysByTypeName[$typeName])) { return false; } $key = $this->keysByTypeName[$typeName]; return isset($this->bindingsByKey[$key]) || $this->store->exists('b:'.$key); }
[ "protected", "function", "hasBindingsWithTypeName", "(", "$", "typeName", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ")", ")", "{", "return", "false", ";", "}", "$", "key", "=", "$", "this", "->", "keysByTypeName", "[", "$", "typeName", "]", ";", "return", "isset", "(", "$", "this", "->", "bindingsByKey", "[", "$", "key", "]", ")", "||", "$", "this", "->", "store", "->", "exists", "(", "'b:'", ".", "$", "key", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/puli/discovery/blob/975f5e099563f1096bfabc17fbe4d1816408ad98/src/KeyValueStoreDiscovery.php#L403-L412
czim/laravel-pxlcms
src/Models/Scopes/CmsOrderedScope.php
CmsOrderedScope.apply
public function apply(Builder $builder, Model $model) { $columns = $model->getQualifiedOrderByColumns(); foreach ($columns as $column => $direction) { $builder->orderBy($column, $direction); } $this->addUnordered($builder); }
php
public function apply(Builder $builder, Model $model) { $columns = $model->getQualifiedOrderByColumns(); foreach ($columns as $column => $direction) { $builder->orderBy($column, $direction); } $this->addUnordered($builder); }
[ "public", "function", "apply", "(", "Builder", "$", "builder", ",", "Model", "$", "model", ")", "{", "$", "columns", "=", "$", "model", "->", "getQualifiedOrderByColumns", "(", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", "=>", "$", "direction", ")", "{", "$", "builder", "->", "orderBy", "(", "$", "column", ",", "$", "direction", ")", ";", "}", "$", "this", "->", "addUnordered", "(", "$", "builder", ")", ";", "}" ]
Apply scope on the query @param \Illuminate\Database\Eloquent\Builder $builder @param \Illuminate\Database\Eloquent\Model $model
[ "Apply", "scope", "on", "the", "query" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/Scopes/CmsOrderedScope.php#L18-L28
czim/laravel-pxlcms
src/Models/Scopes/CmsOrderedScope.php
CmsOrderedScope.remove
public function remove(Builder $builder, Model $model) { $query = $builder->getQuery(); $columns = $model->getQualifiedOrderByColumns(); foreach ($columns as $column => $direction) { foreach ((array) $query->orders as $key => $order) { if ($order['column'] == $column) { $this->removeOrderBy($query, $key); } } } }
php
public function remove(Builder $builder, Model $model) { $query = $builder->getQuery(); $columns = $model->getQualifiedOrderByColumns(); foreach ($columns as $column => $direction) { foreach ((array) $query->orders as $key => $order) { if ($order['column'] == $column) { $this->removeOrderBy($query, $key); } } } }
[ "public", "function", "remove", "(", "Builder", "$", "builder", ",", "Model", "$", "model", ")", "{", "$", "query", "=", "$", "builder", "->", "getQuery", "(", ")", ";", "$", "columns", "=", "$", "model", "->", "getQualifiedOrderByColumns", "(", ")", ";", "foreach", "(", "$", "columns", "as", "$", "column", "=>", "$", "direction", ")", "{", "foreach", "(", "(", "array", ")", "$", "query", "->", "orders", "as", "$", "key", "=>", "$", "order", ")", "{", "if", "(", "$", "order", "[", "'column'", "]", "==", "$", "column", ")", "{", "$", "this", "->", "removeOrderBy", "(", "$", "query", ",", "$", "key", ")", ";", "}", "}", "}", "}" ]
Remove scope from the query @param \Illuminate\Database\Eloquent\Builder $builder @param \Illuminate\Database\Eloquent\Model $model
[ "Remove", "scope", "from", "the", "query" ]
train
https://github.com/czim/laravel-pxlcms/blob/910297d2a3f2db86dde51b0e10fe5aad45f1aa1a/src/Models/Scopes/CmsOrderedScope.php#L36-L50
awesomite/chariot
src/Pattern/StdPatterns/DatePattern.php
DatePattern.toUrl
public function toUrl($rawData): string { $data = $this->processRawData($rawData); if (\is_object($data) && $data instanceof \DateTimeInterface) { return $data->format(static::DATE_FORMAT); } if (\is_int($data)) { return (new \DateTime())->setTimestamp($data)->format(static::DATE_FORMAT); } if (\is_string($data) && $this->match($data)) { $sData = (string) $data; if ($this->checkDate($sData)) { return $sData; } } throw $this->newInvalidToUrl($data); }
php
public function toUrl($rawData): string { $data = $this->processRawData($rawData); if (\is_object($data) && $data instanceof \DateTimeInterface) { return $data->format(static::DATE_FORMAT); } if (\is_int($data)) { return (new \DateTime())->setTimestamp($data)->format(static::DATE_FORMAT); } if (\is_string($data) && $this->match($data)) { $sData = (string) $data; if ($this->checkDate($sData)) { return $sData; } } throw $this->newInvalidToUrl($data); }
[ "public", "function", "toUrl", "(", "$", "rawData", ")", ":", "string", "{", "$", "data", "=", "$", "this", "->", "processRawData", "(", "$", "rawData", ")", ";", "if", "(", "\\", "is_object", "(", "$", "data", ")", "&&", "$", "data", "instanceof", "\\", "DateTimeInterface", ")", "{", "return", "$", "data", "->", "format", "(", "static", "::", "DATE_FORMAT", ")", ";", "}", "if", "(", "\\", "is_int", "(", "$", "data", ")", ")", "{", "return", "(", "new", "\\", "DateTime", "(", ")", ")", "->", "setTimestamp", "(", "$", "data", ")", "->", "format", "(", "static", "::", "DATE_FORMAT", ")", ";", "}", "if", "(", "\\", "is_string", "(", "$", "data", ")", "&&", "$", "this", "->", "match", "(", "$", "data", ")", ")", "{", "$", "sData", "=", "(", "string", ")", "$", "data", ";", "if", "(", "$", "this", "->", "checkDate", "(", "$", "sData", ")", ")", "{", "return", "$", "sData", ";", "}", "}", "throw", "$", "this", "->", "newInvalidToUrl", "(", "$", "data", ")", ";", "}" ]
Convert passed argument to date in format YYYY-mm-dd @param int|string|\DateTimeInterface $rawData @return string @throws PatternException
[ "Convert", "passed", "argument", "to", "date", "in", "format", "YYYY", "-", "mm", "-", "dd" ]
train
https://github.com/awesomite/chariot/blob/3229e38537b857be1d352308ba340dc530b12afb/src/Pattern/StdPatterns/DatePattern.php#L53-L73
awesomite/chariot
src/Pattern/StdPatterns/DatePattern.php
DatePattern.fromUrl
public function fromUrl(string $param) { if ($this->checkDate($param)) { return new \DateTimeImmutable($param, $this->timezone); } throw $this->newInvalidFromUrl($param); }
php
public function fromUrl(string $param) { if ($this->checkDate($param)) { return new \DateTimeImmutable($param, $this->timezone); } throw $this->newInvalidFromUrl($param); }
[ "public", "function", "fromUrl", "(", "string", "$", "param", ")", "{", "if", "(", "$", "this", "->", "checkDate", "(", "$", "param", ")", ")", "{", "return", "new", "\\", "DateTimeImmutable", "(", "$", "param", ",", "$", "this", "->", "timezone", ")", ";", "}", "throw", "$", "this", "->", "newInvalidFromUrl", "(", "$", "param", ")", ";", "}" ]
Convert date in format YYYY-mm-dd to \DateTimeImmutable object @param string $param @return \DateTimeImmutable @throws PatternException
[ "Convert", "date", "in", "format", "YYYY", "-", "mm", "-", "dd", "to", "\\", "DateTimeImmutable", "object" ]
train
https://github.com/awesomite/chariot/blob/3229e38537b857be1d352308ba340dc530b12afb/src/Pattern/StdPatterns/DatePattern.php#L104-L111
sulu/SuluSalesShippingBundle
src/Sulu/Bundle/Sales/CoreBundle/Entity/BaseOrderAddress.php
BaseOrderAddress.copyValuesFromInterface
public function copyValuesFromInterface(OrderAddressInterface $from, OrderAddressInterface $to) { // account $to->setAccountName($from->getAccountName()); $to->setUid($from->getUid()); // contact $to->setTitle($from->getTitle()); $to->setSalutation($from->getSalutation()); $to->setFirstName($from->getFirstName()); $to->setLastName($from->getLastName()); $to->setEmail($from->getEmail()); $to->setPhone($from->getPhone()); $to->setPhoneMobile($from->getPhoneMobile()); // address $to->setStreet($from->getStreet()); $to->setNumber($from->getNumber()); $to->setAddition($from->getAddition()); $to->setZip($from->getZip()); $to->setCity($from->getCity()); $to->setState($from->getState()); $to->setCountry($from->getCountry()); $to->setContactAddress($from->getContactAddress()); $to->setNote($from->getNote()); // postbox $to->setPostboxCity($from->getPostboxCity()); $to->setPostboxNumber($from->getPostboxNumber()); $to->setPostboxPostcode($from->getPostboxPostcode()); }
php
public function copyValuesFromInterface(OrderAddressInterface $from, OrderAddressInterface $to) { // account $to->setAccountName($from->getAccountName()); $to->setUid($from->getUid()); // contact $to->setTitle($from->getTitle()); $to->setSalutation($from->getSalutation()); $to->setFirstName($from->getFirstName()); $to->setLastName($from->getLastName()); $to->setEmail($from->getEmail()); $to->setPhone($from->getPhone()); $to->setPhoneMobile($from->getPhoneMobile()); // address $to->setStreet($from->getStreet()); $to->setNumber($from->getNumber()); $to->setAddition($from->getAddition()); $to->setZip($from->getZip()); $to->setCity($from->getCity()); $to->setState($from->getState()); $to->setCountry($from->getCountry()); $to->setContactAddress($from->getContactAddress()); $to->setNote($from->getNote()); // postbox $to->setPostboxCity($from->getPostboxCity()); $to->setPostboxNumber($from->getPostboxNumber()); $to->setPostboxPostcode($from->getPostboxPostcode()); }
[ "public", "function", "copyValuesFromInterface", "(", "OrderAddressInterface", "$", "from", ",", "OrderAddressInterface", "$", "to", ")", "{", "// account", "$", "to", "->", "setAccountName", "(", "$", "from", "->", "getAccountName", "(", ")", ")", ";", "$", "to", "->", "setUid", "(", "$", "from", "->", "getUid", "(", ")", ")", ";", "// contact", "$", "to", "->", "setTitle", "(", "$", "from", "->", "getTitle", "(", ")", ")", ";", "$", "to", "->", "setSalutation", "(", "$", "from", "->", "getSalutation", "(", ")", ")", ";", "$", "to", "->", "setFirstName", "(", "$", "from", "->", "getFirstName", "(", ")", ")", ";", "$", "to", "->", "setLastName", "(", "$", "from", "->", "getLastName", "(", ")", ")", ";", "$", "to", "->", "setEmail", "(", "$", "from", "->", "getEmail", "(", ")", ")", ";", "$", "to", "->", "setPhone", "(", "$", "from", "->", "getPhone", "(", ")", ")", ";", "$", "to", "->", "setPhoneMobile", "(", "$", "from", "->", "getPhoneMobile", "(", ")", ")", ";", "// address", "$", "to", "->", "setStreet", "(", "$", "from", "->", "getStreet", "(", ")", ")", ";", "$", "to", "->", "setNumber", "(", "$", "from", "->", "getNumber", "(", ")", ")", ";", "$", "to", "->", "setAddition", "(", "$", "from", "->", "getAddition", "(", ")", ")", ";", "$", "to", "->", "setZip", "(", "$", "from", "->", "getZip", "(", ")", ")", ";", "$", "to", "->", "setCity", "(", "$", "from", "->", "getCity", "(", ")", ")", ";", "$", "to", "->", "setState", "(", "$", "from", "->", "getState", "(", ")", ")", ";", "$", "to", "->", "setCountry", "(", "$", "from", "->", "getCountry", "(", ")", ")", ";", "$", "to", "->", "setContactAddress", "(", "$", "from", "->", "getContactAddress", "(", ")", ")", ";", "$", "to", "->", "setNote", "(", "$", "from", "->", "getNote", "(", ")", ")", ";", "// postbox", "$", "to", "->", "setPostboxCity", "(", "$", "from", "->", "getPostboxCity", "(", ")", ")", ";", "$", "to", "->", "setPostboxNumber", "(", "$", "from", "->", "getPostboxNumber", "(", ")", ")", ";", "$", "to", "->", "setPostboxPostcode", "(", "$", "from", "->", "getPostboxPostcode", "(", ")", ")", ";", "}" ]
Copies address data from one order-address-interface to another @param OrderAddressInterface $from @param OrderAddressInterface $to
[ "Copies", "address", "data", "from", "one", "order", "-", "address", "-", "interface", "to", "another" ]
train
https://github.com/sulu/SuluSalesShippingBundle/blob/0d39de262d58579e5679db99a77dbf717d600b5e/src/Sulu/Bundle/Sales/CoreBundle/Entity/BaseOrderAddress.php#L651-L678
sulu/SuluSalesShippingBundle
src/Sulu/Bundle/Sales/CoreBundle/Entity/BaseOrderAddress.php
BaseOrderAddress.toArray
public function toArray() { return array( // account 'accountName' => $this->getAccountName(), 'uid' => $this->getUid(), // contact 'title' => $this->getTitle(), 'salutation' => $this->getSalutation(), 'firstName' => $this->getFirstName(), 'lastName' => $this->getLastName(), 'email' => $this->getEmail(), 'phone' => $this->getPhone(), 'phoneMobile' => $this->getPhoneMobile(), // address 'street' => $this->getStreet(), 'number' => $this->getNumber(), 'addition' => $this->getAddition(), 'zip' => $this->getZip(), 'city' => $this->getCity(), 'state' => $this->getState(), 'country' => $this->getCountry(), 'note' => $this->getNote(), 'contactAddress' => $this->getContactAddress() ? array( 'id' => $this->getContactAddress()->getId() ) : null, // postbox 'postboxCity' => $this->getPostboxCity(), 'postboxNumber' => $this->getPostboxNumber(), 'postboxPostcode' => $this->getPostboxPostcode(), ); }
php
public function toArray() { return array( // account 'accountName' => $this->getAccountName(), 'uid' => $this->getUid(), // contact 'title' => $this->getTitle(), 'salutation' => $this->getSalutation(), 'firstName' => $this->getFirstName(), 'lastName' => $this->getLastName(), 'email' => $this->getEmail(), 'phone' => $this->getPhone(), 'phoneMobile' => $this->getPhoneMobile(), // address 'street' => $this->getStreet(), 'number' => $this->getNumber(), 'addition' => $this->getAddition(), 'zip' => $this->getZip(), 'city' => $this->getCity(), 'state' => $this->getState(), 'country' => $this->getCountry(), 'note' => $this->getNote(), 'contactAddress' => $this->getContactAddress() ? array( 'id' => $this->getContactAddress()->getId() ) : null, // postbox 'postboxCity' => $this->getPostboxCity(), 'postboxNumber' => $this->getPostboxNumber(), 'postboxPostcode' => $this->getPostboxPostcode(), ); }
[ "public", "function", "toArray", "(", ")", "{", "return", "array", "(", "// account", "'accountName'", "=>", "$", "this", "->", "getAccountName", "(", ")", ",", "'uid'", "=>", "$", "this", "->", "getUid", "(", ")", ",", "// contact", "'title'", "=>", "$", "this", "->", "getTitle", "(", ")", ",", "'salutation'", "=>", "$", "this", "->", "getSalutation", "(", ")", ",", "'firstName'", "=>", "$", "this", "->", "getFirstName", "(", ")", ",", "'lastName'", "=>", "$", "this", "->", "getLastName", "(", ")", ",", "'email'", "=>", "$", "this", "->", "getEmail", "(", ")", ",", "'phone'", "=>", "$", "this", "->", "getPhone", "(", ")", ",", "'phoneMobile'", "=>", "$", "this", "->", "getPhoneMobile", "(", ")", ",", "// address", "'street'", "=>", "$", "this", "->", "getStreet", "(", ")", ",", "'number'", "=>", "$", "this", "->", "getNumber", "(", ")", ",", "'addition'", "=>", "$", "this", "->", "getAddition", "(", ")", ",", "'zip'", "=>", "$", "this", "->", "getZip", "(", ")", ",", "'city'", "=>", "$", "this", "->", "getCity", "(", ")", ",", "'state'", "=>", "$", "this", "->", "getState", "(", ")", ",", "'country'", "=>", "$", "this", "->", "getCountry", "(", ")", ",", "'note'", "=>", "$", "this", "->", "getNote", "(", ")", ",", "'contactAddress'", "=>", "$", "this", "->", "getContactAddress", "(", ")", "?", "array", "(", "'id'", "=>", "$", "this", "->", "getContactAddress", "(", ")", "->", "getId", "(", ")", ")", ":", "null", ",", "// postbox", "'postboxCity'", "=>", "$", "this", "->", "getPostboxCity", "(", ")", ",", "'postboxNumber'", "=>", "$", "this", "->", "getPostboxNumber", "(", ")", ",", "'postboxPostcode'", "=>", "$", "this", "->", "getPostboxPostcode", "(", ")", ",", ")", ";", "}" ]
Converts a BaseOrderAddress
[ "Converts", "a", "BaseOrderAddress" ]
train
https://github.com/sulu/SuluSalesShippingBundle/blob/0d39de262d58579e5679db99a77dbf717d600b5e/src/Sulu/Bundle/Sales/CoreBundle/Entity/BaseOrderAddress.php#L683-L714
gisostallenberg/file-permission-calculator
src/FilePermissionCalculator.php
FilePermissionCalculator.getStringRepresentation
public static function getStringRepresentation($mode) { $permissions = ''; if (($mode & 0xC000) == 0xC000) { $permissions = 's'; // socket } elseif (($mode & 0xA000) == 0xA000) { $permissions = 'l'; // symbolic link } elseif (($mode & 0x8000) == 0x8000) { $permissions = '-'; // regular } elseif (($mode & 0x6000) == 0x6000) { $permissions = 'b'; // block special } elseif (($mode & 0x4000) == 0x4000) { $permissions = 'd'; // directory } elseif (($mode & 0x2000) == 0x2000) { $permissions = 'c'; // character special } elseif (($mode & 0x1000) == 0x1000) { $permissions = 'p'; // FIFO pipe } else { $permissions = 'u'; // unknown } // owner $permissions .= (($mode & 0x0100) ? 'r' : '-'); $permissions .= (($mode & 0x0080) ? 'w' : '-'); $permissions .= (($mode & 0x0040) ? (($mode & 0x0800) ? 's' : 'x') : (($mode & 0x0800) ? 'S' : '-')); // group $permissions .= (($mode & 0x0020) ? 'r' : '-'); $permissions .= (($mode & 0x0010) ? 'w' : '-'); $permissions .= (($mode & 0x0008) ? (($mode & 0x0400) ? 's' : 'x') : (($mode & 0x0400) ? 'S' : '-')); // world $permissions .= (($mode & 0x0004) ? 'r' : '-'); $permissions .= (($mode & 0x0002) ? 'w' : '-'); $permissions .= (($mode & 0x0001) ? (($mode & 0x0200) ? 't' : 'x') : (($mode & 0x0200) ? 'T' : '-')); return $permissions; }
php
public static function getStringRepresentation($mode) { $permissions = ''; if (($mode & 0xC000) == 0xC000) { $permissions = 's'; // socket } elseif (($mode & 0xA000) == 0xA000) { $permissions = 'l'; // symbolic link } elseif (($mode & 0x8000) == 0x8000) { $permissions = '-'; // regular } elseif (($mode & 0x6000) == 0x6000) { $permissions = 'b'; // block special } elseif (($mode & 0x4000) == 0x4000) { $permissions = 'd'; // directory } elseif (($mode & 0x2000) == 0x2000) { $permissions = 'c'; // character special } elseif (($mode & 0x1000) == 0x1000) { $permissions = 'p'; // FIFO pipe } else { $permissions = 'u'; // unknown } // owner $permissions .= (($mode & 0x0100) ? 'r' : '-'); $permissions .= (($mode & 0x0080) ? 'w' : '-'); $permissions .= (($mode & 0x0040) ? (($mode & 0x0800) ? 's' : 'x') : (($mode & 0x0800) ? 'S' : '-')); // group $permissions .= (($mode & 0x0020) ? 'r' : '-'); $permissions .= (($mode & 0x0010) ? 'w' : '-'); $permissions .= (($mode & 0x0008) ? (($mode & 0x0400) ? 's' : 'x') : (($mode & 0x0400) ? 'S' : '-')); // world $permissions .= (($mode & 0x0004) ? 'r' : '-'); $permissions .= (($mode & 0x0002) ? 'w' : '-'); $permissions .= (($mode & 0x0001) ? (($mode & 0x0200) ? 't' : 'x') : (($mode & 0x0200) ? 'T' : '-')); return $permissions; }
[ "public", "static", "function", "getStringRepresentation", "(", "$", "mode", ")", "{", "$", "permissions", "=", "''", ";", "if", "(", "(", "$", "mode", "&", "0xC000", ")", "==", "0xC000", ")", "{", "$", "permissions", "=", "'s'", ";", "// socket", "}", "elseif", "(", "(", "$", "mode", "&", "0xA000", ")", "==", "0xA000", ")", "{", "$", "permissions", "=", "'l'", ";", "// symbolic link", "}", "elseif", "(", "(", "$", "mode", "&", "0x8000", ")", "==", "0x8000", ")", "{", "$", "permissions", "=", "'-'", ";", "// regular", "}", "elseif", "(", "(", "$", "mode", "&", "0x6000", ")", "==", "0x6000", ")", "{", "$", "permissions", "=", "'b'", ";", "// block special", "}", "elseif", "(", "(", "$", "mode", "&", "0x4000", ")", "==", "0x4000", ")", "{", "$", "permissions", "=", "'d'", ";", "// directory", "}", "elseif", "(", "(", "$", "mode", "&", "0x2000", ")", "==", "0x2000", ")", "{", "$", "permissions", "=", "'c'", ";", "// character special", "}", "elseif", "(", "(", "$", "mode", "&", "0x1000", ")", "==", "0x1000", ")", "{", "$", "permissions", "=", "'p'", ";", "// FIFO pipe", "}", "else", "{", "$", "permissions", "=", "'u'", ";", "// unknown", "}", "// owner", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0100", ")", "?", "'r'", ":", "'-'", ")", ";", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0080", ")", "?", "'w'", ":", "'-'", ")", ";", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0040", ")", "?", "(", "(", "$", "mode", "&", "0x0800", ")", "?", "'s'", ":", "'x'", ")", ":", "(", "(", "$", "mode", "&", "0x0800", ")", "?", "'S'", ":", "'-'", ")", ")", ";", "// group", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0020", ")", "?", "'r'", ":", "'-'", ")", ";", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0010", ")", "?", "'w'", ":", "'-'", ")", ";", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0008", ")", "?", "(", "(", "$", "mode", "&", "0x0400", ")", "?", "'s'", ":", "'x'", ")", ":", "(", "(", "$", "mode", "&", "0x0400", ")", "?", "'S'", ":", "'-'", ")", ")", ";", "// world", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0004", ")", "?", "'r'", ":", "'-'", ")", ";", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0002", ")", "?", "'w'", ":", "'-'", ")", ";", "$", "permissions", ".=", "(", "(", "$", "mode", "&", "0x0001", ")", "?", "(", "(", "$", "mode", "&", "0x0200", ")", "?", "'t'", ":", "'x'", ")", ":", "(", "(", "$", "mode", "&", "0x0200", ")", "?", "'T'", ":", "'-'", ")", ")", ";", "return", "$", "permissions", ";", "}" ]
Gives a string representation of the permissions. See "Example #2 Display full permissions" on http://php.net/manual/en/function.fileperms.php @param int $mode @return FilePermissionCalculator
[ "Gives", "a", "string", "representation", "of", "the", "permissions", "." ]
train
https://github.com/gisostallenberg/file-permission-calculator/blob/ac7fa1fe3c0792890c3834d0e978964dbb1cdbd8/src/FilePermissionCalculator.php#L175-L219
gisostallenberg/file-permission-calculator
src/FilePermissionCalculator.php
FilePermissionCalculator.getModeFromStringRepresentation
public static function getModeFromStringRepresentation($permissions) { if (strlen($permissions) !== 10) { throw new InvalidArgumentException('Please provide a 10 character long string'); } $mode = 0; if ($permissions[0] == 's') { $mode = 0140000; } elseif ($permissions[0] == 'l') { $mode = 0120000; } elseif ($permissions[0] == '-') { $mode = 0100000; } elseif ($permissions[0] == 'b') { $mode = 060000; } elseif ($permissions[0] == 'd') { $mode = 040000; } elseif ($permissions[0] == 'c') { $mode = 020000; } elseif ($permissions[0] == 'p') { $mode = 010000; } elseif ($permissions[0] == 'u') { $mode = 0; } if ($permissions[1] == 'r') { $mode += 0400; } if ($permissions[2] == 'w') { $mode += 0200; } if ($permissions[3] == 'x') { $mode += 0100; } elseif ($permissions[3] == 's') { $mode += 04100; } elseif ($permissions[3] == 'S') { $mode += 04000; } if ($permissions[4] == 'r') { $mode += 040; } if ($permissions[5] == 'w') { $mode += 020; } if ($permissions[6] == 'x') { $mode += 010; } elseif ($permissions[6] == 's') { $mode += 02010; } elseif ($permissions[6] == 'S') { $mode += 02000; } if ($permissions[7] == 'r') { $mode += 04; } if ($permissions[8] == 'w') { $mode += 02; } if ($permissions[9] == 'x') { $mode += 01; } elseif ($permissions[9] == 't') { $mode += 01001; } elseif ($permissions[9] == 'T') { $mode += 01000; } return $mode; }
php
public static function getModeFromStringRepresentation($permissions) { if (strlen($permissions) !== 10) { throw new InvalidArgumentException('Please provide a 10 character long string'); } $mode = 0; if ($permissions[0] == 's') { $mode = 0140000; } elseif ($permissions[0] == 'l') { $mode = 0120000; } elseif ($permissions[0] == '-') { $mode = 0100000; } elseif ($permissions[0] == 'b') { $mode = 060000; } elseif ($permissions[0] == 'd') { $mode = 040000; } elseif ($permissions[0] == 'c') { $mode = 020000; } elseif ($permissions[0] == 'p') { $mode = 010000; } elseif ($permissions[0] == 'u') { $mode = 0; } if ($permissions[1] == 'r') { $mode += 0400; } if ($permissions[2] == 'w') { $mode += 0200; } if ($permissions[3] == 'x') { $mode += 0100; } elseif ($permissions[3] == 's') { $mode += 04100; } elseif ($permissions[3] == 'S') { $mode += 04000; } if ($permissions[4] == 'r') { $mode += 040; } if ($permissions[5] == 'w') { $mode += 020; } if ($permissions[6] == 'x') { $mode += 010; } elseif ($permissions[6] == 's') { $mode += 02010; } elseif ($permissions[6] == 'S') { $mode += 02000; } if ($permissions[7] == 'r') { $mode += 04; } if ($permissions[8] == 'w') { $mode += 02; } if ($permissions[9] == 'x') { $mode += 01; } elseif ($permissions[9] == 't') { $mode += 01001; } elseif ($permissions[9] == 'T') { $mode += 01000; } return $mode; }
[ "public", "static", "function", "getModeFromStringRepresentation", "(", "$", "permissions", ")", "{", "if", "(", "strlen", "(", "$", "permissions", ")", "!==", "10", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Please provide a 10 character long string'", ")", ";", "}", "$", "mode", "=", "0", ";", "if", "(", "$", "permissions", "[", "0", "]", "==", "'s'", ")", "{", "$", "mode", "=", "0140000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'l'", ")", "{", "$", "mode", "=", "0120000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'-'", ")", "{", "$", "mode", "=", "0100000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'b'", ")", "{", "$", "mode", "=", "060000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'d'", ")", "{", "$", "mode", "=", "040000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'c'", ")", "{", "$", "mode", "=", "020000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'p'", ")", "{", "$", "mode", "=", "010000", ";", "}", "elseif", "(", "$", "permissions", "[", "0", "]", "==", "'u'", ")", "{", "$", "mode", "=", "0", ";", "}", "if", "(", "$", "permissions", "[", "1", "]", "==", "'r'", ")", "{", "$", "mode", "+=", "0400", ";", "}", "if", "(", "$", "permissions", "[", "2", "]", "==", "'w'", ")", "{", "$", "mode", "+=", "0200", ";", "}", "if", "(", "$", "permissions", "[", "3", "]", "==", "'x'", ")", "{", "$", "mode", "+=", "0100", ";", "}", "elseif", "(", "$", "permissions", "[", "3", "]", "==", "'s'", ")", "{", "$", "mode", "+=", "04100", ";", "}", "elseif", "(", "$", "permissions", "[", "3", "]", "==", "'S'", ")", "{", "$", "mode", "+=", "04000", ";", "}", "if", "(", "$", "permissions", "[", "4", "]", "==", "'r'", ")", "{", "$", "mode", "+=", "040", ";", "}", "if", "(", "$", "permissions", "[", "5", "]", "==", "'w'", ")", "{", "$", "mode", "+=", "020", ";", "}", "if", "(", "$", "permissions", "[", "6", "]", "==", "'x'", ")", "{", "$", "mode", "+=", "010", ";", "}", "elseif", "(", "$", "permissions", "[", "6", "]", "==", "'s'", ")", "{", "$", "mode", "+=", "02010", ";", "}", "elseif", "(", "$", "permissions", "[", "6", "]", "==", "'S'", ")", "{", "$", "mode", "+=", "02000", ";", "}", "if", "(", "$", "permissions", "[", "7", "]", "==", "'r'", ")", "{", "$", "mode", "+=", "04", ";", "}", "if", "(", "$", "permissions", "[", "8", "]", "==", "'w'", ")", "{", "$", "mode", "+=", "02", ";", "}", "if", "(", "$", "permissions", "[", "9", "]", "==", "'x'", ")", "{", "$", "mode", "+=", "01", ";", "}", "elseif", "(", "$", "permissions", "[", "9", "]", "==", "'t'", ")", "{", "$", "mode", "+=", "01001", ";", "}", "elseif", "(", "$", "permissions", "[", "9", "]", "==", "'T'", ")", "{", "$", "mode", "+=", "01000", ";", "}", "return", "$", "mode", ";", "}" ]
Converts the string representation to a mode. See comment of 'paul maybe at squirrel mail org' on http://php.net/manual/en/function.chmod.php @param string $permissions @return int
[ "Converts", "the", "string", "representation", "to", "a", "mode", "." ]
train
https://github.com/gisostallenberg/file-permission-calculator/blob/ac7fa1fe3c0792890c3834d0e978964dbb1cdbd8/src/FilePermissionCalculator.php#L230-L298
esperecyan/dictionary-php
src/parser/PictsenseParser.php
PictsenseParser.parseLine
protected function parseLine(string $line): string { if (!$this->isHiraganaCodePoints($line)) { throw new SyntaxException(_('ピクトセンスで使用可能の文字はひらがな、「ヴ」「ー」のみです。ただし、「ゔ」「ゕ」「ゖ」「𛀁」も使用できません: ') . $line); } if (mb_strlen($line, 'UTF-8') > self::WORD_MAX) { throw new SyntaxException(sprintf(_('「%1$s」は%2$d文字を越えています。'), $line, self::WORDS_MAX)); } return str_replace('ヴ', 'ゔ', $line); }
php
protected function parseLine(string $line): string { if (!$this->isHiraganaCodePoints($line)) { throw new SyntaxException(_('ピクトセンスで使用可能の文字はひらがな、「ヴ」「ー」のみです。ただし、「ゔ」「ゕ」「ゖ」「𛀁」も使用できません: ') . $line); } if (mb_strlen($line, 'UTF-8') > self::WORD_MAX) { throw new SyntaxException(sprintf(_('「%1$s」は%2$d文字を越えています。'), $line, self::WORDS_MAX)); } return str_replace('ヴ', 'ゔ', $line); }
[ "protected", "function", "parseLine", "(", "string", "$", "line", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "isHiraganaCodePoints", "(", "$", "line", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'ピクトセンスで使用可能の文字はひらがな、「ヴ」「ー」のみです。ただし、「ゔ」「ゕ」「ゖ」「𛀁」も使用できません: ') . $line);", "", "", "", "", "", "", "}", "if", "(", "mb_strlen", "(", "$", "line", ",", "'UTF-8'", ")", ">", "self", "::", "WORD_MAX", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%1$s」は%2$d文字を越えています。'), $line, self::WORDS_MAX)", ")", ";", "", "", "", "", "", "", "", "", "", "}", "return", "str_replace", "(", "'ヴ', ", "'", "', $l", "i", "e", ");", "", "", "}" ]
行を解析します。 @param string $line @throws SyntaxException ひらがな以外が含まれている。字数制限を超えている。 @return string
[ "行を解析します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/PictsenseParser.php#L49-L60
Wonail/wocenter
libs/Utils.php
Utils.getIpLocation
public static function getIpLocation() { $last_ip = static::getClientIp(); $last_location = ''; if ($last_ip) { //如果获取到客户端IP,则获取其物理位置 $Ip = new IpLocation(); // 实例化类 $location = $Ip->getlocation($last_ip); // 获取某个IP地址所在的位置 if ($location['country'] && $location['country'] != 'CZ88.NET') $last_location .= $location['country']; if ($location['area'] && $location['area'] != 'CZ88.NET') $last_location .= ' ' . $location['area']; } return $last_location; }
php
public static function getIpLocation() { $last_ip = static::getClientIp(); $last_location = ''; if ($last_ip) { //如果获取到客户端IP,则获取其物理位置 $Ip = new IpLocation(); // 实例化类 $location = $Ip->getlocation($last_ip); // 获取某个IP地址所在的位置 if ($location['country'] && $location['country'] != 'CZ88.NET') $last_location .= $location['country']; if ($location['area'] && $location['area'] != 'CZ88.NET') $last_location .= ' ' . $location['area']; } return $last_location; }
[ "public", "static", "function", "getIpLocation", "(", ")", "{", "$", "last_ip", "=", "static", "::", "getClientIp", "(", ")", ";", "$", "last_location", "=", "''", ";", "if", "(", "$", "last_ip", ")", "{", "//如果获取到客户端IP,则获取其物理位置", "$", "Ip", "=", "new", "IpLocation", "(", ")", ";", "// 实例化类", "$", "location", "=", "$", "Ip", "->", "getlocation", "(", "$", "last_ip", ")", ";", "// 获取某个IP地址所在的位置", "if", "(", "$", "location", "[", "'country'", "]", "&&", "$", "location", "[", "'country'", "]", "!=", "'CZ88.NET'", ")", "$", "last_location", ".=", "$", "location", "[", "'country'", "]", ";", "if", "(", "$", "location", "[", "'area'", "]", "&&", "$", "location", "[", "'area'", "]", "!=", "'CZ88.NET'", ")", "$", "last_location", ".=", "' '", ".", "$", "location", "[", "'area'", "]", ";", "}", "return", "$", "last_location", ";", "}" ]
获取客户端IP地址信息 @return mixed
[ "获取客户端IP地址信息" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/libs/Utils.php#L62-L78
Wonail/wocenter
libs/Utils.php
Utils.formatBytes
public static function formatBytes($size, $delimiter = '') { $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024; return round($size, 2) . $delimiter . $units[$i]; }
php
public static function formatBytes($size, $delimiter = '') { $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024; return round($size, 2) . $delimiter . $units[$i]; }
[ "public", "static", "function", "formatBytes", "(", "$", "size", ",", "$", "delimiter", "=", "''", ")", "{", "$", "units", "=", "[", "'B'", ",", "'KB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "size", ">=", "1024", "&&", "$", "i", "<", "5", ";", "$", "i", "++", ")", "$", "size", "/=", "1024", ";", "return", "round", "(", "$", "size", ",", "2", ")", ".", "$", "delimiter", ".", "$", "units", "[", "$", "i", "]", ";", "}" ]
格式化字节大小 @param number $size 字节数 @param string $delimiter 数字和单位分隔符 @return string 格式化后的带单位的大小
[ "格式化字节大小" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/libs/Utils.php#L88-L95
Wonail/wocenter
libs/Utils.php
Utils.pagination
public static function pagination($query, $defaultPageSize = 20) { $pagination = new Pagination([ 'totalCount' => $query->count(), 'defaultPageSize' => $defaultPageSize, ]); $result = $query->offset($pagination->offset) ->limit($pagination->limit) ->all(); return ['pages' => $pagination, 'result' => $result]; }
php
public static function pagination($query, $defaultPageSize = 20) { $pagination = new Pagination([ 'totalCount' => $query->count(), 'defaultPageSize' => $defaultPageSize, ]); $result = $query->offset($pagination->offset) ->limit($pagination->limit) ->all(); return ['pages' => $pagination, 'result' => $result]; }
[ "public", "static", "function", "pagination", "(", "$", "query", ",", "$", "defaultPageSize", "=", "20", ")", "{", "$", "pagination", "=", "new", "Pagination", "(", "[", "'totalCount'", "=>", "$", "query", "->", "count", "(", ")", ",", "'defaultPageSize'", "=>", "$", "defaultPageSize", ",", "]", ")", ";", "$", "result", "=", "$", "query", "->", "offset", "(", "$", "pagination", "->", "offset", ")", "->", "limit", "(", "$", "pagination", "->", "limit", ")", "->", "all", "(", ")", ";", "return", "[", "'pages'", "=>", "$", "pagination", ",", "'result'", "=>", "$", "result", "]", ";", "}" ]
Example: ```php $query = new \yii\db\Query; $query->select('*') ->from('{{%post}}') ->where('user_id=:user_id', [':user_id' => $user->id]); $pages = Utils::Pagination($query); $posts = $pages['result']; foreach($posts as $post) { echo $post['content']; } echo \yii\widgets\LinkPager::widget([ 'pagination' => $pages['pages'], ]); ``` @param Query $query SELECT SQL statement @param $defaultPageSize @return array ['result', 'pages']
[ "Example", ":" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/libs/Utils.php#L120-L132
Atlantic18/CoralCoreBundle
Service/Request/CurlRequestHandle.php
CurlRequestHandle.setHeader
public function setHeader($key, $value) { $this->headers[$key] = $value; //Headers can't be passed as key: value associative array $tmpHeaders = array(); foreach($this->headers as $tmpKey => $tmpValue) { $tmpHeaders[] = "$tmpKey: $tmpValue"; } curl_setopt($this->handle, CURLOPT_HTTPHEADER, $tmpHeaders); }
php
public function setHeader($key, $value) { $this->headers[$key] = $value; //Headers can't be passed as key: value associative array $tmpHeaders = array(); foreach($this->headers as $tmpKey => $tmpValue) { $tmpHeaders[] = "$tmpKey: $tmpValue"; } curl_setopt($this->handle, CURLOPT_HTTPHEADER, $tmpHeaders); }
[ "public", "function", "setHeader", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "headers", "[", "$", "key", "]", "=", "$", "value", ";", "//Headers can't be passed as key: value associative array", "$", "tmpHeaders", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "tmpKey", "=>", "$", "tmpValue", ")", "{", "$", "tmpHeaders", "[", "]", "=", "\"$tmpKey: $tmpValue\"", ";", "}", "curl_setopt", "(", "$", "this", "->", "handle", ",", "CURLOPT_HTTPHEADER", ",", "$", "tmpHeaders", ")", ";", "}" ]
Set request header @param string $key Request header key @param string $value Request header value
[ "Set", "request", "header" ]
train
https://github.com/Atlantic18/CoralCoreBundle/blob/7d74ffaf51046ad13cbfc2b0b69d656a499f38ab/Service/Request/CurlRequestHandle.php#L62-L74
Atlantic18/CoralCoreBundle
Service/Request/CurlRequestHandle.php
CurlRequestHandle.execute
public function execute() { $rawResponse = curl_exec($this->handle); $this->responseCode = curl_getinfo($this->handle, CURLINFO_HTTP_CODE); if(false === $rawResponse) { curl_close($this->handle); throw new ConnectorException('Unable to connect to CORAL backend. Response code: ' . $this->responseCode); } $this->responseHeaderSize = curl_getinfo($this->handle, CURLINFO_HEADER_SIZE); curl_close($this->handle); return $rawResponse; }
php
public function execute() { $rawResponse = curl_exec($this->handle); $this->responseCode = curl_getinfo($this->handle, CURLINFO_HTTP_CODE); if(false === $rawResponse) { curl_close($this->handle); throw new ConnectorException('Unable to connect to CORAL backend. Response code: ' . $this->responseCode); } $this->responseHeaderSize = curl_getinfo($this->handle, CURLINFO_HEADER_SIZE); curl_close($this->handle); return $rawResponse; }
[ "public", "function", "execute", "(", ")", "{", "$", "rawResponse", "=", "curl_exec", "(", "$", "this", "->", "handle", ")", ";", "$", "this", "->", "responseCode", "=", "curl_getinfo", "(", "$", "this", "->", "handle", ",", "CURLINFO_HTTP_CODE", ")", ";", "if", "(", "false", "===", "$", "rawResponse", ")", "{", "curl_close", "(", "$", "this", "->", "handle", ")", ";", "throw", "new", "ConnectorException", "(", "'Unable to connect to CORAL backend. Response code: '", ".", "$", "this", "->", "responseCode", ")", ";", "}", "$", "this", "->", "responseHeaderSize", "=", "curl_getinfo", "(", "$", "this", "->", "handle", ",", "CURLINFO_HEADER_SIZE", ")", ";", "curl_close", "(", "$", "this", "->", "handle", ")", ";", "return", "$", "rawResponse", ";", "}" ]
Execute request @return string Response
[ "Execute", "request" ]
train
https://github.com/Atlantic18/CoralCoreBundle/blob/7d74ffaf51046ad13cbfc2b0b69d656a499f38ab/Service/Request/CurlRequestHandle.php#L81-L96
FrenchFrogs/framework
src/Container/Head.php
Head.meta
public function meta($name, $content, $conditional = null) { $meta = html('meta', ['name' => $name, 'content' => $content]); // if conditionnal if (!is_null($conditional)) { $meta = '<!--[if '.$conditional.']>'.PHP_EOL . $meta . PHP_EOL . '<![endif]-->'; } return $this->append($meta); }
php
public function meta($name, $content, $conditional = null) { $meta = html('meta', ['name' => $name, 'content' => $content]); // if conditionnal if (!is_null($conditional)) { $meta = '<!--[if '.$conditional.']>'.PHP_EOL . $meta . PHP_EOL . '<![endif]-->'; } return $this->append($meta); }
[ "public", "function", "meta", "(", "$", "name", ",", "$", "content", ",", "$", "conditional", "=", "null", ")", "{", "$", "meta", "=", "html", "(", "'meta'", ",", "[", "'name'", "=>", "$", "name", ",", "'content'", "=>", "$", "content", "]", ")", ";", "// if conditionnal", "if", "(", "!", "is_null", "(", "$", "conditional", ")", ")", "{", "$", "meta", "=", "'<!--[if '", ".", "$", "conditional", ".", "']>'", ".", "PHP_EOL", ".", "$", "meta", ".", "PHP_EOL", ".", "'<![endif]-->'", ";", "}", "return", "$", "this", "->", "append", "(", "$", "meta", ")", ";", "}" ]
Meta @param $name @param $content @param null $conditional @return $this
[ "Meta" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Container/Head.php#L23-L33
FrenchFrogs/framework
src/Container/Head.php
Head.identity
public function identity($title, $description) { $this->title($title); $this->meta('description', $description); return $this; }
php
public function identity($title, $description) { $this->title($title); $this->meta('description', $description); return $this; }
[ "public", "function", "identity", "(", "$", "title", ",", "$", "description", ")", "{", "$", "this", "->", "title", "(", "$", "title", ")", ";", "$", "this", "->", "meta", "(", "'description'", ",", "$", "description", ")", ";", "return", "$", "this", ";", "}" ]
Fast identity set @param $title @param $description @return $this
[ "Fast", "identity", "set" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Container/Head.php#L43-L48
FrenchFrogs/framework
src/Container/Head.php
Head.fb
public function fb($title = null, $site = null, $url = null, $description = null, $type = null, $app = null) { if (!is_null($title)) { $this->property('og:title', $title); } if (!is_null($site)) { $this->property('og:site_name', $site); } if (!is_null($url)) { $this->property('og:url', $url); } if (!is_null($description)) { $this->property('og:description', $description); } if (!is_null($url)) { $this->property('og:type', $type); } if (!is_null($app)) { $this->property('fb:app_id', $app); } }
php
public function fb($title = null, $site = null, $url = null, $description = null, $type = null, $app = null) { if (!is_null($title)) { $this->property('og:title', $title); } if (!is_null($site)) { $this->property('og:site_name', $site); } if (!is_null($url)) { $this->property('og:url', $url); } if (!is_null($description)) { $this->property('og:description', $description); } if (!is_null($url)) { $this->property('og:type', $type); } if (!is_null($app)) { $this->property('fb:app_id', $app); } }
[ "public", "function", "fb", "(", "$", "title", "=", "null", ",", "$", "site", "=", "null", ",", "$", "url", "=", "null", ",", "$", "description", "=", "null", ",", "$", "type", "=", "null", ",", "$", "app", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "title", ")", ")", "{", "$", "this", "->", "property", "(", "'og:title'", ",", "$", "title", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "site", ")", ")", "{", "$", "this", "->", "property", "(", "'og:site_name'", ",", "$", "site", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "url", ")", ")", "{", "$", "this", "->", "property", "(", "'og:url'", ",", "$", "url", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "description", ")", ")", "{", "$", "this", "->", "property", "(", "'og:description'", ",", "$", "description", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "url", ")", ")", "{", "$", "this", "->", "property", "(", "'og:type'", ",", "$", "type", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "app", ")", ")", "{", "$", "this", "->", "property", "(", "'fb:app_id'", ",", "$", "app", ")", ";", "}", "}" ]
Usefool facebook open graph @param null $title @param null $site @param null $url @param null $description @param null $type @param null $app
[ "Usefool", "facebook", "open", "graph" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Container/Head.php#L95-L120
FrenchFrogs/framework
src/Container/Head.php
Head.twitter
public function twitter($title, $site, $description, $image = null, $card = 'summary') { $this->meta('twitter:card', $card); $this->meta('twitter:site', $site); $this->meta('twitter:title', $title); $this->meta('twitter:description', $description); $this->meta('twitter:card', $title); if (!is_null($image)) { $this->meta('twitter:image', $image); } }
php
public function twitter($title, $site, $description, $image = null, $card = 'summary') { $this->meta('twitter:card', $card); $this->meta('twitter:site', $site); $this->meta('twitter:title', $title); $this->meta('twitter:description', $description); $this->meta('twitter:card', $title); if (!is_null($image)) { $this->meta('twitter:image', $image); } }
[ "public", "function", "twitter", "(", "$", "title", ",", "$", "site", ",", "$", "description", ",", "$", "image", "=", "null", ",", "$", "card", "=", "'summary'", ")", "{", "$", "this", "->", "meta", "(", "'twitter:card'", ",", "$", "card", ")", ";", "$", "this", "->", "meta", "(", "'twitter:site'", ",", "$", "site", ")", ";", "$", "this", "->", "meta", "(", "'twitter:title'", ",", "$", "title", ")", ";", "$", "this", "->", "meta", "(", "'twitter:description'", ",", "$", "description", ")", ";", "$", "this", "->", "meta", "(", "'twitter:card'", ",", "$", "title", ")", ";", "if", "(", "!", "is_null", "(", "$", "image", ")", ")", "{", "$", "this", "->", "meta", "(", "'twitter:image'", ",", "$", "image", ")", ";", "}", "}" ]
Set twitter meta @param string $card @param $site @param $title @param $description @param null $image
[ "Set", "twitter", "meta" ]
train
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Container/Head.php#L131-L142