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
flipboxstudio/orm-manager
src/Flipbox/OrmManager/Relations/HasManyThrough.php
HasManyThrough.beforeApplyOptions
protected function beforeApplyOptions($stub) { $refModel = new ReflectionClass($this->model); $refIntermeidateModel = new ReflectionClass($this->defaultOptions['intermediate_model']); $model = $refIntermeidateModel->getShortName(); if ($refModel->getNamespaceName() !== $refIntermeidateModel->getNamespaceName()) { $model = '\\'.$refIntermeidateModel->getName(); } return str_replace('DummyIntermediateModel', $model, $stub); }
php
protected function beforeApplyOptions($stub) { $refModel = new ReflectionClass($this->model); $refIntermeidateModel = new ReflectionClass($this->defaultOptions['intermediate_model']); $model = $refIntermeidateModel->getShortName(); if ($refModel->getNamespaceName() !== $refIntermeidateModel->getNamespaceName()) { $model = '\\'.$refIntermeidateModel->getName(); } return str_replace('DummyIntermediateModel', $model, $stub); }
[ "protected", "function", "beforeApplyOptions", "(", "$", "stub", ")", "{", "$", "refModel", "=", "new", "ReflectionClass", "(", "$", "this", "->", "model", ")", ";", "$", "refIntermeidateModel", "=", "new", "ReflectionClass", "(", "$", "this", "->", "defaultOptions", "[", "'intermediate_model'", "]", ")", ";", "$", "model", "=", "$", "refIntermeidateModel", "->", "getShortName", "(", ")", ";", "if", "(", "$", "refModel", "->", "getNamespaceName", "(", ")", "!==", "$", "refIntermeidateModel", "->", "getNamespaceName", "(", ")", ")", "{", "$", "model", "=", "'\\\\'", ".", "$", "refIntermeidateModel", "->", "getName", "(", ")", ";", "}", "return", "str_replace", "(", "'DummyIntermediateModel'", ",", "$", "model", ",", "$", "stub", ")", ";", "}" ]
replace more before apply options code @param string $stub @return string
[ "replace", "more", "before", "apply", "options", "code" ]
train
https://github.com/flipboxstudio/orm-manager/blob/4288426517f53d05177b8729c4ba94c5beca9a98/src/Flipbox/OrmManager/Relations/HasManyThrough.php#L147-L159
barebone-php/barebone-core
lib/Session.php
Session.instance
public static function instance() { if (null === self::$_instance) { $session_factory = new SessionFactory; $session = $session_factory->newInstance($_COOKIE); $segment = $session->getSegment('Barebone\Session'); self::$_instance = $segment; } return self::$_instance; }
php
public static function instance() { if (null === self::$_instance) { $session_factory = new SessionFactory; $session = $session_factory->newInstance($_COOKIE); $segment = $session->getSegment('Barebone\Session'); self::$_instance = $segment; } return self::$_instance; }
[ "public", "static", "function", "instance", "(", ")", "{", "if", "(", "null", "===", "self", "::", "$", "_instance", ")", "{", "$", "session_factory", "=", "new", "SessionFactory", ";", "$", "session", "=", "$", "session_factory", "->", "newInstance", "(", "$", "_COOKIE", ")", ";", "$", "segment", "=", "$", "session", "->", "getSegment", "(", "'Barebone\\Session'", ")", ";", "self", "::", "$", "_instance", "=", "$", "segment", ";", "}", "return", "self", "::", "$", "_instance", ";", "}" ]
Instantiate Session Segment @return Segment
[ "Instantiate", "Session", "Segment" ]
train
https://github.com/barebone-php/barebone-core/blob/7fda3a62d5fa103cdc4d2d34e1adf8f3ccbfe2bc/lib/Session.php#L46-L56
yuncms/framework
src/rest/models/User.php
User.fields
public function fields() { return [ 'id', 'nickname', 'faceUrl' => function () { return $this->getAvatar(AvatarHelper::AVATAR_MIDDLE); }, 'identified', "created_datetime" => function () { return gmdate(DATE_ISO8601, $this->created_at); }, "updated_datetime" => function () { return gmdate(DATE_ISO8601, $this->updated_at); }, 'blocked_datetime' => function () { return gmdate(DATE_ISO8601, $this->blocked_at); } ]; }
php
public function fields() { return [ 'id', 'nickname', 'faceUrl' => function () { return $this->getAvatar(AvatarHelper::AVATAR_MIDDLE); }, 'identified', "created_datetime" => function () { return gmdate(DATE_ISO8601, $this->created_at); }, "updated_datetime" => function () { return gmdate(DATE_ISO8601, $this->updated_at); }, 'blocked_datetime' => function () { return gmdate(DATE_ISO8601, $this->blocked_at); } ]; }
[ "public", "function", "fields", "(", ")", "{", "return", "[", "'id'", ",", "'nickname'", ",", "'faceUrl'", "=>", "function", "(", ")", "{", "return", "$", "this", "->", "getAvatar", "(", "AvatarHelper", "::", "AVATAR_MIDDLE", ")", ";", "}", ",", "'identified'", ",", "\"created_datetime\"", "=>", "function", "(", ")", "{", "return", "gmdate", "(", "DATE_ISO8601", ",", "$", "this", "->", "created_at", ")", ";", "}", ",", "\"updated_datetime\"", "=>", "function", "(", ")", "{", "return", "gmdate", "(", "DATE_ISO8601", ",", "$", "this", "->", "updated_at", ")", ";", "}", ",", "'blocked_datetime'", "=>", "function", "(", ")", "{", "return", "gmdate", "(", "DATE_ISO8601", ",", "$", "this", "->", "blocked_at", ")", ";", "}", "]", ";", "}" ]
客户端允许访问的字段 @return array
[ "客户端允许访问的字段" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/rest/models/User.php#L24-L43
CakeCMS/Core
src/Theme.php
Theme.setup
public static function setup($prefix = null) { $theme = self::name($prefix); $path = self::find($theme); if ($path !== null) { $config = self::getData($theme, 'meta'); if ($config->get('type') == 'theme') { return $theme; } } return null; }
php
public static function setup($prefix = null) { $theme = self::name($prefix); $path = self::find($theme); if ($path !== null) { $config = self::getData($theme, 'meta'); if ($config->get('type') == 'theme') { return $theme; } } return null; }
[ "public", "static", "function", "setup", "(", "$", "prefix", "=", "null", ")", "{", "$", "theme", "=", "self", "::", "name", "(", "$", "prefix", ")", ";", "$", "path", "=", "self", "::", "find", "(", "$", "theme", ")", ";", "if", "(", "$", "path", "!==", "null", ")", "{", "$", "config", "=", "self", "::", "getData", "(", "$", "theme", ",", "'meta'", ")", ";", "if", "(", "$", "config", "->", "get", "(", "'type'", ")", "==", "'theme'", ")", "{", "return", "$", "theme", ";", "}", "}", "return", "null", ";", "}" ]
Setup current theme. @param null|string $prefix @return null|string
[ "Setup", "current", "theme", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Theme.php#L36-L49
CakeCMS/Core
src/Theme.php
Theme.find
public static function find($theme) { $paths = App::path('Plugin'); foreach ($paths as $path) { $path = FS::clean($path . '/', DS); $themeFolder = $path . $theme; if (FS::isDir($themeFolder)) { return $themeFolder; } } return Configure::read('plugins.' . $theme); }
php
public static function find($theme) { $paths = App::path('Plugin'); foreach ($paths as $path) { $path = FS::clean($path . '/', DS); $themeFolder = $path . $theme; if (FS::isDir($themeFolder)) { return $themeFolder; } } return Configure::read('plugins.' . $theme); }
[ "public", "static", "function", "find", "(", "$", "theme", ")", "{", "$", "paths", "=", "App", "::", "path", "(", "'Plugin'", ")", ";", "foreach", "(", "$", "paths", "as", "$", "path", ")", "{", "$", "path", "=", "FS", "::", "clean", "(", "$", "path", ".", "'/'", ",", "DS", ")", ";", "$", "themeFolder", "=", "$", "path", ".", "$", "theme", ";", "if", "(", "FS", "::", "isDir", "(", "$", "themeFolder", ")", ")", "{", "return", "$", "themeFolder", ";", "}", "}", "return", "Configure", "::", "read", "(", "'plugins.'", ".", "$", "theme", ")", ";", "}" ]
Find theme plugin in path. @param string $theme @return null|string
[ "Find", "theme", "plugin", "in", "path", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Theme.php#L68-L81
liugene/framework
src/Controller.php
Controller.error
protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = []) { if (is_null($url)) { $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);'; } elseif ('' !== $url && !strpos($url, '://') && 0 !== strpos($url, '/')) { $url = $this->request->scheme() . '://' . $this->request->host() . '/' . $url; } $type = $this->getResponseType(); $result = [ 'code' => 0, 'msg' => $msg, 'data' => $data, 'url' => $url, 'wait' => $wait, ]; if ('view' == strtolower($type)) { $this->assign('code', $result['code']); $this->assign('msg', $result['msg']); $this->assign('data', $result['data']); $this->assign('url', $result['url']); $this->assign('wait', $result['wait']); $result = $this->display(Config::get('dispatch_error_tmpl')); } HttpResponse::create($result, $type)->header($header)->send(); }
php
protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = []) { if (is_null($url)) { $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);'; } elseif ('' !== $url && !strpos($url, '://') && 0 !== strpos($url, '/')) { $url = $this->request->scheme() . '://' . $this->request->host() . '/' . $url; } $type = $this->getResponseType(); $result = [ 'code' => 0, 'msg' => $msg, 'data' => $data, 'url' => $url, 'wait' => $wait, ]; if ('view' == strtolower($type)) { $this->assign('code', $result['code']); $this->assign('msg', $result['msg']); $this->assign('data', $result['data']); $this->assign('url', $result['url']); $this->assign('wait', $result['wait']); $result = $this->display(Config::get('dispatch_error_tmpl')); } HttpResponse::create($result, $type)->header($header)->send(); }
[ "protected", "function", "error", "(", "$", "msg", "=", "''", ",", "$", "url", "=", "null", ",", "$", "data", "=", "''", ",", "$", "wait", "=", "3", ",", "array", "$", "header", "=", "[", "]", ")", "{", "if", "(", "is_null", "(", "$", "url", ")", ")", "{", "$", "url", "=", "$", "this", "->", "request", "->", "isAjax", "(", ")", "?", "''", ":", "'javascript:history.back(-1);'", ";", "}", "elseif", "(", "''", "!==", "$", "url", "&&", "!", "strpos", "(", "$", "url", ",", "'://'", ")", "&&", "0", "!==", "strpos", "(", "$", "url", ",", "'/'", ")", ")", "{", "$", "url", "=", "$", "this", "->", "request", "->", "scheme", "(", ")", ".", "'://'", ".", "$", "this", "->", "request", "->", "host", "(", ")", ".", "'/'", ".", "$", "url", ";", "}", "$", "type", "=", "$", "this", "->", "getResponseType", "(", ")", ";", "$", "result", "=", "[", "'code'", "=>", "0", ",", "'msg'", "=>", "$", "msg", ",", "'data'", "=>", "$", "data", ",", "'url'", "=>", "$", "url", ",", "'wait'", "=>", "$", "wait", ",", "]", ";", "if", "(", "'view'", "==", "strtolower", "(", "$", "type", ")", ")", "{", "$", "this", "->", "assign", "(", "'code'", ",", "$", "result", "[", "'code'", "]", ")", ";", "$", "this", "->", "assign", "(", "'msg'", ",", "$", "result", "[", "'msg'", "]", ")", ";", "$", "this", "->", "assign", "(", "'data'", ",", "$", "result", "[", "'data'", "]", ")", ";", "$", "this", "->", "assign", "(", "'url'", ",", "$", "result", "[", "'url'", "]", ")", ";", "$", "this", "->", "assign", "(", "'wait'", ",", "$", "result", "[", "'wait'", "]", ")", ";", "$", "result", "=", "$", "this", "->", "display", "(", "Config", "::", "get", "(", "'dispatch_error_tmpl'", ")", ")", ";", "}", "HttpResponse", "::", "create", "(", "$", "result", ",", "$", "type", ")", "->", "header", "(", "$", "header", ")", "->", "send", "(", ")", ";", "}" ]
操作错误跳转的快捷方法 @access protected @param mixed $msg 提示信息 @param string $url 跳转的 URL 地址 @param mixed $data 返回的数据 @param int $wait 跳转等待时间 @param array $header 发送的 Header 信息 @return void
[ "操作错误跳转的快捷方法" ]
train
https://github.com/liugene/framework/blob/450642242442c5884d47552a588a2639923e7289/src/Controller.php#L108-L136
liugene/framework
src/Controller.php
Controller.getReturnType
public function getReturnType($action) { if(isset($this->returnType[$action])){ return $this->returnType[$action]; } return false; }
php
public function getReturnType($action) { if(isset($this->returnType[$action])){ return $this->returnType[$action]; } return false; }
[ "public", "function", "getReturnType", "(", "$", "action", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "returnType", "[", "$", "action", "]", ")", ")", "{", "return", "$", "this", "->", "returnType", "[", "$", "action", "]", ";", "}", "return", "false", ";", "}" ]
获取当前的 response 输出类型 @access public @param $action string 方法 ['view', 'json', 'console', 'xml', 'jsonp'] @return string|boolean
[ "获取当前的", "response", "输出类型" ]
train
https://github.com/liugene/framework/blob/450642242442c5884d47552a588a2639923e7289/src/Controller.php#L173-L181
ipunkt/laravel-package-manager
src/Providers/ConfigurationServiceProvider.php
ConfigurationServiceProvider.register
public function register() { $this->configurations()->each(function (array $configuration) { $this->mergeConfigFrom( $this->packagePath($configuration['file']), $configuration['key'] ); if ($this->app->runningInConsole()) { $this->publishes([ $this->packagePath($configuration['file']) => config_path($configuration['alias']), ], 'config'); } }); }
php
public function register() { $this->configurations()->each(function (array $configuration) { $this->mergeConfigFrom( $this->packagePath($configuration['file']), $configuration['key'] ); if ($this->app->runningInConsole()) { $this->publishes([ $this->packagePath($configuration['file']) => config_path($configuration['alias']), ], 'config'); } }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "configurations", "(", ")", "->", "each", "(", "function", "(", "array", "$", "configuration", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "$", "this", "->", "packagePath", "(", "$", "configuration", "[", "'file'", "]", ")", ",", "$", "configuration", "[", "'key'", "]", ")", ";", "if", "(", "$", "this", "->", "app", "->", "runningInConsole", "(", ")", ")", "{", "$", "this", "->", "publishes", "(", "[", "$", "this", "->", "packagePath", "(", "$", "configuration", "[", "'file'", "]", ")", "=>", "config_path", "(", "$", "configuration", "[", "'alias'", "]", ")", ",", "]", ",", "'config'", ")", ";", "}", "}", ")", ";", "}" ]
registering
[ "registering" ]
train
https://github.com/ipunkt/laravel-package-manager/blob/6ecfc9d933c37927e52c441d5019126be69e5817/src/Providers/ConfigurationServiceProvider.php#L26-L39
ipunkt/laravel-package-manager
src/Providers/ConfigurationServiceProvider.php
ConfigurationServiceProvider.configurations
protected function configurations(): Collection { $configurations = collect(); foreach ($this->configurationFiles as $alias => $file) { if (is_numeric($alias)) { $alias = $file; } $key = $alias; if (ends_with($key, '.php')) { $key = str_replace('.php', '', $key); } $configurations->push([ 'file' => $file, 'alias' => $alias, 'key' => $key, ]); } return $configurations; }
php
protected function configurations(): Collection { $configurations = collect(); foreach ($this->configurationFiles as $alias => $file) { if (is_numeric($alias)) { $alias = $file; } $key = $alias; if (ends_with($key, '.php')) { $key = str_replace('.php', '', $key); } $configurations->push([ 'file' => $file, 'alias' => $alias, 'key' => $key, ]); } return $configurations; }
[ "protected", "function", "configurations", "(", ")", ":", "Collection", "{", "$", "configurations", "=", "collect", "(", ")", ";", "foreach", "(", "$", "this", "->", "configurationFiles", "as", "$", "alias", "=>", "$", "file", ")", "{", "if", "(", "is_numeric", "(", "$", "alias", ")", ")", "{", "$", "alias", "=", "$", "file", ";", "}", "$", "key", "=", "$", "alias", ";", "if", "(", "ends_with", "(", "$", "key", ",", "'.php'", ")", ")", "{", "$", "key", "=", "str_replace", "(", "'.php'", ",", "''", ",", "$", "key", ")", ";", "}", "$", "configurations", "->", "push", "(", "[", "'file'", "=>", "$", "file", ",", "'alias'", "=>", "$", "alias", ",", "'key'", "=>", "$", "key", ",", "]", ")", ";", "}", "return", "$", "configurations", ";", "}" ]
prepares configuration @return \Illuminate\Support\Collection
[ "prepares", "configuration" ]
train
https://github.com/ipunkt/laravel-package-manager/blob/6ecfc9d933c37927e52c441d5019126be69e5817/src/Providers/ConfigurationServiceProvider.php#L46-L68
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/Sitemap/Changefreq.php
Zend_Validate_Sitemap_Changefreq.isValid
public function isValid($value) { $this->_setValue($value); if (!is_string($value)) { return false; } if (!in_array($value, $this->_changeFreqs, true)) { $this->_error(); return false; } return true; }
php
public function isValid($value) { $this->_setValue($value); if (!is_string($value)) { return false; } if (!in_array($value, $this->_changeFreqs, true)) { $this->_error(); return false; } return true; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "this", "->", "_setValue", "(", "$", "value", ")", ";", "if", "(", "!", "is_string", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "in_array", "(", "$", "value", ",", "$", "this", "->", "_changeFreqs", ",", "true", ")", ")", "{", "$", "this", "->", "_error", "(", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validates if a string is valid as a sitemap changefreq @link http://www.sitemaps.org/protocol.php#changefreqdef <changefreq> @param string $value value to validate @return boolean
[ "Validates", "if", "a", "string", "is", "valid", "as", "a", "sitemap", "changefreq" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/Sitemap/Changefreq.php#L73-L87
ekho/lumberjack-php
src/SecureSocket.php
SecureSocket.mergeOptions
private function mergeOptions(array $options) { foreach ($options as $key => $value) { if (!in_array($key, self::$acceptableOptions)) { throw new InvalidArgumentException("Option '{$key}' does not supported"); } $this->options[$key] = $value; } }
php
private function mergeOptions(array $options) { foreach ($options as $key => $value) { if (!in_array($key, self::$acceptableOptions)) { throw new InvalidArgumentException("Option '{$key}' does not supported"); } $this->options[$key] = $value; } }
[ "private", "function", "mergeOptions", "(", "array", "$", "options", ")", "{", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "self", "::", "$", "acceptableOptions", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Option '{$key}' does not supported\"", ")", ";", "}", "$", "this", "->", "options", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}" ]
merge options @param array $options @throws InvalidArgumentException
[ "merge", "options" ]
train
https://github.com/ekho/lumberjack-php/blob/c2d0d88c6917f8e165d6f828569873df35750ecd/src/SecureSocket.php#L306-L314
liugene/framework
src/Application.php
Application.router
static public function router($rule='',$tag='') { if($rule && $tag){ return self::make(\linkphp\router\Router::class)->rule($rule,$tag); } return self::make(\linkphp\router\Router::class); }
php
static public function router($rule='',$tag='') { if($rule && $tag){ return self::make(\linkphp\router\Router::class)->rule($rule,$tag); } return self::make(\linkphp\router\Router::class); }
[ "static", "public", "function", "router", "(", "$", "rule", "=", "''", ",", "$", "tag", "=", "''", ")", "{", "if", "(", "$", "rule", "&&", "$", "tag", ")", "{", "return", "self", "::", "make", "(", "\\", "linkphp", "\\", "router", "\\", "Router", "::", "class", ")", "->", "rule", "(", "$", "rule", ",", "$", "tag", ")", ";", "}", "return", "self", "::", "make", "(", "\\", "linkphp", "\\", "router", "\\", "Router", "::", "class", ")", ";", "}" ]
获取环境实例 @param string $rule @param string $tag @return Router
[ "获取环境实例" ]
train
https://github.com/liugene/framework/blob/450642242442c5884d47552a588a2639923e7289/src/Application.php#L66-L74
liugene/framework
src/Application.php
Application.event
static public function event($server='',$events='', $eager=false) { $eventObject = self::get('linkphp\event\Event'); if($server == '') return $eventObject; if($events != ''){ if(is_array($events)){ $first = false; foreach($events as $event){ if($first){ $eventObject->getEventMap($server) ->register(new $event); continue; } $eventObject->provider( self::eventDefinition() ->setServer($server) ->register(new $event) ); $first=true; } } else { $eventObject->provider( self::eventDefinition() ->setServer($server) ->register(new $events) ); } if(!$eager){ return; } } return $eventObject->target($server); }
php
static public function event($server='',$events='', $eager=false) { $eventObject = self::get('linkphp\event\Event'); if($server == '') return $eventObject; if($events != ''){ if(is_array($events)){ $first = false; foreach($events as $event){ if($first){ $eventObject->getEventMap($server) ->register(new $event); continue; } $eventObject->provider( self::eventDefinition() ->setServer($server) ->register(new $event) ); $first=true; } } else { $eventObject->provider( self::eventDefinition() ->setServer($server) ->register(new $events) ); } if(!$eager){ return; } } return $eventObject->target($server); }
[ "static", "public", "function", "event", "(", "$", "server", "=", "''", ",", "$", "events", "=", "''", ",", "$", "eager", "=", "false", ")", "{", "$", "eventObject", "=", "self", "::", "get", "(", "'linkphp\\event\\Event'", ")", ";", "if", "(", "$", "server", "==", "''", ")", "return", "$", "eventObject", ";", "if", "(", "$", "events", "!=", "''", ")", "{", "if", "(", "is_array", "(", "$", "events", ")", ")", "{", "$", "first", "=", "false", ";", "foreach", "(", "$", "events", "as", "$", "event", ")", "{", "if", "(", "$", "first", ")", "{", "$", "eventObject", "->", "getEventMap", "(", "$", "server", ")", "->", "register", "(", "new", "$", "event", ")", ";", "continue", ";", "}", "$", "eventObject", "->", "provider", "(", "self", "::", "eventDefinition", "(", ")", "->", "setServer", "(", "$", "server", ")", "->", "register", "(", "new", "$", "event", ")", ")", ";", "$", "first", "=", "true", ";", "}", "}", "else", "{", "$", "eventObject", "->", "provider", "(", "self", "::", "eventDefinition", "(", ")", "->", "setServer", "(", "$", "server", ")", "->", "register", "(", "new", "$", "events", ")", ")", ";", "}", "if", "(", "!", "$", "eager", ")", "{", "return", ";", "}", "}", "return", "$", "eventObject", "->", "target", "(", "$", "server", ")", ";", "}" ]
获取事件类实例 @param string $server @param string|array $events @param bool $eager 是否立即执行 @return mixed
[ "获取事件类实例" ]
train
https://github.com/liugene/framework/blob/450642242442c5884d47552a588a2639923e7289/src/Application.php#L221-L254
cohesion/cohesion-core
src/Environment/HTTPEnvironment.php
HTTPEnvironment.getHighestSupportedValue
private function getHighestSupportedValue($str, $supported) { $accepts = explode(',', $str); $types = array(); foreach ($accepts as $accept) { $tmp = explode(';', trim($accept)); $q = 1; if (count($tmp) > 1) { if (preg_match('/q=(\d+(?:\.\d+)?)/', $tmp[1], $matches)) { $q = $matches[1]; } } if ($q > 0) { $types[strtolower(trim($tmp[0]))] = $q; } } arsort($types); foreach ($types as $type => $q) { if (in_array($type, $supported)) { return $type; } } return null; }
php
private function getHighestSupportedValue($str, $supported) { $accepts = explode(',', $str); $types = array(); foreach ($accepts as $accept) { $tmp = explode(';', trim($accept)); $q = 1; if (count($tmp) > 1) { if (preg_match('/q=(\d+(?:\.\d+)?)/', $tmp[1], $matches)) { $q = $matches[1]; } } if ($q > 0) { $types[strtolower(trim($tmp[0]))] = $q; } } arsort($types); foreach ($types as $type => $q) { if (in_array($type, $supported)) { return $type; } } return null; }
[ "private", "function", "getHighestSupportedValue", "(", "$", "str", ",", "$", "supported", ")", "{", "$", "accepts", "=", "explode", "(", "','", ",", "$", "str", ")", ";", "$", "types", "=", "array", "(", ")", ";", "foreach", "(", "$", "accepts", "as", "$", "accept", ")", "{", "$", "tmp", "=", "explode", "(", "';'", ",", "trim", "(", "$", "accept", ")", ")", ";", "$", "q", "=", "1", ";", "if", "(", "count", "(", "$", "tmp", ")", ">", "1", ")", "{", "if", "(", "preg_match", "(", "'/q=(\\d+(?:\\.\\d+)?)/'", ",", "$", "tmp", "[", "1", "]", ",", "$", "matches", ")", ")", "{", "$", "q", "=", "$", "matches", "[", "1", "]", ";", "}", "}", "if", "(", "$", "q", ">", "0", ")", "{", "$", "types", "[", "strtolower", "(", "trim", "(", "$", "tmp", "[", "0", "]", ")", ")", "]", "=", "$", "q", ";", "}", "}", "arsort", "(", "$", "types", ")", ";", "foreach", "(", "$", "types", "as", "$", "type", "=>", "$", "q", ")", "{", "if", "(", "in_array", "(", "$", "type", ",", "$", "supported", ")", ")", "{", "return", "$", "type", ";", "}", "}", "return", "null", ";", "}" ]
Returns the highest value found in the string that is within the supported array For use with headers such as: Accept: text/html,application/xhtml+xml,application/xml;q=0.9 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6 @param $str The header string to use @param $supported an array of supported values @return The supported value with the highest weighting or NULL if there are no matches
[ "Returns", "the", "highest", "value", "found", "in", "the", "string", "that", "is", "within", "the", "supported", "array", "For", "use", "with", "headers", "such", "as", ":", "Accept", ":", "text", "/", "html", "application", "/", "xhtml", "+", "xml", "application", "/", "xml", ";", "q", "=", "0", ".", "9", "Accept", "-", "Encoding", ":", "gzip", "deflate", "sdch", "Accept", "-", "Language", ":", "en", "-", "GB", "en", "-", "US", ";", "q", "=", "0", ".", "8", "en", ";", "q", "=", "0", ".", "6" ]
train
https://github.com/cohesion/cohesion-core/blob/c6352aef7336e06285f0943da68235dc45523998/src/Environment/HTTPEnvironment.php#L87-L109
PortaText/php-sdk
src/PortaText/Client/Curl.php
Curl.execute
public function execute($descriptor) { $curl = @curl_init(); $headers = array(); foreach ($descriptor->headers as $k => $v) { $headers[] = "$k: $v"; } $fileHandle = null; $fileHandleW = null; $headers[] = "Expect:"; $state = "reading_status"; $retCode = 0; $retHeaders = array(); $retBody = ''; $curlOpts = array( CURLOPT_URL => $descriptor->uri, CURLOPT_HEADER => true, CURLOPT_CUSTOMREQUEST => strtoupper($descriptor->method), CURLOPT_USERAGENT => "PortaText PHP SDK", CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => false, CURLOPT_SSL_VERIFYPEER => true, //CURLOPT_VERBOSE => true, CURLOPT_POSTFIELDS => $descriptor->body ); if (!is_null($descriptor->outputFile)) { $fileHandleW = $this->openFile($descriptor->outputFile, 'w+'); } if (strncmp($descriptor->body, "file:", 5) === 0) { $fileData = explode(":", $descriptor->body); $filename = $fileData[1]; $fileHandle = $this->openFile($filename, 'r'); unset($curlOpts[CURLOPT_POSTFIELDS]); $curlOpts[CURLOPT_UPLOAD] = 1; $curlOpts[CURLOPT_INFILESIZE] = filesize($filename); $curlOpts[CURLOPT_INFILE] = $fileHandle; $curlOpts[CURLOPT_BUFFERSIZE] = 4096; $curlOpts[CURLOPT_NOPROGRESS] = true; } $curlOpts[CURLOPT_WRITEFUNCTION] = function ( $resource, $data ) use ( // @codeCoverageIgnoreStart &$state, &$retCode, &$retHeaders, &$retBody, $fileHandleW // @codeCoverageIgnoreEnd ) { $resource = null; // make MD happy $dataLen = strlen($data); if ($state === "reading_status") { $retCode = $this->parseCode($data); $state = "reading_headers"; return $dataLen; } if ($state === "reading_headers") { if ($data === "\r\n") { $state = "reading_body"; return $dataLen; } list($k, $v) = $this->parseHeader($data); $retHeaders[$k] = $v; return $dataLen; } if ($state === "reading_body") { if ($fileHandleW) { return @fwrite($fileHandleW, $data); } $retBody .= $data; return $dataLen; } }; //@codeCoverageIgnore @curl_setopt_array($curl, $curlOpts); $result = curl_exec($curl); $this->closeFiles(array($fileHandleW, $fileHandle)); $this->assertCurlResult($curl, $result, $descriptor); return array($retCode, $retHeaders, $retBody); }
php
public function execute($descriptor) { $curl = @curl_init(); $headers = array(); foreach ($descriptor->headers as $k => $v) { $headers[] = "$k: $v"; } $fileHandle = null; $fileHandleW = null; $headers[] = "Expect:"; $state = "reading_status"; $retCode = 0; $retHeaders = array(); $retBody = ''; $curlOpts = array( CURLOPT_URL => $descriptor->uri, CURLOPT_HEADER => true, CURLOPT_CUSTOMREQUEST => strtoupper($descriptor->method), CURLOPT_USERAGENT => "PortaText PHP SDK", CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => false, CURLOPT_SSL_VERIFYPEER => true, //CURLOPT_VERBOSE => true, CURLOPT_POSTFIELDS => $descriptor->body ); if (!is_null($descriptor->outputFile)) { $fileHandleW = $this->openFile($descriptor->outputFile, 'w+'); } if (strncmp($descriptor->body, "file:", 5) === 0) { $fileData = explode(":", $descriptor->body); $filename = $fileData[1]; $fileHandle = $this->openFile($filename, 'r'); unset($curlOpts[CURLOPT_POSTFIELDS]); $curlOpts[CURLOPT_UPLOAD] = 1; $curlOpts[CURLOPT_INFILESIZE] = filesize($filename); $curlOpts[CURLOPT_INFILE] = $fileHandle; $curlOpts[CURLOPT_BUFFERSIZE] = 4096; $curlOpts[CURLOPT_NOPROGRESS] = true; } $curlOpts[CURLOPT_WRITEFUNCTION] = function ( $resource, $data ) use ( // @codeCoverageIgnoreStart &$state, &$retCode, &$retHeaders, &$retBody, $fileHandleW // @codeCoverageIgnoreEnd ) { $resource = null; // make MD happy $dataLen = strlen($data); if ($state === "reading_status") { $retCode = $this->parseCode($data); $state = "reading_headers"; return $dataLen; } if ($state === "reading_headers") { if ($data === "\r\n") { $state = "reading_body"; return $dataLen; } list($k, $v) = $this->parseHeader($data); $retHeaders[$k] = $v; return $dataLen; } if ($state === "reading_body") { if ($fileHandleW) { return @fwrite($fileHandleW, $data); } $retBody .= $data; return $dataLen; } }; //@codeCoverageIgnore @curl_setopt_array($curl, $curlOpts); $result = curl_exec($curl); $this->closeFiles(array($fileHandleW, $fileHandle)); $this->assertCurlResult($curl, $result, $descriptor); return array($retCode, $retHeaders, $retBody); }
[ "public", "function", "execute", "(", "$", "descriptor", ")", "{", "$", "curl", "=", "@", "curl_init", "(", ")", ";", "$", "headers", "=", "array", "(", ")", ";", "foreach", "(", "$", "descriptor", "->", "headers", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "headers", "[", "]", "=", "\"$k: $v\"", ";", "}", "$", "fileHandle", "=", "null", ";", "$", "fileHandleW", "=", "null", ";", "$", "headers", "[", "]", "=", "\"Expect:\"", ";", "$", "state", "=", "\"reading_status\"", ";", "$", "retCode", "=", "0", ";", "$", "retHeaders", "=", "array", "(", ")", ";", "$", "retBody", "=", "''", ";", "$", "curlOpts", "=", "array", "(", "CURLOPT_URL", "=>", "$", "descriptor", "->", "uri", ",", "CURLOPT_HEADER", "=>", "true", ",", "CURLOPT_CUSTOMREQUEST", "=>", "strtoupper", "(", "$", "descriptor", "->", "method", ")", ",", "CURLOPT_USERAGENT", "=>", "\"PortaText PHP SDK\"", ",", "CURLOPT_HTTPHEADER", "=>", "$", "headers", ",", "CURLOPT_RETURNTRANSFER", "=>", "false", ",", "CURLOPT_SSL_VERIFYPEER", "=>", "true", ",", "//CURLOPT_VERBOSE => true,", "CURLOPT_POSTFIELDS", "=>", "$", "descriptor", "->", "body", ")", ";", "if", "(", "!", "is_null", "(", "$", "descriptor", "->", "outputFile", ")", ")", "{", "$", "fileHandleW", "=", "$", "this", "->", "openFile", "(", "$", "descriptor", "->", "outputFile", ",", "'w+'", ")", ";", "}", "if", "(", "strncmp", "(", "$", "descriptor", "->", "body", ",", "\"file:\"", ",", "5", ")", "===", "0", ")", "{", "$", "fileData", "=", "explode", "(", "\":\"", ",", "$", "descriptor", "->", "body", ")", ";", "$", "filename", "=", "$", "fileData", "[", "1", "]", ";", "$", "fileHandle", "=", "$", "this", "->", "openFile", "(", "$", "filename", ",", "'r'", ")", ";", "unset", "(", "$", "curlOpts", "[", "CURLOPT_POSTFIELDS", "]", ")", ";", "$", "curlOpts", "[", "CURLOPT_UPLOAD", "]", "=", "1", ";", "$", "curlOpts", "[", "CURLOPT_INFILESIZE", "]", "=", "filesize", "(", "$", "filename", ")", ";", "$", "curlOpts", "[", "CURLOPT_INFILE", "]", "=", "$", "fileHandle", ";", "$", "curlOpts", "[", "CURLOPT_BUFFERSIZE", "]", "=", "4096", ";", "$", "curlOpts", "[", "CURLOPT_NOPROGRESS", "]", "=", "true", ";", "}", "$", "curlOpts", "[", "CURLOPT_WRITEFUNCTION", "]", "=", "function", "(", "$", "resource", ",", "$", "data", ")", "use", "(", "// @codeCoverageIgnoreStart", "&", "$", "state", ",", "&", "$", "retCode", ",", "&", "$", "retHeaders", ",", "&", "$", "retBody", ",", "$", "fileHandleW", "// @codeCoverageIgnoreEnd", ")", "{", "$", "resource", "=", "null", ";", "// make MD happy", "$", "dataLen", "=", "strlen", "(", "$", "data", ")", ";", "if", "(", "$", "state", "===", "\"reading_status\"", ")", "{", "$", "retCode", "=", "$", "this", "->", "parseCode", "(", "$", "data", ")", ";", "$", "state", "=", "\"reading_headers\"", ";", "return", "$", "dataLen", ";", "}", "if", "(", "$", "state", "===", "\"reading_headers\"", ")", "{", "if", "(", "$", "data", "===", "\"\\r\\n\"", ")", "{", "$", "state", "=", "\"reading_body\"", ";", "return", "$", "dataLen", ";", "}", "list", "(", "$", "k", ",", "$", "v", ")", "=", "$", "this", "->", "parseHeader", "(", "$", "data", ")", ";", "$", "retHeaders", "[", "$", "k", "]", "=", "$", "v", ";", "return", "$", "dataLen", ";", "}", "if", "(", "$", "state", "===", "\"reading_body\"", ")", "{", "if", "(", "$", "fileHandleW", ")", "{", "return", "@", "fwrite", "(", "$", "fileHandleW", ",", "$", "data", ")", ";", "}", "$", "retBody", ".=", "$", "data", ";", "return", "$", "dataLen", ";", "}", "}", ";", "//@codeCoverageIgnore", "@", "curl_setopt_array", "(", "$", "curl", ",", "$", "curlOpts", ")", ";", "$", "result", "=", "curl_exec", "(", "$", "curl", ")", ";", "$", "this", "->", "closeFiles", "(", "array", "(", "$", "fileHandleW", ",", "$", "fileHandle", ")", ")", ";", "$", "this", "->", "assertCurlResult", "(", "$", "curl", ",", "$", "result", ",", "$", "descriptor", ")", ";", "return", "array", "(", "$", "retCode", ",", "$", "retHeaders", ",", "$", "retBody", ")", ";", "}" ]
Executes the request. Will depend on the client implementation. Returns an array with code, headers, and body. @param PortaText\Command\Descriptor $descriptor Command descriptor. @return array @throws PortaText\Exception\RequestError
[ "Executes", "the", "request", ".", "Will", "depend", "on", "the", "client", "implementation", ".", "Returns", "an", "array", "with", "code", "headers", "and", "body", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Client/Curl.php#L27-L107
PortaText/php-sdk
src/PortaText/Client/Curl.php
Curl.assertCurlResult
private function assertCurlResult($curl, $result, $descriptor) { if ($result === false) { $error = curl_error($curl); @curl_close($curl); throw new RequestError($error, $descriptor); } @curl_close($curl); return $result; }
php
private function assertCurlResult($curl, $result, $descriptor) { if ($result === false) { $error = curl_error($curl); @curl_close($curl); throw new RequestError($error, $descriptor); } @curl_close($curl); return $result; }
[ "private", "function", "assertCurlResult", "(", "$", "curl", ",", "$", "result", ",", "$", "descriptor", ")", "{", "if", "(", "$", "result", "===", "false", ")", "{", "$", "error", "=", "curl_error", "(", "$", "curl", ")", ";", "@", "curl_close", "(", "$", "curl", ")", ";", "throw", "new", "RequestError", "(", "$", "error", ",", "$", "descriptor", ")", ";", "}", "@", "curl_close", "(", "$", "curl", ")", ";", "return", "$", "result", ";", "}" ]
Asserts that the curl result was successful. @param resource $curl The curl resource. @param mixed $result The result. @param PortaText\Command\Descriptor $descriptor Command descriptor. @return mixed @throws PortaText\Exception\RequestError
[ "Asserts", "that", "the", "curl", "result", "was", "successful", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Client/Curl.php#L119-L128
PortaText/php-sdk
src/PortaText/Client/Curl.php
Curl.parseHeader
private function parseHeader($header) { list($key, $value) = explode(": ", trim($header), 2); return array(strtolower($key), $value); }
php
private function parseHeader($header) { list($key, $value) = explode(": ", trim($header), 2); return array(strtolower($key), $value); }
[ "private", "function", "parseHeader", "(", "$", "header", ")", "{", "list", "(", "$", "key", ",", "$", "value", ")", "=", "explode", "(", "\": \"", ",", "trim", "(", "$", "header", ")", ",", "2", ")", ";", "return", "array", "(", "strtolower", "(", "$", "key", ")", ",", "$", "value", ")", ";", "}" ]
Parses an HTTP header line. @param string $header The HTTP header line. @return array
[ "Parses", "an", "HTTP", "header", "line", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Client/Curl.php#L149-L153
PortaText/php-sdk
src/PortaText/Client/Curl.php
Curl.openFile
private function openFile($file, $mode) { $handle = @fopen($file, $mode); if ($handle === false) { throw new \InvalidArgumentException("Could not open $file"); } return $handle; }
php
private function openFile($file, $mode) { $handle = @fopen($file, $mode); if ($handle === false) { throw new \InvalidArgumentException("Could not open $file"); } return $handle; }
[ "private", "function", "openFile", "(", "$", "file", ",", "$", "mode", ")", "{", "$", "handle", "=", "@", "fopen", "(", "$", "file", ",", "$", "mode", ")", ";", "if", "(", "$", "handle", "===", "false", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Could not open $file\"", ")", ";", "}", "return", "$", "handle", ";", "}" ]
Opens a file and returns a file handle. @param string $file The filename. @param string $mode The mode. @return resource|false
[ "Opens", "a", "file", "and", "returns", "a", "file", "handle", "." ]
train
https://github.com/PortaText/php-sdk/blob/dbe04ef043db5b251953f9de57aa4d0f1785dfcc/src/PortaText/Client/Curl.php#L163-L170
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.addModule
public function addModule(Module $module) { $name = $module->getName(); if (isset($this->modules[$name])) { throw new \LogicException(sprintf('Trying to register two modules with the same name "%s"', $name)); } $this->view->addTemplatePath($module->getPath() . '/Resources/views'); $this->modules[$name] = $module; return $this; }
php
public function addModule(Module $module) { $name = $module->getName(); if (isset($this->modules[$name])) { throw new \LogicException(sprintf('Trying to register two modules with the same name "%s"', $name)); } $this->view->addTemplatePath($module->getPath() . '/Resources/views'); $this->modules[$name] = $module; return $this; }
[ "public", "function", "addModule", "(", "Module", "$", "module", ")", "{", "$", "name", "=", "$", "module", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "modules", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Trying to register two modules with the same name \"%s\"'", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "view", "->", "addTemplatePath", "(", "$", "module", "->", "getPath", "(", ")", ".", "'/Resources/views'", ")", ";", "$", "this", "->", "modules", "[", "$", "name", "]", "=", "$", "module", ";", "return", "$", "this", ";", "}" ]
Add Module @param Module $module @return Container @throws \LogicException
[ "Add", "Module" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L111-L121
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.addProvider
public function addProvider(Provider $provider) { $name = $provider->getName(); if (isset($this->providers[$name])) { throw new \LogicException(sprintf('Trying to register two providers with the same name "%s"', $name)); } $this->providers[$name] = $provider; return $this; }
php
public function addProvider(Provider $provider) { $name = $provider->getName(); if (isset($this->providers[$name])) { throw new \LogicException(sprintf('Trying to register two providers with the same name "%s"', $name)); } $this->providers[$name] = $provider; return $this; }
[ "public", "function", "addProvider", "(", "Provider", "$", "provider", ")", "{", "$", "name", "=", "$", "provider", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "providers", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Trying to register two providers with the same name \"%s\"'", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "providers", "[", "$", "name", "]", "=", "$", "provider", ";", "return", "$", "this", ";", "}" ]
Add Module @param Provider $provider @return Container @throws \LogicException
[ "Add", "Module" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L130-L139
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.addRoute
public function addRoute($route) { if (!$route instanceof Route && !is_array($route)) { throw new \LogicException('Route invalid. Expected Route instance or array.'); } elseif ($route instanceof Route) { $name = $route->getName(); if (isset($this->routes[$name])) { throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name)); } $this->routes[$route->getName()] = $route; } elseif (is_array($route) && !count($route) == 4) { throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).'); } else { list($methods, $patternUri, $action, $name) = array_values($route); $this->routes[$name] = new Route($methods, $patternUri, $action, $name); } return $this; }
php
public function addRoute($route) { if (!$route instanceof Route && !is_array($route)) { throw new \LogicException('Route invalid. Expected Route instance or array.'); } elseif ($route instanceof Route) { $name = $route->getName(); if (isset($this->routes[$name])) { throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name)); } $this->routes[$route->getName()] = $route; } elseif (is_array($route) && !count($route) == 4) { throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).'); } else { list($methods, $patternUri, $action, $name) = array_values($route); $this->routes[$name] = new Route($methods, $patternUri, $action, $name); } return $this; }
[ "public", "function", "addRoute", "(", "$", "route", ")", "{", "if", "(", "!", "$", "route", "instanceof", "Route", "&&", "!", "is_array", "(", "$", "route", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Route invalid. Expected Route instance or array.'", ")", ";", "}", "elseif", "(", "$", "route", "instanceof", "Route", ")", "{", "$", "name", "=", "$", "route", "->", "getName", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "routes", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Trying to register two routes with the same name \"%s\"'", ",", "$", "name", ")", ")", ";", "}", "$", "this", "->", "routes", "[", "$", "route", "->", "getName", "(", ")", "]", "=", "$", "route", ";", "}", "elseif", "(", "is_array", "(", "$", "route", ")", "&&", "!", "count", "(", "$", "route", ")", "==", "4", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).'", ")", ";", "}", "else", "{", "list", "(", "$", "methods", ",", "$", "patternUri", ",", "$", "action", ",", "$", "name", ")", "=", "array_values", "(", "$", "route", ")", ";", "$", "this", "->", "routes", "[", "$", "name", "]", "=", "new", "Route", "(", "$", "methods", ",", "$", "patternUri", ",", "$", "action", ",", "$", "name", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add Route @param Route|array $route @return Container @throws \LogicException
[ "Add", "Route" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L148-L167
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.getModule
public function getModule($name) { if (!isset($this->modules[$name])) { throw new \LogicException(sprintf('The module "%s" don\'t exists.', $name)); } return $this->modules[$name]; }
php
public function getModule($name) { if (!isset($this->modules[$name])) { throw new \LogicException(sprintf('The module "%s" don\'t exists.', $name)); } return $this->modules[$name]; }
[ "public", "function", "getModule", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "modules", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'The module \"%s\" don\\'t exists.'", ",", "$", "name", ")", ")", ";", "}", "return", "$", "this", "->", "modules", "[", "$", "name", "]", ";", "}" ]
Get Module @param string $name @return Module @throws \LogicException
[ "Get", "Module" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L186-L192
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.getProvider
public function getProvider($name) { if (!isset($this->providers[$name])) { throw new \LogicException(sprintf('The provider "%s" don\'t exists.', $name)); } return $this->providers[$name]; }
php
public function getProvider($name) { if (!isset($this->providers[$name])) { throw new \LogicException(sprintf('The provider "%s" don\'t exists.', $name)); } return $this->providers[$name]; }
[ "public", "function", "getProvider", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "providers", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'The provider \"%s\" don\\'t exists.'", ",", "$", "name", ")", ")", ";", "}", "return", "$", "this", "->", "providers", "[", "$", "name", "]", ";", "}" ]
Get Provider @param string $name @return Provider @throws \LogicException
[ "Get", "Provider" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L211-L217
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.getRoute
public function getRoute($name) { if (!isset($this->routes[$name])) { throw new \LogicException(sprintf('Route "%s" not found.', $name)); } return $this->routes[$name]; }
php
public function getRoute($name) { if (!isset($this->routes[$name])) { throw new \LogicException(sprintf('Route "%s" not found.', $name)); } return $this->routes[$name]; }
[ "public", "function", "getRoute", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "routes", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Route \"%s\" not found.'", ",", "$", "name", ")", ")", ";", "}", "return", "$", "this", "->", "routes", "[", "$", "name", "]", ";", "}" ]
Get Route from name @param string $name @return Route @throws \LogicException
[ "Get", "Route", "from", "name" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L266-L273
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.getSetting
public function getSetting($name) { if (!isset($this->settings[$name])) { throw new \LogicException(sprintf('The setting "%s" don\'t exists.', $name)); } return $this->settings[$name]; }
php
public function getSetting($name) { if (!isset($this->settings[$name])) { throw new \LogicException(sprintf('The setting "%s" don\'t exists.', $name)); } return $this->settings[$name]; }
[ "public", "function", "getSetting", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "settings", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'The setting \"%s\" don\\'t exists.'", ",", "$", "name", ")", ")", ";", "}", "return", "$", "this", "->", "settings", "[", "$", "name", "]", ";", "}" ]
Set setting from name @param string $name @return mixed @throws \LogicException
[ "Set", "setting", "from", "name" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L292-L298
simple-php-mvc/simple-php-mvc
src/MVC/Application/Container.php
Container.setSettings
public function setSettings(array $settings) { $this->settings = array_merge($this->settings, $settings); if (isset($settings['templates_path'])) { $this->view->templatesPath = $this->settings['templates_path']; } return $this; }
php
public function setSettings(array $settings) { $this->settings = array_merge($this->settings, $settings); if (isset($settings['templates_path'])) { $this->view->templatesPath = $this->settings['templates_path']; } return $this; }
[ "public", "function", "setSettings", "(", "array", "$", "settings", ")", "{", "$", "this", "->", "settings", "=", "array_merge", "(", "$", "this", "->", "settings", ",", "$", "settings", ")", ";", "if", "(", "isset", "(", "$", "settings", "[", "'templates_path'", "]", ")", ")", "{", "$", "this", "->", "view", "->", "templatesPath", "=", "$", "this", "->", "settings", "[", "'templates_path'", "]", ";", "}", "return", "$", "this", ";", "}" ]
Set settings @param array $settings @return Container
[ "Set", "settings" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/Application/Container.php#L422-L431
phrest/sdk
src/Generator/Helper/Files.php
Files.formPath
public static function formPath($version, $type, $entityName, $className) { return self::$outputDir . '/' . $version . '/' . $type . '/' . $entityName . '/' . $className . '.php'; }
php
public static function formPath($version, $type, $entityName, $className) { return self::$outputDir . '/' . $version . '/' . $type . '/' . $entityName . '/' . $className . '.php'; }
[ "public", "static", "function", "formPath", "(", "$", "version", ",", "$", "type", ",", "$", "entityName", ",", "$", "className", ")", "{", "return", "self", "::", "$", "outputDir", ".", "'/'", ".", "$", "version", ".", "'/'", ".", "$", "type", ".", "'/'", ".", "$", "entityName", ".", "'/'", ".", "$", "className", ".", "'.php'", ";", "}" ]
@param $version @param $type @param $entityName @param $className @return string
[ "@param", "$version", "@param", "$type", "@param", "$entityName", "@param", "$className" ]
train
https://github.com/phrest/sdk/blob/e9f2812ad517b07ca4d284512b530f615305eb47/src/Generator/Helper/Files.php#L62-L69
Articus/DataTransfer
src/Articus/DataTransfer/Metadata/Reader/Annotation.php
Annotation.getMetadata
public function getMetadata($className, $subset) { $classMetadataCacheKey = $this->getClassMetadataCacheKey($className); $classMetadata = $this->cacheStorage->getItem($classMetadataCacheKey); if ($classMetadata === null) { $classMetadata = $this->readClassMetadata($className); $this->cacheStorage->addItem($classMetadataCacheKey, $classMetadata); } if (!is_array($classMetadata)) { throw new \LogicException(sprintf('Invalid metadata for class %s.', $className)); } if (!isset($classMetadata[$subset])) { throw new \LogicException(sprintf('No metadata for subset "%s" in class %s.', $subset, $className)); } $subsetMetadata = $classMetadata[$subset]; if (!($subsetMetadata instanceof DT\Metadata)) { throw new \LogicException(sprintf('Invalid metadata for subset "%s" in class %s.', $subset, $className)); } return $subsetMetadata; }
php
public function getMetadata($className, $subset) { $classMetadataCacheKey = $this->getClassMetadataCacheKey($className); $classMetadata = $this->cacheStorage->getItem($classMetadataCacheKey); if ($classMetadata === null) { $classMetadata = $this->readClassMetadata($className); $this->cacheStorage->addItem($classMetadataCacheKey, $classMetadata); } if (!is_array($classMetadata)) { throw new \LogicException(sprintf('Invalid metadata for class %s.', $className)); } if (!isset($classMetadata[$subset])) { throw new \LogicException(sprintf('No metadata for subset "%s" in class %s.', $subset, $className)); } $subsetMetadata = $classMetadata[$subset]; if (!($subsetMetadata instanceof DT\Metadata)) { throw new \LogicException(sprintf('Invalid metadata for subset "%s" in class %s.', $subset, $className)); } return $subsetMetadata; }
[ "public", "function", "getMetadata", "(", "$", "className", ",", "$", "subset", ")", "{", "$", "classMetadataCacheKey", "=", "$", "this", "->", "getClassMetadataCacheKey", "(", "$", "className", ")", ";", "$", "classMetadata", "=", "$", "this", "->", "cacheStorage", "->", "getItem", "(", "$", "classMetadataCacheKey", ")", ";", "if", "(", "$", "classMetadata", "===", "null", ")", "{", "$", "classMetadata", "=", "$", "this", "->", "readClassMetadata", "(", "$", "className", ")", ";", "$", "this", "->", "cacheStorage", "->", "addItem", "(", "$", "classMetadataCacheKey", ",", "$", "classMetadata", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "classMetadata", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for class %s.'", ",", "$", "className", ")", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "classMetadata", "[", "$", "subset", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'No metadata for subset \"%s\" in class %s.'", ",", "$", "subset", ",", "$", "className", ")", ")", ";", "}", "$", "subsetMetadata", "=", "$", "classMetadata", "[", "$", "subset", "]", ";", "if", "(", "!", "(", "$", "subsetMetadata", "instanceof", "DT", "\\", "Metadata", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for subset \"%s\" in class %s.'", ",", "$", "subset", ",", "$", "className", ")", ")", ";", "}", "return", "$", "subsetMetadata", ";", "}" ]
Returns metadata for specified subset of class fields @param string $className @param string $subset @return DT\Metadata
[ "Returns", "metadata", "for", "specified", "subset", "of", "class", "fields" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Metadata/Reader/Annotation.php#L30-L53
Articus/DataTransfer
src/Articus/DataTransfer/Metadata/Reader/Annotation.php
Annotation.readClassMetadata
protected function readClassMetadata($className) { /** @var DT\Metadata[] $result */ $result = []; $reflection = new \ReflectionClass($className); $reader = new AnnotationReader(); //Read property annotations $propertyFilter = \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PRIVATE; foreach ($reflection->getProperties($propertyFilter) as $property) { foreach (self::readPropertyAnnotations($property, $reader) as $subset => list($data, $strategy, $validators)) { //Get or create metadata for subset $metadata = null; if (isset($result[$subset])) { $metadata = $result[$subset]; } else { $metadata = new DT\Metadata(); $metadata->className = $className; $metadata->subset = $subset; $result[$subset] = $metadata; } //Process field name $field = (empty($data->field)? $property->getName() : $data->field); if (in_array($field, $metadata->fields)) { throw new \LogicException( sprintf('Invalid metadata for %s: duplicate field %s in subset "%s".', $className, $field, $data->subset) ); } $metadata->fields[] = $field; //Process direct access property if ($property->isPublic()) { $metadata->properties[$field] = $property->getName(); } else { $methodNameBase = str_replace('_', '', ucwords($property->getName(), '_')); if ($data->getter === null) { $data->getter = 'get'. $methodNameBase; } if ($data->setter === null) { $data->setter = 'set'. $methodNameBase; } } //Process property getter if ((!empty($data->getter)) && self::isValidGetter($reflection, $data->getter)) { $metadata->getters[$field] = $data->getter; } //Process property setter if ((!empty($data->setter)) && self::isValidSetter($reflection, $data->setter)) { $metadata->setters[$field] = $data->setter; } //Copy strategy $metadata->strategies[$field] = $strategy; //Process nullable flag $metadata->nullables[$field] = $data->nullable; //Copy validators $metadata->validators[$field] = $validators; } } //Read class annotations foreach ($reader->getClassAnnotations($reflection) as $annotation) { if (($annotation instanceof DT\Annotation\Validator) && isset($result[$annotation->subset])) { $result[$annotation->subset]->validators[DT\Validator::GLOBAL_VALIDATOR_KEY][] = $annotation; } } return $result; }
php
protected function readClassMetadata($className) { /** @var DT\Metadata[] $result */ $result = []; $reflection = new \ReflectionClass($className); $reader = new AnnotationReader(); //Read property annotations $propertyFilter = \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PRIVATE; foreach ($reflection->getProperties($propertyFilter) as $property) { foreach (self::readPropertyAnnotations($property, $reader) as $subset => list($data, $strategy, $validators)) { //Get or create metadata for subset $metadata = null; if (isset($result[$subset])) { $metadata = $result[$subset]; } else { $metadata = new DT\Metadata(); $metadata->className = $className; $metadata->subset = $subset; $result[$subset] = $metadata; } //Process field name $field = (empty($data->field)? $property->getName() : $data->field); if (in_array($field, $metadata->fields)) { throw new \LogicException( sprintf('Invalid metadata for %s: duplicate field %s in subset "%s".', $className, $field, $data->subset) ); } $metadata->fields[] = $field; //Process direct access property if ($property->isPublic()) { $metadata->properties[$field] = $property->getName(); } else { $methodNameBase = str_replace('_', '', ucwords($property->getName(), '_')); if ($data->getter === null) { $data->getter = 'get'. $methodNameBase; } if ($data->setter === null) { $data->setter = 'set'. $methodNameBase; } } //Process property getter if ((!empty($data->getter)) && self::isValidGetter($reflection, $data->getter)) { $metadata->getters[$field] = $data->getter; } //Process property setter if ((!empty($data->setter)) && self::isValidSetter($reflection, $data->setter)) { $metadata->setters[$field] = $data->setter; } //Copy strategy $metadata->strategies[$field] = $strategy; //Process nullable flag $metadata->nullables[$field] = $data->nullable; //Copy validators $metadata->validators[$field] = $validators; } } //Read class annotations foreach ($reader->getClassAnnotations($reflection) as $annotation) { if (($annotation instanceof DT\Annotation\Validator) && isset($result[$annotation->subset])) { $result[$annotation->subset]->validators[DT\Validator::GLOBAL_VALIDATOR_KEY][] = $annotation; } } return $result; }
[ "protected", "function", "readClassMetadata", "(", "$", "className", ")", "{", "/** @var DT\\Metadata[] $result */", "$", "result", "=", "[", "]", ";", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "className", ")", ";", "$", "reader", "=", "new", "AnnotationReader", "(", ")", ";", "//Read property annotations", "$", "propertyFilter", "=", "\\", "ReflectionProperty", "::", "IS_PUBLIC", "|", "\\", "ReflectionProperty", "::", "IS_PROTECTED", "|", "\\", "ReflectionProperty", "::", "IS_PRIVATE", ";", "foreach", "(", "$", "reflection", "->", "getProperties", "(", "$", "propertyFilter", ")", "as", "$", "property", ")", "{", "foreach", "(", "self", "::", "readPropertyAnnotations", "(", "$", "property", ",", "$", "reader", ")", "as", "$", "subset", "=>", "list", "(", "$", "data", ",", "$", "strategy", ",", "$", "validators", ")", ")", "{", "//Get or create metadata for subset", "$", "metadata", "=", "null", ";", "if", "(", "isset", "(", "$", "result", "[", "$", "subset", "]", ")", ")", "{", "$", "metadata", "=", "$", "result", "[", "$", "subset", "]", ";", "}", "else", "{", "$", "metadata", "=", "new", "DT", "\\", "Metadata", "(", ")", ";", "$", "metadata", "->", "className", "=", "$", "className", ";", "$", "metadata", "->", "subset", "=", "$", "subset", ";", "$", "result", "[", "$", "subset", "]", "=", "$", "metadata", ";", "}", "//Process field name", "$", "field", "=", "(", "empty", "(", "$", "data", "->", "field", ")", "?", "$", "property", "->", "getName", "(", ")", ":", "$", "data", "->", "field", ")", ";", "if", "(", "in_array", "(", "$", "field", ",", "$", "metadata", "->", "fields", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: duplicate field %s in subset \"%s\".'", ",", "$", "className", ",", "$", "field", ",", "$", "data", "->", "subset", ")", ")", ";", "}", "$", "metadata", "->", "fields", "[", "]", "=", "$", "field", ";", "//Process direct access property", "if", "(", "$", "property", "->", "isPublic", "(", ")", ")", "{", "$", "metadata", "->", "properties", "[", "$", "field", "]", "=", "$", "property", "->", "getName", "(", ")", ";", "}", "else", "{", "$", "methodNameBase", "=", "str_replace", "(", "'_'", ",", "''", ",", "ucwords", "(", "$", "property", "->", "getName", "(", ")", ",", "'_'", ")", ")", ";", "if", "(", "$", "data", "->", "getter", "===", "null", ")", "{", "$", "data", "->", "getter", "=", "'get'", ".", "$", "methodNameBase", ";", "}", "if", "(", "$", "data", "->", "setter", "===", "null", ")", "{", "$", "data", "->", "setter", "=", "'set'", ".", "$", "methodNameBase", ";", "}", "}", "//Process property getter", "if", "(", "(", "!", "empty", "(", "$", "data", "->", "getter", ")", ")", "&&", "self", "::", "isValidGetter", "(", "$", "reflection", ",", "$", "data", "->", "getter", ")", ")", "{", "$", "metadata", "->", "getters", "[", "$", "field", "]", "=", "$", "data", "->", "getter", ";", "}", "//Process property setter", "if", "(", "(", "!", "empty", "(", "$", "data", "->", "setter", ")", ")", "&&", "self", "::", "isValidSetter", "(", "$", "reflection", ",", "$", "data", "->", "setter", ")", ")", "{", "$", "metadata", "->", "setters", "[", "$", "field", "]", "=", "$", "data", "->", "setter", ";", "}", "//Copy strategy", "$", "metadata", "->", "strategies", "[", "$", "field", "]", "=", "$", "strategy", ";", "//Process nullable flag", "$", "metadata", "->", "nullables", "[", "$", "field", "]", "=", "$", "data", "->", "nullable", ";", "//Copy validators", "$", "metadata", "->", "validators", "[", "$", "field", "]", "=", "$", "validators", ";", "}", "}", "//Read class annotations", "foreach", "(", "$", "reader", "->", "getClassAnnotations", "(", "$", "reflection", ")", "as", "$", "annotation", ")", "{", "if", "(", "(", "$", "annotation", "instanceof", "DT", "\\", "Annotation", "\\", "Validator", ")", "&&", "isset", "(", "$", "result", "[", "$", "annotation", "->", "subset", "]", ")", ")", "{", "$", "result", "[", "$", "annotation", "->", "subset", "]", "->", "validators", "[", "DT", "\\", "Validator", "::", "GLOBAL_VALIDATOR_KEY", "]", "[", "]", "=", "$", "annotation", ";", "}", "}", "return", "$", "result", ";", "}" ]
Reads class metadata from annotations @param string $className @return DT\Metadata[] @throws \ReflectionException @throws \Doctrine\Common\Annotations\AnnotationException
[ "Reads", "class", "metadata", "from", "annotations" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Metadata/Reader/Annotation.php#L72-L150
Articus/DataTransfer
src/Articus/DataTransfer/Metadata/Reader/Annotation.php
Annotation.readPropertyAnnotations
protected static function readPropertyAnnotations(\ReflectionProperty &$property, AnnotationReader &$reader) { $dataMap = []; $strategyMap = []; $validatorsMap = []; foreach ($reader->getPropertyAnnotations($property) as $annotation) { switch (true) { case ($annotation instanceof DT\Annotation\Data): $dataMap[$annotation->subset] = $annotation; break; case ($annotation instanceof DT\Annotation\Strategy): $strategyMap[$annotation->subset] = $annotation; break; case ($annotation instanceof DT\Annotation\Validator): $validatorsMap[$annotation->subset][] = $annotation; break; } } foreach ($dataMap as $subset => $data) { $strategy = isset($strategyMap[$subset])? $strategyMap[$subset] : null; $validators = isset($validatorsMap[$subset])? $validatorsMap[$subset] : []; yield $subset => [$data, $strategy, $validators]; } }
php
protected static function readPropertyAnnotations(\ReflectionProperty &$property, AnnotationReader &$reader) { $dataMap = []; $strategyMap = []; $validatorsMap = []; foreach ($reader->getPropertyAnnotations($property) as $annotation) { switch (true) { case ($annotation instanceof DT\Annotation\Data): $dataMap[$annotation->subset] = $annotation; break; case ($annotation instanceof DT\Annotation\Strategy): $strategyMap[$annotation->subset] = $annotation; break; case ($annotation instanceof DT\Annotation\Validator): $validatorsMap[$annotation->subset][] = $annotation; break; } } foreach ($dataMap as $subset => $data) { $strategy = isset($strategyMap[$subset])? $strategyMap[$subset] : null; $validators = isset($validatorsMap[$subset])? $validatorsMap[$subset] : []; yield $subset => [$data, $strategy, $validators]; } }
[ "protected", "static", "function", "readPropertyAnnotations", "(", "\\", "ReflectionProperty", "&", "$", "property", ",", "AnnotationReader", "&", "$", "reader", ")", "{", "$", "dataMap", "=", "[", "]", ";", "$", "strategyMap", "=", "[", "]", ";", "$", "validatorsMap", "=", "[", "]", ";", "foreach", "(", "$", "reader", "->", "getPropertyAnnotations", "(", "$", "property", ")", "as", "$", "annotation", ")", "{", "switch", "(", "true", ")", "{", "case", "(", "$", "annotation", "instanceof", "DT", "\\", "Annotation", "\\", "Data", ")", ":", "$", "dataMap", "[", "$", "annotation", "->", "subset", "]", "=", "$", "annotation", ";", "break", ";", "case", "(", "$", "annotation", "instanceof", "DT", "\\", "Annotation", "\\", "Strategy", ")", ":", "$", "strategyMap", "[", "$", "annotation", "->", "subset", "]", "=", "$", "annotation", ";", "break", ";", "case", "(", "$", "annotation", "instanceof", "DT", "\\", "Annotation", "\\", "Validator", ")", ":", "$", "validatorsMap", "[", "$", "annotation", "->", "subset", "]", "[", "]", "=", "$", "annotation", ";", "break", ";", "}", "}", "foreach", "(", "$", "dataMap", "as", "$", "subset", "=>", "$", "data", ")", "{", "$", "strategy", "=", "isset", "(", "$", "strategyMap", "[", "$", "subset", "]", ")", "?", "$", "strategyMap", "[", "$", "subset", "]", ":", "null", ";", "$", "validators", "=", "isset", "(", "$", "validatorsMap", "[", "$", "subset", "]", ")", "?", "$", "validatorsMap", "[", "$", "subset", "]", ":", "[", "]", ";", "yield", "$", "subset", "=>", "[", "$", "data", ",", "$", "strategy", ",", "$", "validators", "]", ";", "}", "}" ]
Reads and groups up annotations for specified property @param \ReflectionProperty $property @param AnnotationReader $reader @return \Generator
[ "Reads", "and", "groups", "up", "annotations", "for", "specified", "property" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Metadata/Reader/Annotation.php#L158-L184
Articus/DataTransfer
src/Articus/DataTransfer/Metadata/Reader/Annotation.php
Annotation.isValidGetter
protected static function isValidGetter(\ReflectionClass &$reflection, $name) { if (!$reflection->hasMethod($name)) { throw new \LogicException( sprintf('Invalid metadata for %s: no getter %s.', $reflection->getName(), $name) ); } $getter = $reflection->getMethod($name); if (!$getter->isPublic()) { throw new \LogicException( sprintf('Invalid metadata for %s: getter %s is not public.', $reflection->getName(), $name) ); } if ($getter->getNumberOfRequiredParameters() > 0) { throw new \LogicException( sprintf('Invalid metadata for %s: getter %s should not require parameters.', $reflection->getName(), $name) ); } return true; }
php
protected static function isValidGetter(\ReflectionClass &$reflection, $name) { if (!$reflection->hasMethod($name)) { throw new \LogicException( sprintf('Invalid metadata for %s: no getter %s.', $reflection->getName(), $name) ); } $getter = $reflection->getMethod($name); if (!$getter->isPublic()) { throw new \LogicException( sprintf('Invalid metadata for %s: getter %s is not public.', $reflection->getName(), $name) ); } if ($getter->getNumberOfRequiredParameters() > 0) { throw new \LogicException( sprintf('Invalid metadata for %s: getter %s should not require parameters.', $reflection->getName(), $name) ); } return true; }
[ "protected", "static", "function", "isValidGetter", "(", "\\", "ReflectionClass", "&", "$", "reflection", ",", "$", "name", ")", "{", "if", "(", "!", "$", "reflection", "->", "hasMethod", "(", "$", "name", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: no getter %s.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "$", "getter", "=", "$", "reflection", "->", "getMethod", "(", "$", "name", ")", ";", "if", "(", "!", "$", "getter", "->", "isPublic", "(", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: getter %s is not public.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "if", "(", "$", "getter", "->", "getNumberOfRequiredParameters", "(", ")", ">", "0", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: getter %s should not require parameters.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "return", "true", ";", "}" ]
Validates if class has valid getter method with specified name @param \ReflectionClass $reflection @param string $name @return bool
[ "Validates", "if", "class", "has", "valid", "getter", "method", "with", "specified", "name" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Metadata/Reader/Annotation.php#L192-L214
Articus/DataTransfer
src/Articus/DataTransfer/Metadata/Reader/Annotation.php
Annotation.isValidSetter
protected static function isValidSetter(\ReflectionClass &$reflection, $name) { if (!$reflection->hasMethod($name)) { throw new \LogicException( sprintf('Invalid metadata for %s: no setter %s.', $reflection->getName(), $name) ); } $setter = $reflection->getMethod($name); if (!$setter->isPublic()) { throw new \LogicException( sprintf('Invalid metadata for %s: setter %s is not public.', $reflection->getName(), $name) ); } if ($setter->getNumberOfParameters() < 1) { throw new \LogicException( sprintf('Invalid metadata for %s: setter %s should accept at least one parameter.', $reflection->getName(), $name) ); } if ($setter->getNumberOfRequiredParameters() > 1) { throw new \LogicException( sprintf('Invalid metadata for %s: setter %s requires too many parameters.', $reflection->getName(), $name) ); } return true; }
php
protected static function isValidSetter(\ReflectionClass &$reflection, $name) { if (!$reflection->hasMethod($name)) { throw new \LogicException( sprintf('Invalid metadata for %s: no setter %s.', $reflection->getName(), $name) ); } $setter = $reflection->getMethod($name); if (!$setter->isPublic()) { throw new \LogicException( sprintf('Invalid metadata for %s: setter %s is not public.', $reflection->getName(), $name) ); } if ($setter->getNumberOfParameters() < 1) { throw new \LogicException( sprintf('Invalid metadata for %s: setter %s should accept at least one parameter.', $reflection->getName(), $name) ); } if ($setter->getNumberOfRequiredParameters() > 1) { throw new \LogicException( sprintf('Invalid metadata for %s: setter %s requires too many parameters.', $reflection->getName(), $name) ); } return true; }
[ "protected", "static", "function", "isValidSetter", "(", "\\", "ReflectionClass", "&", "$", "reflection", ",", "$", "name", ")", "{", "if", "(", "!", "$", "reflection", "->", "hasMethod", "(", "$", "name", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: no setter %s.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "$", "setter", "=", "$", "reflection", "->", "getMethod", "(", "$", "name", ")", ";", "if", "(", "!", "$", "setter", "->", "isPublic", "(", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: setter %s is not public.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "if", "(", "$", "setter", "->", "getNumberOfParameters", "(", ")", "<", "1", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: setter %s should accept at least one parameter.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "if", "(", "$", "setter", "->", "getNumberOfRequiredParameters", "(", ")", ">", "1", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Invalid metadata for %s: setter %s requires too many parameters.'", ",", "$", "reflection", "->", "getName", "(", ")", ",", "$", "name", ")", ")", ";", "}", "return", "true", ";", "}" ]
Validates if class has valid setter method with specified name @param \ReflectionClass $reflection @param string $name @return bool
[ "Validates", "if", "class", "has", "valid", "setter", "method", "with", "specified", "name" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Metadata/Reader/Annotation.php#L222-L250
hametuha/gapiwp
src/Hametuha/GapiWP/Utility/Input.php
Input.verify_nonce
public function verify_nonce($action, $key = '_wpnonce'){ $nonce = $this->request($key); return $nonce && wp_verify_nonce($this->request($key), $action); }
php
public function verify_nonce($action, $key = '_wpnonce'){ $nonce = $this->request($key); return $nonce && wp_verify_nonce($this->request($key), $action); }
[ "public", "function", "verify_nonce", "(", "$", "action", ",", "$", "key", "=", "'_wpnonce'", ")", "{", "$", "nonce", "=", "$", "this", "->", "request", "(", "$", "key", ")", ";", "return", "$", "nonce", "&&", "wp_verify_nonce", "(", "$", "this", "->", "request", "(", "$", "key", ")", ",", "$", "action", ")", ";", "}" ]
Verify nonce @param string $action @param string $key Default '_wpnonce' @return bool
[ "Verify", "nonce" ]
train
https://github.com/hametuha/gapiwp/blob/7b9716d0ebd54c4ab79cca94a4c5aef099a54266/src/Hametuha/GapiWP/Utility/Input.php#L98-L101
Articus/DataTransfer
src/Articus/DataTransfer/Validator.php
Validator.validate
public function validate(array $array) { $messages = []; foreach ($this->metadata->fields as $field) { $value = array_key_exists($field, $array)? $array[$field] : null; if (!(($value === null) && $this->metadata->nullables[$field])) { $validator = $this->getValidator($field); if (!$validator->isValid($value)) { $messages[$field] = $validator->getMessages(); } } } $globalValidator = $this->getValidator(self::GLOBAL_VALIDATOR_KEY); if (!$globalValidator->isValid($array)) { $messages[self::GLOBAL_VALIDATOR_KEY] = $globalValidator->getMessages(); } return $messages; }
php
public function validate(array $array) { $messages = []; foreach ($this->metadata->fields as $field) { $value = array_key_exists($field, $array)? $array[$field] : null; if (!(($value === null) && $this->metadata->nullables[$field])) { $validator = $this->getValidator($field); if (!$validator->isValid($value)) { $messages[$field] = $validator->getMessages(); } } } $globalValidator = $this->getValidator(self::GLOBAL_VALIDATOR_KEY); if (!$globalValidator->isValid($array)) { $messages[self::GLOBAL_VALIDATOR_KEY] = $globalValidator->getMessages(); } return $messages; }
[ "public", "function", "validate", "(", "array", "$", "array", ")", "{", "$", "messages", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "metadata", "->", "fields", "as", "$", "field", ")", "{", "$", "value", "=", "array_key_exists", "(", "$", "field", ",", "$", "array", ")", "?", "$", "array", "[", "$", "field", "]", ":", "null", ";", "if", "(", "!", "(", "(", "$", "value", "===", "null", ")", "&&", "$", "this", "->", "metadata", "->", "nullables", "[", "$", "field", "]", ")", ")", "{", "$", "validator", "=", "$", "this", "->", "getValidator", "(", "$", "field", ")", ";", "if", "(", "!", "$", "validator", "->", "isValid", "(", "$", "value", ")", ")", "{", "$", "messages", "[", "$", "field", "]", "=", "$", "validator", "->", "getMessages", "(", ")", ";", "}", "}", "}", "$", "globalValidator", "=", "$", "this", "->", "getValidator", "(", "self", "::", "GLOBAL_VALIDATOR_KEY", ")", ";", "if", "(", "!", "$", "globalValidator", "->", "isValid", "(", "$", "array", ")", ")", "{", "$", "messages", "[", "self", "::", "GLOBAL_VALIDATOR_KEY", "]", "=", "$", "globalValidator", "->", "getMessages", "(", ")", ";", "}", "return", "$", "messages", ";", "}" ]
Validates associative array according metadata @param array $array @return array
[ "Validates", "associative", "array", "according", "metadata" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Validator.php#L70-L91
Articus/DataTransfer
src/Articus/DataTransfer/Validator.php
Validator.getValidator
protected function getValidator($field) { $result = null; if (isset($this->validators[$field])) { $result = $this->validators[$field]; } else { $result = new ValidatorChain(); $result->setPluginManager($this->validatorPluginManager); if (isset($this->metadata->validators[$field])) { foreach ($this->metadata->validators[$field] as $validator) { /** @var $validator Annotation\Validator */ $result->attachByName($validator->name, $validator->options, true, $validator->priority); } } if (($field !== self::GLOBAL_VALIDATOR_KEY) && ($this->metadata->nullables[$field] === false)) { $result->attachByName(NotEmpty::class, ['type' => NotEmpty::NULL | NotEmpty::OBJECT], true, 10000); } $this->validators[$field] = $result; } return $result; }
php
protected function getValidator($field) { $result = null; if (isset($this->validators[$field])) { $result = $this->validators[$field]; } else { $result = new ValidatorChain(); $result->setPluginManager($this->validatorPluginManager); if (isset($this->metadata->validators[$field])) { foreach ($this->metadata->validators[$field] as $validator) { /** @var $validator Annotation\Validator */ $result->attachByName($validator->name, $validator->options, true, $validator->priority); } } if (($field !== self::GLOBAL_VALIDATOR_KEY) && ($this->metadata->nullables[$field] === false)) { $result->attachByName(NotEmpty::class, ['type' => NotEmpty::NULL | NotEmpty::OBJECT], true, 10000); } $this->validators[$field] = $result; } return $result; }
[ "protected", "function", "getValidator", "(", "$", "field", ")", "{", "$", "result", "=", "null", ";", "if", "(", "isset", "(", "$", "this", "->", "validators", "[", "$", "field", "]", ")", ")", "{", "$", "result", "=", "$", "this", "->", "validators", "[", "$", "field", "]", ";", "}", "else", "{", "$", "result", "=", "new", "ValidatorChain", "(", ")", ";", "$", "result", "->", "setPluginManager", "(", "$", "this", "->", "validatorPluginManager", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "metadata", "->", "validators", "[", "$", "field", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "metadata", "->", "validators", "[", "$", "field", "]", "as", "$", "validator", ")", "{", "/** @var $validator Annotation\\Validator */", "$", "result", "->", "attachByName", "(", "$", "validator", "->", "name", ",", "$", "validator", "->", "options", ",", "true", ",", "$", "validator", "->", "priority", ")", ";", "}", "}", "if", "(", "(", "$", "field", "!==", "self", "::", "GLOBAL_VALIDATOR_KEY", ")", "&&", "(", "$", "this", "->", "metadata", "->", "nullables", "[", "$", "field", "]", "===", "false", ")", ")", "{", "$", "result", "->", "attachByName", "(", "NotEmpty", "::", "class", ",", "[", "'type'", "=>", "NotEmpty", "::", "NULL", "|", "NotEmpty", "::", "OBJECT", "]", ",", "true", ",", "10000", ")", ";", "}", "$", "this", "->", "validators", "[", "$", "field", "]", "=", "$", "result", ";", "}", "return", "$", "result", ";", "}" ]
Builds validator chain for specified field according metadata @param string $field @return ValidatorInterface
[ "Builds", "validator", "chain", "for", "specified", "field", "according", "metadata" ]
train
https://github.com/Articus/DataTransfer/blob/c119666fa042f7e9f311c3bc1e9a1d0468b9992d/src/Articus/DataTransfer/Validator.php#L98-L124
zircote/AMQP
library/AMQP/AbstractChannel.php
AbstractChannel.dispatch
public function dispatch($methodSig, $args, $content) { if (!array_key_exists($methodSig, $this->methodMap)) { throw new \Exception("Unknown AMQP method $methodSig"); } $amqpMethod = $this->methodMap[$methodSig]; if ($content == null) { return call_user_func(array($this, $amqpMethod), $args); } else { return call_user_func( array($this, $amqpMethod), $args, $content ); } }
php
public function dispatch($methodSig, $args, $content) { if (!array_key_exists($methodSig, $this->methodMap)) { throw new \Exception("Unknown AMQP method $methodSig"); } $amqpMethod = $this->methodMap[$methodSig]; if ($content == null) { return call_user_func(array($this, $amqpMethod), $args); } else { return call_user_func( array($this, $amqpMethod), $args, $content ); } }
[ "public", "function", "dispatch", "(", "$", "methodSig", ",", "$", "args", ",", "$", "content", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "methodSig", ",", "$", "this", "->", "methodMap", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Unknown AMQP method $methodSig\"", ")", ";", "}", "$", "amqpMethod", "=", "$", "this", "->", "methodMap", "[", "$", "methodSig", "]", ";", "if", "(", "$", "content", "==", "null", ")", "{", "return", "call_user_func", "(", "array", "(", "$", "this", ",", "$", "amqpMethod", ")", ",", "$", "args", ")", ";", "}", "else", "{", "return", "call_user_func", "(", "array", "(", "$", "this", ",", "$", "amqpMethod", ")", ",", "$", "args", ",", "$", "content", ")", ";", "}", "}" ]
@todo tie in an event handler interface and decouple. @param $methodSig @param $args @param $content @return mixed @throws \Exception
[ "@todo", "tie", "in", "an", "event", "handler", "interface", "and", "decouple", "." ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/AbstractChannel.php#L151-L166
zircote/AMQP
library/AMQP/AbstractChannel.php
AbstractChannel.wait
public function wait($allowedMethods = array(), $nonBlocking = false) { if ($allowedMethods) { if ($this->debug) { Helper::debugMsg( sprintf('waiting for %s', implode(', ', $allowedMethods)) ); } } else { if ($this->debug) { Helper::debugMsg('waiting for any method'); } } //Process deferred methods foreach ($this->methodQueue as $queueKey => $queuedMethod) { if ($this->debug) { Helper::debugMsg( sprintf('checking queue method %s', $queueKey) ); } $methodSig = $queuedMethod[0]; if ($allowedMethods == null || in_array($methodSig, $allowedMethods) ) { unset($this->methodQueue[$queueKey]); if ($this->debug) { Helper::debugMsg( sprintf( 'Executing queued method: $methodSig: %s', self::$globalMethodNames[Helper::methodSig( $methodSig )] ) ); } return $this->dispatch( $queuedMethod[0], $queuedMethod[1], $queuedMethod[2] ); } } // No deferred methods? wait for new ones while (true) { $frame = $this->nextFrame(); $frameType = $frame[0]; $payload = $frame[1]; if ($frameType != 1) { throw new \Exception( sprintf( 'Expecting AMQP method, received frame type: %s', $frameType ) ); } if (strlen($payload) < 4) { throw new \Exception('Method frame too short'); } $methodSigArray = unpack('n2', substr($payload, 0, 4)); $methodSig = '' . $methodSigArray[1] . ',' . $methodSigArray[2]; $args = new Reader(substr($payload, 4)); if ($this->debug) { Helper::debugMsg( '> ' . $methodSig . ': ' . self::$globalMethodNames[Helper::methodSig($methodSig)] ); } if (in_array($methodSig, self::$contentMethods)) { $content = $this->waitContent(); } else { $content = null; } if ($allowedMethods == null || in_array($methodSig, $allowedMethods) || in_array($methodSig, self::$closeMethods) ) { return $this->dispatch($methodSig, $args, $content); } // Wasn't what we were looking for? save it for later if ($this->debug) { Helper::debugMsg( sprintf( 'Queueing for later: %s: %s', $methodSig, self::$globalMethodNames[Helper::methodSig( $methodSig )] ) ); } $this->methodQueue[] = array($methodSig, $args, $content); if ($nonBlocking) { break; } } return null; }
php
public function wait($allowedMethods = array(), $nonBlocking = false) { if ($allowedMethods) { if ($this->debug) { Helper::debugMsg( sprintf('waiting for %s', implode(', ', $allowedMethods)) ); } } else { if ($this->debug) { Helper::debugMsg('waiting for any method'); } } //Process deferred methods foreach ($this->methodQueue as $queueKey => $queuedMethod) { if ($this->debug) { Helper::debugMsg( sprintf('checking queue method %s', $queueKey) ); } $methodSig = $queuedMethod[0]; if ($allowedMethods == null || in_array($methodSig, $allowedMethods) ) { unset($this->methodQueue[$queueKey]); if ($this->debug) { Helper::debugMsg( sprintf( 'Executing queued method: $methodSig: %s', self::$globalMethodNames[Helper::methodSig( $methodSig )] ) ); } return $this->dispatch( $queuedMethod[0], $queuedMethod[1], $queuedMethod[2] ); } } // No deferred methods? wait for new ones while (true) { $frame = $this->nextFrame(); $frameType = $frame[0]; $payload = $frame[1]; if ($frameType != 1) { throw new \Exception( sprintf( 'Expecting AMQP method, received frame type: %s', $frameType ) ); } if (strlen($payload) < 4) { throw new \Exception('Method frame too short'); } $methodSigArray = unpack('n2', substr($payload, 0, 4)); $methodSig = '' . $methodSigArray[1] . ',' . $methodSigArray[2]; $args = new Reader(substr($payload, 4)); if ($this->debug) { Helper::debugMsg( '> ' . $methodSig . ': ' . self::$globalMethodNames[Helper::methodSig($methodSig)] ); } if (in_array($methodSig, self::$contentMethods)) { $content = $this->waitContent(); } else { $content = null; } if ($allowedMethods == null || in_array($methodSig, $allowedMethods) || in_array($methodSig, self::$closeMethods) ) { return $this->dispatch($methodSig, $args, $content); } // Wasn't what we were looking for? save it for later if ($this->debug) { Helper::debugMsg( sprintf( 'Queueing for later: %s: %s', $methodSig, self::$globalMethodNames[Helper::methodSig( $methodSig )] ) ); } $this->methodQueue[] = array($methodSig, $args, $content); if ($nonBlocking) { break; } } return null; }
[ "public", "function", "wait", "(", "$", "allowedMethods", "=", "array", "(", ")", ",", "$", "nonBlocking", "=", "false", ")", "{", "if", "(", "$", "allowedMethods", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "sprintf", "(", "'waiting for %s'", ",", "implode", "(", "', '", ",", "$", "allowedMethods", ")", ")", ")", ";", "}", "}", "else", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "'waiting for any method'", ")", ";", "}", "}", "//Process deferred methods", "foreach", "(", "$", "this", "->", "methodQueue", "as", "$", "queueKey", "=>", "$", "queuedMethod", ")", "{", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "sprintf", "(", "'checking queue method %s'", ",", "$", "queueKey", ")", ")", ";", "}", "$", "methodSig", "=", "$", "queuedMethod", "[", "0", "]", ";", "if", "(", "$", "allowedMethods", "==", "null", "||", "in_array", "(", "$", "methodSig", ",", "$", "allowedMethods", ")", ")", "{", "unset", "(", "$", "this", "->", "methodQueue", "[", "$", "queueKey", "]", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "sprintf", "(", "'Executing queued method: $methodSig: %s'", ",", "self", "::", "$", "globalMethodNames", "[", "Helper", "::", "methodSig", "(", "$", "methodSig", ")", "]", ")", ")", ";", "}", "return", "$", "this", "->", "dispatch", "(", "$", "queuedMethod", "[", "0", "]", ",", "$", "queuedMethod", "[", "1", "]", ",", "$", "queuedMethod", "[", "2", "]", ")", ";", "}", "}", "// No deferred methods? wait for new ones", "while", "(", "true", ")", "{", "$", "frame", "=", "$", "this", "->", "nextFrame", "(", ")", ";", "$", "frameType", "=", "$", "frame", "[", "0", "]", ";", "$", "payload", "=", "$", "frame", "[", "1", "]", ";", "if", "(", "$", "frameType", "!=", "1", ")", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "(", "'Expecting AMQP method, received frame type: %s'", ",", "$", "frameType", ")", ")", ";", "}", "if", "(", "strlen", "(", "$", "payload", ")", "<", "4", ")", "{", "throw", "new", "\\", "Exception", "(", "'Method frame too short'", ")", ";", "}", "$", "methodSigArray", "=", "unpack", "(", "'n2'", ",", "substr", "(", "$", "payload", ",", "0", ",", "4", ")", ")", ";", "$", "methodSig", "=", "''", ".", "$", "methodSigArray", "[", "1", "]", ".", "','", ".", "$", "methodSigArray", "[", "2", "]", ";", "$", "args", "=", "new", "Reader", "(", "substr", "(", "$", "payload", ",", "4", ")", ")", ";", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "'> '", ".", "$", "methodSig", ".", "': '", ".", "self", "::", "$", "globalMethodNames", "[", "Helper", "::", "methodSig", "(", "$", "methodSig", ")", "]", ")", ";", "}", "if", "(", "in_array", "(", "$", "methodSig", ",", "self", "::", "$", "contentMethods", ")", ")", "{", "$", "content", "=", "$", "this", "->", "waitContent", "(", ")", ";", "}", "else", "{", "$", "content", "=", "null", ";", "}", "if", "(", "$", "allowedMethods", "==", "null", "||", "in_array", "(", "$", "methodSig", ",", "$", "allowedMethods", ")", "||", "in_array", "(", "$", "methodSig", ",", "self", "::", "$", "closeMethods", ")", ")", "{", "return", "$", "this", "->", "dispatch", "(", "$", "methodSig", ",", "$", "args", ",", "$", "content", ")", ";", "}", "// Wasn't what we were looking for? save it for later", "if", "(", "$", "this", "->", "debug", ")", "{", "Helper", "::", "debugMsg", "(", "sprintf", "(", "'Queueing for later: %s: %s'", ",", "$", "methodSig", ",", "self", "::", "$", "globalMethodNames", "[", "Helper", "::", "methodSig", "(", "$", "methodSig", ")", "]", ")", ")", ";", "}", "$", "this", "->", "methodQueue", "[", "]", "=", "array", "(", "$", "methodSig", ",", "$", "args", ",", "$", "content", ")", ";", "if", "(", "$", "nonBlocking", ")", "{", "break", ";", "}", "}", "return", "null", ";", "}" ]
@todo refactor Wait for some expected AMQP methods and dispatch to them. Unexpected methods are queued up for later calls to this PHP method. @param array $allowedMethods @param bool $nonBlocking @return mixed|null @throws \Exception
[ "@todo", "refactor" ]
train
https://github.com/zircote/AMQP/blob/b96777b372f556797db4fd0ba02edb18d4bf4a1e/library/AMQP/AbstractChannel.php#L272-L381
periaptio/empress-generator
src/Generators/ControllerGenerator.php
ControllerGenerator.getTemplatePath
public function getTemplatePath() { // get template filename $useRepositoryLayer = config('generator.use_repository_layer', true); $useServiceLayer = config('generator.use_service_layer', true); if ($useServiceLayer && $useRepositoryLayer) { $templateFilename = 'Controller_Service'; } elseif ($useRepositoryLayer) { $templateFilename = 'Controller_Repository'; } else { $templateFilename = 'Controller'; } return 'scaffold/'.$templateFilename; }
php
public function getTemplatePath() { // get template filename $useRepositoryLayer = config('generator.use_repository_layer', true); $useServiceLayer = config('generator.use_service_layer', true); if ($useServiceLayer && $useRepositoryLayer) { $templateFilename = 'Controller_Service'; } elseif ($useRepositoryLayer) { $templateFilename = 'Controller_Repository'; } else { $templateFilename = 'Controller'; } return 'scaffold/'.$templateFilename; }
[ "public", "function", "getTemplatePath", "(", ")", "{", "// get template filename", "$", "useRepositoryLayer", "=", "config", "(", "'generator.use_repository_layer'", ",", "true", ")", ";", "$", "useServiceLayer", "=", "config", "(", "'generator.use_service_layer'", ",", "true", ")", ";", "if", "(", "$", "useServiceLayer", "&&", "$", "useRepositoryLayer", ")", "{", "$", "templateFilename", "=", "'Controller_Service'", ";", "}", "elseif", "(", "$", "useRepositoryLayer", ")", "{", "$", "templateFilename", "=", "'Controller_Repository'", ";", "}", "else", "{", "$", "templateFilename", "=", "'Controller'", ";", "}", "return", "'scaffold/'", ".", "$", "templateFilename", ";", "}" ]
Get the template path for generate @return string
[ "Get", "the", "template", "path", "for", "generate" ]
train
https://github.com/periaptio/empress-generator/blob/749fb4b12755819e9c97377ebfb446ee0822168a/src/Generators/ControllerGenerator.php#L22-L35
ConnectHolland/tulip-api-client
src/ResponseParser.php
ResponseParser.getResponseCode
public function getResponseCode() { $code = 0; $dom = $this->getDOMDocument(); $xpath = new DOMXPath($dom); if (($codeAttribute = $xpath->query('/response/@code')->item(0)) instanceof DOMAttr) { $code = intval($codeAttribute->nodeValue); } return $code; }
php
public function getResponseCode() { $code = 0; $dom = $this->getDOMDocument(); $xpath = new DOMXPath($dom); if (($codeAttribute = $xpath->query('/response/@code')->item(0)) instanceof DOMAttr) { $code = intval($codeAttribute->nodeValue); } return $code; }
[ "public", "function", "getResponseCode", "(", ")", "{", "$", "code", "=", "0", ";", "$", "dom", "=", "$", "this", "->", "getDOMDocument", "(", ")", ";", "$", "xpath", "=", "new", "DOMXPath", "(", "$", "dom", ")", ";", "if", "(", "(", "$", "codeAttribute", "=", "$", "xpath", "->", "query", "(", "'/response/@code'", ")", "->", "item", "(", "0", ")", ")", "instanceof", "DOMAttr", ")", "{", "$", "code", "=", "intval", "(", "$", "codeAttribute", "->", "nodeValue", ")", ";", "}", "return", "$", "code", ";", "}" ]
Returns the response code from the API. @param ResponseInterface $response @return int
[ "Returns", "the", "response", "code", "from", "the", "API", "." ]
train
https://github.com/ConnectHolland/tulip-api-client/blob/641325e2d57c1c272ede7fd8b47d4f2b67b73507/src/ResponseParser.php#L49-L60
ConnectHolland/tulip-api-client
src/ResponseParser.php
ResponseParser.getErrorMessage
public function getErrorMessage() { $errorMessage = ''; $dom = $this->getDOMDocument(); $xpath = new DOMXPath($dom); if (($errorNode = $xpath->query('/response/error')->item(0)) instanceof DOMNode) { $errorMessage = $errorNode->nodeValue; } return $errorMessage; }
php
public function getErrorMessage() { $errorMessage = ''; $dom = $this->getDOMDocument(); $xpath = new DOMXPath($dom); if (($errorNode = $xpath->query('/response/error')->item(0)) instanceof DOMNode) { $errorMessage = $errorNode->nodeValue; } return $errorMessage; }
[ "public", "function", "getErrorMessage", "(", ")", "{", "$", "errorMessage", "=", "''", ";", "$", "dom", "=", "$", "this", "->", "getDOMDocument", "(", ")", ";", "$", "xpath", "=", "new", "DOMXPath", "(", "$", "dom", ")", ";", "if", "(", "(", "$", "errorNode", "=", "$", "xpath", "->", "query", "(", "'/response/error'", ")", "->", "item", "(", "0", ")", ")", "instanceof", "DOMNode", ")", "{", "$", "errorMessage", "=", "$", "errorNode", "->", "nodeValue", ";", "}", "return", "$", "errorMessage", ";", "}" ]
Returns the error message from the Tulip API. @return string
[ "Returns", "the", "error", "message", "from", "the", "Tulip", "API", "." ]
train
https://github.com/ConnectHolland/tulip-api-client/blob/641325e2d57c1c272ede7fd8b47d4f2b67b73507/src/ResponseParser.php#L67-L78
ConnectHolland/tulip-api-client
src/ResponseParser.php
ResponseParser.getDOMDocument
public function getDOMDocument() { if ($this->domDocument instanceof DOMDocument === false) { $this->domDocument = new DOMDocument('1.0', 'UTF-8'); libxml_clear_errors(); $previousSetting = libxml_use_internal_errors(true); @$this->domDocument->loadXML($this->response->getBody()); libxml_clear_errors(); libxml_use_internal_errors($previousSetting); } return $this->domDocument; }
php
public function getDOMDocument() { if ($this->domDocument instanceof DOMDocument === false) { $this->domDocument = new DOMDocument('1.0', 'UTF-8'); libxml_clear_errors(); $previousSetting = libxml_use_internal_errors(true); @$this->domDocument->loadXML($this->response->getBody()); libxml_clear_errors(); libxml_use_internal_errors($previousSetting); } return $this->domDocument; }
[ "public", "function", "getDOMDocument", "(", ")", "{", "if", "(", "$", "this", "->", "domDocument", "instanceof", "DOMDocument", "===", "false", ")", "{", "$", "this", "->", "domDocument", "=", "new", "DOMDocument", "(", "'1.0'", ",", "'UTF-8'", ")", ";", "libxml_clear_errors", "(", ")", ";", "$", "previousSetting", "=", "libxml_use_internal_errors", "(", "true", ")", ";", "@", "$", "this", "->", "domDocument", "->", "loadXML", "(", "$", "this", "->", "response", "->", "getBody", "(", ")", ")", ";", "libxml_clear_errors", "(", ")", ";", "libxml_use_internal_errors", "(", "$", "previousSetting", ")", ";", "}", "return", "$", "this", "->", "domDocument", ";", "}" ]
Returns the response body as DOMDocument instance. @return DOMDocument
[ "Returns", "the", "response", "body", "as", "DOMDocument", "instance", "." ]
train
https://github.com/ConnectHolland/tulip-api-client/blob/641325e2d57c1c272ede7fd8b47d4f2b67b73507/src/ResponseParser.php#L85-L100
yuncms/framework
src/rest/ActiveController.php
ActiveController.behaviors
public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => CompositeAuth::class, 'authMethods' => $this->authMethods, ]; $behaviors['corsFilter'] = [ 'class' => \yii\filters\Cors::class, 'cors' => [ // restrict access to 'Origin' => ['*'], 'Access-Control-Request-Method' => ['POST', 'PUT', 'GET'], // Allow only POST and PUT methods 'Access-Control-Request-Headers' => ['*'], // Allow only headers 'X-Wsse' 'Access-Control-Allow-Credentials' => true, // Allow OPTIONS caching 'Access-Control-Max-Age' => 3600, // Allow the X-Pagination-Current-Page header to be exposed to the browser. 'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'], ], ]; return $behaviors; }
php
public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => CompositeAuth::class, 'authMethods' => $this->authMethods, ]; $behaviors['corsFilter'] = [ 'class' => \yii\filters\Cors::class, 'cors' => [ // restrict access to 'Origin' => ['*'], 'Access-Control-Request-Method' => ['POST', 'PUT', 'GET'], // Allow only POST and PUT methods 'Access-Control-Request-Headers' => ['*'], // Allow only headers 'X-Wsse' 'Access-Control-Allow-Credentials' => true, // Allow OPTIONS caching 'Access-Control-Max-Age' => 3600, // Allow the X-Pagination-Current-Page header to be exposed to the browser. 'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'], ], ]; return $behaviors; }
[ "public", "function", "behaviors", "(", ")", "{", "$", "behaviors", "=", "parent", "::", "behaviors", "(", ")", ";", "$", "behaviors", "[", "'authenticator'", "]", "=", "[", "'class'", "=>", "CompositeAuth", "::", "class", ",", "'authMethods'", "=>", "$", "this", "->", "authMethods", ",", "]", ";", "$", "behaviors", "[", "'corsFilter'", "]", "=", "[", "'class'", "=>", "\\", "yii", "\\", "filters", "\\", "Cors", "::", "class", ",", "'cors'", "=>", "[", "// restrict access to", "'Origin'", "=>", "[", "'*'", "]", ",", "'Access-Control-Request-Method'", "=>", "[", "'POST'", ",", "'PUT'", ",", "'GET'", "]", ",", "// Allow only POST and PUT methods", "'Access-Control-Request-Headers'", "=>", "[", "'*'", "]", ",", "// Allow only headers 'X-Wsse'", "'Access-Control-Allow-Credentials'", "=>", "true", ",", "// Allow OPTIONS caching", "'Access-Control-Max-Age'", "=>", "3600", ",", "// Allow the X-Pagination-Current-Page header to be exposed to the browser.", "'Access-Control-Expose-Headers'", "=>", "[", "'X-Pagination-Current-Page'", "]", ",", "]", ",", "]", ";", "return", "$", "behaviors", ";", "}" ]
初始化 API 控制器验证 @return array
[ "初始化", "API", "控制器验证" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/rest/ActiveController.php#L52-L76
yuncms/framework
src/rest/ActiveController.php
ActiveController.prepareDataProvider
public function prepareDataProvider(IndexAction $action, $filter) { /* @var $modelClass \yii\db\BaseActiveRecord */ $modelClass = $this->modelClass; $query = $modelClass::find(); if (!empty($filter)) { $query->andWhere($filter); } return Yii::createObject([ 'class' => ActiveDataProvider::class, 'query' => $query, 'sort' => [ 'defaultOrder' => [ 'created_at' => SORT_DESC, 'id' => SORT_ASC, ] ], ]); }
php
public function prepareDataProvider(IndexAction $action, $filter) { /* @var $modelClass \yii\db\BaseActiveRecord */ $modelClass = $this->modelClass; $query = $modelClass::find(); if (!empty($filter)) { $query->andWhere($filter); } return Yii::createObject([ 'class' => ActiveDataProvider::class, 'query' => $query, 'sort' => [ 'defaultOrder' => [ 'created_at' => SORT_DESC, 'id' => SORT_ASC, ] ], ]); }
[ "public", "function", "prepareDataProvider", "(", "IndexAction", "$", "action", ",", "$", "filter", ")", "{", "/* @var $modelClass \\yii\\db\\BaseActiveRecord */", "$", "modelClass", "=", "$", "this", "->", "modelClass", ";", "$", "query", "=", "$", "modelClass", "::", "find", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "filter", ")", ")", "{", "$", "query", "->", "andWhere", "(", "$", "filter", ")", ";", "}", "return", "Yii", "::", "createObject", "(", "[", "'class'", "=>", "ActiveDataProvider", "::", "class", ",", "'query'", "=>", "$", "query", ",", "'sort'", "=>", "[", "'defaultOrder'", "=>", "[", "'created_at'", "=>", "SORT_DESC", ",", "'id'", "=>", "SORT_ASC", ",", "]", "]", ",", "]", ")", ";", "}" ]
Prepares the data provider that should return the requested collection of the models. @param IndexAction $action @param mixed $filter @return ActiveDataProvider @throws \yii\base\InvalidConfigException
[ "Prepares", "the", "data", "provider", "that", "should", "return", "the", "requested", "collection", "of", "the", "models", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/rest/ActiveController.php#L97-L116
yuncms/framework
src/rest/ActiveController.php
ActiveController.checkAccess
public function checkAccess($action, $model = null, $params = []) { if ($action === 'update' || $action === 'delete') { if ($model && $model->user_id !== Yii::$app->user->id) { throw new ForbiddenHttpException('You do not have permission to perform this operation.'); } } }
php
public function checkAccess($action, $model = null, $params = []) { if ($action === 'update' || $action === 'delete') { if ($model && $model->user_id !== Yii::$app->user->id) { throw new ForbiddenHttpException('You do not have permission to perform this operation.'); } } }
[ "public", "function", "checkAccess", "(", "$", "action", ",", "$", "model", "=", "null", ",", "$", "params", "=", "[", "]", ")", "{", "if", "(", "$", "action", "===", "'update'", "||", "$", "action", "===", "'delete'", ")", "{", "if", "(", "$", "model", "&&", "$", "model", "->", "user_id", "!==", "Yii", "::", "$", "app", "->", "user", "->", "id", ")", "{", "throw", "new", "ForbiddenHttpException", "(", "'You do not have permission to perform this operation.'", ")", ";", "}", "}", "}" ]
检查当前用户的权限 This method should be overridden to check whether the current user has the privilege to run the specified action against the specified data model. If the user does not have access, a [[ForbiddenHttpException]] should be thrown. @param string $action the ID of the action to be executed @param object $model the model to be accessed. If null, it means no specific model is being accessed. @param array $params additional parameters @throws ForbiddenHttpException if the user does not have access
[ "检查当前用户的权限" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/rest/ActiveController.php#L130-L137
zodream/thirdparty
src/OAuth/ALiPay.php
ALiPay.info
public function info() { /** * avatar 用户头像 String 如果没有数据的时候不会返回该数据,请做好容错 可空 https://tfsimg.alipay.com/images/partner/T1k0xiXXRnXXXXXXXX nick_name 用户昵称 String 如果没有数据的时候不会返回该数据,请做好容错 可空 张三 province 省份 String 用户注册时填写的省份 如果没有数据的时候不会返回该数据,请做好容错 可空 浙江省 city 城市 String 用户注册时填写的城市, 如果没有数据的时候不会返回该数据,请做好容错 可空 杭州 gender 用户性别 String M为男性,F为女性, 如果没有数据的时候不会返回该数据,请做好容错 可空 M user_type_value 用户类型 String (1/2),1代表公司账户;2代表个人账户 不可空 1 is_licence_auth 是否经过营业执照认证 String T为通过营业执照认证,F为没有通过 不可空 T is_certified 是否通过实名认证 String T是通过;F是没有实名认证 不可空 F is_certify_grade_a 是否A类认证 String T表示是A类认证,F表示非A类认证,A类认证用户是指上传过身份证照片并且通过审核的支付宝用户 不可空 T is_student_certified 是否是学生 String T表示是学生,F表示不是学生 不可空 T is_bank_auth 是否经过银行卡认证 String T为经过银行卡认证,F为未经过银行卡认证 不可空 T is_mobile_auth 是否经过手机认证 String T为经过手机认证,F为未经过手机认证 不可空 T alipay_user_id 当前用户的userId String 支付宝用户的userId 不可空 2088411964574197 user_id 已废弃,请勿使用 String 已废弃,请勿使用 不可空 已废弃,请勿使用 user_status 用户状态(Q/T/B/W) String Q代表快速注册用户;T代表已认证用户;B代表被冻结账户;W代表已注册,未激活的账户 不可空 T is_id_auth 是否身份证认证 String T为是身份证认证,F为非身份证认证 不可空 T */ $user = (new OAuth())->info($this->get('access_token')); if (!is_array($user) || $user['code'] != 10000) { return false; } $user['username'] = $user['nick_name']; $user['sex'] = $user['gender']; $this->set($user); return $user; }
php
public function info() { /** * avatar 用户头像 String 如果没有数据的时候不会返回该数据,请做好容错 可空 https://tfsimg.alipay.com/images/partner/T1k0xiXXRnXXXXXXXX nick_name 用户昵称 String 如果没有数据的时候不会返回该数据,请做好容错 可空 张三 province 省份 String 用户注册时填写的省份 如果没有数据的时候不会返回该数据,请做好容错 可空 浙江省 city 城市 String 用户注册时填写的城市, 如果没有数据的时候不会返回该数据,请做好容错 可空 杭州 gender 用户性别 String M为男性,F为女性, 如果没有数据的时候不会返回该数据,请做好容错 可空 M user_type_value 用户类型 String (1/2),1代表公司账户;2代表个人账户 不可空 1 is_licence_auth 是否经过营业执照认证 String T为通过营业执照认证,F为没有通过 不可空 T is_certified 是否通过实名认证 String T是通过;F是没有实名认证 不可空 F is_certify_grade_a 是否A类认证 String T表示是A类认证,F表示非A类认证,A类认证用户是指上传过身份证照片并且通过审核的支付宝用户 不可空 T is_student_certified 是否是学生 String T表示是学生,F表示不是学生 不可空 T is_bank_auth 是否经过银行卡认证 String T为经过银行卡认证,F为未经过银行卡认证 不可空 T is_mobile_auth 是否经过手机认证 String T为经过手机认证,F为未经过手机认证 不可空 T alipay_user_id 当前用户的userId String 支付宝用户的userId 不可空 2088411964574197 user_id 已废弃,请勿使用 String 已废弃,请勿使用 不可空 已废弃,请勿使用 user_status 用户状态(Q/T/B/W) String Q代表快速注册用户;T代表已认证用户;B代表被冻结账户;W代表已注册,未激活的账户 不可空 T is_id_auth 是否身份证认证 String T为是身份证认证,F为非身份证认证 不可空 T */ $user = (new OAuth())->info($this->get('access_token')); if (!is_array($user) || $user['code'] != 10000) { return false; } $user['username'] = $user['nick_name']; $user['sex'] = $user['gender']; $this->set($user); return $user; }
[ "public", "function", "info", "(", ")", "{", "/**\n * avatar\t用户头像\tString\t如果没有数据的时候不会返回该数据,请做好容错\t可空\thttps://tfsimg.alipay.com/images/partner/T1k0xiXXRnXXXXXXXX\n nick_name\t用户昵称\tString\t如果没有数据的时候不会返回该数据,请做好容错\t可空\t张三\n province\t省份\tString\t用户注册时填写的省份 如果没有数据的时候不会返回该数据,请做好容错\t可空\t浙江省\n city\t城市\tString\t用户注册时填写的城市, 如果没有数据的时候不会返回该数据,请做好容错\t可空\t杭州\n gender\t用户性别\tString\tM为男性,F为女性, 如果没有数据的时候不会返回该数据,请做好容错\t可空\tM\n user_type_value\t用户类型\tString\t(1/2),1代表公司账户;2代表个人账户\t不可空\t1\n is_licence_auth\t是否经过营业执照认证\tString\tT为通过营业执照认证,F为没有通过\t不可空\tT\n is_certified\t是否通过实名认证\tString\tT是通过;F是没有实名认证\t不可空\tF\n is_certify_grade_a\t是否A类认证\tString\tT表示是A类认证,F表示非A类认证,A类认证用户是指上传过身份证照片并且通过审核的支付宝用户\t不可空\tT\n is_student_certified\t是否是学生\tString\tT表示是学生,F表示不是学生\t不可空\tT\n is_bank_auth\t是否经过银行卡认证\tString\tT为经过银行卡认证,F为未经过银行卡认证\t不可空\tT\n is_mobile_auth\t是否经过手机认证\tString\tT为经过手机认证,F为未经过手机认证\t不可空\tT\n alipay_user_id\t当前用户的userId\tString\t支付宝用户的userId\t不可空\t2088411964574197\n user_id\t已废弃,请勿使用\tString\t已废弃,请勿使用\t不可空\t已废弃,请勿使用\n user_status\t用户状态(Q/T/B/W)\tString\tQ代表快速注册用户;T代表已认证用户;B代表被冻结账户;W代表已注册,未激活的账户\t不可空\tT\n is_id_auth\t是否身份证认证\tString\tT为是身份证认证,F为非身份证认证\t不可空\tT\n */", "$", "user", "=", "(", "new", "OAuth", "(", ")", ")", "->", "info", "(", "$", "this", "->", "get", "(", "'access_token'", ")", ")", ";", "if", "(", "!", "is_array", "(", "$", "user", ")", "||", "$", "user", "[", "'code'", "]", "!=", "10000", ")", "{", "return", "false", ";", "}", "$", "user", "[", "'username'", "]", "=", "$", "user", "[", "'nick_name'", "]", ";", "$", "user", "[", "'sex'", "]", "=", "$", "user", "[", "'gender'", "]", ";", "$", "this", "->", "set", "(", "$", "user", ")", ";", "return", "$", "user", ";", "}" ]
获取用户信息 @return array|false @throws \Exception
[ "获取用户信息" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/OAuth/ALiPay.php#L58-L85
ondrakoupil/tools
src/Html.php
Html.processLinksInText
static function processLinksInText($input, $stripTags=false, $blankTarget=true) { if ($stripTags) $input=strip_tags($input); //Add protocol to www links without one. We use ahttp to strip it later $input = preg_replace("~([^\w\/:-_]|^)(www\.[^<>,\s\)]+\.\w+)~i","\\1ahttp://\\2", $input); //Make classical links $input = preg_replace("~([a-zA-Z]{2,10}):\/\/([^<>,\s\)]+)~i","<a href=\"\\0\"".($blankTarget?" target=\"_blank\"":"").">\\0</a>", $input); //Strip ahttp back $input = str_replace("href=\"ahttp://","href=\"http://", $input); $input = str_replace("ahttp://","", $input); //E-mailové odkazy $input = preg_replace('~[\w\.\-]+@[^<>\s]+[\w]~',"<a href=\"mailto:\\0\">\\0</a>", $input); $input=trim($input); return $input; }
php
static function processLinksInText($input, $stripTags=false, $blankTarget=true) { if ($stripTags) $input=strip_tags($input); //Add protocol to www links without one. We use ahttp to strip it later $input = preg_replace("~([^\w\/:-_]|^)(www\.[^<>,\s\)]+\.\w+)~i","\\1ahttp://\\2", $input); //Make classical links $input = preg_replace("~([a-zA-Z]{2,10}):\/\/([^<>,\s\)]+)~i","<a href=\"\\0\"".($blankTarget?" target=\"_blank\"":"").">\\0</a>", $input); //Strip ahttp back $input = str_replace("href=\"ahttp://","href=\"http://", $input); $input = str_replace("ahttp://","", $input); //E-mailové odkazy $input = preg_replace('~[\w\.\-]+@[^<>\s]+[\w]~',"<a href=\"mailto:\\0\">\\0</a>", $input); $input=trim($input); return $input; }
[ "static", "function", "processLinksInText", "(", "$", "input", ",", "$", "stripTags", "=", "false", ",", "$", "blankTarget", "=", "true", ")", "{", "if", "(", "$", "stripTags", ")", "$", "input", "=", "strip_tags", "(", "$", "input", ")", ";", "//Add protocol to www links without one. We use ahttp to strip it later", "$", "input", "=", "preg_replace", "(", "\"~([^\\w\\/:-_]|^)(www\\.[^<>,\\s\\)]+\\.\\w+)~i\"", ",", "\"\\\\1ahttp://\\\\2\"", ",", "$", "input", ")", ";", "//Make classical links", "$", "input", "=", "preg_replace", "(", "\"~([a-zA-Z]{2,10}):\\/\\/([^<>,\\s\\)]+)~i\"", ",", "\"<a href=\\\"\\\\0\\\"\"", ".", "(", "$", "blankTarget", "?", "\" target=\\\"_blank\\\"\"", ":", "\"\"", ")", ".", "\">\\\\0</a>\"", ",", "$", "input", ")", ";", "//Strip ahttp back", "$", "input", "=", "str_replace", "(", "\"href=\\\"ahttp://\"", ",", "\"href=\\\"http://\"", ",", "$", "input", ")", ";", "$", "input", "=", "str_replace", "(", "\"ahttp://\"", ",", "\"\"", ",", "$", "input", ")", ";", "//E-mailové odkazy", "$", "input", "=", "preg_replace", "(", "'~[\\w\\.\\-]+@[^<>\\s]+[\\w]~'", ",", "\"<a href=\\\"mailto:\\\\0\\\">\\\\0</a>\"", ",", "$", "input", ")", ";", "$", "input", "=", "trim", "(", "$", "input", ")", ";", "return", "$", "input", ";", "}" ]
Z plaintextu udělá HTML kód tím, že zaktivní odkazy @param type $input @param type $stripTags @param type $blankTarget @return type
[ "Z", "plaintextu", "udělá", "HTML", "kód", "tím", "že", "zaktivní", "odkazy" ]
train
https://github.com/ondrakoupil/tools/blob/7ecbe3652e379802fbaabf4fe8f27b96dcbadb22/src/Html.php#L14-L33
ondrakoupil/tools
src/Html.php
Html.shortenHtml
static function shortenHtml($text, $length = 100, $ending = true, $exact = false, $considerHtml = true) { if ($ending===true) { $ending="&hellip;"; $length+=7; //Jde o jediný znak, ne o 8 znaků } if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text if (Strings::length(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = Strings::length($ending); $open_tags = array(); $truncate = ''; foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { // delete tag from $open_tags list $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } // if tag is an opening tag } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {//<? //Toto je kvůli mému blbému editoru, který si myslí, že je ukončeno PHP // add tag to the beginning of $open_tags list array_unshift($open_tags, Strings::lower($tag_matchings[1])); } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = Strings::length(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length+$content_length> $length) { // the number of characters which are left $left = $length - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1]+1-$entities_length <= $left) { $left--; $entities_length += Strings::length($entity[0]); } else { // no more characters left break; } } } $truncate .= Strings::substring($line_matchings[2], 0, $left+$entities_length); // maximum lenght is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if($total_length>= $length) { break; } } } else { if (Strings::length($text) <= $length) { return $text; } else { $truncate = Strings::substring($text, 0, $length - Strings::length($ending)); } } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurance of a space... $spacepos = strrpos($truncate, ' '); if (isset($spacepos)) { // ...and cut the text in this position $truncate = substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; if($considerHtml) { // close all unclosed html-tags foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; }
php
static function shortenHtml($text, $length = 100, $ending = true, $exact = false, $considerHtml = true) { if ($ending===true) { $ending="&hellip;"; $length+=7; //Jde o jediný znak, ne o 8 znaků } if ($considerHtml) { // if the plain text is shorter than the maximum length, return the whole text if (Strings::length(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } // splits all html-tags to scanable lines preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = Strings::length($ending); $open_tags = array(); $truncate = ''; foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) { // delete tag from $open_tags list $pos = array_search($tag_matchings[1], $open_tags); if ($pos !== false) { unset($open_tags[$pos]); } // if tag is an opening tag } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {//<? //Toto je kvůli mému blbému editoru, který si myslí, že je ukončeno PHP // add tag to the beginning of $open_tags list array_unshift($open_tags, Strings::lower($tag_matchings[1])); } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = Strings::length(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length+$content_length> $length) { // the number of characters which are left $left = $length - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1]+1-$entities_length <= $left) { $left--; $entities_length += Strings::length($entity[0]); } else { // no more characters left break; } } } $truncate .= Strings::substring($line_matchings[2], 0, $left+$entities_length); // maximum lenght is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if($total_length>= $length) { break; } } } else { if (Strings::length($text) <= $length) { return $text; } else { $truncate = Strings::substring($text, 0, $length - Strings::length($ending)); } } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurance of a space... $spacepos = strrpos($truncate, ' '); if (isset($spacepos)) { // ...and cut the text in this position $truncate = substr($truncate, 0, $spacepos); } } // add the defined ending to the text $truncate .= $ending; if($considerHtml) { // close all unclosed html-tags foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } } return $truncate; }
[ "static", "function", "shortenHtml", "(", "$", "text", ",", "$", "length", "=", "100", ",", "$", "ending", "=", "true", ",", "$", "exact", "=", "false", ",", "$", "considerHtml", "=", "true", ")", "{", "if", "(", "$", "ending", "===", "true", ")", "{", "$", "ending", "=", "\"&hellip;\"", ";", "$", "length", "+=", "7", ";", "//Jde o jediný znak, ne o 8 znaků", "}", "if", "(", "$", "considerHtml", ")", "{", "// if the plain text is shorter than the maximum length, return the whole text", "if", "(", "Strings", "::", "length", "(", "preg_replace", "(", "'/<.*?>/'", ",", "''", ",", "$", "text", ")", ")", "<=", "$", "length", ")", "{", "return", "$", "text", ";", "}", "// splits all html-tags to scanable lines", "preg_match_all", "(", "'/(<.+?>)?([^<>]*)/s'", ",", "$", "text", ",", "$", "lines", ",", "PREG_SET_ORDER", ")", ";", "$", "total_length", "=", "Strings", "::", "length", "(", "$", "ending", ")", ";", "$", "open_tags", "=", "array", "(", ")", ";", "$", "truncate", "=", "''", ";", "foreach", "(", "$", "lines", "as", "$", "line_matchings", ")", "{", "// if there is any html-tag in this line, handle it and add it (uncounted) to the output", "if", "(", "!", "empty", "(", "$", "line_matchings", "[", "1", "]", ")", ")", "{", "// if it's an \"empty element\" with or without xhtml-conform closing slash", "if", "(", "preg_match", "(", "'/^<(\\s*.+?\\/\\s*|\\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\\s.+?)?)>$/is'", ",", "$", "line_matchings", "[", "1", "]", ")", ")", "{", "// do nothing", "// if tag is a closing tag", "}", "else", "if", "(", "preg_match", "(", "'/^<\\s*\\/([^\\s]+?)\\s*>$/s'", ",", "$", "line_matchings", "[", "1", "]", ",", "$", "tag_matchings", ")", ")", "{", "// delete tag from $open_tags list", "$", "pos", "=", "array_search", "(", "$", "tag_matchings", "[", "1", "]", ",", "$", "open_tags", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "unset", "(", "$", "open_tags", "[", "$", "pos", "]", ")", ";", "}", "// if tag is an opening tag", "}", "else", "if", "(", "preg_match", "(", "'/^<\\s*([^\\s>!]+).*?>$/s'", ",", "$", "line_matchings", "[", "1", "]", ",", "$", "tag_matchings", ")", ")", "{", "//<? //Toto je kvůli mému blbému editoru, který si myslí, že je ukončeno PHP", "// add tag to the beginning of $open_tags list", "array_unshift", "(", "$", "open_tags", ",", "Strings", "::", "lower", "(", "$", "tag_matchings", "[", "1", "]", ")", ")", ";", "}", "// add html-tag to $truncate'd text", "$", "truncate", ".=", "$", "line_matchings", "[", "1", "]", ";", "}", "// calculate the length of the plain text part of the line; handle entities as one character", "$", "content_length", "=", "Strings", "::", "length", "(", "preg_replace", "(", "'/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i'", ",", "' '", ",", "$", "line_matchings", "[", "2", "]", ")", ")", ";", "if", "(", "$", "total_length", "+", "$", "content_length", ">", "$", "length", ")", "{", "// the number of characters which are left", "$", "left", "=", "$", "length", "-", "$", "total_length", ";", "$", "entities_length", "=", "0", ";", "// search for html entities", "if", "(", "preg_match_all", "(", "'/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i'", ",", "$", "line_matchings", "[", "2", "]", ",", "$", "entities", ",", "PREG_OFFSET_CAPTURE", ")", ")", "{", "// calculate the real length of all entities in the legal range", "foreach", "(", "$", "entities", "[", "0", "]", "as", "$", "entity", ")", "{", "if", "(", "$", "entity", "[", "1", "]", "+", "1", "-", "$", "entities_length", "<=", "$", "left", ")", "{", "$", "left", "--", ";", "$", "entities_length", "+=", "Strings", "::", "length", "(", "$", "entity", "[", "0", "]", ")", ";", "}", "else", "{", "// no more characters left", "break", ";", "}", "}", "}", "$", "truncate", ".=", "Strings", "::", "substring", "(", "$", "line_matchings", "[", "2", "]", ",", "0", ",", "$", "left", "+", "$", "entities_length", ")", ";", "// maximum lenght is reached, so get off the loop", "break", ";", "}", "else", "{", "$", "truncate", ".=", "$", "line_matchings", "[", "2", "]", ";", "$", "total_length", "+=", "$", "content_length", ";", "}", "// if the maximum length is reached, get off the loop", "if", "(", "$", "total_length", ">=", "$", "length", ")", "{", "break", ";", "}", "}", "}", "else", "{", "if", "(", "Strings", "::", "length", "(", "$", "text", ")", "<=", "$", "length", ")", "{", "return", "$", "text", ";", "}", "else", "{", "$", "truncate", "=", "Strings", "::", "substring", "(", "$", "text", ",", "0", ",", "$", "length", "-", "Strings", "::", "length", "(", "$", "ending", ")", ")", ";", "}", "}", "// if the words shouldn't be cut in the middle...", "if", "(", "!", "$", "exact", ")", "{", "// ...search the last occurance of a space...", "$", "spacepos", "=", "strrpos", "(", "$", "truncate", ",", "' '", ")", ";", "if", "(", "isset", "(", "$", "spacepos", ")", ")", "{", "// ...and cut the text in this position", "$", "truncate", "=", "substr", "(", "$", "truncate", ",", "0", ",", "$", "spacepos", ")", ";", "}", "}", "// add the defined ending to the text", "$", "truncate", ".=", "$", "ending", ";", "if", "(", "$", "considerHtml", ")", "{", "// close all unclosed html-tags", "foreach", "(", "$", "open_tags", "as", "$", "tag", ")", "{", "$", "truncate", ".=", "'</'", ".", "$", "tag", ".", "'>'", ";", "}", "}", "return", "$", "truncate", ";", "}" ]
Zkracování řetězce na požadovanou délku při zachování všech HTML tagů. Nenahrazuje konce řádků za <br />. @param string $text Řetězec ke zkrácení @param int $length Požadovaná délka výsledného řetězce (včetně ukončení) @param string $ending Ukončení, které se přilepí na konec zkráceného řetězce. TRUE = použít &amp;hellip;, tj. trojtečku. @param bool $exact False (default) ořízne s ohledem na slova. True ořízne přesně. @param bool $considerHtml TRUE = zachovat správným způsobem HTML tagy. @return string Zkrácený řetězec.
[ "Zkracování", "řetězce", "na", "požadovanou", "délku", "při", "zachování", "všech", "HTML", "tagů", ".", "Nenahrazuje", "konce", "řádků", "za", "<br", "/", ">", "." ]
train
https://github.com/ondrakoupil/tools/blob/7ecbe3652e379802fbaabf4fe8f27b96dcbadb22/src/Html.php#L45-L137
ondrakoupil/tools
src/Html.php
Html.diff
public static function diff($old, $new, $startIns = "<ins>", $endIns = "</ins>", $startDel = "<del>", $endDel = "</del>") { $ret = ''; $diff = Arrays::diff(preg_split("/[\s]+/", $old), preg_split("/[\s]+/", $new)); foreach($diff as $k){ if(is_array($k)) $ret .= (!empty($k['d'])?$startDel.implode(' ',$k['d']).$endDel." ":''). (!empty($k['i'])?$startIns.implode(' ',$k['i']).$endIns." ":''); else $ret .= $k . ' '; } return $ret; }
php
public static function diff($old, $new, $startIns = "<ins>", $endIns = "</ins>", $startDel = "<del>", $endDel = "</del>") { $ret = ''; $diff = Arrays::diff(preg_split("/[\s]+/", $old), preg_split("/[\s]+/", $new)); foreach($diff as $k){ if(is_array($k)) $ret .= (!empty($k['d'])?$startDel.implode(' ',$k['d']).$endDel." ":''). (!empty($k['i'])?$startIns.implode(' ',$k['i']).$endIns." ":''); else $ret .= $k . ' '; } return $ret; }
[ "public", "static", "function", "diff", "(", "$", "old", ",", "$", "new", ",", "$", "startIns", "=", "\"<ins>\"", ",", "$", "endIns", "=", "\"</ins>\"", ",", "$", "startDel", "=", "\"<del>\"", ",", "$", "endDel", "=", "\"</del>\"", ")", "{", "$", "ret", "=", "''", ";", "$", "diff", "=", "Arrays", "::", "diff", "(", "preg_split", "(", "\"/[\\s]+/\"", ",", "$", "old", ")", ",", "preg_split", "(", "\"/[\\s]+/\"", ",", "$", "new", ")", ")", ";", "foreach", "(", "$", "diff", "as", "$", "k", ")", "{", "if", "(", "is_array", "(", "$", "k", ")", ")", "$", "ret", ".=", "(", "!", "empty", "(", "$", "k", "[", "'d'", "]", ")", "?", "$", "startDel", ".", "implode", "(", "' '", ",", "$", "k", "[", "'d'", "]", ")", ".", "$", "endDel", ".", "\" \"", ":", "''", ")", ".", "(", "!", "empty", "(", "$", "k", "[", "'i'", "]", ")", "?", "$", "startIns", ".", "implode", "(", "' '", ",", "$", "k", "[", "'i'", "]", ")", ".", "$", "endIns", ".", "\" \"", ":", "''", ")", ";", "else", "$", "ret", ".=", "$", "k", ".", "' '", ";", "}", "return", "$", "ret", ";", "}" ]
Jednoduché zvýraznění změn v řetězci. Pracuje s přesností na jednotlivá slova. @param string $old @param string $new @param string $startIns @param string $endIns @param string $startDel @param string $endDel @return string @author Paul's Simple Diff Algorithm v 0.1 (C) Paul Butler 2007 <http://www.paulbutler.org/> May be used and distributed under the zlib/libpng license.
[ "Jednoduché", "zvýraznění", "změn", "v", "řetězci", ".", "Pracuje", "s", "přesností", "na", "jednotlivá", "slova", "." ]
train
https://github.com/ondrakoupil/tools/blob/7ecbe3652e379802fbaabf4fe8f27b96dcbadb22/src/Html.php#L164-L174
guillaumebarranco/twitter-api-php-symfony
TwitterAPIExchange.php
TwitterAPIExchange.setPostfields
public function setPostfields(array $array) { if (!is_null($this->getGetfield())) { throw new Exception('You can only choose get OR post fields.'); } if (isset($array['status']) && substr($array['status'], 0, 1) === '@') { $array['status'] = sprintf("\0%s", $array['status']); } $this->postfields = $array; return $this; }
php
public function setPostfields(array $array) { if (!is_null($this->getGetfield())) { throw new Exception('You can only choose get OR post fields.'); } if (isset($array['status']) && substr($array['status'], 0, 1) === '@') { $array['status'] = sprintf("\0%s", $array['status']); } $this->postfields = $array; return $this; }
[ "public", "function", "setPostfields", "(", "array", "$", "array", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "getGetfield", "(", ")", ")", ")", "{", "throw", "new", "Exception", "(", "'You can only choose get OR post fields.'", ")", ";", "}", "if", "(", "isset", "(", "$", "array", "[", "'status'", "]", ")", "&&", "substr", "(", "$", "array", "[", "'status'", "]", ",", "0", ",", "1", ")", "===", "'@'", ")", "{", "$", "array", "[", "'status'", "]", "=", "sprintf", "(", "\"\\0%s\"", ",", "$", "array", "[", "'status'", "]", ")", ";", "}", "$", "this", "->", "postfields", "=", "$", "array", ";", "return", "$", "this", ";", "}" ]
Set postfields array, example: array('screen_name' => 'J7mbo') @param array $array Array of parameters to send to API @return TwitterAPIExchange Instance of self for method chaining
[ "Set", "postfields", "array", "example", ":", "array", "(", "screen_name", "=", ">", "J7mbo", ")" ]
train
https://github.com/guillaumebarranco/twitter-api-php-symfony/blob/34f3d21b2a96b9090b74f7ec14443b085283375e/TwitterAPIExchange.php#L63-L78
guillaumebarranco/twitter-api-php-symfony
TwitterAPIExchange.php
TwitterAPIExchange.setGetfield
public function setGetfield($string) { if (!is_null($this->getPostfields())) { throw new Exception('You can only choose get OR post fields.'); } $search = array('#', ',', '+', ':'); $replace = array('%23', '%2C', '%2B', '%3A'); $string = str_replace($search, $replace, $string); $this->getfield = $string; return $this; }
php
public function setGetfield($string) { if (!is_null($this->getPostfields())) { throw new Exception('You can only choose get OR post fields.'); } $search = array('#', ',', '+', ':'); $replace = array('%23', '%2C', '%2B', '%3A'); $string = str_replace($search, $replace, $string); $this->getfield = $string; return $this; }
[ "public", "function", "setGetfield", "(", "$", "string", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "getPostfields", "(", ")", ")", ")", "{", "throw", "new", "Exception", "(", "'You can only choose get OR post fields.'", ")", ";", "}", "$", "search", "=", "array", "(", "'#'", ",", "','", ",", "'+'", ",", "':'", ")", ";", "$", "replace", "=", "array", "(", "'%23'", ",", "'%2C'", ",", "'%2B'", ",", "'%3A'", ")", ";", "$", "string", "=", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "string", ")", ";", "$", "this", "->", "getfield", "=", "$", "string", ";", "return", "$", "this", ";", "}" ]
Set getfield string, example: '?screen_name=J7mbo' @param string $string Get key and value pairs as string @return \TwitterAPIExchange Instance of self for method chaining
[ "Set", "getfield", "string", "example", ":", "?screen_name", "=", "J7mbo" ]
train
https://github.com/guillaumebarranco/twitter-api-php-symfony/blob/34f3d21b2a96b9090b74f7ec14443b085283375e/TwitterAPIExchange.php#L87-L101
guillaumebarranco/twitter-api-php-symfony
TwitterAPIExchange.php
TwitterAPIExchange.performRequest
public function performRequest($return = true) { if (!is_bool($return)) { throw new Exception('performRequest parameter must be true or false'); } $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:'); $getfield = $this->getGetfield(); $postfields = $this->getPostfields(); $options = array( CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => false, CURLOPT_URL => $this->url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => false ); if (!is_null($postfields)) { $options[CURLOPT_POSTFIELDS] = $postfields; } else { if ($getfield !== '') { $options[CURLOPT_URL] .= $getfield; } } $feed = curl_init(); curl_setopt_array($feed, $options); $json = curl_exec($feed); curl_close($feed); if ($return) { return $json; } }
php
public function performRequest($return = true) { if (!is_bool($return)) { throw new Exception('performRequest parameter must be true or false'); } $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:'); $getfield = $this->getGetfield(); $postfields = $this->getPostfields(); $options = array( CURLOPT_HTTPHEADER => $header, CURLOPT_HEADER => false, CURLOPT_URL => $this->url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => false ); if (!is_null($postfields)) { $options[CURLOPT_POSTFIELDS] = $postfields; } else { if ($getfield !== '') { $options[CURLOPT_URL] .= $getfield; } } $feed = curl_init(); curl_setopt_array($feed, $options); $json = curl_exec($feed); curl_close($feed); if ($return) { return $json; } }
[ "public", "function", "performRequest", "(", "$", "return", "=", "true", ")", "{", "if", "(", "!", "is_bool", "(", "$", "return", ")", ")", "{", "throw", "new", "Exception", "(", "'performRequest parameter must be true or false'", ")", ";", "}", "$", "header", "=", "array", "(", "$", "this", "->", "buildAuthorizationHeader", "(", "$", "this", "->", "oauth", ")", ",", "'Expect:'", ")", ";", "$", "getfield", "=", "$", "this", "->", "getGetfield", "(", ")", ";", "$", "postfields", "=", "$", "this", "->", "getPostfields", "(", ")", ";", "$", "options", "=", "array", "(", "CURLOPT_HTTPHEADER", "=>", "$", "header", ",", "CURLOPT_HEADER", "=>", "false", ",", "CURLOPT_URL", "=>", "$", "this", "->", "url", ",", "CURLOPT_RETURNTRANSFER", "=>", "true", ",", "CURLOPT_TIMEOUT", "=>", "10", ",", "CURLOPT_SSL_VERIFYPEER", "=>", "false", ")", ";", "if", "(", "!", "is_null", "(", "$", "postfields", ")", ")", "{", "$", "options", "[", "CURLOPT_POSTFIELDS", "]", "=", "$", "postfields", ";", "}", "else", "{", "if", "(", "$", "getfield", "!==", "''", ")", "{", "$", "options", "[", "CURLOPT_URL", "]", ".=", "$", "getfield", ";", "}", "}", "$", "feed", "=", "curl_init", "(", ")", ";", "curl_setopt_array", "(", "$", "feed", ",", "$", "options", ")", ";", "$", "json", "=", "curl_exec", "(", "$", "feed", ")", ";", "curl_close", "(", "$", "feed", ")", ";", "if", "(", "$", "return", ")", "{", "return", "$", "json", ";", "}", "}" ]
Perform the actual data retrieval from the API @param boolean $return If true, returns data. @return string json If $return param is true, returns json data.
[ "Perform", "the", "actual", "data", "retrieval", "from", "the", "API" ]
train
https://github.com/guillaumebarranco/twitter-api-php-symfony/blob/34f3d21b2a96b9090b74f7ec14443b085283375e/TwitterAPIExchange.php#L182-L221
guillaumebarranco/twitter-api-php-symfony
TwitterAPIExchange.php
TwitterAPIExchange.buildAuthorizationHeader
private function buildAuthorizationHeader($oauth) { $return = 'Authorization: OAuth '; $values = array(); foreach($oauth as $key => $value) { $values[] = "$key=\"" . rawurlencode($value) . "\""; } $return .= implode(', ', $values); return $return; }
php
private function buildAuthorizationHeader($oauth) { $return = 'Authorization: OAuth '; $values = array(); foreach($oauth as $key => $value) { $values[] = "$key=\"" . rawurlencode($value) . "\""; } $return .= implode(', ', $values); return $return; }
[ "private", "function", "buildAuthorizationHeader", "(", "$", "oauth", ")", "{", "$", "return", "=", "'Authorization: OAuth '", ";", "$", "values", "=", "array", "(", ")", ";", "foreach", "(", "$", "oauth", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "values", "[", "]", "=", "\"$key=\\\"\"", ".", "rawurlencode", "(", "$", "value", ")", ".", "\"\\\"\"", ";", "}", "$", "return", ".=", "implode", "(", "', '", ",", "$", "values", ")", ";", "return", "$", "return", ";", "}" ]
Private method to generate authorization header used by cURL @param array $oauth Array of oauth data generated by buildOauth() @return string $return Header used by cURL for request
[ "Private", "method", "to", "generate", "authorization", "header", "used", "by", "cURL" ]
train
https://github.com/guillaumebarranco/twitter-api-php-symfony/blob/34f3d21b2a96b9090b74f7ec14443b085283375e/TwitterAPIExchange.php#L252-L264
discordier/justtextwidgets
src/Widgets/JustATextOption.php
JustATextOption.generate
public function generate() { // Add empty option (XHTML) if there are none if (empty($this->arrOptions)) { $this->arrOptions = array( array( 'value' => '', 'label' => '-' ) ); } $strClass = ('' !== $this->strClass ? ' class="' . $this->strClass . '"' : ''); $strStyle = ('' !== $this->arrAttributes['style'] ? ' style="' . $this->arrAttributes['style'] . '"' : ''); return $this->checkOptGroup($this->arrOptions, $strClass, $strStyle); }
php
public function generate() { // Add empty option (XHTML) if there are none if (empty($this->arrOptions)) { $this->arrOptions = array( array( 'value' => '', 'label' => '-' ) ); } $strClass = ('' !== $this->strClass ? ' class="' . $this->strClass . '"' : ''); $strStyle = ('' !== $this->arrAttributes['style'] ? ' style="' . $this->arrAttributes['style'] . '"' : ''); return $this->checkOptGroup($this->arrOptions, $strClass, $strStyle); }
[ "public", "function", "generate", "(", ")", "{", "// Add empty option (XHTML) if there are none", "if", "(", "empty", "(", "$", "this", "->", "arrOptions", ")", ")", "{", "$", "this", "->", "arrOptions", "=", "array", "(", "array", "(", "'value'", "=>", "''", ",", "'label'", "=>", "'-'", ")", ")", ";", "}", "$", "strClass", "=", "(", "''", "!==", "$", "this", "->", "strClass", "?", "' class=\"'", ".", "$", "this", "->", "strClass", ".", "'\"'", ":", "''", ")", ";", "$", "strStyle", "=", "(", "''", "!==", "$", "this", "->", "arrAttributes", "[", "'style'", "]", "?", "' style=\"'", ".", "$", "this", "->", "arrAttributes", "[", "'style'", "]", ".", "'\"'", ":", "''", ")", ";", "return", "$", "this", "->", "checkOptGroup", "(", "$", "this", "->", "arrOptions", ",", "$", "strClass", ",", "$", "strStyle", ")", ";", "}" ]
Generate the widget and return it as string. @return string
[ "Generate", "the", "widget", "and", "return", "it", "as", "string", "." ]
train
https://github.com/discordier/justtextwidgets/blob/585f20eec05d592bb13281ca8ef0972e956d3f06/src/Widgets/JustATextOption.php#L70-L86
discordier/justtextwidgets
src/Widgets/JustATextOption.php
JustATextOption.checkOptGroup
private function checkOptGroup($options, $class, $style) { foreach ($options as $option) { // If it is an option group, handle it. if (!isset($option['value'])) { $result = $this->checkOptGroup($option, $class, $style); if ($result) { return $result; } continue; } // No option group, check if it is selected. if ($this->isSelected($option)) { return sprintf( '<input type="hidden" id="ctrl_%s" name="%s" value="%s" /><span%s>%s</span>', $this->strId, $this->strName, StringUtil::specialchars($option['value']), $class . $style, $option['label'] ); } } return null; }
php
private function checkOptGroup($options, $class, $style) { foreach ($options as $option) { // If it is an option group, handle it. if (!isset($option['value'])) { $result = $this->checkOptGroup($option, $class, $style); if ($result) { return $result; } continue; } // No option group, check if it is selected. if ($this->isSelected($option)) { return sprintf( '<input type="hidden" id="ctrl_%s" name="%s" value="%s" /><span%s>%s</span>', $this->strId, $this->strName, StringUtil::specialchars($option['value']), $class . $style, $option['label'] ); } } return null; }
[ "private", "function", "checkOptGroup", "(", "$", "options", ",", "$", "class", ",", "$", "style", ")", "{", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "// If it is an option group, handle it.", "if", "(", "!", "isset", "(", "$", "option", "[", "'value'", "]", ")", ")", "{", "$", "result", "=", "$", "this", "->", "checkOptGroup", "(", "$", "option", ",", "$", "class", ",", "$", "style", ")", ";", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "continue", ";", "}", "// No option group, check if it is selected.", "if", "(", "$", "this", "->", "isSelected", "(", "$", "option", ")", ")", "{", "return", "sprintf", "(", "'<input type=\"hidden\" id=\"ctrl_%s\" name=\"%s\" value=\"%s\" /><span%s>%s</span>'", ",", "$", "this", "->", "strId", ",", "$", "this", "->", "strName", ",", "StringUtil", "::", "specialchars", "(", "$", "option", "[", "'value'", "]", ")", ",", "$", "class", ".", "$", "style", ",", "$", "option", "[", "'label'", "]", ")", ";", "}", "}", "return", "null", ";", "}" ]
Scan an option group for the selected option. @param array $options The option array. @param string $class The html class to use. @param string $style The html style to use. @return null|string
[ "Scan", "an", "option", "group", "for", "the", "selected", "option", "." ]
train
https://github.com/discordier/justtextwidgets/blob/585f20eec05d592bb13281ca8ef0972e956d3f06/src/Widgets/JustATextOption.php#L99-L126
dms-org/package.blog
src/Domain/Entities/BlogAuthor.php
BlogAuthor.defineEntity
protected function defineEntity(ClassDefinition $class) { $class->property($this->name)->asString(); $class->property($this->slug)->asString(); $class->property($this->role)->asString(); $class->property($this->bio)->asObject(Html::class); $class->property($this->articles)->asType(BlogArticle::collectionType()); $this->defineMetadata($class); }
php
protected function defineEntity(ClassDefinition $class) { $class->property($this->name)->asString(); $class->property($this->slug)->asString(); $class->property($this->role)->asString(); $class->property($this->bio)->asObject(Html::class); $class->property($this->articles)->asType(BlogArticle::collectionType()); $this->defineMetadata($class); }
[ "protected", "function", "defineEntity", "(", "ClassDefinition", "$", "class", ")", "{", "$", "class", "->", "property", "(", "$", "this", "->", "name", ")", "->", "asString", "(", ")", ";", "$", "class", "->", "property", "(", "$", "this", "->", "slug", ")", "->", "asString", "(", ")", ";", "$", "class", "->", "property", "(", "$", "this", "->", "role", ")", "->", "asString", "(", ")", ";", "$", "class", "->", "property", "(", "$", "this", "->", "bio", ")", "->", "asObject", "(", "Html", "::", "class", ")", ";", "$", "class", "->", "property", "(", "$", "this", "->", "articles", ")", "->", "asType", "(", "BlogArticle", "::", "collectionType", "(", ")", ")", ";", "$", "this", "->", "defineMetadata", "(", "$", "class", ")", ";", "}" ]
Defines the structure of this entity. @param ClassDefinition $class
[ "Defines", "the", "structure", "of", "this", "entity", "." ]
train
https://github.com/dms-org/package.blog/blob/1500f6fad20d81289a0dfa617fc1c54699f01e16/src/Domain/Entities/BlogAuthor.php#L77-L90
aedart/laravel-helpers
src/Traits/Auth/AuthManagerTrait.php
AuthManagerTrait.getAuthManager
public function getAuthManager(): ?AuthManager { if (!$this->hasAuthManager()) { $this->setAuthManager($this->getDefaultAuthManager()); } return $this->authManager; }
php
public function getAuthManager(): ?AuthManager { if (!$this->hasAuthManager()) { $this->setAuthManager($this->getDefaultAuthManager()); } return $this->authManager; }
[ "public", "function", "getAuthManager", "(", ")", ":", "?", "AuthManager", "{", "if", "(", "!", "$", "this", "->", "hasAuthManager", "(", ")", ")", "{", "$", "this", "->", "setAuthManager", "(", "$", "this", "->", "getDefaultAuthManager", "(", ")", ")", ";", "}", "return", "$", "this", "->", "authManager", ";", "}" ]
Get auth manager If no auth manager has been set, this method will set and return a default auth manager, if any such value is available @see getDefaultAuthManager() @return AuthManager|null auth manager or null if none auth manager has been set
[ "Get", "auth", "manager" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Auth/AuthManagerTrait.php#L53-L59
miisieq/InfaktClient
src/Infakt/Collections/SortClause.php
SortClause.setOrder
public function setOrder($order) { if (!in_array($order, [self::ORDER_ASC, self::ORDER_DESC])) { throw new LogicException('Invalid order argument.'); } $this->order = $order; return $this; }
php
public function setOrder($order) { if (!in_array($order, [self::ORDER_ASC, self::ORDER_DESC])) { throw new LogicException('Invalid order argument.'); } $this->order = $order; return $this; }
[ "public", "function", "setOrder", "(", "$", "order", ")", "{", "if", "(", "!", "in_array", "(", "$", "order", ",", "[", "self", "::", "ORDER_ASC", ",", "self", "::", "ORDER_DESC", "]", ")", ")", "{", "throw", "new", "LogicException", "(", "'Invalid order argument.'", ")", ";", "}", "$", "this", "->", "order", "=", "$", "order", ";", "return", "$", "this", ";", "}" ]
@param $order @throws LogicException @return $this
[ "@param", "$order" ]
train
https://github.com/miisieq/InfaktClient/blob/5f0ae58c7be32580f3c92c2a7e7a7808d83d4e81/src/Infakt/Collections/SortClause.php#L64-L73
aryelgois/yasql-php
src/Controller.php
Controller.build
public static function build( string $output, string $config, string $vendor, array $vendors = null ) { $builder = new Builder($output, $vendor); try { $builder->build($config, $vendors); } catch (\Exception $e) { throw $e; } finally { echo $builder->getLog(); } }
php
public static function build( string $output, string $config, string $vendor, array $vendors = null ) { $builder = new Builder($output, $vendor); try { $builder->build($config, $vendors); } catch (\Exception $e) { throw $e; } finally { echo $builder->getLog(); } }
[ "public", "static", "function", "build", "(", "string", "$", "output", ",", "string", "$", "config", ",", "string", "$", "vendor", ",", "array", "$", "vendors", "=", "null", ")", "{", "$", "builder", "=", "new", "Builder", "(", "$", "output", ",", "$", "vendor", ")", ";", "try", "{", "$", "builder", "->", "build", "(", "$", "config", ",", "$", "vendors", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "finally", "{", "echo", "$", "builder", "->", "getLog", "(", ")", ";", "}", "}" ]
Builds database schemas into a directory @param string $output Path to output directory @param string $config Path to config file @param string $vendor Path to vendors directory @param array $vendors List of additional vendors to include
[ "Builds", "database", "schemas", "into", "a", "directory" ]
train
https://github.com/aryelgois/yasql-php/blob/f428b180d35bfc1ddf1f9b3323f9b085fbc09ac7/src/Controller.php#L29-L44
aryelgois/yasql-php
src/Controller.php
Controller.generate
public static function generate( string $yasql, string $name = null, int $indent = null ) { $model = new Parser($yasql, $name); $view = new Generator($model, $indent); return $view->output(); }
php
public static function generate( string $yasql, string $name = null, int $indent = null ) { $model = new Parser($yasql, $name); $view = new Generator($model, $indent); return $view->output(); }
[ "public", "static", "function", "generate", "(", "string", "$", "yasql", ",", "string", "$", "name", "=", "null", ",", "int", "$", "indent", "=", "null", ")", "{", "$", "model", "=", "new", "Parser", "(", "$", "yasql", ",", "$", "name", ")", ";", "$", "view", "=", "new", "Generator", "(", "$", "model", ",", "$", "indent", ")", ";", "return", "$", "view", "->", "output", "(", ")", ";", "}" ]
Generates the SQL from a YASQL @param string $yasql A string following YAML Ain't SQL specifications @param string $name Overwrite database's name @param int $indent How many spaces per indentation level @return string
[ "Generates", "the", "SQL", "from", "a", "YASQL" ]
train
https://github.com/aryelgois/yasql-php/blob/f428b180d35bfc1ddf1f9b3323f9b085fbc09ac7/src/Controller.php#L55-L63
aryelgois/yasql-php
src/Controller.php
Controller.parse
public static function parse(string $yasql, string $name = null) { $parser = new Parser($yasql, $name); return $parser->getData(); }
php
public static function parse(string $yasql, string $name = null) { $parser = new Parser($yasql, $name); return $parser->getData(); }
[ "public", "static", "function", "parse", "(", "string", "$", "yasql", ",", "string", "$", "name", "=", "null", ")", "{", "$", "parser", "=", "new", "Parser", "(", "$", "yasql", ",", "$", "name", ")", ";", "return", "$", "parser", "->", "getData", "(", ")", ";", "}" ]
Parses a YASQL and returns the parsed data @param string $yasql A string following YAML Ain't SQL specifications @param string $name Overwrite database's name @return array
[ "Parses", "a", "YASQL", "and", "returns", "the", "parsed", "data" ]
train
https://github.com/aryelgois/yasql-php/blob/f428b180d35bfc1ddf1f9b3323f9b085fbc09ac7/src/Controller.php#L73-L77
aedart/laravel-helpers
src/Traits/Mail/MailerTrait.php
MailerTrait.getMailer
public function getMailer(): ?Mailer { if (!$this->hasMailer()) { $this->setMailer($this->getDefaultMailer()); } return $this->mailer; }
php
public function getMailer(): ?Mailer { if (!$this->hasMailer()) { $this->setMailer($this->getDefaultMailer()); } return $this->mailer; }
[ "public", "function", "getMailer", "(", ")", ":", "?", "Mailer", "{", "if", "(", "!", "$", "this", "->", "hasMailer", "(", ")", ")", "{", "$", "this", "->", "setMailer", "(", "$", "this", "->", "getDefaultMailer", "(", ")", ")", ";", "}", "return", "$", "this", "->", "mailer", ";", "}" ]
Get mailer If no mailer has been set, this method will set and return a default mailer, if any such value is available @see getDefaultMailer() @return Mailer|null mailer or null if none mailer has been set
[ "Get", "mailer" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Mail/MailerTrait.php#L53-L59
aedart/laravel-helpers
src/Traits/Cache/CacheFactoryTrait.php
CacheFactoryTrait.getCacheFactory
public function getCacheFactory(): ?Factory { if (!$this->hasCacheFactory()) { $this->setCacheFactory($this->getDefaultCacheFactory()); } return $this->cacheFactory; }
php
public function getCacheFactory(): ?Factory { if (!$this->hasCacheFactory()) { $this->setCacheFactory($this->getDefaultCacheFactory()); } return $this->cacheFactory; }
[ "public", "function", "getCacheFactory", "(", ")", ":", "?", "Factory", "{", "if", "(", "!", "$", "this", "->", "hasCacheFactory", "(", ")", ")", "{", "$", "this", "->", "setCacheFactory", "(", "$", "this", "->", "getDefaultCacheFactory", "(", ")", ")", ";", "}", "return", "$", "this", "->", "cacheFactory", ";", "}" ]
Get cache factory If no cache factory has been set, this method will set and return a default cache factory, if any such value is available @see getDefaultCacheFactory() @return Factory|null cache factory or null if none cache factory has been set
[ "Get", "cache", "factory" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Cache/CacheFactoryTrait.php#L53-L59
nyeholt/silverstripe-external-content
thirdparty/Zend/Feed/Atom.php
Zend_Feed_Atom.link
public function link($rel = null) { if ($rel === null) { return parent::__call('link', null); } // index link tags by their "rel" attribute. $links = parent::__get('link'); if (!is_array($links)) { if ($links instanceof Zend_Feed_Element) { $links = array($links); } else { return $links; } } foreach ($links as $link) { if (empty($link['rel'])) { continue; } if ($rel == $link['rel']) { return $link['href']; } } return null; }
php
public function link($rel = null) { if ($rel === null) { return parent::__call('link', null); } // index link tags by their "rel" attribute. $links = parent::__get('link'); if (!is_array($links)) { if ($links instanceof Zend_Feed_Element) { $links = array($links); } else { return $links; } } foreach ($links as $link) { if (empty($link['rel'])) { continue; } if ($rel == $link['rel']) { return $link['href']; } } return null; }
[ "public", "function", "link", "(", "$", "rel", "=", "null", ")", "{", "if", "(", "$", "rel", "===", "null", ")", "{", "return", "parent", "::", "__call", "(", "'link'", ",", "null", ")", ";", "}", "// index link tags by their \"rel\" attribute.", "$", "links", "=", "parent", "::", "__get", "(", "'link'", ")", ";", "if", "(", "!", "is_array", "(", "$", "links", ")", ")", "{", "if", "(", "$", "links", "instanceof", "Zend_Feed_Element", ")", "{", "$", "links", "=", "array", "(", "$", "links", ")", ";", "}", "else", "{", "return", "$", "links", ";", "}", "}", "foreach", "(", "$", "links", "as", "$", "link", ")", "{", "if", "(", "empty", "(", "$", "link", "[", "'rel'", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "$", "rel", "==", "$", "link", "[", "'rel'", "]", ")", "{", "return", "$", "link", "[", "'href'", "]", ";", "}", "}", "return", "null", ";", "}" ]
Easy access to <link> tags keyed by "rel" attributes. If $elt->link() is called with no arguments, we will attempt to return the value of the <link> tag(s) like all other method-syntax attribute access. If an argument is passed to link(), however, then we will return the "href" value of the first <link> tag that has a "rel" attribute matching $rel: $elt->link(): returns the value of the link tag. $elt->link('self'): returns the href from the first <link rel="self"> in the entry. @param string $rel The "rel" attribute to look for. @return mixed
[ "Easy", "access", "to", "<link", ">", "tags", "keyed", "by", "rel", "attributes", "." ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Feed/Atom.php#L130-L156
nyeholt/silverstripe-external-content
thirdparty/Zend/Feed/Atom.php
Zend_Feed_Atom._mapFeedHeaders
protected function _mapFeedHeaders($array) { $feed = $this->_element->createElement('feed'); $feed->setAttribute('xmlns', 'http://www.w3.org/2005/Atom'); $id = $this->_element->createElement('id', $array->link); $feed->appendChild($id); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($array->title)); $feed->appendChild($title); if (isset($array->author)) { $author = $this->_element->createElement('author'); $name = $this->_element->createElement('name', $array->author); $author->appendChild($name); if (isset($array->email)) { $email = $this->_element->createElement('email', $array->email); $author->appendChild($email); } $feed->appendChild($author); } $updated = isset($array->lastUpdate) ? $array->lastUpdate : time(); $updated = $this->_element->createElement('updated', date(DATE_ATOM, $updated)); $feed->appendChild($updated); if (isset($array->published)) { $published = $this->_element->createElement('published', date(DATE_ATOM, $array->published)); $feed->appendChild($published); } $link = $this->_element->createElement('link'); $link->setAttribute('rel', 'self'); $link->setAttribute('href', $array->link); if (isset($array->language)) { $link->setAttribute('hreflang', $array->language); } $feed->appendChild($link); if (isset($array->description)) { $subtitle = $this->_element->createElement('subtitle'); $subtitle->appendChild($this->_element->createCDATASection($array->description)); $feed->appendChild($subtitle); } if (isset($array->copyright)) { $copyright = $this->_element->createElement('rights', $array->copyright); $feed->appendChild($copyright); } if (isset($array->image)) { $image = $this->_element->createElement('logo', $array->image); $feed->appendChild($image); } $generator = !empty($array->generator) ? $array->generator : 'Zend_Feed'; $generator = $this->_element->createElement('generator', $generator); $feed->appendChild($generator); return $feed; }
php
protected function _mapFeedHeaders($array) { $feed = $this->_element->createElement('feed'); $feed->setAttribute('xmlns', 'http://www.w3.org/2005/Atom'); $id = $this->_element->createElement('id', $array->link); $feed->appendChild($id); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($array->title)); $feed->appendChild($title); if (isset($array->author)) { $author = $this->_element->createElement('author'); $name = $this->_element->createElement('name', $array->author); $author->appendChild($name); if (isset($array->email)) { $email = $this->_element->createElement('email', $array->email); $author->appendChild($email); } $feed->appendChild($author); } $updated = isset($array->lastUpdate) ? $array->lastUpdate : time(); $updated = $this->_element->createElement('updated', date(DATE_ATOM, $updated)); $feed->appendChild($updated); if (isset($array->published)) { $published = $this->_element->createElement('published', date(DATE_ATOM, $array->published)); $feed->appendChild($published); } $link = $this->_element->createElement('link'); $link->setAttribute('rel', 'self'); $link->setAttribute('href', $array->link); if (isset($array->language)) { $link->setAttribute('hreflang', $array->language); } $feed->appendChild($link); if (isset($array->description)) { $subtitle = $this->_element->createElement('subtitle'); $subtitle->appendChild($this->_element->createCDATASection($array->description)); $feed->appendChild($subtitle); } if (isset($array->copyright)) { $copyright = $this->_element->createElement('rights', $array->copyright); $feed->appendChild($copyright); } if (isset($array->image)) { $image = $this->_element->createElement('logo', $array->image); $feed->appendChild($image); } $generator = !empty($array->generator) ? $array->generator : 'Zend_Feed'; $generator = $this->_element->createElement('generator', $generator); $feed->appendChild($generator); return $feed; }
[ "protected", "function", "_mapFeedHeaders", "(", "$", "array", ")", "{", "$", "feed", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'feed'", ")", ";", "$", "feed", "->", "setAttribute", "(", "'xmlns'", ",", "'http://www.w3.org/2005/Atom'", ")", ";", "$", "id", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'id'", ",", "$", "array", "->", "link", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "id", ")", ";", "$", "title", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'title'", ")", ";", "$", "title", "->", "appendChild", "(", "$", "this", "->", "_element", "->", "createCDATASection", "(", "$", "array", "->", "title", ")", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "title", ")", ";", "if", "(", "isset", "(", "$", "array", "->", "author", ")", ")", "{", "$", "author", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'author'", ")", ";", "$", "name", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'name'", ",", "$", "array", "->", "author", ")", ";", "$", "author", "->", "appendChild", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "array", "->", "email", ")", ")", "{", "$", "email", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'email'", ",", "$", "array", "->", "email", ")", ";", "$", "author", "->", "appendChild", "(", "$", "email", ")", ";", "}", "$", "feed", "->", "appendChild", "(", "$", "author", ")", ";", "}", "$", "updated", "=", "isset", "(", "$", "array", "->", "lastUpdate", ")", "?", "$", "array", "->", "lastUpdate", ":", "time", "(", ")", ";", "$", "updated", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'updated'", ",", "date", "(", "DATE_ATOM", ",", "$", "updated", ")", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "updated", ")", ";", "if", "(", "isset", "(", "$", "array", "->", "published", ")", ")", "{", "$", "published", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'published'", ",", "date", "(", "DATE_ATOM", ",", "$", "array", "->", "published", ")", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "published", ")", ";", "}", "$", "link", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'link'", ")", ";", "$", "link", "->", "setAttribute", "(", "'rel'", ",", "'self'", ")", ";", "$", "link", "->", "setAttribute", "(", "'href'", ",", "$", "array", "->", "link", ")", ";", "if", "(", "isset", "(", "$", "array", "->", "language", ")", ")", "{", "$", "link", "->", "setAttribute", "(", "'hreflang'", ",", "$", "array", "->", "language", ")", ";", "}", "$", "feed", "->", "appendChild", "(", "$", "link", ")", ";", "if", "(", "isset", "(", "$", "array", "->", "description", ")", ")", "{", "$", "subtitle", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'subtitle'", ")", ";", "$", "subtitle", "->", "appendChild", "(", "$", "this", "->", "_element", "->", "createCDATASection", "(", "$", "array", "->", "description", ")", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "subtitle", ")", ";", "}", "if", "(", "isset", "(", "$", "array", "->", "copyright", ")", ")", "{", "$", "copyright", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'rights'", ",", "$", "array", "->", "copyright", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "copyright", ")", ";", "}", "if", "(", "isset", "(", "$", "array", "->", "image", ")", ")", "{", "$", "image", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'logo'", ",", "$", "array", "->", "image", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "image", ")", ";", "}", "$", "generator", "=", "!", "empty", "(", "$", "array", "->", "generator", ")", "?", "$", "array", "->", "generator", ":", "'Zend_Feed'", ";", "$", "generator", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'generator'", ",", "$", "generator", ")", ";", "$", "feed", "->", "appendChild", "(", "$", "generator", ")", ";", "return", "$", "feed", ";", "}" ]
Generate the header of the feed when working in write mode @param array $array the data to use @return DOMElement root node
[ "Generate", "the", "header", "of", "the", "feed", "when", "working", "in", "write", "mode" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Feed/Atom.php#L189-L250
nyeholt/silverstripe-external-content
thirdparty/Zend/Feed/Atom.php
Zend_Feed_Atom._mapFeedEntries
protected function _mapFeedEntries(DOMElement $root, $array) { foreach ($array as $dataentry) { $entry = $this->_element->createElement('entry'); $id = $this->_element->createElement('id', isset($dataentry->guid) ? $dataentry->guid : $dataentry->link); $entry->appendChild($id); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($dataentry->title)); $entry->appendChild($title); $updated = isset($dataentry->lastUpdate) ? $dataentry->lastUpdate : time(); $updated = $this->_element->createElement('updated', date(DATE_ATOM, $updated)); $entry->appendChild($updated); $link = $this->_element->createElement('link'); $link->setAttribute('rel', 'alternate'); $link->setAttribute('href', $dataentry->link); $entry->appendChild($link); $summary = $this->_element->createElement('summary'); $summary->appendChild($this->_element->createCDATASection($dataentry->description)); $entry->appendChild($summary); if (isset($dataentry->content)) { $content = $this->_element->createElement('content'); $content->setAttribute('type', 'html'); $content->appendChild($this->_element->createCDATASection($dataentry->content)); $entry->appendChild($content); } if (isset($dataentry->category)) { foreach ($dataentry->category as $category) { $node = $this->_element->createElement('category'); $node->setAttribute('term', $category['term']); if (isset($category['scheme'])) { $node->setAttribute('scheme', $category['scheme']); } $entry->appendChild($node); } } if (isset($dataentry->source)) { $source = $this->_element->createElement('source'); $title = $this->_element->createElement('title', $dataentry->source['title']); $source->appendChild($title); $link = $this->_element->createElement('link', $dataentry->source['title']); $link->setAttribute('rel', 'alternate'); $link->setAttribute('href', $dataentry->source['url']); $source->appendChild($link); } if (isset($dataentry->enclosure)) { foreach ($dataentry->enclosure as $enclosure) { $node = $this->_element->createElement('link'); $node->setAttribute('rel', 'enclosure'); $node->setAttribute('href', $enclosure['url']); if (isset($enclosure['type'])) { $node->setAttribute('type', $enclosure['type']); } if (isset($enclosure['length'])) { $node->setAttribute('length', $enclosure['length']); } $entry->appendChild($node); } } if (isset($dataentry->comments)) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:comment', $dataentry->comments); $entry->appendChild($comments); } if (isset($dataentry->commentRss)) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:commentRss', $dataentry->commentRss); $entry->appendChild($comments); } $root->appendChild($entry); } }
php
protected function _mapFeedEntries(DOMElement $root, $array) { foreach ($array as $dataentry) { $entry = $this->_element->createElement('entry'); $id = $this->_element->createElement('id', isset($dataentry->guid) ? $dataentry->guid : $dataentry->link); $entry->appendChild($id); $title = $this->_element->createElement('title'); $title->appendChild($this->_element->createCDATASection($dataentry->title)); $entry->appendChild($title); $updated = isset($dataentry->lastUpdate) ? $dataentry->lastUpdate : time(); $updated = $this->_element->createElement('updated', date(DATE_ATOM, $updated)); $entry->appendChild($updated); $link = $this->_element->createElement('link'); $link->setAttribute('rel', 'alternate'); $link->setAttribute('href', $dataentry->link); $entry->appendChild($link); $summary = $this->_element->createElement('summary'); $summary->appendChild($this->_element->createCDATASection($dataentry->description)); $entry->appendChild($summary); if (isset($dataentry->content)) { $content = $this->_element->createElement('content'); $content->setAttribute('type', 'html'); $content->appendChild($this->_element->createCDATASection($dataentry->content)); $entry->appendChild($content); } if (isset($dataentry->category)) { foreach ($dataentry->category as $category) { $node = $this->_element->createElement('category'); $node->setAttribute('term', $category['term']); if (isset($category['scheme'])) { $node->setAttribute('scheme', $category['scheme']); } $entry->appendChild($node); } } if (isset($dataentry->source)) { $source = $this->_element->createElement('source'); $title = $this->_element->createElement('title', $dataentry->source['title']); $source->appendChild($title); $link = $this->_element->createElement('link', $dataentry->source['title']); $link->setAttribute('rel', 'alternate'); $link->setAttribute('href', $dataentry->source['url']); $source->appendChild($link); } if (isset($dataentry->enclosure)) { foreach ($dataentry->enclosure as $enclosure) { $node = $this->_element->createElement('link'); $node->setAttribute('rel', 'enclosure'); $node->setAttribute('href', $enclosure['url']); if (isset($enclosure['type'])) { $node->setAttribute('type', $enclosure['type']); } if (isset($enclosure['length'])) { $node->setAttribute('length', $enclosure['length']); } $entry->appendChild($node); } } if (isset($dataentry->comments)) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:comment', $dataentry->comments); $entry->appendChild($comments); } if (isset($dataentry->commentRss)) { $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/', 'wfw:commentRss', $dataentry->commentRss); $entry->appendChild($comments); } $root->appendChild($entry); } }
[ "protected", "function", "_mapFeedEntries", "(", "DOMElement", "$", "root", ",", "$", "array", ")", "{", "foreach", "(", "$", "array", "as", "$", "dataentry", ")", "{", "$", "entry", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'entry'", ")", ";", "$", "id", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'id'", ",", "isset", "(", "$", "dataentry", "->", "guid", ")", "?", "$", "dataentry", "->", "guid", ":", "$", "dataentry", "->", "link", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "id", ")", ";", "$", "title", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'title'", ")", ";", "$", "title", "->", "appendChild", "(", "$", "this", "->", "_element", "->", "createCDATASection", "(", "$", "dataentry", "->", "title", ")", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "title", ")", ";", "$", "updated", "=", "isset", "(", "$", "dataentry", "->", "lastUpdate", ")", "?", "$", "dataentry", "->", "lastUpdate", ":", "time", "(", ")", ";", "$", "updated", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'updated'", ",", "date", "(", "DATE_ATOM", ",", "$", "updated", ")", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "updated", ")", ";", "$", "link", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'link'", ")", ";", "$", "link", "->", "setAttribute", "(", "'rel'", ",", "'alternate'", ")", ";", "$", "link", "->", "setAttribute", "(", "'href'", ",", "$", "dataentry", "->", "link", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "link", ")", ";", "$", "summary", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'summary'", ")", ";", "$", "summary", "->", "appendChild", "(", "$", "this", "->", "_element", "->", "createCDATASection", "(", "$", "dataentry", "->", "description", ")", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "summary", ")", ";", "if", "(", "isset", "(", "$", "dataentry", "->", "content", ")", ")", "{", "$", "content", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'content'", ")", ";", "$", "content", "->", "setAttribute", "(", "'type'", ",", "'html'", ")", ";", "$", "content", "->", "appendChild", "(", "$", "this", "->", "_element", "->", "createCDATASection", "(", "$", "dataentry", "->", "content", ")", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "content", ")", ";", "}", "if", "(", "isset", "(", "$", "dataentry", "->", "category", ")", ")", "{", "foreach", "(", "$", "dataentry", "->", "category", "as", "$", "category", ")", "{", "$", "node", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'category'", ")", ";", "$", "node", "->", "setAttribute", "(", "'term'", ",", "$", "category", "[", "'term'", "]", ")", ";", "if", "(", "isset", "(", "$", "category", "[", "'scheme'", "]", ")", ")", "{", "$", "node", "->", "setAttribute", "(", "'scheme'", ",", "$", "category", "[", "'scheme'", "]", ")", ";", "}", "$", "entry", "->", "appendChild", "(", "$", "node", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "dataentry", "->", "source", ")", ")", "{", "$", "source", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'source'", ")", ";", "$", "title", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'title'", ",", "$", "dataentry", "->", "source", "[", "'title'", "]", ")", ";", "$", "source", "->", "appendChild", "(", "$", "title", ")", ";", "$", "link", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'link'", ",", "$", "dataentry", "->", "source", "[", "'title'", "]", ")", ";", "$", "link", "->", "setAttribute", "(", "'rel'", ",", "'alternate'", ")", ";", "$", "link", "->", "setAttribute", "(", "'href'", ",", "$", "dataentry", "->", "source", "[", "'url'", "]", ")", ";", "$", "source", "->", "appendChild", "(", "$", "link", ")", ";", "}", "if", "(", "isset", "(", "$", "dataentry", "->", "enclosure", ")", ")", "{", "foreach", "(", "$", "dataentry", "->", "enclosure", "as", "$", "enclosure", ")", "{", "$", "node", "=", "$", "this", "->", "_element", "->", "createElement", "(", "'link'", ")", ";", "$", "node", "->", "setAttribute", "(", "'rel'", ",", "'enclosure'", ")", ";", "$", "node", "->", "setAttribute", "(", "'href'", ",", "$", "enclosure", "[", "'url'", "]", ")", ";", "if", "(", "isset", "(", "$", "enclosure", "[", "'type'", "]", ")", ")", "{", "$", "node", "->", "setAttribute", "(", "'type'", ",", "$", "enclosure", "[", "'type'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "enclosure", "[", "'length'", "]", ")", ")", "{", "$", "node", "->", "setAttribute", "(", "'length'", ",", "$", "enclosure", "[", "'length'", "]", ")", ";", "}", "$", "entry", "->", "appendChild", "(", "$", "node", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "dataentry", "->", "comments", ")", ")", "{", "$", "comments", "=", "$", "this", "->", "_element", "->", "createElementNS", "(", "'http://wellformedweb.org/CommentAPI/'", ",", "'wfw:comment'", ",", "$", "dataentry", "->", "comments", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "comments", ")", ";", "}", "if", "(", "isset", "(", "$", "dataentry", "->", "commentRss", ")", ")", "{", "$", "comments", "=", "$", "this", "->", "_element", "->", "createElementNS", "(", "'http://wellformedweb.org/CommentAPI/'", ",", "'wfw:commentRss'", ",", "$", "dataentry", "->", "commentRss", ")", ";", "$", "entry", "->", "appendChild", "(", "$", "comments", ")", ";", "}", "$", "root", "->", "appendChild", "(", "$", "entry", ")", ";", "}", "}" ]
Generate the entries of the feed when working in write mode The following nodes are constructed for each feed entry <entry> <id>url to feed entry</id> <title>entry title</title> <updated>last update</updated> <link rel="alternate" href="url to feed entry" /> <summary>short text</summary> <content>long version, can contain html</content> </entry> @param array $array the data to use @param DOMElement $root the root node to use @return void
[ "Generate", "the", "entries", "of", "the", "feed", "when", "working", "in", "write", "mode" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Feed/Atom.php#L269-L352
nyeholt/silverstripe-external-content
thirdparty/Zend/Feed/Atom.php
Zend_Feed_Atom.saveXml
public function saveXml() { // Return a complete document including XML prologue. $doc = new DOMDocument($this->_element->ownerDocument->version, $this->_element->ownerDocument->actualEncoding); $doc->appendChild($doc->importNode($this->_element, true)); $doc->formatOutput = true; return $doc->saveXML(); }
php
public function saveXml() { // Return a complete document including XML prologue. $doc = new DOMDocument($this->_element->ownerDocument->version, $this->_element->ownerDocument->actualEncoding); $doc->appendChild($doc->importNode($this->_element, true)); $doc->formatOutput = true; return $doc->saveXML(); }
[ "public", "function", "saveXml", "(", ")", "{", "// Return a complete document including XML prologue.", "$", "doc", "=", "new", "DOMDocument", "(", "$", "this", "->", "_element", "->", "ownerDocument", "->", "version", ",", "$", "this", "->", "_element", "->", "ownerDocument", "->", "actualEncoding", ")", ";", "$", "doc", "->", "appendChild", "(", "$", "doc", "->", "importNode", "(", "$", "this", "->", "_element", ",", "true", ")", ")", ";", "$", "doc", "->", "formatOutput", "=", "true", ";", "return", "$", "doc", "->", "saveXML", "(", ")", ";", "}" ]
Override Zend_Feed_Element to allow formated feeds @return string
[ "Override", "Zend_Feed_Element", "to", "allow", "formated", "feeds" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Feed/Atom.php#L359-L368
nyeholt/silverstripe-external-content
thirdparty/Zend/Feed/Atom.php
Zend_Feed_Atom.send
public function send() { if (headers_sent()) { /** * @see Zend_Feed_Exception */ require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Cannot send ATOM because headers have already been sent.'); } header('Content-Type: application/atom+xml; charset=' . $this->_element->ownerDocument->actualEncoding); echo $this->saveXML(); }
php
public function send() { if (headers_sent()) { /** * @see Zend_Feed_Exception */ require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Cannot send ATOM because headers have already been sent.'); } header('Content-Type: application/atom+xml; charset=' . $this->_element->ownerDocument->actualEncoding); echo $this->saveXML(); }
[ "public", "function", "send", "(", ")", "{", "if", "(", "headers_sent", "(", ")", ")", "{", "/** \n * @see Zend_Feed_Exception\n */", "require_once", "'Zend/Feed/Exception.php'", ";", "throw", "new", "Zend_Feed_Exception", "(", "'Cannot send ATOM because headers have already been sent.'", ")", ";", "}", "header", "(", "'Content-Type: application/atom+xml; charset='", ".", "$", "this", "->", "_element", "->", "ownerDocument", "->", "actualEncoding", ")", ";", "echo", "$", "this", "->", "saveXML", "(", ")", ";", "}" ]
Send feed to a http client with the correct header @return void @throws Zend_Feed_Exception if headers have already been sent
[ "Send", "feed", "to", "a", "http", "client", "with", "the", "correct", "header" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Feed/Atom.php#L376-L389
hisorange/traits
src/RunTimeCache.php
RunTimeCache.runTimeCacheGet
public function runTimeCacheGet($key, $default = null) { // Is this key exists? if (array_key_exists($key, $this->runTimeCache)) { return $this->runTimeCache[$key]; } return $default; }
php
public function runTimeCacheGet($key, $default = null) { // Is this key exists? if (array_key_exists($key, $this->runTimeCache)) { return $this->runTimeCache[$key]; } return $default; }
[ "public", "function", "runTimeCacheGet", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "// Is this key exists?", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "runTimeCache", ")", ")", "{", "return", "$", "this", "->", "runTimeCache", "[", "$", "key", "]", ";", "}", "return", "$", "default", ";", "}" ]
Get a value from the cache. @param string $key @param mixed $default @return mixed
[ "Get", "a", "value", "from", "the", "cache", "." ]
train
https://github.com/hisorange/traits/blob/465baf32faaf155b867dcc11218621e23ef4cac2/src/RunTimeCache.php#L43-L51
GrahamDeprecated/CMS-Core
src/migrations/2013_11_16_115153_add_stuff_to_pages.php
AddStuffToPages.up
public function up() { Schema::table('pages', function ($table) { $table->text('css')->default(''); $table->text('js')->default(''); }); foreach (PageProvider::all() as $page) { $page->update(array('css' => '', 'js' => '')); } }
php
public function up() { Schema::table('pages', function ($table) { $table->text('css')->default(''); $table->text('js')->default(''); }); foreach (PageProvider::all() as $page) { $page->update(array('css' => '', 'js' => '')); } }
[ "public", "function", "up", "(", ")", "{", "Schema", "::", "table", "(", "'pages'", ",", "function", "(", "$", "table", ")", "{", "$", "table", "->", "text", "(", "'css'", ")", "->", "default", "(", "''", ")", ";", "$", "table", "->", "text", "(", "'js'", ")", "->", "default", "(", "''", ")", ";", "}", ")", ";", "foreach", "(", "PageProvider", "::", "all", "(", ")", "as", "$", "page", ")", "{", "$", "page", "->", "update", "(", "array", "(", "'css'", "=>", "''", ",", "'js'", "=>", "''", ")", ")", ";", "}", "}" ]
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/GrahamDeprecated/CMS-Core/blob/5603e2bfa2fac6cf46ca3ed62d21518f2f653675/src/migrations/2013_11_16_115153_add_stuff_to_pages.php#L37-L47
lmammino/e-foundation
src/Cart/Model/CartAdjustment.php
CartAdjustment.setAdjustable
public function setAdjustable(AdjustableInterface $adjustable = null) { $this->adjustable = $this->cart = $adjustable; return $this; }
php
public function setAdjustable(AdjustableInterface $adjustable = null) { $this->adjustable = $this->cart = $adjustable; return $this; }
[ "public", "function", "setAdjustable", "(", "AdjustableInterface", "$", "adjustable", "=", "null", ")", "{", "$", "this", "->", "adjustable", "=", "$", "this", "->", "cart", "=", "$", "adjustable", ";", "return", "$", "this", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/lmammino/e-foundation/blob/198b7047d93eb11c9bc0c7ddf0bfa8229d42807a/src/Cart/Model/CartAdjustment.php#L39-L44
yuncms/framework
src/rest/models/UserBindMobileForm.php
UserBindMobileForm.bind
public function bind() { if ($this->validate() && ($user = $this->getUser()) != null) { $user->updateAttributes(['mobile' => $this->mobile, 'mobile_confirmed_at' => time()]); return $user; } return false; }
php
public function bind() { if ($this->validate() && ($user = $this->getUser()) != null) { $user->updateAttributes(['mobile' => $this->mobile, 'mobile_confirmed_at' => time()]); return $user; } return false; }
[ "public", "function", "bind", "(", ")", "{", "if", "(", "$", "this", "->", "validate", "(", ")", "&&", "(", "$", "user", "=", "$", "this", "->", "getUser", "(", ")", ")", "!=", "null", ")", "{", "$", "user", "->", "updateAttributes", "(", "[", "'mobile'", "=>", "$", "this", "->", "mobile", ",", "'mobile_confirmed_at'", "=>", "time", "(", ")", "]", ")", ";", "return", "$", "user", ";", "}", "return", "false", ";", "}" ]
绑定手机 @return bool|User
[ "绑定手机" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/rest/models/UserBindMobileForm.php#L72-L79
VincentChalnot/SidusAdminBundle
Doctrine/DoctrineHelper.php
DoctrineHelper.getManagerForEntity
public function getManagerForEntity($entity): EntityManagerInterface { $class = ClassUtils::getClass($entity); $entityManager = $this->doctrine->getManagerForClass($class); if (!$entityManager instanceof EntityManagerInterface) { throw new \InvalidArgumentException("No manager found for class {$class}"); } return $entityManager; }
php
public function getManagerForEntity($entity): EntityManagerInterface { $class = ClassUtils::getClass($entity); $entityManager = $this->doctrine->getManagerForClass($class); if (!$entityManager instanceof EntityManagerInterface) { throw new \InvalidArgumentException("No manager found for class {$class}"); } return $entityManager; }
[ "public", "function", "getManagerForEntity", "(", "$", "entity", ")", ":", "EntityManagerInterface", "{", "$", "class", "=", "ClassUtils", "::", "getClass", "(", "$", "entity", ")", ";", "$", "entityManager", "=", "$", "this", "->", "doctrine", "->", "getManagerForClass", "(", "$", "class", ")", ";", "if", "(", "!", "$", "entityManager", "instanceof", "EntityManagerInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"No manager found for class {$class}\"", ")", ";", "}", "return", "$", "entityManager", ";", "}" ]
@param mixed $entity @throws \LogicException @return EntityManagerInterface
[ "@param", "mixed", "$entity" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Doctrine/DoctrineHelper.php#L49-L58
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.build
public function build(IUrl $url, $encode = false) { $pattern = $this->pattern; $pattern = $this->setProtocol($pattern, $url, $encode); $pattern = $this->setCredentials($pattern, $url, $encode); $pattern = $this->setHost($pattern, $url, $encode); $pattern = $this->setPort($pattern, $url, $encode); $pattern = $this->setPath($pattern, $url, $encode); $pattern = $this->setQuery($pattern, $url, $encode); $pattern = $this->setFragment($pattern, $url, $encode); return $pattern; }
php
public function build(IUrl $url, $encode = false) { $pattern = $this->pattern; $pattern = $this->setProtocol($pattern, $url, $encode); $pattern = $this->setCredentials($pattern, $url, $encode); $pattern = $this->setHost($pattern, $url, $encode); $pattern = $this->setPort($pattern, $url, $encode); $pattern = $this->setPath($pattern, $url, $encode); $pattern = $this->setQuery($pattern, $url, $encode); $pattern = $this->setFragment($pattern, $url, $encode); return $pattern; }
[ "public", "function", "build", "(", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ")", "{", "$", "pattern", "=", "$", "this", "->", "pattern", ";", "$", "pattern", "=", "$", "this", "->", "setProtocol", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "$", "pattern", "=", "$", "this", "->", "setCredentials", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "$", "pattern", "=", "$", "this", "->", "setHost", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "$", "pattern", "=", "$", "this", "->", "setPort", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "$", "pattern", "=", "$", "this", "->", "setPath", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "$", "pattern", "=", "$", "this", "->", "setQuery", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "$", "pattern", "=", "$", "this", "->", "setFragment", "(", "$", "pattern", ",", "$", "url", ",", "$", "encode", ")", ";", "return", "$", "pattern", ";", "}" ]
@param IUrl $url @param bool $encode @return string
[ "@param", "IUrl", "$url", "@param", "bool", "$encode" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L17-L28
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.buildHost
public function buildHost($tld, $domain, $subdomain) { $parts = []; if ($tld !== null) { array_unshift($parts, $tld); } if ($domain !== null) { array_unshift($parts, $domain); } if ($subdomain !== null) { array_unshift($parts, $subdomain); } $host = implode('.', $parts); return $host; }
php
public function buildHost($tld, $domain, $subdomain) { $parts = []; if ($tld !== null) { array_unshift($parts, $tld); } if ($domain !== null) { array_unshift($parts, $domain); } if ($subdomain !== null) { array_unshift($parts, $subdomain); } $host = implode('.', $parts); return $host; }
[ "public", "function", "buildHost", "(", "$", "tld", ",", "$", "domain", ",", "$", "subdomain", ")", "{", "$", "parts", "=", "[", "]", ";", "if", "(", "$", "tld", "!==", "null", ")", "{", "array_unshift", "(", "$", "parts", ",", "$", "tld", ")", ";", "}", "if", "(", "$", "domain", "!==", "null", ")", "{", "array_unshift", "(", "$", "parts", ",", "$", "domain", ")", ";", "}", "if", "(", "$", "subdomain", "!==", "null", ")", "{", "array_unshift", "(", "$", "parts", ",", "$", "subdomain", ")", ";", "}", "$", "host", "=", "implode", "(", "'.'", ",", "$", "parts", ")", ";", "return", "$", "host", ";", "}" ]
@param string $tld @param string $domain @param string $subdomain @return string
[ "@param", "string", "$tld", "@param", "string", "$domain", "@param", "string", "$subdomain" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L37-L55
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setProtocol
protected function setProtocol($pattern, IUrl $url, $encode = false, $key = ':scheme') { $scheme = $url->getProtocol(); if ($scheme) { $scheme = s('%s://', $scheme); } $pattern = s($pattern, [$key => $scheme]); return $pattern; }
php
protected function setProtocol($pattern, IUrl $url, $encode = false, $key = ':scheme') { $scheme = $url->getProtocol(); if ($scheme) { $scheme = s('%s://', $scheme); } $pattern = s($pattern, [$key => $scheme]); return $pattern; }
[ "protected", "function", "setProtocol", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':scheme'", ")", "{", "$", "scheme", "=", "$", "url", "->", "getProtocol", "(", ")", ";", "if", "(", "$", "scheme", ")", "{", "$", "scheme", "=", "s", "(", "'%s://'", ",", "$", "scheme", ")", ";", "}", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "scheme", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L65-L75
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setCredentials
protected function setCredentials($pattern, IUrl $url, $encode = false, $key = ':credentials') { $username = $url->getUsername(); $password = $url->getPassword(); $credentials = ''; if ($encode) { $username = rawurlencode($username); $password = rawurlencode($password); } if ($username && $password) { $credentials = s('%s:%s@', $username, $password); } $pattern = s($pattern, [$key => $credentials]); return $pattern; }
php
protected function setCredentials($pattern, IUrl $url, $encode = false, $key = ':credentials') { $username = $url->getUsername(); $password = $url->getPassword(); $credentials = ''; if ($encode) { $username = rawurlencode($username); $password = rawurlencode($password); } if ($username && $password) { $credentials = s('%s:%s@', $username, $password); } $pattern = s($pattern, [$key => $credentials]); return $pattern; }
[ "protected", "function", "setCredentials", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':credentials'", ")", "{", "$", "username", "=", "$", "url", "->", "getUsername", "(", ")", ";", "$", "password", "=", "$", "url", "->", "getPassword", "(", ")", ";", "$", "credentials", "=", "''", ";", "if", "(", "$", "encode", ")", "{", "$", "username", "=", "rawurlencode", "(", "$", "username", ")", ";", "$", "password", "=", "rawurlencode", "(", "$", "password", ")", ";", "}", "if", "(", "$", "username", "&&", "$", "password", ")", "{", "$", "credentials", "=", "s", "(", "'%s:%s@'", ",", "$", "username", ",", "$", "password", ")", ";", "}", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "credentials", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L85-L102
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setHost
protected function setHost($pattern, IUrl $url, $encode = false, $key = ':host') { $host = $url->getHost(); $pattern = s($pattern, [$key => $host]); return $pattern; }
php
protected function setHost($pattern, IUrl $url, $encode = false, $key = ':host') { $host = $url->getHost(); $pattern = s($pattern, [$key => $host]); return $pattern; }
[ "protected", "function", "setHost", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':host'", ")", "{", "$", "host", "=", "$", "url", "->", "getHost", "(", ")", ";", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "host", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L112-L117
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setPort
protected function setPort($pattern, IUrl $url, $encode = false, $key = ':port') { $port = $url->getPort(); if ($port) { $port = s(':%s', $port); } $pattern = s($pattern, [$key => $port]); return $pattern; }
php
protected function setPort($pattern, IUrl $url, $encode = false, $key = ':port') { $port = $url->getPort(); if ($port) { $port = s(':%s', $port); } $pattern = s($pattern, [$key => $port]); return $pattern; }
[ "protected", "function", "setPort", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':port'", ")", "{", "$", "port", "=", "$", "url", "->", "getPort", "(", ")", ";", "if", "(", "$", "port", ")", "{", "$", "port", "=", "s", "(", "':%s'", ",", "$", "port", ")", ";", "}", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "port", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L127-L137
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setPath
protected function setPath($pattern, IUrl $url, $encode = false, $key = ':path') { $path = $url->getPath(); $pattern = s($pattern, [$key => $path]); return $pattern; }
php
protected function setPath($pattern, IUrl $url, $encode = false, $key = ':path') { $path = $url->getPath(); $pattern = s($pattern, [$key => $path]); return $pattern; }
[ "protected", "function", "setPath", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':path'", ")", "{", "$", "path", "=", "$", "url", "->", "getPath", "(", ")", ";", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "path", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L147-L152
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setQuery
protected function setQuery($pattern, IUrl $url, $encode = false, $key = ':query') { $query = $url->getQuery()->toString($encode); if ($query) { $query = s('?%s', $query); } $pattern = s($pattern, [$key => $query]); return $pattern; }
php
protected function setQuery($pattern, IUrl $url, $encode = false, $key = ':query') { $query = $url->getQuery()->toString($encode); if ($query) { $query = s('?%s', $query); } $pattern = s($pattern, [$key => $query]); return $pattern; }
[ "protected", "function", "setQuery", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':query'", ")", "{", "$", "query", "=", "$", "url", "->", "getQuery", "(", ")", "->", "toString", "(", "$", "encode", ")", ";", "if", "(", "$", "query", ")", "{", "$", "query", "=", "s", "(", "'?%s'", ",", "$", "query", ")", ";", "}", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "query", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L162-L172
weew/url
src/Weew/Url/UrlBuilder.php
UrlBuilder.setFragment
protected function setFragment($pattern, IUrl $url, $encode = false, $key = ':fragment') { $fragment = $url->getFragment(); if ($fragment) { $fragment = s('#%s', $fragment); } $pattern = s($pattern, [$key => $fragment]); return $pattern; }
php
protected function setFragment($pattern, IUrl $url, $encode = false, $key = ':fragment') { $fragment = $url->getFragment(); if ($fragment) { $fragment = s('#%s', $fragment); } $pattern = s($pattern, [$key => $fragment]); return $pattern; }
[ "protected", "function", "setFragment", "(", "$", "pattern", ",", "IUrl", "$", "url", ",", "$", "encode", "=", "false", ",", "$", "key", "=", "':fragment'", ")", "{", "$", "fragment", "=", "$", "url", "->", "getFragment", "(", ")", ";", "if", "(", "$", "fragment", ")", "{", "$", "fragment", "=", "s", "(", "'#%s'", ",", "$", "fragment", ")", ";", "}", "$", "pattern", "=", "s", "(", "$", "pattern", ",", "[", "$", "key", "=>", "$", "fragment", "]", ")", ";", "return", "$", "pattern", ";", "}" ]
@param string $pattern @param IUrl $url @param bool $encode @param string $key @return string
[ "@param", "string", "$pattern", "@param", "IUrl", "$url", "@param", "bool", "$encode", "@param", "string", "$key" ]
train
https://github.com/weew/url/blob/117be15e899cc343f22f04f5eb9e92e2164c56c1/src/Weew/Url/UrlBuilder.php#L182-L192
ronanguilloux/SilexMarkdownServiceProvider
src/Rg/Markdown/MarkdownExtended.php
MarkdownExtended.getTitle
public function getTitle($markdown) { $html = "<xml>" . self::transform($markdown) . "</xml>"; $dom = new \DOMDocument; $dom->loadXml($html); return $dom->getElementsByTagName('h1')->item(0)->nodeValue; }
php
public function getTitle($markdown) { $html = "<xml>" . self::transform($markdown) . "</xml>"; $dom = new \DOMDocument; $dom->loadXml($html); return $dom->getElementsByTagName('h1')->item(0)->nodeValue; }
[ "public", "function", "getTitle", "(", "$", "markdown", ")", "{", "$", "html", "=", "\"<xml>\"", ".", "self", "::", "transform", "(", "$", "markdown", ")", ".", "\"</xml>\"", ";", "$", "dom", "=", "new", "\\", "DOMDocument", ";", "$", "dom", "->", "loadXml", "(", "$", "html", ")", ";", "return", "$", "dom", "->", "getElementsByTagName", "(", "'h1'", ")", "->", "item", "(", "0", ")", "->", "nodeValue", ";", "}" ]
getTitle Returns title from a markdown source eventually containing "====" underlined label, usually parsed as <h1> @param string $markdown @return string $title
[ "getTitle", "Returns", "title", "from", "a", "markdown", "source", "eventually", "containing", "====", "underlined", "label", "usually", "parsed", "as", "<h1", ">" ]
train
https://github.com/ronanguilloux/SilexMarkdownServiceProvider/blob/8266baf0b8a74a98ea32ba1417d767dca6b374b3/src/Rg/Markdown/MarkdownExtended.php#L36-L43
aedart/laravel-helpers
src/Traits/Redis/RedisFactoryTrait.php
RedisFactoryTrait.getRedisFactory
public function getRedisFactory(): ?Factory { if (!$this->hasRedisFactory()) { $this->setRedisFactory($this->getDefaultRedisFactory()); } return $this->redisFactory; }
php
public function getRedisFactory(): ?Factory { if (!$this->hasRedisFactory()) { $this->setRedisFactory($this->getDefaultRedisFactory()); } return $this->redisFactory; }
[ "public", "function", "getRedisFactory", "(", ")", ":", "?", "Factory", "{", "if", "(", "!", "$", "this", "->", "hasRedisFactory", "(", ")", ")", "{", "$", "this", "->", "setRedisFactory", "(", "$", "this", "->", "getDefaultRedisFactory", "(", ")", ")", ";", "}", "return", "$", "this", "->", "redisFactory", ";", "}" ]
Get redis factory If no redis factory has been set, this method will set and return a default redis factory, if any such value is available @see getDefaultRedisFactory() @return Factory|null redis factory or null if none redis factory has been set
[ "Get", "redis", "factory" ]
train
https://github.com/aedart/laravel-helpers/blob/8b81a2d6658f3f8cb62b6be2c34773aaa2df219a/src/Traits/Redis/RedisFactoryTrait.php#L53-L59
redaigbaria/oauth2
src/Util/KeyAlgorithm/DefaultAlgorithm.php
DefaultAlgorithm.generate
public function generate($len = 40) { $stripped = ''; do { $bytes = openssl_random_pseudo_bytes($len, $strong); // We want to stop execution if the key fails because, well, that is bad. if ($bytes === false || $strong === false) { // @codeCoverageIgnoreStart throw new \Exception('Error Generating Key'); // @codeCoverageIgnoreEnd } $stripped .= str_replace(['/', '+', '='], '', base64_encode($bytes)); } while (strlen($stripped) < $len); return substr($stripped, 0, $len); }
php
public function generate($len = 40) { $stripped = ''; do { $bytes = openssl_random_pseudo_bytes($len, $strong); // We want to stop execution if the key fails because, well, that is bad. if ($bytes === false || $strong === false) { // @codeCoverageIgnoreStart throw new \Exception('Error Generating Key'); // @codeCoverageIgnoreEnd } $stripped .= str_replace(['/', '+', '='], '', base64_encode($bytes)); } while (strlen($stripped) < $len); return substr($stripped, 0, $len); }
[ "public", "function", "generate", "(", "$", "len", "=", "40", ")", "{", "$", "stripped", "=", "''", ";", "do", "{", "$", "bytes", "=", "openssl_random_pseudo_bytes", "(", "$", "len", ",", "$", "strong", ")", ";", "// We want to stop execution if the key fails because, well, that is bad.", "if", "(", "$", "bytes", "===", "false", "||", "$", "strong", "===", "false", ")", "{", "// @codeCoverageIgnoreStart", "throw", "new", "\\", "Exception", "(", "'Error Generating Key'", ")", ";", "// @codeCoverageIgnoreEnd", "}", "$", "stripped", ".=", "str_replace", "(", "[", "'/'", ",", "'+'", ",", "'='", "]", ",", "''", ",", "base64_encode", "(", "$", "bytes", ")", ")", ";", "}", "while", "(", "strlen", "(", "$", "stripped", ")", "<", "$", "len", ")", ";", "return", "substr", "(", "$", "stripped", ",", "0", ",", "$", "len", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Util/KeyAlgorithm/DefaultAlgorithm.php#L19-L35
webforge-labs/psc-cms
lib/Psc/Doctrine/EntityRelationInterfaceBuilder.php
EntityRelationInterfaceBuilder.buildSource
public function buildSource(GClass $gClass) { if ($this->relation->isWithoutInterface()) { return FALSE; } if ($this->relation->getType() === EntityRelation::ONE_TO_MANY || $this->relation->getType() === EntityRelation::MANY_TO_MANY) { $this->createCollectionAdder($gClass); $this->createCollectionRemover($gClass); $this->createCollectionChecker($gClass); } if ($this->relation->getType() === EntityRelation::MANY_TO_ONE || $this->relation->getType() === EntityRelation::ONE_TO_ONE) { $this->injectToSetter($gClass); } }
php
public function buildSource(GClass $gClass) { if ($this->relation->isWithoutInterface()) { return FALSE; } if ($this->relation->getType() === EntityRelation::ONE_TO_MANY || $this->relation->getType() === EntityRelation::MANY_TO_MANY) { $this->createCollectionAdder($gClass); $this->createCollectionRemover($gClass); $this->createCollectionChecker($gClass); } if ($this->relation->getType() === EntityRelation::MANY_TO_ONE || $this->relation->getType() === EntityRelation::ONE_TO_ONE) { $this->injectToSetter($gClass); } }
[ "public", "function", "buildSource", "(", "GClass", "$", "gClass", ")", "{", "if", "(", "$", "this", "->", "relation", "->", "isWithoutInterface", "(", ")", ")", "{", "return", "FALSE", ";", "}", "if", "(", "$", "this", "->", "relation", "->", "getType", "(", ")", "===", "EntityRelation", "::", "ONE_TO_MANY", "||", "$", "this", "->", "relation", "->", "getType", "(", ")", "===", "EntityRelation", "::", "MANY_TO_MANY", ")", "{", "$", "this", "->", "createCollectionAdder", "(", "$", "gClass", ")", ";", "$", "this", "->", "createCollectionRemover", "(", "$", "gClass", ")", ";", "$", "this", "->", "createCollectionChecker", "(", "$", "gClass", ")", ";", "}", "if", "(", "$", "this", "->", "relation", "->", "getType", "(", ")", "===", "EntityRelation", "::", "MANY_TO_ONE", "||", "$", "this", "->", "relation", "->", "getType", "(", ")", "===", "EntityRelation", "::", "ONE_TO_ONE", ")", "{", "$", "this", "->", "injectToSetter", "(", "$", "gClass", ")", ";", "}", "}" ]
Erstellt alle Methoden des RelationInterfaces in der Angegebenen Klasse für die Source Seite
[ "Erstellt", "alle", "Methoden", "des", "RelationInterfaces", "in", "der", "Angegebenen", "Klasse", "für", "die", "Source", "Seite" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/EntityRelationInterfaceBuilder.php#L26-L40
djgadd/themosis-illuminate
src/Validation/ValidationServiceProvider.php
ValidationServiceProvider.boot
public function boot () { ValidatorFacade::extend('valid_nonce', function ($attaribute, $value, $params, $validator) { $action = $params[0]; return (bool) wp_verify_nonce($value, $action); }); }
php
public function boot () { ValidatorFacade::extend('valid_nonce', function ($attaribute, $value, $params, $validator) { $action = $params[0]; return (bool) wp_verify_nonce($value, $action); }); }
[ "public", "function", "boot", "(", ")", "{", "ValidatorFacade", "::", "extend", "(", "'valid_nonce'", ",", "function", "(", "$", "attaribute", ",", "$", "value", ",", "$", "params", ",", "$", "validator", ")", "{", "$", "action", "=", "$", "params", "[", "0", "]", ";", "return", "(", "bool", ")", "wp_verify_nonce", "(", "$", "value", ",", "$", "action", ")", ";", "}", ")", ";", "}" ]
Add valid_nonce validation rule @return void
[ "Add", "valid_nonce", "validation", "rule" ]
train
https://github.com/djgadd/themosis-illuminate/blob/13ee4c3413cddd85a2f262ac361f35c81da0c53c/src/Validation/ValidationServiceProvider.php#L23-L29
ppetermann/king23
src/Mongo/Result.php
Result.current
public function current() { $documentData = $this->myResultCursor->current(); if (is_null($documentData)) { return null; } /** @var MongoObject $document */ $document = $this->container->get( $this->classMapInterface->getClassForResult($this->collection, $documentData) ); $document->setCollection($this->collection); $document->loadFromArray($documentData); return $document; }
php
public function current() { $documentData = $this->myResultCursor->current(); if (is_null($documentData)) { return null; } /** @var MongoObject $document */ $document = $this->container->get( $this->classMapInterface->getClassForResult($this->collection, $documentData) ); $document->setCollection($this->collection); $document->loadFromArray($documentData); return $document; }
[ "public", "function", "current", "(", ")", "{", "$", "documentData", "=", "$", "this", "->", "myResultCursor", "->", "current", "(", ")", ";", "if", "(", "is_null", "(", "$", "documentData", ")", ")", "{", "return", "null", ";", "}", "/** @var MongoObject $document */", "$", "document", "=", "$", "this", "->", "container", "->", "get", "(", "$", "this", "->", "classMapInterface", "->", "getClassForResult", "(", "$", "this", "->", "collection", ",", "$", "documentData", ")", ")", ";", "$", "document", "->", "setCollection", "(", "$", "this", "->", "collection", ")", ";", "$", "document", "->", "loadFromArray", "(", "$", "documentData", ")", ";", "return", "$", "document", ";", "}" ]
Iterator::current return current specific object @return MongoObject @throws Exception @throws \MongoException
[ "Iterator", "::", "current", "return", "current", "specific", "object" ]
train
https://github.com/ppetermann/king23/blob/603896083ec89f5ac4d744abd3b1b4db3e914c95/src/Mongo/Result.php#L124-L139
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.getEntity
public function getEntity($id, $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { return $this->getQueryBuilder(['id' => $id]) ->getQuery() ->setMaxResults(1) ->getOneOrNullResult($hydrationMode); }
php
public function getEntity($id, $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { return $this->getQueryBuilder(['id' => $id]) ->getQuery() ->setMaxResults(1) ->getOneOrNullResult($hydrationMode); }
[ "public", "function", "getEntity", "(", "$", "id", ",", "$", "hydrationMode", "=", "AbstractQuery", "::", "HYDRATE_OBJECT", ")", "{", "return", "$", "this", "->", "getQueryBuilder", "(", "[", "'id'", "=>", "$", "id", "]", ")", "->", "getQuery", "(", ")", "->", "setMaxResults", "(", "1", ")", "->", "getOneOrNullResult", "(", "$", "hydrationMode", ")", ";", "}" ]
Returns an entity by its ID. @param mixed $id @param integer $hydrationMode @return mixed @deprecated Deprecated since 2.0.4; to be removed in 3.0.0. Use the basic `find()` method instead
[ "Returns", "an", "entity", "by", "its", "ID", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L37-L43
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.getEntitiesById
public function getEntitiesById(array $ids, $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { return $this->getQueryBuilder(['id' => $ids]) ->getQuery() ->execute(null, $hydrationMode); }
php
public function getEntitiesById(array $ids, $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { return $this->getQueryBuilder(['id' => $ids]) ->getQuery() ->execute(null, $hydrationMode); }
[ "public", "function", "getEntitiesById", "(", "array", "$", "ids", ",", "$", "hydrationMode", "=", "AbstractQuery", "::", "HYDRATE_OBJECT", ")", "{", "return", "$", "this", "->", "getQueryBuilder", "(", "[", "'id'", "=>", "$", "ids", "]", ")", "->", "getQuery", "(", ")", "->", "execute", "(", "null", ",", "$", "hydrationMode", ")", ";", "}" ]
Returns a list of entities extracted by their IDs. @param array $ids @param integer $hydrationMode @return array
[ "Returns", "a", "list", "of", "entities", "extracted", "by", "their", "IDs", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L65-L70
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.getEntities
public function getEntities(array $options = [], $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { $options = EntityRepositoryOptionsResolver::createAndResolve($options); return $this->getQueryBuilder($options['filters'], $options['sorting']) ->getQuery() ->execute(null, $hydrationMode); }
php
public function getEntities(array $options = [], $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { $options = EntityRepositoryOptionsResolver::createAndResolve($options); return $this->getQueryBuilder($options['filters'], $options['sorting']) ->getQuery() ->execute(null, $hydrationMode); }
[ "public", "function", "getEntities", "(", "array", "$", "options", "=", "[", "]", ",", "$", "hydrationMode", "=", "AbstractQuery", "::", "HYDRATE_OBJECT", ")", "{", "$", "options", "=", "EntityRepositoryOptionsResolver", "::", "createAndResolve", "(", "$", "options", ")", ";", "return", "$", "this", "->", "getQueryBuilder", "(", "$", "options", "[", "'filters'", "]", ",", "$", "options", "[", "'sorting'", "]", ")", "->", "getQuery", "(", ")", "->", "execute", "(", "null", ",", "$", "hydrationMode", ")", ";", "}" ]
Returns a list of all the entities. @param array $options @param integer $hydrationMode @return array
[ "Returns", "a", "list", "of", "all", "the", "entities", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L79-L85
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.getPaginatedEntities
public function getPaginatedEntities(array $options = [], $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { $options = PaginatedEntityRepositoryOptionsResolver::createAndResolve($options); $queryBuilder = $this->addPagination( $this->getQueryBuilder($options['filters'], $options['sorting']), $options['elementsPerPage'], $options['page'] ); return new Paginator($queryBuilder->getQuery()->setHydrationMode($hydrationMode)); }
php
public function getPaginatedEntities(array $options = [], $hydrationMode = AbstractQuery::HYDRATE_OBJECT) { $options = PaginatedEntityRepositoryOptionsResolver::createAndResolve($options); $queryBuilder = $this->addPagination( $this->getQueryBuilder($options['filters'], $options['sorting']), $options['elementsPerPage'], $options['page'] ); return new Paginator($queryBuilder->getQuery()->setHydrationMode($hydrationMode)); }
[ "public", "function", "getPaginatedEntities", "(", "array", "$", "options", "=", "[", "]", ",", "$", "hydrationMode", "=", "AbstractQuery", "::", "HYDRATE_OBJECT", ")", "{", "$", "options", "=", "PaginatedEntityRepositoryOptionsResolver", "::", "createAndResolve", "(", "$", "options", ")", ";", "$", "queryBuilder", "=", "$", "this", "->", "addPagination", "(", "$", "this", "->", "getQueryBuilder", "(", "$", "options", "[", "'filters'", "]", ",", "$", "options", "[", "'sorting'", "]", ")", ",", "$", "options", "[", "'elementsPerPage'", "]", ",", "$", "options", "[", "'page'", "]", ")", ";", "return", "new", "Paginator", "(", "$", "queryBuilder", "->", "getQuery", "(", ")", "->", "setHydrationMode", "(", "$", "hydrationMode", ")", ")", ";", "}" ]
Returns a paginated list of entities. @param array $options @param integer $hydrationMode @return \Doctrine\ORM\Tools\Pagination\Paginator
[ "Returns", "a", "paginated", "list", "of", "entities", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L94-L104
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.getQueryBuilder
protected function getQueryBuilder(array $filters = [], array $sorting = []) { $queryBuilder = $this->getBaseQueryBuilder(); if (!empty($filters)) { $this->addFilters($queryBuilder, $filters); } if (empty($sorting)) { $this->addSorting($queryBuilder, $this->getDefaultSorting()); } else { $this->addSorting($queryBuilder, $sorting); } return $queryBuilder; }
php
protected function getQueryBuilder(array $filters = [], array $sorting = []) { $queryBuilder = $this->getBaseQueryBuilder(); if (!empty($filters)) { $this->addFilters($queryBuilder, $filters); } if (empty($sorting)) { $this->addSorting($queryBuilder, $this->getDefaultSorting()); } else { $this->addSorting($queryBuilder, $sorting); } return $queryBuilder; }
[ "protected", "function", "getQueryBuilder", "(", "array", "$", "filters", "=", "[", "]", ",", "array", "$", "sorting", "=", "[", "]", ")", "{", "$", "queryBuilder", "=", "$", "this", "->", "getBaseQueryBuilder", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "filters", ")", ")", "{", "$", "this", "->", "addFilters", "(", "$", "queryBuilder", ",", "$", "filters", ")", ";", "}", "if", "(", "empty", "(", "$", "sorting", ")", ")", "{", "$", "this", "->", "addSorting", "(", "$", "queryBuilder", ",", "$", "this", "->", "getDefaultSorting", "(", ")", ")", ";", "}", "else", "{", "$", "this", "->", "addSorting", "(", "$", "queryBuilder", ",", "$", "sorting", ")", ";", "}", "return", "$", "queryBuilder", ";", "}" ]
Returns a complete QueryBuilder instance for the current entity. @param array $filters @param array $sorting @return \Doctrine\ORM\QueryBuilder
[ "Returns", "a", "complete", "QueryBuilder", "instance", "for", "the", "current", "entity", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L113-L127
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.addFilters
protected function addFilters(QueryBuilder $queryBuilder, $filters = array()) { foreach ($filters as $field => $value) { $methodName = sprintf('add%sFilter', ucfirst($field)); if (method_exists($this, $methodName)) { // This field has a custom filtering method $this->$methodName($queryBuilder, $value); continue; } if (null === $value || '' === $value || (is_array($value) && 0 == count($value))) { // Skip: value is blank continue; } $field = $this->addEntityAlias($field); if (is_array($value)) { $queryBuilder->andWhere($queryBuilder->expr()->in($field, $value)); } else { $queryBuilder->andWhere($queryBuilder->expr()->eq($field, $queryBuilder->expr()->literal($value))); } } return $queryBuilder; }
php
protected function addFilters(QueryBuilder $queryBuilder, $filters = array()) { foreach ($filters as $field => $value) { $methodName = sprintf('add%sFilter', ucfirst($field)); if (method_exists($this, $methodName)) { // This field has a custom filtering method $this->$methodName($queryBuilder, $value); continue; } if (null === $value || '' === $value || (is_array($value) && 0 == count($value))) { // Skip: value is blank continue; } $field = $this->addEntityAlias($field); if (is_array($value)) { $queryBuilder->andWhere($queryBuilder->expr()->in($field, $value)); } else { $queryBuilder->andWhere($queryBuilder->expr()->eq($field, $queryBuilder->expr()->literal($value))); } } return $queryBuilder; }
[ "protected", "function", "addFilters", "(", "QueryBuilder", "$", "queryBuilder", ",", "$", "filters", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "filters", "as", "$", "field", "=>", "$", "value", ")", "{", "$", "methodName", "=", "sprintf", "(", "'add%sFilter'", ",", "ucfirst", "(", "$", "field", ")", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "methodName", ")", ")", "{", "// This field has a custom filtering method", "$", "this", "->", "$", "methodName", "(", "$", "queryBuilder", ",", "$", "value", ")", ";", "continue", ";", "}", "if", "(", "null", "===", "$", "value", "||", "''", "===", "$", "value", "||", "(", "is_array", "(", "$", "value", ")", "&&", "0", "==", "count", "(", "$", "value", ")", ")", ")", "{", "// Skip: value is blank", "continue", ";", "}", "$", "field", "=", "$", "this", "->", "addEntityAlias", "(", "$", "field", ")", ";", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "queryBuilder", "->", "andWhere", "(", "$", "queryBuilder", "->", "expr", "(", ")", "->", "in", "(", "$", "field", ",", "$", "value", ")", ")", ";", "}", "else", "{", "$", "queryBuilder", "->", "andWhere", "(", "$", "queryBuilder", "->", "expr", "(", ")", "->", "eq", "(", "$", "field", ",", "$", "queryBuilder", "->", "expr", "(", ")", "->", "literal", "(", "$", "value", ")", ")", ")", ";", "}", "}", "return", "$", "queryBuilder", ";", "}" ]
Adds filters to the QueryBuilder instance. @param \Doctrine\ORM\QueryBuilder $queryBuilder @param array $filters @return \Doctrine\ORM\QueryBuilder
[ "Adds", "filters", "to", "the", "QueryBuilder", "instance", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L136-L160
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.addSorting
protected function addSorting(QueryBuilder $queryBuilder, array $sorting = []) { foreach ($sorting as $field => $sortOrder) { if (!$this->isFieldSortable($field)) { // Skip: invalid field continue; } if (!$this->isSortOrderValid($sortOrder)) { // Skip: invalid sort order continue; } $methodName = sprintf('add%sSorting', ucfirst($field)); if (method_exists($this, $methodName)) { $this->$methodName($queryBuilder, $sortOrder); continue; } $queryBuilder->addOrderBy($this->addEntityAlias($field), strtolower($sortOrder)); } return $queryBuilder; }
php
protected function addSorting(QueryBuilder $queryBuilder, array $sorting = []) { foreach ($sorting as $field => $sortOrder) { if (!$this->isFieldSortable($field)) { // Skip: invalid field continue; } if (!$this->isSortOrderValid($sortOrder)) { // Skip: invalid sort order continue; } $methodName = sprintf('add%sSorting', ucfirst($field)); if (method_exists($this, $methodName)) { $this->$methodName($queryBuilder, $sortOrder); continue; } $queryBuilder->addOrderBy($this->addEntityAlias($field), strtolower($sortOrder)); } return $queryBuilder; }
[ "protected", "function", "addSorting", "(", "QueryBuilder", "$", "queryBuilder", ",", "array", "$", "sorting", "=", "[", "]", ")", "{", "foreach", "(", "$", "sorting", "as", "$", "field", "=>", "$", "sortOrder", ")", "{", "if", "(", "!", "$", "this", "->", "isFieldSortable", "(", "$", "field", ")", ")", "{", "// Skip: invalid field", "continue", ";", "}", "if", "(", "!", "$", "this", "->", "isSortOrderValid", "(", "$", "sortOrder", ")", ")", "{", "// Skip: invalid sort order", "continue", ";", "}", "$", "methodName", "=", "sprintf", "(", "'add%sSorting'", ",", "ucfirst", "(", "$", "field", ")", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "methodName", ")", ")", "{", "$", "this", "->", "$", "methodName", "(", "$", "queryBuilder", ",", "$", "sortOrder", ")", ";", "continue", ";", "}", "$", "queryBuilder", "->", "addOrderBy", "(", "$", "this", "->", "addEntityAlias", "(", "$", "field", ")", ",", "strtolower", "(", "$", "sortOrder", ")", ")", ";", "}", "return", "$", "queryBuilder", ";", "}" ]
Adds sorting to the specified query builder. @param \Doctrine\ORM\QueryBuilder $queryBuilder @param array $sorting @return \Doctrine\ORM\QueryBuilder
[ "Adds", "sorting", "to", "the", "specified", "query", "builder", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L169-L191
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.addPagination
protected function addPagination(QueryBuilder $queryBuilder, $elementsPerPage, $page = 1) { $elementsPerPage = (int)$elementsPerPage; $page = (int)$page; return $queryBuilder ->setMaxResults($elementsPerPage) ->setFirstResult($elementsPerPage * ($page - 1)); }
php
protected function addPagination(QueryBuilder $queryBuilder, $elementsPerPage, $page = 1) { $elementsPerPage = (int)$elementsPerPage; $page = (int)$page; return $queryBuilder ->setMaxResults($elementsPerPage) ->setFirstResult($elementsPerPage * ($page - 1)); }
[ "protected", "function", "addPagination", "(", "QueryBuilder", "$", "queryBuilder", ",", "$", "elementsPerPage", ",", "$", "page", "=", "1", ")", "{", "$", "elementsPerPage", "=", "(", "int", ")", "$", "elementsPerPage", ";", "$", "page", "=", "(", "int", ")", "$", "page", ";", "return", "$", "queryBuilder", "->", "setMaxResults", "(", "$", "elementsPerPage", ")", "->", "setFirstResult", "(", "$", "elementsPerPage", "*", "(", "$", "page", "-", "1", ")", ")", ";", "}" ]
Adds pagination to the specified query builder. @param \Doctrine\ORM\QueryBuilder $queryBuilder @param integer $elementsPerPage @param integer $page @return \Doctrine\ORM\QueryBuilder
[ "Adds", "pagination", "to", "the", "specified", "query", "builder", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L201-L209
gibilogic/crud-bundle
Entity/EntityRepository.php
EntityRepository.hasJoin
protected function hasJoin(QueryBuilder $queryBuilder, $joinString) { /* @var \Doctrine\ORM\Query\Expr\Join $joinExpression */ foreach ($queryBuilder->getDQLPart('join') as $joinsList) { foreach ($joinsList as $joinExpression) { if ($joinExpression->getJoin() == $joinString) { return true; } } } return false; }
php
protected function hasJoin(QueryBuilder $queryBuilder, $joinString) { /* @var \Doctrine\ORM\Query\Expr\Join $joinExpression */ foreach ($queryBuilder->getDQLPart('join') as $joinsList) { foreach ($joinsList as $joinExpression) { if ($joinExpression->getJoin() == $joinString) { return true; } } } return false; }
[ "protected", "function", "hasJoin", "(", "QueryBuilder", "$", "queryBuilder", ",", "$", "joinString", ")", "{", "/* @var \\Doctrine\\ORM\\Query\\Expr\\Join $joinExpression */", "foreach", "(", "$", "queryBuilder", "->", "getDQLPart", "(", "'join'", ")", "as", "$", "joinsList", ")", "{", "foreach", "(", "$", "joinsList", "as", "$", "joinExpression", ")", "{", "if", "(", "$", "joinExpression", "->", "getJoin", "(", ")", "==", "$", "joinString", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Returns TRUE if the join string is already present inside the query builder, FALSE otherwise. @param \Doctrine\ORM\QueryBuilder $queryBuilder @param string $joinString @return boolean
[ "Returns", "TRUE", "if", "the", "join", "string", "is", "already", "present", "inside", "the", "query", "builder", "FALSE", "otherwise", "." ]
train
https://github.com/gibilogic/crud-bundle/blob/847e7c7bee4016026411eb230154f24986335633/Entity/EntityRepository.php#L218-L230
2amigos/yiifoundation
widgets/JoyRide.php
JoyRide.init
public function init() { $this->assets = array( 'js' => YII_DEBUG ? 'foundation/foundation.joyride.js' : 'foundation.min.js' ); Html::addCssClass($this->htmlOptions, Enum::JOYRIDE_LIST); ArrayHelper::addValue('data-joyride', 'data-joyride', $this->htmlOptions); $this->registerClientScript(); parent::init(); }
php
public function init() { $this->assets = array( 'js' => YII_DEBUG ? 'foundation/foundation.joyride.js' : 'foundation.min.js' ); Html::addCssClass($this->htmlOptions, Enum::JOYRIDE_LIST); ArrayHelper::addValue('data-joyride', 'data-joyride', $this->htmlOptions); $this->registerClientScript(); parent::init(); }
[ "public", "function", "init", "(", ")", "{", "$", "this", "->", "assets", "=", "array", "(", "'js'", "=>", "YII_DEBUG", "?", "'foundation/foundation.joyride.js'", ":", "'foundation.min.js'", ")", ";", "Html", "::", "addCssClass", "(", "$", "this", "->", "htmlOptions", ",", "Enum", "::", "JOYRIDE_LIST", ")", ";", "ArrayHelper", "::", "addValue", "(", "'data-joyride'", ",", "'data-joyride'", ",", "$", "this", "->", "htmlOptions", ")", ";", "$", "this", "->", "registerClientScript", "(", ")", ";", "parent", "::", "init", "(", ")", ";", "}" ]
Initializes the widget
[ "Initializes", "the", "widget" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/widgets/JoyRide.php#L84-L95
2amigos/yiifoundation
widgets/JoyRide.php
JoyRide.renderStop
public function renderStop($stop) { $options = array(); $options['data-id'] = ArrayHelper::getValue($stop, 'id'); $options['data-text'] = ArrayHelper::getValue($stop, 'text'); $options['data-button'] = ArrayHelper::getValue($stop, 'button'); $options['data-class'] = ArrayHelper::getValue($stop, 'class'); $options['data-options'] = ArrayHelper::getValue($stop, 'options'); if ($options['data-options'] !== null) { $config = array(); foreach ($options['data-options'] as $key => $option) { $config[] = $key . ':' . $option; } $options['data-options'] = implode(';', $config); } $title = ArrayHelper::getValue($stop, 'title'); if (!empty($title)) { $title = "<h4>{$title}</h4>"; } $content = '<p>' . ArrayHelper::getValue($stop, 'body', '') . '</p>'; return \CHtml::tag('li', $options, $title . $content); }
php
public function renderStop($stop) { $options = array(); $options['data-id'] = ArrayHelper::getValue($stop, 'id'); $options['data-text'] = ArrayHelper::getValue($stop, 'text'); $options['data-button'] = ArrayHelper::getValue($stop, 'button'); $options['data-class'] = ArrayHelper::getValue($stop, 'class'); $options['data-options'] = ArrayHelper::getValue($stop, 'options'); if ($options['data-options'] !== null) { $config = array(); foreach ($options['data-options'] as $key => $option) { $config[] = $key . ':' . $option; } $options['data-options'] = implode(';', $config); } $title = ArrayHelper::getValue($stop, 'title'); if (!empty($title)) { $title = "<h4>{$title}</h4>"; } $content = '<p>' . ArrayHelper::getValue($stop, 'body', '') . '</p>'; return \CHtml::tag('li', $options, $title . $content); }
[ "public", "function", "renderStop", "(", "$", "stop", ")", "{", "$", "options", "=", "array", "(", ")", ";", "$", "options", "[", "'data-id'", "]", "=", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'id'", ")", ";", "$", "options", "[", "'data-text'", "]", "=", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'text'", ")", ";", "$", "options", "[", "'data-button'", "]", "=", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'button'", ")", ";", "$", "options", "[", "'data-class'", "]", "=", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'class'", ")", ";", "$", "options", "[", "'data-options'", "]", "=", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'options'", ")", ";", "if", "(", "$", "options", "[", "'data-options'", "]", "!==", "null", ")", "{", "$", "config", "=", "array", "(", ")", ";", "foreach", "(", "$", "options", "[", "'data-options'", "]", "as", "$", "key", "=>", "$", "option", ")", "{", "$", "config", "[", "]", "=", "$", "key", ".", "':'", ".", "$", "option", ";", "}", "$", "options", "[", "'data-options'", "]", "=", "implode", "(", "';'", ",", "$", "config", ")", ";", "}", "$", "title", "=", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'title'", ")", ";", "if", "(", "!", "empty", "(", "$", "title", ")", ")", "{", "$", "title", "=", "\"<h4>{$title}</h4>\"", ";", "}", "$", "content", "=", "'<p>'", ".", "ArrayHelper", "::", "getValue", "(", "$", "stop", ",", "'body'", ",", "''", ")", ".", "'</p>'", ";", "return", "\\", "CHtml", "::", "tag", "(", "'li'", ",", "$", "options", ",", "$", "title", ".", "$", "content", ")", ";", "}" ]
Renders a single stop @param array $stop the stop configuration @return string the resulting li tag
[ "Renders", "a", "single", "stop" ]
train
https://github.com/2amigos/yiifoundation/blob/49bed0d3ca1a9bac9299000e48a2661bdc8f9a29/widgets/JoyRide.php#L124-L146
fubhy/graphql-php
src/Type/Definition/Types/Scalars/IdType.php
IdType.coerceLiteral
public function coerceLiteral(Node $node) { if ($node instanceof StringValue || $node instanceof IntValue) { return $node->get('value'); } return NULL; }
php
public function coerceLiteral(Node $node) { if ($node instanceof StringValue || $node instanceof IntValue) { return $node->get('value'); } return NULL; }
[ "public", "function", "coerceLiteral", "(", "Node", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "StringValue", "||", "$", "node", "instanceof", "IntValue", ")", "{", "return", "$", "node", "->", "get", "(", "'value'", ")", ";", "}", "return", "NULL", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fubhy/graphql-php/blob/c1de2233c731ca29e5c5db4c43f3b9db36478c83/src/Type/Definition/Types/Scalars/IdType.php#L28-L35
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section/Table/Cell.php
PHPWord_Section_Table_Cell.addText
public function addText($text, $styleFont = null, $styleParagraph = null) { $text = new PHPWord_Section_Text($text, $styleFont, $styleParagraph); $this->_elementCollection[] = $text; return $text; }
php
public function addText($text, $styleFont = null, $styleParagraph = null) { $text = new PHPWord_Section_Text($text, $styleFont, $styleParagraph); $this->_elementCollection[] = $text; return $text; }
[ "public", "function", "addText", "(", "$", "text", ",", "$", "styleFont", "=", "null", ",", "$", "styleParagraph", "=", "null", ")", "{", "$", "text", "=", "new", "PHPWord_Section_Text", "(", "$", "text", ",", "$", "styleFont", ",", "$", "styleParagraph", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "text", ";", "return", "$", "text", ";", "}" ]
Add a Text Element @param string $text @param mixed $style @return PHPWord_Section_Text
[ "Add", "a", "Text", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section/Table/Cell.php#L110-L114