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
blast-project/CoreBundle
src/CodeGenerator/CodeGeneratorRegistry.php
CodeGeneratorRegistry.register
public static function register(CodeGeneratorInterface $codeGenerator) { $class = get_class($codeGenerator); if (!defined("$class::ENTITY_CLASS")) { throw new \Exception($class . ' must define a ENTITY_CLASS constant.'); } if (!defined("$class::ENTITY_FIELD")) { throw new \Exception($class . ' must define a ENTITY_FIELD constant.'); } self::$generators[$codeGenerator::ENTITY_CLASS][$codeGenerator::ENTITY_FIELD] = $codeGenerator; }
php
public static function register(CodeGeneratorInterface $codeGenerator) { $class = get_class($codeGenerator); if (!defined("$class::ENTITY_CLASS")) { throw new \Exception($class . ' must define a ENTITY_CLASS constant.'); } if (!defined("$class::ENTITY_FIELD")) { throw new \Exception($class . ' must define a ENTITY_FIELD constant.'); } self::$generators[$codeGenerator::ENTITY_CLASS][$codeGenerator::ENTITY_FIELD] = $codeGenerator; }
[ "public", "static", "function", "register", "(", "CodeGeneratorInterface", "$", "codeGenerator", ")", "{", "$", "class", "=", "get_class", "(", "$", "codeGenerator", ")", ";", "if", "(", "!", "defined", "(", "\"$class::ENTITY_CLASS\"", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "$", "class", ".", "' must define a ENTITY_CLASS constant.'", ")", ";", "}", "if", "(", "!", "defined", "(", "\"$class::ENTITY_FIELD\"", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "$", "class", ".", "' must define a ENTITY_FIELD constant.'", ")", ";", "}", "self", "::", "$", "generators", "[", "$", "codeGenerator", "::", "ENTITY_CLASS", "]", "[", "$", "codeGenerator", "::", "ENTITY_FIELD", "]", "=", "$", "codeGenerator", ";", "}" ]
Registers an entity code generator service. @param CodeGeneratorInterface $codeGenerator the entity code generator service @throws \Exception
[ "Registers", "an", "entity", "code", "generator", "service", "." ]
train
https://github.com/blast-project/CoreBundle/blob/7a0832758ca14e5bc5d65515532c1220df3930ae/src/CodeGenerator/CodeGeneratorRegistry.php#L26-L36
blast-project/CoreBundle
src/CodeGenerator/CodeGeneratorRegistry.php
CodeGeneratorRegistry.getCodeGenerator
public static function getCodeGenerator($entityClass, $entityField = 'code') { if (!isset(self::$generators[$entityClass][$entityField])) { throw new \Exception("There is no registered entity code generator for class $entityClass and field $entityField"); } return self::$generators[$entityClass][$entityField]; }
php
public static function getCodeGenerator($entityClass, $entityField = 'code') { if (!isset(self::$generators[$entityClass][$entityField])) { throw new \Exception("There is no registered entity code generator for class $entityClass and field $entityField"); } return self::$generators[$entityClass][$entityField]; }
[ "public", "static", "function", "getCodeGenerator", "(", "$", "entityClass", ",", "$", "entityField", "=", "'code'", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "generators", "[", "$", "entityClass", "]", "[", "$", "entityField", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"There is no registered entity code generator for class $entityClass and field $entityField\"", ")", ";", "}", "return", "self", "::", "$", "generators", "[", "$", "entityClass", "]", "[", "$", "entityField", "]", ";", "}" ]
Returns the last registered entity code generator service id for a given entity class and field. @param string $entityClass @param string $entityField @return CodeGeneratorInterface @throws \Exception
[ "Returns", "the", "last", "registered", "entity", "code", "generator", "service", "id", "for", "a", "given", "entity", "class", "and", "field", "." ]
train
https://github.com/blast-project/CoreBundle/blob/7a0832758ca14e5bc5d65515532c1220df3930ae/src/CodeGenerator/CodeGeneratorRegistry.php#L48-L55
blast-project/CoreBundle
src/CodeGenerator/CodeGeneratorRegistry.php
CodeGeneratorRegistry.getCodeGenerators
public static function getCodeGenerators($entityClass = null) { if ($entityClass) { if (!isset(self::$generators[$entityClass])) { throw new \Exception("There is no registered entity code generator for class $entityClass"); } return self::$generators[$entityClass]; } else { return self::$generators; } }
php
public static function getCodeGenerators($entityClass = null) { if ($entityClass) { if (!isset(self::$generators[$entityClass])) { throw new \Exception("There is no registered entity code generator for class $entityClass"); } return self::$generators[$entityClass]; } else { return self::$generators; } }
[ "public", "static", "function", "getCodeGenerators", "(", "$", "entityClass", "=", "null", ")", "{", "if", "(", "$", "entityClass", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "generators", "[", "$", "entityClass", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"There is no registered entity code generator for class $entityClass\"", ")", ";", "}", "return", "self", "::", "$", "generators", "[", "$", "entityClass", "]", ";", "}", "else", "{", "return", "self", "::", "$", "generators", ";", "}", "}" ]
Returns registred code generators for specifyed entity class. @param string $entityClass @return array
[ "Returns", "registred", "code", "generators", "for", "specifyed", "entity", "class", "." ]
train
https://github.com/blast-project/CoreBundle/blob/7a0832758ca14e5bc5d65515532c1220df3930ae/src/CodeGenerator/CodeGeneratorRegistry.php#L64-L75
BugBuster1701/banner
classes/ModuleBannerTag.php
ModuleBannerTag.getModuleData
protected function getModuleData($moduleId) { $this->module_id = $moduleId; //for RandomBlocker Session //DEBUG log_message('getModuleData Banner Modul ID:'.$moduleId,'Banner.log'); $objBannerModule = \Database::getInstance()->prepare("SELECT banner_hideempty, banner_firstview, banner_categories, banner_template, banner_redirect, banner_useragent, cssID, space, headline FROM tl_module WHERE id=? AND type=?") ->execute($moduleId, 'banner'); if ($objBannerModule->numRows == 0) { return false; } $this->banner_hideempty = $objBannerModule->banner_hideempty; $this->banner_firstview = $objBannerModule->banner_firstview; $this->banner_categories = $objBannerModule->banner_categories; $this->banner_template = $objBannerModule->banner_template; $this->banner_redirect = $objBannerModule->banner_redirect; $this->banner_useragent = $objBannerModule->banner_useragent; $this->cssID = $objBannerModule->cssID; $this->space = $objBannerModule->space; $this->headline = $objBannerModule->headline; return true; }
php
protected function getModuleData($moduleId) { $this->module_id = $moduleId; //for RandomBlocker Session //DEBUG log_message('getModuleData Banner Modul ID:'.$moduleId,'Banner.log'); $objBannerModule = \Database::getInstance()->prepare("SELECT banner_hideempty, banner_firstview, banner_categories, banner_template, banner_redirect, banner_useragent, cssID, space, headline FROM tl_module WHERE id=? AND type=?") ->execute($moduleId, 'banner'); if ($objBannerModule->numRows == 0) { return false; } $this->banner_hideempty = $objBannerModule->banner_hideempty; $this->banner_firstview = $objBannerModule->banner_firstview; $this->banner_categories = $objBannerModule->banner_categories; $this->banner_template = $objBannerModule->banner_template; $this->banner_redirect = $objBannerModule->banner_redirect; $this->banner_useragent = $objBannerModule->banner_useragent; $this->cssID = $objBannerModule->cssID; $this->space = $objBannerModule->space; $this->headline = $objBannerModule->headline; return true; }
[ "protected", "function", "getModuleData", "(", "$", "moduleId", ")", "{", "$", "this", "->", "module_id", "=", "$", "moduleId", ";", "//for RandomBlocker Session", "//DEBUG log_message('getModuleData Banner Modul ID:'.$moduleId,'Banner.log');", "$", "objBannerModule", "=", "\\", "Database", "::", "getInstance", "(", ")", "->", "prepare", "(", "\"SELECT \n banner_hideempty,\n \t banner_firstview,\n \t banner_categories,\n \t banner_template,\n \t banner_redirect,\n \t banner_useragent,\n cssID,\n space,\n headline \n FROM \n tl_module \n WHERE \n id=?\n AND\n type=?\"", ")", "->", "execute", "(", "$", "moduleId", ",", "'banner'", ")", ";", "if", "(", "$", "objBannerModule", "->", "numRows", "==", "0", ")", "{", "return", "false", ";", "}", "$", "this", "->", "banner_hideempty", "=", "$", "objBannerModule", "->", "banner_hideempty", ";", "$", "this", "->", "banner_firstview", "=", "$", "objBannerModule", "->", "banner_firstview", ";", "$", "this", "->", "banner_categories", "=", "$", "objBannerModule", "->", "banner_categories", ";", "$", "this", "->", "banner_template", "=", "$", "objBannerModule", "->", "banner_template", ";", "$", "this", "->", "banner_redirect", "=", "$", "objBannerModule", "->", "banner_redirect", ";", "$", "this", "->", "banner_useragent", "=", "$", "objBannerModule", "->", "banner_useragent", ";", "$", "this", "->", "cssID", "=", "$", "objBannerModule", "->", "cssID", ";", "$", "this", "->", "space", "=", "$", "objBannerModule", "->", "space", ";", "$", "this", "->", "headline", "=", "$", "objBannerModule", "->", "headline", ";", "return", "true", ";", "}" ]
Wrapper for backward compatibility @param integer $moduleId @return boolean
[ "Wrapper", "for", "backward", "compatibility" ]
train
https://github.com/BugBuster1701/banner/blob/3ffac36837923194ab0ebaf308c0b23a3684b005/classes/ModuleBannerTag.php#L115-L150
seeren/http
src/Uri/ServerRequestUri.php
ServerRequestUri.getPath
public final function getPath(): string { return ltrim((!$this->redirect ? parent::getPath() : $this->redirect), self::SEPARATOR); }
php
public final function getPath(): string { return ltrim((!$this->redirect ? parent::getPath() : $this->redirect), self::SEPARATOR); }
[ "public", "final", "function", "getPath", "(", ")", ":", "string", "{", "return", "ltrim", "(", "(", "!", "$", "this", "->", "redirect", "?", "parent", "::", "getPath", "(", ")", ":", "$", "this", "->", "redirect", ")", ",", "self", "::", "SEPARATOR", ")", ";", "}" ]
{@inheritDoc} @see \Seeren\Http\Uri\AbstractUri::getPath()
[ "{" ]
train
https://github.com/seeren/http/blob/b5e692e085c41fe25714d17ee90ba78eaf1923c4/src/Uri/ServerRequestUri.php#L70-L75
seeren/http
src/Uri/ServerRequestUri.php
ServerRequestUri.withPath
public final function withPath($path): UriInterface { try { $uri = parent::withPath($path); } catch (InvalidArgumentException $e) { throw $e; } if ($uri->redirect) { $uri->redirect = ""; } return $uri; }
php
public final function withPath($path): UriInterface { try { $uri = parent::withPath($path); } catch (InvalidArgumentException $e) { throw $e; } if ($uri->redirect) { $uri->redirect = ""; } return $uri; }
[ "public", "final", "function", "withPath", "(", "$", "path", ")", ":", "UriInterface", "{", "try", "{", "$", "uri", "=", "parent", "::", "withPath", "(", "$", "path", ")", ";", "}", "catch", "(", "InvalidArgumentException", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "if", "(", "$", "uri", "->", "redirect", ")", "{", "$", "uri", "->", "redirect", "=", "\"\"", ";", "}", "return", "$", "uri", ";", "}" ]
{@inheritDoc} @see \Seeren\Http\Uri\AbstractUri::withPath()
[ "{" ]
train
https://github.com/seeren/http/blob/b5e692e085c41fe25714d17ee90ba78eaf1923c4/src/Uri/ServerRequestUri.php#L81-L92
kderyabin/logger
src/Logger.php
Logger.log
public function log($level, $message, array $context = array()) { if (!$this->canLog($level)) { return; } $levelCode = $this->levelCode[$level]; $data = $this->message->process($levelCode, $level, $message, $context); foreach ($this->channels as $channel) { $channel->deliver($level, $data); } }
php
public function log($level, $message, array $context = array()) { if (!$this->canLog($level)) { return; } $levelCode = $this->levelCode[$level]; $data = $this->message->process($levelCode, $level, $message, $context); foreach ($this->channels as $channel) { $channel->deliver($level, $data); } }
[ "public", "function", "log", "(", "$", "level", ",", "$", "message", ",", "array", "$", "context", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "canLog", "(", "$", "level", ")", ")", "{", "return", ";", "}", "$", "levelCode", "=", "$", "this", "->", "levelCode", "[", "$", "level", "]", ";", "$", "data", "=", "$", "this", "->", "message", "->", "process", "(", "$", "levelCode", ",", "$", "level", ",", "$", "message", ",", "$", "context", ")", ";", "foreach", "(", "$", "this", "->", "channels", "as", "$", "channel", ")", "{", "$", "channel", "->", "deliver", "(", "$", "level", ",", "$", "data", ")", ";", "}", "}" ]
Logs with an arbitrary level. @param mixed $level @param string $message @param array $context @return void
[ "Logs", "with", "an", "arbitrary", "level", "." ]
train
https://github.com/kderyabin/logger/blob/683890192b37fe9d36611972e12c2994669f5b85/src/Logger.php#L64-L74
yosmanyga/resource
src/Yosmanyga/Resource/Normalizer/DirectoryNormalizer.php
DirectoryNormalizer.supports
public function supports($data, Resource $resource) { if (!$resource->hasMetadata('dir') || !$resource->hasMetadata('type')) { return false; } return parent::supports($data, $this->convertResource($resource)); }
php
public function supports($data, Resource $resource) { if (!$resource->hasMetadata('dir') || !$resource->hasMetadata('type')) { return false; } return parent::supports($data, $this->convertResource($resource)); }
[ "public", "function", "supports", "(", "$", "data", ",", "Resource", "$", "resource", ")", "{", "if", "(", "!", "$", "resource", "->", "hasMetadata", "(", "'dir'", ")", "||", "!", "$", "resource", "->", "hasMetadata", "(", "'type'", ")", ")", "{", "return", "false", ";", "}", "return", "parent", "::", "supports", "(", "$", "data", ",", "$", "this", "->", "convertResource", "(", "$", "resource", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Normalizer/DirectoryNormalizer.php#L12-L19
yosmanyga/resource
src/Yosmanyga/Resource/Normalizer/DirectoryNormalizer.php
DirectoryNormalizer.normalize
public function normalize($data, Resource $resource) { return parent::normalize($data, $this->convertResource($resource)); }
php
public function normalize($data, Resource $resource) { return parent::normalize($data, $this->convertResource($resource)); }
[ "public", "function", "normalize", "(", "$", "data", ",", "Resource", "$", "resource", ")", "{", "return", "parent", "::", "normalize", "(", "$", "data", ",", "$", "this", "->", "convertResource", "(", "$", "resource", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosmanyga/resource/blob/a8b505c355920a908917a0484f764ddfa63205fa/src/Yosmanyga/Resource/Normalizer/DirectoryNormalizer.php#L24-L27
tjbp/laravel-verify-emails
src/Auth/VerifyEmails/DatabaseTokenRepository.php
DatabaseTokenRepository.create
public function create(CanVerifyEmailContract $user) { $email = $user->getEmailToVerify(); $this->deleteExisting($user); // We will create a new, random token for the user so that we can e-mail them // a safe link to verify their email address. Then we will insert a record in // the database so that we can verify the token later. $token = $this->createNewToken(); $this->getTable()->insert($this->getPayload($email, $token)); return $token; }
php
public function create(CanVerifyEmailContract $user) { $email = $user->getEmailToVerify(); $this->deleteExisting($user); // We will create a new, random token for the user so that we can e-mail them // a safe link to verify their email address. Then we will insert a record in // the database so that we can verify the token later. $token = $this->createNewToken(); $this->getTable()->insert($this->getPayload($email, $token)); return $token; }
[ "public", "function", "create", "(", "CanVerifyEmailContract", "$", "user", ")", "{", "$", "email", "=", "$", "user", "->", "getEmailToVerify", "(", ")", ";", "$", "this", "->", "deleteExisting", "(", "$", "user", ")", ";", "// We will create a new, random token for the user so that we can e-mail them", "// a safe link to verify their email address. Then we will insert a record in", "// the database so that we can verify the token later.", "$", "token", "=", "$", "this", "->", "createNewToken", "(", ")", ";", "$", "this", "->", "getTable", "(", ")", "->", "insert", "(", "$", "this", "->", "getPayload", "(", "$", "email", ",", "$", "token", ")", ")", ";", "return", "$", "token", ";", "}" ]
Create a new token record. @param \LaravelVerifyEmails\Contracts\Auth\CanVerifyEmail $user @return string
[ "Create", "a", "new", "token", "record", "." ]
train
https://github.com/tjbp/laravel-verify-emails/blob/1e2ac10a696c10f2fdf0d7de6c3388d549bc07c6/src/Auth/VerifyEmails/DatabaseTokenRepository.php#L63-L77
tjbp/laravel-verify-emails
src/Auth/VerifyEmails/DatabaseTokenRepository.php
DatabaseTokenRepository.exists
public function exists(CanVerifyEmailContract $user, $token) { $email = $user->getEmailToVerify(); $token = (array) $this->getTable()->where('email', $email)->where('token', $token)->first(); return $token && ! $this->tokenExpired($token); }
php
public function exists(CanVerifyEmailContract $user, $token) { $email = $user->getEmailToVerify(); $token = (array) $this->getTable()->where('email', $email)->where('token', $token)->first(); return $token && ! $this->tokenExpired($token); }
[ "public", "function", "exists", "(", "CanVerifyEmailContract", "$", "user", ",", "$", "token", ")", "{", "$", "email", "=", "$", "user", "->", "getEmailToVerify", "(", ")", ";", "$", "token", "=", "(", "array", ")", "$", "this", "->", "getTable", "(", ")", "->", "where", "(", "'email'", ",", "$", "email", ")", "->", "where", "(", "'token'", ",", "$", "token", ")", "->", "first", "(", ")", ";", "return", "$", "token", "&&", "!", "$", "this", "->", "tokenExpired", "(", "$", "token", ")", ";", "}" ]
Determine if a token record exists and is valid. @param \LaravelVerifyEmails\Contracts\Auth\CanVerifyEmail $user @param string $token @return bool
[ "Determine", "if", "a", "token", "record", "exists", "and", "is", "valid", "." ]
train
https://github.com/tjbp/laravel-verify-emails/blob/1e2ac10a696c10f2fdf0d7de6c3388d549bc07c6/src/Auth/VerifyEmails/DatabaseTokenRepository.php#L109-L116
Wonail/wocenter
core/BaseWc.php
BaseWc.dump
public static function dump($arr, $echo = true, $label = null, $strict = true) { ArrayHelper::dump($arr, $echo, $label, $strict); }
php
public static function dump($arr, $echo = true, $label = null, $strict = true) { ArrayHelper::dump($arr, $echo, $label, $strict); }
[ "public", "static", "function", "dump", "(", "$", "arr", ",", "$", "echo", "=", "true", ",", "$", "label", "=", "null", ",", "$", "strict", "=", "true", ")", "{", "ArrayHelper", "::", "dump", "(", "$", "arr", ",", "$", "echo", ",", "$", "label", ",", "$", "strict", ")", ";", "}" ]
浏览器友好的变量输出 @param mixed $arr 变量 @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串 @param string $label 标签 默认为空 @param boolean $strict 是否严谨 默认为true @return void|string
[ "浏览器友好的变量输出" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/core/BaseWc.php#L61-L64
Wonail/wocenter
core/BaseWc.php
BaseWc.getOrSet
public static function getOrSet($key, $callable, $duration = null, $dependency = null, $cache = 'cache') { /** @var \yii\caching\Cache $component */ $component = Yii::$app->get($cache); if ($duration === false) { $component->delete($key); } return $component->getOrSet($key, $callable, $duration, $dependency); }
php
public static function getOrSet($key, $callable, $duration = null, $dependency = null, $cache = 'cache') { /** @var \yii\caching\Cache $component */ $component = Yii::$app->get($cache); if ($duration === false) { $component->delete($key); } return $component->getOrSet($key, $callable, $duration, $dependency); }
[ "public", "static", "function", "getOrSet", "(", "$", "key", ",", "$", "callable", ",", "$", "duration", "=", "null", ",", "$", "dependency", "=", "null", ",", "$", "cache", "=", "'cache'", ")", "{", "/** @var \\yii\\caching\\Cache $component */", "$", "component", "=", "Yii", "::", "$", "app", "->", "get", "(", "$", "cache", ")", ";", "if", "(", "$", "duration", "===", "false", ")", "{", "$", "component", "->", "delete", "(", "$", "key", ")", ";", "}", "return", "$", "component", "->", "getOrSet", "(", "$", "key", ",", "$", "callable", ",", "$", "duration", ",", "$", "dependency", ")", ";", "}" ]
扩展[[Yii::$app->getCache()->getOrSet()]]该方法,当`$duration`为`false`时先删除缓存再缓存执行数据结果 @param mixed $key a key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key. @param callable|Closure $callable the callable or closure that will be used to generate a value to be cached. In case $callable returns `false`, the value will not be cached. @param int $duration default duration in seconds before the cache will expire. If not set, [[defaultDuration]] value will be used. @param Dependency $dependency dependency of the cached item. If the dependency changes, the corresponding value in the cache will be invalidated when it is fetched via [[get()]]. This parameter is ignored if [[serializer]] is `false`. @param string $cache cache component @return mixed result of $callable execution
[ "扩展", "[[", "Yii", "::", "$app", "-", ">", "getCache", "()", "-", ">", "getOrSet", "()", "]]", "该方法,当", "$duration", "为", "false", "时先删除缓存再缓存执行数据结果" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/core/BaseWc.php#L155-L164
Wonail/wocenter
core/BaseWc.php
BaseWc.transaction
public static function transaction(callable $callback, $isolationLevel = null) { self::setThrowException(); $result = Yii::$app->getDb()->transaction($callback, $isolationLevel); self::setThrowException(false); return $result; }
php
public static function transaction(callable $callback, $isolationLevel = null) { self::setThrowException(); $result = Yii::$app->getDb()->transaction($callback, $isolationLevel); self::setThrowException(false); return $result; }
[ "public", "static", "function", "transaction", "(", "callable", "$", "callback", ",", "$", "isolationLevel", "=", "null", ")", "{", "self", "::", "setThrowException", "(", ")", ";", "$", "result", "=", "Yii", "::", "$", "app", "->", "getDb", "(", ")", "->", "transaction", "(", "$", "callback", ",", "$", "isolationLevel", ")", ";", "self", "::", "setThrowException", "(", "false", ")", ";", "return", "$", "result", ";", "}" ]
支持抛出模型类(Model|ActiveRecord)验证错误的事务操作 事务操作默认只抛出异常错误,如果需要抛出模型类产生的验证错误,`$callback`函数内需要被获取到的模型类必须使用 [[traits\ExtendModelTrait()]]用以支持该方法 @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter. @param string|null $isolationLevel The isolation level to use for this transaction. @throws \Exception @return mixed result of callback function
[ "支持抛出模型类(Model|ActiveRecord)验证错误的事务操作" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/core/BaseWc.php#L178-L185
digiaonline/json-helpers
src/JsonEncoder.php
JsonEncoder.encode
public static function encode($data, int $options = 0, int $depth = 512): string { $json = json_encode($data, $options, $depth); $jsonLastError = json_last_error(); if ($jsonLastError !== JSON_ERROR_NONE) { throw new \InvalidArgumentException('Failed to encode JSON: ' . json_last_error_msg(), $jsonLastError); } return $json; }
php
public static function encode($data, int $options = 0, int $depth = 512): string { $json = json_encode($data, $options, $depth); $jsonLastError = json_last_error(); if ($jsonLastError !== JSON_ERROR_NONE) { throw new \InvalidArgumentException('Failed to encode JSON: ' . json_last_error_msg(), $jsonLastError); } return $json; }
[ "public", "static", "function", "encode", "(", "$", "data", ",", "int", "$", "options", "=", "0", ",", "int", "$", "depth", "=", "512", ")", ":", "string", "{", "$", "json", "=", "json_encode", "(", "$", "data", ",", "$", "options", ",", "$", "depth", ")", ";", "$", "jsonLastError", "=", "json_last_error", "(", ")", ";", "if", "(", "$", "jsonLastError", "!==", "JSON_ERROR_NONE", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Failed to encode JSON: '", ".", "json_last_error_msg", "(", ")", ",", "$", "jsonLastError", ")", ";", "}", "return", "$", "json", ";", "}" ]
Encodes the specified data as JSON. In contrast to just using json_encode(), this method throws an exception if encoding fails. @param mixed $data the data to encode @param int $options @param int $depth @return string the encoded JSON @throws \InvalidArgumentException
[ "Encodes", "the", "specified", "data", "as", "JSON", ".", "In", "contrast", "to", "just", "using", "json_encode", "()", "this", "method", "throws", "an", "exception", "if", "encoding", "fails", "." ]
train
https://github.com/digiaonline/json-helpers/blob/596dfca3fb85fba026cc0a498fbcefbda6377a15/src/JsonEncoder.php#L24-L34
EcomDev/magento-psr6-bridge
src/Model/CacheItem.php
CacheItem.expiresAt
public function expiresAt($expiration) { $now = new \DateTime('now', $expiration->getTimezone()); $this->cacheLifetime = $expiration->getTimestamp() - $now->getTimestamp(); return $this; }
php
public function expiresAt($expiration) { $now = new \DateTime('now', $expiration->getTimezone()); $this->cacheLifetime = $expiration->getTimestamp() - $now->getTimestamp(); return $this; }
[ "public", "function", "expiresAt", "(", "$", "expiration", ")", "{", "$", "now", "=", "new", "\\", "DateTime", "(", "'now'", ",", "$", "expiration", "->", "getTimezone", "(", ")", ")", ";", "$", "this", "->", "cacheLifetime", "=", "$", "expiration", "->", "getTimestamp", "(", ")", "-", "$", "now", "->", "getTimestamp", "(", ")", ";", "return", "$", "this", ";", "}" ]
Sets the expiration time for this cache item. @param \DateTimeInterface $expiration The point in time after which the item MUST be considered expired. If null is passed explicitly, a default value MAY be used. If none is set, the value should be stored permanently or for as long as the implementation allows. @return static The called object.
[ "Sets", "the", "expiration", "time", "for", "this", "cache", "item", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItem.php#L155-L160
EcomDev/magento-psr6-bridge
src/Model/CacheItem.php
CacheItem.expiresAfter
public function expiresAfter($time) { if ($time instanceof \DateInterval) { $now = new \DateTime(); $after = clone $now; $after->add($time); $this->cacheLifetime = $after->getTimestamp() - $now->getTimestamp(); } elseif (is_int($time) || $time === null) { $this->cacheLifetime = $time; } return $this; }
php
public function expiresAfter($time) { if ($time instanceof \DateInterval) { $now = new \DateTime(); $after = clone $now; $after->add($time); $this->cacheLifetime = $after->getTimestamp() - $now->getTimestamp(); } elseif (is_int($time) || $time === null) { $this->cacheLifetime = $time; } return $this; }
[ "public", "function", "expiresAfter", "(", "$", "time", ")", "{", "if", "(", "$", "time", "instanceof", "\\", "DateInterval", ")", "{", "$", "now", "=", "new", "\\", "DateTime", "(", ")", ";", "$", "after", "=", "clone", "$", "now", ";", "$", "after", "->", "add", "(", "$", "time", ")", ";", "$", "this", "->", "cacheLifetime", "=", "$", "after", "->", "getTimestamp", "(", ")", "-", "$", "now", "->", "getTimestamp", "(", ")", ";", "}", "elseif", "(", "is_int", "(", "$", "time", ")", "||", "$", "time", "===", "null", ")", "{", "$", "this", "->", "cacheLifetime", "=", "$", "time", ";", "}", "return", "$", "this", ";", "}" ]
Sets the expiration time for this cache item. @param int|\DateInterval $time The period of time from the present after which the item MUST be considered expired. An integer parameter is understood to be the time in seconds until expiration. If null is passed explicitly, a default value MAY be used. If none is set, the value should be stored permanently or for as long as the implementation allows. @return static The called object.
[ "Sets", "the", "expiration", "time", "for", "this", "cache", "item", "." ]
train
https://github.com/EcomDev/magento-psr6-bridge/blob/405c5b455f239fe8dc1b710df5fe9438f09d4715/src/Model/CacheItem.php#L176-L188
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.set
public function set($csdl) { if ($csdl === false) { $this->_csdl = false; } else { if (! is_string($csdl)) { throw new DataSift_Exception_InvalidData('Definitions must be strings.'); } // Trim the incoming string $csdl = trim($csdl); // If the string has changed, reset the hash if ($this->_csdl != $csdl) { $this->clearHash(); } $this->_csdl = $csdl; } }
php
public function set($csdl) { if ($csdl === false) { $this->_csdl = false; } else { if (! is_string($csdl)) { throw new DataSift_Exception_InvalidData('Definitions must be strings.'); } // Trim the incoming string $csdl = trim($csdl); // If the string has changed, reset the hash if ($this->_csdl != $csdl) { $this->clearHash(); } $this->_csdl = $csdl; } }
[ "public", "function", "set", "(", "$", "csdl", ")", "{", "if", "(", "$", "csdl", "===", "false", ")", "{", "$", "this", "->", "_csdl", "=", "false", ";", "}", "else", "{", "if", "(", "!", "is_string", "(", "$", "csdl", ")", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Definitions must be strings.'", ")", ";", "}", "// Trim the incoming string", "$", "csdl", "=", "trim", "(", "$", "csdl", ")", ";", "// If the string has changed, reset the hash", "if", "(", "$", "this", "->", "_csdl", "!=", "$", "csdl", ")", "{", "$", "this", "->", "clearHash", "(", ")", ";", "}", "$", "this", "->", "_csdl", "=", "$", "csdl", ";", "}", "}" ]
Sets the definition string. @param string $csdl The new definition string. @return void @throws DataSift_Exception_InvalidData
[ "Sets", "the", "definition", "string", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L101-L120
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.clearHash
protected function clearHash() { if ($this->_csdl === false) { throw new DataSift_Exception_InvalidData('Cannot clear the hash of a hash-only definition object'); } $this->_hash = false; $this->_created_at = false; $this->_total_dpu = false; }
php
protected function clearHash() { if ($this->_csdl === false) { throw new DataSift_Exception_InvalidData('Cannot clear the hash of a hash-only definition object'); } $this->_hash = false; $this->_created_at = false; $this->_total_dpu = false; }
[ "protected", "function", "clearHash", "(", ")", "{", "if", "(", "$", "this", "->", "_csdl", "===", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot clear the hash of a hash-only definition object'", ")", ";", "}", "$", "this", "->", "_hash", "=", "false", ";", "$", "this", "->", "_created_at", "=", "false", ";", "$", "this", "->", "_total_dpu", "=", "false", ";", "}" ]
Reset the hash to false. The effect of this is to mark the definition as requiring compilation. Also resets other variables that depend on the CSDL. @return void
[ "Reset", "the", "hash", "to", "false", ".", "The", "effect", "of", "this", "is", "to", "mark", "the", "definition", "as", "requiring", "compilation", ".", "Also", "resets", "other", "variables", "that", "depend", "on", "the", "CSDL", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L146-L154
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.getCreatedAt
public function getCreatedAt() { if ($this->_csdl === false) { throw new DataSift_Exception_InvalidData('Created at date not available'); } if ($this->_created_at === false) { // Catch any compilation errors so they don't pass up to the caller try { $this->validate(); } catch (DataSift_Exception_CompileFailed $e) { } } return $this->_created_at; }
php
public function getCreatedAt() { if ($this->_csdl === false) { throw new DataSift_Exception_InvalidData('Created at date not available'); } if ($this->_created_at === false) { // Catch any compilation errors so they don't pass up to the caller try { $this->validate(); } catch (DataSift_Exception_CompileFailed $e) { } } return $this->_created_at; }
[ "public", "function", "getCreatedAt", "(", ")", "{", "if", "(", "$", "this", "->", "_csdl", "===", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Created at date not available'", ")", ";", "}", "if", "(", "$", "this", "->", "_created_at", "===", "false", ")", "{", "// Catch any compilation errors so they don't pass up to the caller", "try", "{", "$", "this", "->", "validate", "(", ")", ";", "}", "catch", "(", "DataSift_Exception_CompileFailed", "$", "e", ")", "{", "}", "}", "return", "$", "this", "->", "_created_at", ";", "}" ]
Returns the date when the stream was first created. If the created at date has not yet been obtained it validates the definition first. @return int The date as a unix timestamp. @throws DataSift_Exception_APIError @throws DataSift_Exception_RateLimitExceeded @throws DataSift_Exception_InvalidData
[ "Returns", "the", "date", "when", "the", "stream", "was", "first", "created", ".", "If", "the", "created", "at", "date", "has", "not", "yet", "been", "obtained", "it", "validates", "the", "definition", "first", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L165-L178
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.getTotalDPU
public function getTotalDPU() { if ($this->_csdl === false) { throw new DataSift_Exception_InvalidData('Total DPU not available'); } if ($this->_total_dpu === false) { // Catch any compilation errors so they don't pass up to the caller try { $this->validate(); } catch (DataSift_Exception_CompileFailed $e) { } } return $this->_total_dpu; }
php
public function getTotalDPU() { if ($this->_csdl === false) { throw new DataSift_Exception_InvalidData('Total DPU not available'); } if ($this->_total_dpu === false) { // Catch any compilation errors so they don't pass up to the caller try { $this->validate(); } catch (DataSift_Exception_CompileFailed $e) { } } return $this->_total_dpu; }
[ "public", "function", "getTotalDPU", "(", ")", "{", "if", "(", "$", "this", "->", "_csdl", "===", "false", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Total DPU not available'", ")", ";", "}", "if", "(", "$", "this", "->", "_total_dpu", "===", "false", ")", "{", "// Catch any compilation errors so they don't pass up to the caller", "try", "{", "$", "this", "->", "validate", "(", ")", ";", "}", "catch", "(", "DataSift_Exception_CompileFailed", "$", "e", ")", "{", "}", "}", "return", "$", "this", "->", "_total_dpu", ";", "}" ]
Returns the total DPU of the stream. If the DPU has not yet been obtained it validates the definition first. @return int The total DPU. @throws DataSift_Exception_APIError @throws DataSift_Exception_RateLimitExceeded @throws DataSift_Exception_InvalidData
[ "Returns", "the", "total", "DPU", "of", "the", "stream", ".", "If", "the", "DPU", "has", "not", "yet", "been", "obtained", "it", "validates", "the", "definition", "first", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L189-L202
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.compile
public function compile() { if (strlen($this->_csdl) == 0) { throw new DataSift_Exception_InvalidData('Cannot compile an empty definition.'); } try { $res = $this->_user->post('compile', array('csdl' => $this->_csdl)); if (isset($res['hash'])) { $this->_hash = $res['hash']; } else { throw new DataSift_Exception_CompileFailed('Compiled successfully but no hash in the response'); } if (isset($res['created_at'])) { $this->_created_at = strtotime($res['created_at']); } else { throw new DataSift_Exception_CompileFailed('Compiled successfully but no created_at in the response'); } if (isset($res['dpu'])) { $this->_total_dpu = $res['dpu']; } else { throw new DataSift_Exception_CompileFailed('Compiled successfully but no DPU in the response'); } } catch (DataSift_Exception_APIError $e) { // Reset the hash $this->clearHash(); switch ($e->getCode()) { case 400: // Compilation failed, we should have an error message throw new DataSift_Exception_CompileFailed($e->getMessage()); break; default: throw new DataSift_Exception_CompileFailed( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
php
public function compile() { if (strlen($this->_csdl) == 0) { throw new DataSift_Exception_InvalidData('Cannot compile an empty definition.'); } try { $res = $this->_user->post('compile', array('csdl' => $this->_csdl)); if (isset($res['hash'])) { $this->_hash = $res['hash']; } else { throw new DataSift_Exception_CompileFailed('Compiled successfully but no hash in the response'); } if (isset($res['created_at'])) { $this->_created_at = strtotime($res['created_at']); } else { throw new DataSift_Exception_CompileFailed('Compiled successfully but no created_at in the response'); } if (isset($res['dpu'])) { $this->_total_dpu = $res['dpu']; } else { throw new DataSift_Exception_CompileFailed('Compiled successfully but no DPU in the response'); } } catch (DataSift_Exception_APIError $e) { // Reset the hash $this->clearHash(); switch ($e->getCode()) { case 400: // Compilation failed, we should have an error message throw new DataSift_Exception_CompileFailed($e->getMessage()); break; default: throw new DataSift_Exception_CompileFailed( 'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']' ); } } }
[ "public", "function", "compile", "(", ")", "{", "if", "(", "strlen", "(", "$", "this", "->", "_csdl", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot compile an empty definition.'", ")", ";", "}", "try", "{", "$", "res", "=", "$", "this", "->", "_user", "->", "post", "(", "'compile'", ",", "array", "(", "'csdl'", "=>", "$", "this", "->", "_csdl", ")", ")", ";", "if", "(", "isset", "(", "$", "res", "[", "'hash'", "]", ")", ")", "{", "$", "this", "->", "_hash", "=", "$", "res", "[", "'hash'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_CompileFailed", "(", "'Compiled successfully but no hash in the response'", ")", ";", "}", "if", "(", "isset", "(", "$", "res", "[", "'created_at'", "]", ")", ")", "{", "$", "this", "->", "_created_at", "=", "strtotime", "(", "$", "res", "[", "'created_at'", "]", ")", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_CompileFailed", "(", "'Compiled successfully but no created_at in the response'", ")", ";", "}", "if", "(", "isset", "(", "$", "res", "[", "'dpu'", "]", ")", ")", "{", "$", "this", "->", "_total_dpu", "=", "$", "res", "[", "'dpu'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_CompileFailed", "(", "'Compiled successfully but no DPU in the response'", ")", ";", "}", "}", "catch", "(", "DataSift_Exception_APIError", "$", "e", ")", "{", "// Reset the hash", "$", "this", "->", "clearHash", "(", ")", ";", "switch", "(", "$", "e", "->", "getCode", "(", ")", ")", "{", "case", "400", ":", "// Compilation failed, we should have an error message", "throw", "new", "DataSift_Exception_CompileFailed", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "break", ";", "default", ":", "throw", "new", "DataSift_Exception_CompileFailed", "(", "'Unexpected APIError code: '", ".", "$", "e", "->", "getCode", "(", ")", ".", "' ['", ".", "$", "e", "->", "getMessage", "(", ")", ".", "']'", ")", ";", "}", "}", "}" ]
Call the DataSift API to compile this defintion. On success it will store the returned hash. @return void @throws DataSift_Exception_APIError @throws DataSift_Exception_RateLimitExceeded @throws DataSift_Exception_InvalidData @throws DataSift_Exception_CompileFailed
[ "Call", "the", "DataSift", "API", "to", "compile", "this", "defintion", ".", "On", "success", "it", "will", "store", "the", "returned", "hash", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L214-L254
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.getDPUBreakdown
public function getDPUBreakdown() { $retval = false; if (strlen(trim($this->_csdl)) == 0) { throw new DataSift_Exception_InvalidData('Cannot get the DPU for an empty definition.'); } $retval = $this->_user->post('dpu', array('hash' => $this->getHash())); $this->_total_dpu = $retval['dpu']; return $retval; }
php
public function getDPUBreakdown() { $retval = false; if (strlen(trim($this->_csdl)) == 0) { throw new DataSift_Exception_InvalidData('Cannot get the DPU for an empty definition.'); } $retval = $this->_user->post('dpu', array('hash' => $this->getHash())); $this->_total_dpu = $retval['dpu']; return $retval; }
[ "public", "function", "getDPUBreakdown", "(", ")", "{", "$", "retval", "=", "false", ";", "if", "(", "strlen", "(", "trim", "(", "$", "this", "->", "_csdl", ")", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot get the DPU for an empty definition.'", ")", ";", "}", "$", "retval", "=", "$", "this", "->", "_user", "->", "post", "(", "'dpu'", ",", "array", "(", "'hash'", "=>", "$", "this", "->", "getHash", "(", ")", ")", ")", ";", "$", "this", "->", "_total_dpu", "=", "$", "retval", "[", "'dpu'", "]", ";", "return", "$", "retval", ";", "}" ]
Call the DataSift API to get the DPU for this definition. Returns an array containing... dpu => The breakdown of running the rule total => The total dpu of the rule @return array @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_CompileError
[ "Call", "the", "DataSift", "API", "to", "get", "the", "DPU", "for", "this", "definition", ".", "Returns", "an", "array", "containing", "...", "dpu", "=", ">", "The", "breakdown", "of", "running", "the", "rule", "total", "=", ">", "The", "total", "dpu", "of", "the", "rule" ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L319-L330
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.getBuffered
public function getBuffered($count = false, $from_id = false) { $retval = false; if (strlen(trim($this->_csdl)) == 0) { throw new DataSift_Exception_InvalidData('Cannot get buffered interactions for an empty definition.'); } $params = array('hash' => $this->getHash()); if ($count !== false) { $params['count'] = $count; } if ($from_id !== false) { $params['interaction_id'] = $from_id; } $retval = $this->_user->post('stream', $params); if (isset($retval['stream'])) { $retval = $retval['stream']; } else { throw new DataSift_Exception_APIError('No data in the response'); } return $retval; }
php
public function getBuffered($count = false, $from_id = false) { $retval = false; if (strlen(trim($this->_csdl)) == 0) { throw new DataSift_Exception_InvalidData('Cannot get buffered interactions for an empty definition.'); } $params = array('hash' => $this->getHash()); if ($count !== false) { $params['count'] = $count; } if ($from_id !== false) { $params['interaction_id'] = $from_id; } $retval = $this->_user->post('stream', $params); if (isset($retval['stream'])) { $retval = $retval['stream']; } else { throw new DataSift_Exception_APIError('No data in the response'); } return $retval; }
[ "public", "function", "getBuffered", "(", "$", "count", "=", "false", ",", "$", "from_id", "=", "false", ")", "{", "$", "retval", "=", "false", ";", "if", "(", "strlen", "(", "trim", "(", "$", "this", "->", "_csdl", ")", ")", "==", "0", ")", "{", "throw", "new", "DataSift_Exception_InvalidData", "(", "'Cannot get buffered interactions for an empty definition.'", ")", ";", "}", "$", "params", "=", "array", "(", "'hash'", "=>", "$", "this", "->", "getHash", "(", ")", ")", ";", "if", "(", "$", "count", "!==", "false", ")", "{", "$", "params", "[", "'count'", "]", "=", "$", "count", ";", "}", "if", "(", "$", "from_id", "!==", "false", ")", "{", "$", "params", "[", "'interaction_id'", "]", "=", "$", "from_id", ";", "}", "$", "retval", "=", "$", "this", "->", "_user", "->", "post", "(", "'stream'", ",", "$", "params", ")", ";", "if", "(", "isset", "(", "$", "retval", "[", "'stream'", "]", ")", ")", "{", "$", "retval", "=", "$", "retval", "[", "'stream'", "]", ";", "}", "else", "{", "throw", "new", "DataSift_Exception_APIError", "(", "'No data in the response'", ")", ";", "}", "return", "$", "retval", ";", "}" ]
Call the DataSift API to get buffered interactions. @param int $count Optional number of interactions to return (max 200). @param int $from_id Optional start ID. @return array @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_CompileError
[ "Call", "the", "DataSift", "API", "to", "get", "buffered", "interactions", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L343-L368
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.createHistoric
public function createHistoric($start, $end, $sources, $name, $sample = DataSift_Historic::DEFAULT_SAMPLE) { return new DataSift_Historic($this->_user, $this->getHash(), $start, $end, $sources, $name, $sample); }
php
public function createHistoric($start, $end, $sources, $name, $sample = DataSift_Historic::DEFAULT_SAMPLE) { return new DataSift_Historic($this->_user, $this->getHash(), $start, $end, $sources, $name, $sample); }
[ "public", "function", "createHistoric", "(", "$", "start", ",", "$", "end", ",", "$", "sources", ",", "$", "name", ",", "$", "sample", "=", "DataSift_Historic", "::", "DEFAULT_SAMPLE", ")", "{", "return", "new", "DataSift_Historic", "(", "$", "this", "->", "_user", ",", "$", "this", "->", "getHash", "(", ")", ",", "$", "start", ",", "$", "end", ",", "$", "sources", ",", "$", "name", ",", "$", "sample", ")", ";", "}" ]
Create a historic based on this CSDL. @param int $start The timestamp from which to start the query. @param int $end The timestamp at which to end the query. @param array $sources An array of sources required. @param string $name An optional name for this historic. @param float $sample Sample size (10 or 100) @return DataSift_Historic @throws DataSift_Exception_InvalidData @throws DataSift_Exception_APIError @throws DataSift_Exception_CompileError
[ "Create", "a", "historic", "based", "on", "this", "CSDL", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L384-L387
datasift/datasift-php
lib/DataSift/Definition.php
DataSift_Definition.getConsumer
public function getConsumer($type, $eventHandler) { return DataSift_StreamConsumer::factory($this->_user, $type, $this, $eventHandler); }
php
public function getConsumer($type, $eventHandler) { return DataSift_StreamConsumer::factory($this->_user, $type, $this, $eventHandler); }
[ "public", "function", "getConsumer", "(", "$", "type", ",", "$", "eventHandler", ")", "{", "return", "DataSift_StreamConsumer", "::", "factory", "(", "$", "this", "->", "_user", ",", "$", "type", ",", "$", "this", ",", "$", "eventHandler", ")", ";", "}" ]
Returns a DataSift_StreamConsumer-derived object for this definition, for the given type. @param string $type The consumer type for which to construct a consumer. @param DataSift_IStreamConsumerEventHandler $eventHandler An instance of DataSift_IStreamConsumerEventHandler @return DataSift_StreamConsumer The consumer object. @throws DataSift_Exception_InvalidData @see DataSift_StreamConsumer
[ "Returns", "a", "DataSift_StreamConsumer", "-", "derived", "object", "for", "this", "definition", "for", "the", "given", "type", "." ]
train
https://github.com/datasift/datasift-php/blob/35282461ad3e54880e5940bb5afce26c75dc4bb9/lib/DataSift/Definition.php#L400-L403
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareCreateTableStatement
public function prepareCreateTableStatement(TypeInterface $type) { $result = []; $result[] = 'CREATE TABLE IF NOT EXISTS ' . $this->getConnection()->escapeTableName($type->getName()) . ' ('; $generaterd_field_indexes = []; foreach ($type->getAllFields() as $field) { if ($field instanceof ScalarField) { $result[] = ' ' . $this->prepareFieldStatement($field) . ','; } if ($field instanceof JsonFieldInterface) { foreach ($field->getValueExtractors() as $value_extractor) { $result[] = ' ' . $this->prepareGeneratedFieldStatement($field, $value_extractor) . ','; if ($value_extractor->getAddIndex()) { $generaterd_field_indexes[] = new Index($value_extractor->getFieldName()); } } } } $indexes = $type->getAllIndexes(); if (!empty($generaterd_field_indexes)) { $indexes = array_merge($indexes, $generaterd_field_indexes); } foreach ($indexes as $index) { $result[] = ' ' . $this->prepareIndexStatement($index) . ','; } $last_line = count($result) - 1; $result[$last_line] = rtrim($result[$last_line], ','); $result[] = ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'; return implode("\n", $result); }
php
public function prepareCreateTableStatement(TypeInterface $type) { $result = []; $result[] = 'CREATE TABLE IF NOT EXISTS ' . $this->getConnection()->escapeTableName($type->getName()) . ' ('; $generaterd_field_indexes = []; foreach ($type->getAllFields() as $field) { if ($field instanceof ScalarField) { $result[] = ' ' . $this->prepareFieldStatement($field) . ','; } if ($field instanceof JsonFieldInterface) { foreach ($field->getValueExtractors() as $value_extractor) { $result[] = ' ' . $this->prepareGeneratedFieldStatement($field, $value_extractor) . ','; if ($value_extractor->getAddIndex()) { $generaterd_field_indexes[] = new Index($value_extractor->getFieldName()); } } } } $indexes = $type->getAllIndexes(); if (!empty($generaterd_field_indexes)) { $indexes = array_merge($indexes, $generaterd_field_indexes); } foreach ($indexes as $index) { $result[] = ' ' . $this->prepareIndexStatement($index) . ','; } $last_line = count($result) - 1; $result[$last_line] = rtrim($result[$last_line], ','); $result[] = ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'; return implode("\n", $result); }
[ "public", "function", "prepareCreateTableStatement", "(", "TypeInterface", "$", "type", ")", "{", "$", "result", "=", "[", "]", ";", "$", "result", "[", "]", "=", "'CREATE TABLE IF NOT EXISTS '", ".", "$", "this", "->", "getConnection", "(", ")", "->", "escapeTableName", "(", "$", "type", "->", "getName", "(", ")", ")", ".", "' ('", ";", "$", "generaterd_field_indexes", "=", "[", "]", ";", "foreach", "(", "$", "type", "->", "getAllFields", "(", ")", "as", "$", "field", ")", "{", "if", "(", "$", "field", "instanceof", "ScalarField", ")", "{", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareFieldStatement", "(", "$", "field", ")", ".", "','", ";", "}", "if", "(", "$", "field", "instanceof", "JsonFieldInterface", ")", "{", "foreach", "(", "$", "field", "->", "getValueExtractors", "(", ")", "as", "$", "value_extractor", ")", "{", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareGeneratedFieldStatement", "(", "$", "field", ",", "$", "value_extractor", ")", ".", "','", ";", "if", "(", "$", "value_extractor", "->", "getAddIndex", "(", ")", ")", "{", "$", "generaterd_field_indexes", "[", "]", "=", "new", "Index", "(", "$", "value_extractor", "->", "getFieldName", "(", ")", ")", ";", "}", "}", "}", "}", "$", "indexes", "=", "$", "type", "->", "getAllIndexes", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "generaterd_field_indexes", ")", ")", "{", "$", "indexes", "=", "array_merge", "(", "$", "indexes", ",", "$", "generaterd_field_indexes", ")", ";", "}", "foreach", "(", "$", "indexes", "as", "$", "index", ")", "{", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareIndexStatement", "(", "$", "index", ")", ".", "','", ";", "}", "$", "last_line", "=", "count", "(", "$", "result", ")", "-", "1", ";", "$", "result", "[", "$", "last_line", "]", "=", "rtrim", "(", "$", "result", "[", "$", "last_line", "]", ",", "','", ")", ";", "$", "result", "[", "]", "=", "') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "result", ")", ";", "}" ]
Prepare CREATE TABLE statement for the given type. @param TypeInterface $type @return string
[ "Prepare", "CREATE", "TABLE", "statement", "for", "the", "given", "type", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L124-L164
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareFieldStatement
private function prepareFieldStatement(ScalarField $field) { $result = $this->getConnection()->escapeFieldName($field->getName()) . ' ' . $this->prepareTypeDefinition($field); if ($field->getDefaultValue() !== null) { $result .= ' NOT NULL'; } if (!($field instanceof IntegerField && $field->getName() == 'id')) { $result .= ' DEFAULT ' . $this->prepareDefaultValue($field); } return $result; }
php
private function prepareFieldStatement(ScalarField $field) { $result = $this->getConnection()->escapeFieldName($field->getName()) . ' ' . $this->prepareTypeDefinition($field); if ($field->getDefaultValue() !== null) { $result .= ' NOT NULL'; } if (!($field instanceof IntegerField && $field->getName() == 'id')) { $result .= ' DEFAULT ' . $this->prepareDefaultValue($field); } return $result; }
[ "private", "function", "prepareFieldStatement", "(", "ScalarField", "$", "field", ")", "{", "$", "result", "=", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "field", "->", "getName", "(", ")", ")", ".", "' '", ".", "$", "this", "->", "prepareTypeDefinition", "(", "$", "field", ")", ";", "if", "(", "$", "field", "->", "getDefaultValue", "(", ")", "!==", "null", ")", "{", "$", "result", ".=", "' NOT NULL'", ";", "}", "if", "(", "!", "(", "$", "field", "instanceof", "IntegerField", "&&", "$", "field", "->", "getName", "(", ")", "==", "'id'", ")", ")", "{", "$", "result", ".=", "' DEFAULT '", ".", "$", "this", "->", "prepareDefaultValue", "(", "$", "field", ")", ";", "}", "return", "$", "result", ";", "}" ]
Prepare field statement based on the field settings. @param ScalarField $field @return string
[ "Prepare", "field", "statement", "based", "on", "the", "field", "settings", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L172-L185
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareTypeDefinition
private function prepareTypeDefinition(ScalarField $field) { if ($field instanceof IntegerField) { switch ($field->getSize()) { case FieldInterface::SIZE_TINY: $result = 'TINYINT'; break; case ScalarField::SIZE_SMALL: $result = 'SMALLINT'; break; case FieldInterface::SIZE_MEDIUM: $result = 'MEDIUMINT'; break; case FieldInterface::SIZE_BIG: $result = 'BIGINT'; break; default: $result = 'INT'; } if ($field->isUnsigned()) { $result .= ' UNSIGNED'; } if ($field->getName() == 'id') { $result .= ' AUTO_INCREMENT'; } return $result; } elseif ($field instanceof BooleanField) { return 'TINYINT(1) UNSIGNED'; } elseif ($field instanceof DateField) { return 'DATE'; } elseif ($field instanceof DateTimeField) { return 'DATETIME'; } elseif ($field instanceof DecimalField) { $result = 'DECIMAL(' . $field->getLength() . ', ' . $field->getScale() . ')'; if ($field->isUnsigned()) { $result .= ' UNSIGNED'; } return $result; } elseif ($field instanceof EnumField) { return 'ENUM(' . implode(',', array_map(function ($possibility) { return $this->getConnection()->escapeValue($possibility); }, $field->getPossibilities())) . ')'; } elseif ($field instanceof FloatField) { $result = 'FLOAT(' . $field->getLength() . ', ' . $field->getScale() . ')'; if ($field->isUnsigned()) { $result .= ' UNSIGNED'; } return $result; } elseif ($field instanceof JsonField) { return 'JSON'; } elseif ($field instanceof StringField) { return 'VARCHAR(' . $field->getLength() . ')'; } elseif ($field instanceof TextField) { switch ($field->getSize()) { case FieldInterface::SIZE_TINY: return 'TINYTEXT'; case ScalarField::SIZE_SMALL: return 'TEXT'; case FieldInterface::SIZE_MEDIUM: return 'MEDIUMTEXT'; default: return 'LONGTEXT'; } } elseif ($field instanceof TimeField) { return 'TIME'; } else { throw new InvalidArgumentException('Field ' . get_class($field) . ' is not a support scalar field'); } }
php
private function prepareTypeDefinition(ScalarField $field) { if ($field instanceof IntegerField) { switch ($field->getSize()) { case FieldInterface::SIZE_TINY: $result = 'TINYINT'; break; case ScalarField::SIZE_SMALL: $result = 'SMALLINT'; break; case FieldInterface::SIZE_MEDIUM: $result = 'MEDIUMINT'; break; case FieldInterface::SIZE_BIG: $result = 'BIGINT'; break; default: $result = 'INT'; } if ($field->isUnsigned()) { $result .= ' UNSIGNED'; } if ($field->getName() == 'id') { $result .= ' AUTO_INCREMENT'; } return $result; } elseif ($field instanceof BooleanField) { return 'TINYINT(1) UNSIGNED'; } elseif ($field instanceof DateField) { return 'DATE'; } elseif ($field instanceof DateTimeField) { return 'DATETIME'; } elseif ($field instanceof DecimalField) { $result = 'DECIMAL(' . $field->getLength() . ', ' . $field->getScale() . ')'; if ($field->isUnsigned()) { $result .= ' UNSIGNED'; } return $result; } elseif ($field instanceof EnumField) { return 'ENUM(' . implode(',', array_map(function ($possibility) { return $this->getConnection()->escapeValue($possibility); }, $field->getPossibilities())) . ')'; } elseif ($field instanceof FloatField) { $result = 'FLOAT(' . $field->getLength() . ', ' . $field->getScale() . ')'; if ($field->isUnsigned()) { $result .= ' UNSIGNED'; } return $result; } elseif ($field instanceof JsonField) { return 'JSON'; } elseif ($field instanceof StringField) { return 'VARCHAR(' . $field->getLength() . ')'; } elseif ($field instanceof TextField) { switch ($field->getSize()) { case FieldInterface::SIZE_TINY: return 'TINYTEXT'; case ScalarField::SIZE_SMALL: return 'TEXT'; case FieldInterface::SIZE_MEDIUM: return 'MEDIUMTEXT'; default: return 'LONGTEXT'; } } elseif ($field instanceof TimeField) { return 'TIME'; } else { throw new InvalidArgumentException('Field ' . get_class($field) . ' is not a support scalar field'); } }
[ "private", "function", "prepareTypeDefinition", "(", "ScalarField", "$", "field", ")", "{", "if", "(", "$", "field", "instanceof", "IntegerField", ")", "{", "switch", "(", "$", "field", "->", "getSize", "(", ")", ")", "{", "case", "FieldInterface", "::", "SIZE_TINY", ":", "$", "result", "=", "'TINYINT'", ";", "break", ";", "case", "ScalarField", "::", "SIZE_SMALL", ":", "$", "result", "=", "'SMALLINT'", ";", "break", ";", "case", "FieldInterface", "::", "SIZE_MEDIUM", ":", "$", "result", "=", "'MEDIUMINT'", ";", "break", ";", "case", "FieldInterface", "::", "SIZE_BIG", ":", "$", "result", "=", "'BIGINT'", ";", "break", ";", "default", ":", "$", "result", "=", "'INT'", ";", "}", "if", "(", "$", "field", "->", "isUnsigned", "(", ")", ")", "{", "$", "result", ".=", "' UNSIGNED'", ";", "}", "if", "(", "$", "field", "->", "getName", "(", ")", "==", "'id'", ")", "{", "$", "result", ".=", "' AUTO_INCREMENT'", ";", "}", "return", "$", "result", ";", "}", "elseif", "(", "$", "field", "instanceof", "BooleanField", ")", "{", "return", "'TINYINT(1) UNSIGNED'", ";", "}", "elseif", "(", "$", "field", "instanceof", "DateField", ")", "{", "return", "'DATE'", ";", "}", "elseif", "(", "$", "field", "instanceof", "DateTimeField", ")", "{", "return", "'DATETIME'", ";", "}", "elseif", "(", "$", "field", "instanceof", "DecimalField", ")", "{", "$", "result", "=", "'DECIMAL('", ".", "$", "field", "->", "getLength", "(", ")", ".", "', '", ".", "$", "field", "->", "getScale", "(", ")", ".", "')'", ";", "if", "(", "$", "field", "->", "isUnsigned", "(", ")", ")", "{", "$", "result", ".=", "' UNSIGNED'", ";", "}", "return", "$", "result", ";", "}", "elseif", "(", "$", "field", "instanceof", "EnumField", ")", "{", "return", "'ENUM('", ".", "implode", "(", "','", ",", "array_map", "(", "function", "(", "$", "possibility", ")", "{", "return", "$", "this", "->", "getConnection", "(", ")", "->", "escapeValue", "(", "$", "possibility", ")", ";", "}", ",", "$", "field", "->", "getPossibilities", "(", ")", ")", ")", ".", "')'", ";", "}", "elseif", "(", "$", "field", "instanceof", "FloatField", ")", "{", "$", "result", "=", "'FLOAT('", ".", "$", "field", "->", "getLength", "(", ")", ".", "', '", ".", "$", "field", "->", "getScale", "(", ")", ".", "')'", ";", "if", "(", "$", "field", "->", "isUnsigned", "(", ")", ")", "{", "$", "result", ".=", "' UNSIGNED'", ";", "}", "return", "$", "result", ";", "}", "elseif", "(", "$", "field", "instanceof", "JsonField", ")", "{", "return", "'JSON'", ";", "}", "elseif", "(", "$", "field", "instanceof", "StringField", ")", "{", "return", "'VARCHAR('", ".", "$", "field", "->", "getLength", "(", ")", ".", "')'", ";", "}", "elseif", "(", "$", "field", "instanceof", "TextField", ")", "{", "switch", "(", "$", "field", "->", "getSize", "(", ")", ")", "{", "case", "FieldInterface", "::", "SIZE_TINY", ":", "return", "'TINYTEXT'", ";", "case", "ScalarField", "::", "SIZE_SMALL", ":", "return", "'TEXT'", ";", "case", "FieldInterface", "::", "SIZE_MEDIUM", ":", "return", "'MEDIUMTEXT'", ";", "default", ":", "return", "'LONGTEXT'", ";", "}", "}", "elseif", "(", "$", "field", "instanceof", "TimeField", ")", "{", "return", "'TIME'", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Field '", ".", "get_class", "(", "$", "field", ")", ".", "' is not a support scalar field'", ")", ";", "}", "}" ]
Prepare type definition for the given field. @param ScalarField $field @return string
[ "Prepare", "type", "definition", "for", "the", "given", "field", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L193-L268
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareDefaultValue
public function prepareDefaultValue(ScalarField $field) { $default_value = $field->getDefaultValue(); if ($default_value === null) { return 'NULL'; } if ($field instanceof DateField || $field instanceof DateTimeField) { $timestamp = is_int($default_value) ? $default_value : strtotime($default_value); if ($field instanceof DateTimeField) { return $this->getConnection()->escapeValue(date('Y-m-d H:i:s', $timestamp)); } else { return $this->getConnection()->escapeValue(date('Y-m-d', $timestamp)); } } return $this->getConnection()->escapeValue($default_value); }
php
public function prepareDefaultValue(ScalarField $field) { $default_value = $field->getDefaultValue(); if ($default_value === null) { return 'NULL'; } if ($field instanceof DateField || $field instanceof DateTimeField) { $timestamp = is_int($default_value) ? $default_value : strtotime($default_value); if ($field instanceof DateTimeField) { return $this->getConnection()->escapeValue(date('Y-m-d H:i:s', $timestamp)); } else { return $this->getConnection()->escapeValue(date('Y-m-d', $timestamp)); } } return $this->getConnection()->escapeValue($default_value); }
[ "public", "function", "prepareDefaultValue", "(", "ScalarField", "$", "field", ")", "{", "$", "default_value", "=", "$", "field", "->", "getDefaultValue", "(", ")", ";", "if", "(", "$", "default_value", "===", "null", ")", "{", "return", "'NULL'", ";", "}", "if", "(", "$", "field", "instanceof", "DateField", "||", "$", "field", "instanceof", "DateTimeField", ")", "{", "$", "timestamp", "=", "is_int", "(", "$", "default_value", ")", "?", "$", "default_value", ":", "strtotime", "(", "$", "default_value", ")", ";", "if", "(", "$", "field", "instanceof", "DateTimeField", ")", "{", "return", "$", "this", "->", "getConnection", "(", ")", "->", "escapeValue", "(", "date", "(", "'Y-m-d H:i:s'", ",", "$", "timestamp", ")", ")", ";", "}", "else", "{", "return", "$", "this", "->", "getConnection", "(", ")", "->", "escapeValue", "(", "date", "(", "'Y-m-d'", ",", "$", "timestamp", ")", ")", ";", "}", "}", "return", "$", "this", "->", "getConnection", "(", ")", "->", "escapeValue", "(", "$", "default_value", ")", ";", "}" ]
Prepare default value. @param ScalarField $field @return string
[ "Prepare", "default", "value", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L276-L295
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareGeneratedFieldStatement
public function prepareGeneratedFieldStatement(FieldInterface $source_field, ValueExtractorInterface $extractor) { $generated_field_name = $this->getConnection()->escapeFieldName($extractor->getFieldName()); switch ($extractor->getValueCaster()) { case ValueCasterInterface::CAST_INT: $field_type = 'INT'; break; case ValueCasterInterface::CAST_FLOAT: $field_type = 'DECIMAL(12, 2)'; break; case ValueCasterInterface::CAST_BOOL: $field_type = 'TINYINT(1) UNSIGNED'; break; case ValueCasterInterface::CAST_DATE: $field_type = 'DATE'; break; case ValueCasterInterface::CAST_DATETIME: $field_type = 'DATETIME'; break; case ValueCasterInterface::CAST_JSON: $field_type = 'JSON'; break; default: $field_type = 'VARCHAR(191)'; } $expression = $this->prepareGeneratedFieldExpression( $this->getConnection()->escapeFieldName($source_field->getName()), var_export($extractor->getExpression(), true), $extractor->getValueCaster(), $this->getConnection()->escapeValue($extractor->getDefaultValue()) ); $storage = $extractor->getStoreValue() ? 'STORED' : 'VIRTUAL'; return trim("$generated_field_name $field_type AS ($expression) $storage"); }
php
public function prepareGeneratedFieldStatement(FieldInterface $source_field, ValueExtractorInterface $extractor) { $generated_field_name = $this->getConnection()->escapeFieldName($extractor->getFieldName()); switch ($extractor->getValueCaster()) { case ValueCasterInterface::CAST_INT: $field_type = 'INT'; break; case ValueCasterInterface::CAST_FLOAT: $field_type = 'DECIMAL(12, 2)'; break; case ValueCasterInterface::CAST_BOOL: $field_type = 'TINYINT(1) UNSIGNED'; break; case ValueCasterInterface::CAST_DATE: $field_type = 'DATE'; break; case ValueCasterInterface::CAST_DATETIME: $field_type = 'DATETIME'; break; case ValueCasterInterface::CAST_JSON: $field_type = 'JSON'; break; default: $field_type = 'VARCHAR(191)'; } $expression = $this->prepareGeneratedFieldExpression( $this->getConnection()->escapeFieldName($source_field->getName()), var_export($extractor->getExpression(), true), $extractor->getValueCaster(), $this->getConnection()->escapeValue($extractor->getDefaultValue()) ); $storage = $extractor->getStoreValue() ? 'STORED' : 'VIRTUAL'; return trim("$generated_field_name $field_type AS ($expression) $storage"); }
[ "public", "function", "prepareGeneratedFieldStatement", "(", "FieldInterface", "$", "source_field", ",", "ValueExtractorInterface", "$", "extractor", ")", "{", "$", "generated_field_name", "=", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "extractor", "->", "getFieldName", "(", ")", ")", ";", "switch", "(", "$", "extractor", "->", "getValueCaster", "(", ")", ")", "{", "case", "ValueCasterInterface", "::", "CAST_INT", ":", "$", "field_type", "=", "'INT'", ";", "break", ";", "case", "ValueCasterInterface", "::", "CAST_FLOAT", ":", "$", "field_type", "=", "'DECIMAL(12, 2)'", ";", "break", ";", "case", "ValueCasterInterface", "::", "CAST_BOOL", ":", "$", "field_type", "=", "'TINYINT(1) UNSIGNED'", ";", "break", ";", "case", "ValueCasterInterface", "::", "CAST_DATE", ":", "$", "field_type", "=", "'DATE'", ";", "break", ";", "case", "ValueCasterInterface", "::", "CAST_DATETIME", ":", "$", "field_type", "=", "'DATETIME'", ";", "break", ";", "case", "ValueCasterInterface", "::", "CAST_JSON", ":", "$", "field_type", "=", "'JSON'", ";", "break", ";", "default", ":", "$", "field_type", "=", "'VARCHAR(191)'", ";", "}", "$", "expression", "=", "$", "this", "->", "prepareGeneratedFieldExpression", "(", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "source_field", "->", "getName", "(", ")", ")", ",", "var_export", "(", "$", "extractor", "->", "getExpression", "(", ")", ",", "true", ")", ",", "$", "extractor", "->", "getValueCaster", "(", ")", ",", "$", "this", "->", "getConnection", "(", ")", "->", "escapeValue", "(", "$", "extractor", "->", "getDefaultValue", "(", ")", ")", ")", ";", "$", "storage", "=", "$", "extractor", "->", "getStoreValue", "(", ")", "?", "'STORED'", ":", "'VIRTUAL'", ";", "return", "trim", "(", "\"$generated_field_name $field_type AS ($expression) $storage\"", ")", ";", "}" ]
Prpeare generated field statement. @param FieldInterface $source_field @param ValueExtractorInterface $extractor @return string
[ "Prpeare", "generated", "field", "statement", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L304-L340
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareGeneratedFieldExpression
private function prepareGeneratedFieldExpression($escaped_field_name, $escaped_expression, $caster, $escaped_default_value) { $value_extractor_expression = "{$escaped_field_name}->>{$escaped_expression}"; switch ($caster) { case ValueCasterInterface::CAST_BOOL: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, IF({$value_extractor_expression} = 'true' OR ({$value_extractor_expression} REGEXP '^-?[0-9]+$' AND CAST({$value_extractor_expression} AS SIGNED) != 0), 1, 0))"; case ValueCasterInterface::CAST_DATE: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATE))"; case ValueCasterInterface::CAST_DATETIME: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATETIME))"; case ValueCasterInterface::CAST_INT: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS SIGNED INTEGER))"; case ValueCasterInterface::CAST_FLOAT: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DECIMAL(12, 2)))"; default: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, {$value_extractor_expression})"; } }
php
private function prepareGeneratedFieldExpression($escaped_field_name, $escaped_expression, $caster, $escaped_default_value) { $value_extractor_expression = "{$escaped_field_name}->>{$escaped_expression}"; switch ($caster) { case ValueCasterInterface::CAST_BOOL: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, IF({$value_extractor_expression} = 'true' OR ({$value_extractor_expression} REGEXP '^-?[0-9]+$' AND CAST({$value_extractor_expression} AS SIGNED) != 0), 1, 0))"; case ValueCasterInterface::CAST_DATE: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATE))"; case ValueCasterInterface::CAST_DATETIME: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATETIME))"; case ValueCasterInterface::CAST_INT: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS SIGNED INTEGER))"; case ValueCasterInterface::CAST_FLOAT: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DECIMAL(12, 2)))"; default: return "IF({$value_extractor_expression} IS NULL, $escaped_default_value, {$value_extractor_expression})"; } }
[ "private", "function", "prepareGeneratedFieldExpression", "(", "$", "escaped_field_name", ",", "$", "escaped_expression", ",", "$", "caster", ",", "$", "escaped_default_value", ")", "{", "$", "value_extractor_expression", "=", "\"{$escaped_field_name}->>{$escaped_expression}\"", ";", "switch", "(", "$", "caster", ")", "{", "case", "ValueCasterInterface", "::", "CAST_BOOL", ":", "return", "\"IF({$value_extractor_expression} IS NULL, $escaped_default_value, IF({$value_extractor_expression} = 'true' OR ({$value_extractor_expression} REGEXP '^-?[0-9]+$' AND CAST({$value_extractor_expression} AS SIGNED) != 0), 1, 0))\"", ";", "case", "ValueCasterInterface", "::", "CAST_DATE", ":", "return", "\"IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATE))\"", ";", "case", "ValueCasterInterface", "::", "CAST_DATETIME", ":", "return", "\"IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DATETIME))\"", ";", "case", "ValueCasterInterface", "::", "CAST_INT", ":", "return", "\"IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS SIGNED INTEGER))\"", ";", "case", "ValueCasterInterface", "::", "CAST_FLOAT", ":", "return", "\"IF({$value_extractor_expression} IS NULL, $escaped_default_value, CAST({$value_extractor_expression} AS DECIMAL(12, 2)))\"", ";", "default", ":", "return", "\"IF({$value_extractor_expression} IS NULL, $escaped_default_value, {$value_extractor_expression})\"", ";", "}", "}" ]
Prepare extraction statement based on expression. @param string $escaped_field_name @param string $escaped_expression @param string $caster @param mixed $escaped_default_value @return string
[ "Prepare", "extraction", "statement", "based", "on", "expression", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L351-L369
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareIndexStatement
public function prepareIndexStatement(IndexInterface $index) { switch ($index->getIndexType()) { case IndexInterface::PRIMARY: $result = 'PRIMARY KEY'; break; case IndexInterface::UNIQUE: $result = 'UNIQUE ' . $this->getConnection()->escapeFieldName($index->getName()); break; case IndexInterface::FULLTEXT: $result = 'FULLTEXT ' . $this->getConnection()->escapeFieldName($index->getName()); break; default: $result = 'INDEX ' . $this->getConnection()->escapeFieldName($index->getName()); break; } return $result . ' (' . implode(', ', array_map(function ($field_name) { return $this->getConnection()->escapeFieldName($field_name); }, $index->getFields())) . ')'; }
php
public function prepareIndexStatement(IndexInterface $index) { switch ($index->getIndexType()) { case IndexInterface::PRIMARY: $result = 'PRIMARY KEY'; break; case IndexInterface::UNIQUE: $result = 'UNIQUE ' . $this->getConnection()->escapeFieldName($index->getName()); break; case IndexInterface::FULLTEXT: $result = 'FULLTEXT ' . $this->getConnection()->escapeFieldName($index->getName()); break; default: $result = 'INDEX ' . $this->getConnection()->escapeFieldName($index->getName()); break; } return $result . ' (' . implode(', ', array_map(function ($field_name) { return $this->getConnection()->escapeFieldName($field_name); }, $index->getFields())) . ')'; }
[ "public", "function", "prepareIndexStatement", "(", "IndexInterface", "$", "index", ")", "{", "switch", "(", "$", "index", "->", "getIndexType", "(", ")", ")", "{", "case", "IndexInterface", "::", "PRIMARY", ":", "$", "result", "=", "'PRIMARY KEY'", ";", "break", ";", "case", "IndexInterface", "::", "UNIQUE", ":", "$", "result", "=", "'UNIQUE '", ".", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "index", "->", "getName", "(", ")", ")", ";", "break", ";", "case", "IndexInterface", "::", "FULLTEXT", ":", "$", "result", "=", "'FULLTEXT '", ".", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "index", "->", "getName", "(", ")", ")", ";", "break", ";", "default", ":", "$", "result", "=", "'INDEX '", ".", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "index", "->", "getName", "(", ")", ")", ";", "break", ";", "}", "return", "$", "result", ".", "' ('", ".", "implode", "(", "', '", ",", "array_map", "(", "function", "(", "$", "field_name", ")", "{", "return", "$", "this", "->", "getConnection", "(", ")", "->", "escapeFieldName", "(", "$", "field_name", ")", ";", "}", ",", "$", "index", "->", "getFields", "(", ")", ")", ")", ".", "')'", ";", "}" ]
Prepare index statement. @param IndexInterface $index @return string
[ "Prepare", "index", "statement", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L377-L397
activecollab/databasestructure
src/Builder/TypeTableBuilder.php
TypeTableBuilder.prepareConnectionCreateTableStatement
public function prepareConnectionCreateTableStatement(TypeInterface $source, TypeInterface $target, HasAndBelongsToManyAssociation $association) { $result = []; $result[] = 'CREATE TABLE IF NOT EXISTS ' . $this->getConnection()->escapeTableName($association->getConnectionTableName()) . ' ('; $left_field_name = $association->getLeftFieldName(); $right_field_name = $association->getRightFieldName(); $left_field = (new IntegerField($left_field_name, 0))->unsigned(true)->size($source->getIdField()->getSize()); $right_field = (new IntegerField($right_field_name, 0))->unsigned(true)->size($target->getIdField()->getSize()); $result[] = ' ' . $this->prepareFieldStatement($left_field) . ','; $result[] = ' ' . $this->prepareFieldStatement($right_field) . ','; $result[] = ' ' . $this->prepareIndexStatement(new Index('PRIMARY', [$left_field->getName(), $right_field->getName()], IndexInterface::PRIMARY)) . ','; $result[] = ' ' . $this->prepareIndexStatement(new Index($right_field->getName())); $result[] = ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'; return implode("\n", $result); }
php
public function prepareConnectionCreateTableStatement(TypeInterface $source, TypeInterface $target, HasAndBelongsToManyAssociation $association) { $result = []; $result[] = 'CREATE TABLE IF NOT EXISTS ' . $this->getConnection()->escapeTableName($association->getConnectionTableName()) . ' ('; $left_field_name = $association->getLeftFieldName(); $right_field_name = $association->getRightFieldName(); $left_field = (new IntegerField($left_field_name, 0))->unsigned(true)->size($source->getIdField()->getSize()); $right_field = (new IntegerField($right_field_name, 0))->unsigned(true)->size($target->getIdField()->getSize()); $result[] = ' ' . $this->prepareFieldStatement($left_field) . ','; $result[] = ' ' . $this->prepareFieldStatement($right_field) . ','; $result[] = ' ' . $this->prepareIndexStatement(new Index('PRIMARY', [$left_field->getName(), $right_field->getName()], IndexInterface::PRIMARY)) . ','; $result[] = ' ' . $this->prepareIndexStatement(new Index($right_field->getName())); $result[] = ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'; return implode("\n", $result); }
[ "public", "function", "prepareConnectionCreateTableStatement", "(", "TypeInterface", "$", "source", ",", "TypeInterface", "$", "target", ",", "HasAndBelongsToManyAssociation", "$", "association", ")", "{", "$", "result", "=", "[", "]", ";", "$", "result", "[", "]", "=", "'CREATE TABLE IF NOT EXISTS '", ".", "$", "this", "->", "getConnection", "(", ")", "->", "escapeTableName", "(", "$", "association", "->", "getConnectionTableName", "(", ")", ")", ".", "' ('", ";", "$", "left_field_name", "=", "$", "association", "->", "getLeftFieldName", "(", ")", ";", "$", "right_field_name", "=", "$", "association", "->", "getRightFieldName", "(", ")", ";", "$", "left_field", "=", "(", "new", "IntegerField", "(", "$", "left_field_name", ",", "0", ")", ")", "->", "unsigned", "(", "true", ")", "->", "size", "(", "$", "source", "->", "getIdField", "(", ")", "->", "getSize", "(", ")", ")", ";", "$", "right_field", "=", "(", "new", "IntegerField", "(", "$", "right_field_name", ",", "0", ")", ")", "->", "unsigned", "(", "true", ")", "->", "size", "(", "$", "target", "->", "getIdField", "(", ")", "->", "getSize", "(", ")", ")", ";", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareFieldStatement", "(", "$", "left_field", ")", ".", "','", ";", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareFieldStatement", "(", "$", "right_field", ")", ".", "','", ";", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareIndexStatement", "(", "new", "Index", "(", "'PRIMARY'", ",", "[", "$", "left_field", "->", "getName", "(", ")", ",", "$", "right_field", "->", "getName", "(", ")", "]", ",", "IndexInterface", "::", "PRIMARY", ")", ")", ".", "','", ";", "$", "result", "[", "]", "=", "' '", ".", "$", "this", "->", "prepareIndexStatement", "(", "new", "Index", "(", "$", "right_field", "->", "getName", "(", ")", ")", ")", ";", "$", "result", "[", "]", "=", "') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "result", ")", ";", "}" ]
Prepare create connection table statement. @param TypeInterface $source @param TypeInterface $target @param HasAndBelongsToManyAssociation $association @return string
[ "Prepare", "create", "connection", "table", "statement", "." ]
train
https://github.com/activecollab/databasestructure/blob/4b2353c4422186bcfce63b3212da3e70e63eb5df/src/Builder/TypeTableBuilder.php#L419-L439
crossjoin/Css
src/Crossjoin/Css/Format/Rule/TraitComments.php
TraitComments.setComments
public function setComments($comments) { $this->comments = []; if (!is_array($comments)) { $comments = [$comments]; } foreach ($comments as $comment) { $this->addComment($comment); } return $this; }
php
public function setComments($comments) { $this->comments = []; if (!is_array($comments)) { $comments = [$comments]; } foreach ($comments as $comment) { $this->addComment($comment); } return $this; }
[ "public", "function", "setComments", "(", "$", "comments", ")", "{", "$", "this", "->", "comments", "=", "[", "]", ";", "if", "(", "!", "is_array", "(", "$", "comments", ")", ")", "{", "$", "comments", "=", "[", "$", "comments", "]", ";", "}", "foreach", "(", "$", "comments", "as", "$", "comment", ")", "{", "$", "this", "->", "addComment", "(", "$", "comment", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets comments. @param string[]|string $comments @return $this
[ "Sets", "comments", "." ]
train
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/TraitComments.php#L19-L30
crossjoin/Css
src/Crossjoin/Css/Format/Rule/TraitComments.php
TraitComments.addComment
public function addComment($comment) { if (is_string($comment)) { $comment = Placeholder::replaceCommentPlaceholders($comment, true); $this->comments[] = $comment; } else { throw new \InvalidArgumentException( "Invalid type '" . gettype($comment). "' for argument 'comment' given." ); } return $this; }
php
public function addComment($comment) { if (is_string($comment)) { $comment = Placeholder::replaceCommentPlaceholders($comment, true); $this->comments[] = $comment; } else { throw new \InvalidArgumentException( "Invalid type '" . gettype($comment). "' for argument 'comment' given." ); } return $this; }
[ "public", "function", "addComment", "(", "$", "comment", ")", "{", "if", "(", "is_string", "(", "$", "comment", ")", ")", "{", "$", "comment", "=", "Placeholder", "::", "replaceCommentPlaceholders", "(", "$", "comment", ",", "true", ")", ";", "$", "this", "->", "comments", "[", "]", "=", "$", "comment", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid type '\"", ".", "gettype", "(", "$", "comment", ")", ".", "\"' for argument 'comment' given.\"", ")", ";", "}", "return", "$", "this", ";", "}" ]
Adds a comment. @param string $comment @return $this
[ "Adds", "a", "comment", "." ]
train
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Format/Rule/TraitComments.php#L38-L51
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor.execute
public function execute($sqlQuery, $params = [], $prefix = '') { if ($prefix !== '') $this->_testQueryStarts($sqlQuery, $prefix); $statement = $this->_executeQuery($sqlQuery, $params); return $statement->rowCount(); }
php
public function execute($sqlQuery, $params = [], $prefix = '') { if ($prefix !== '') $this->_testQueryStarts($sqlQuery, $prefix); $statement = $this->_executeQuery($sqlQuery, $params); return $statement->rowCount(); }
[ "public", "function", "execute", "(", "$", "sqlQuery", ",", "$", "params", "=", "[", "]", ",", "$", "prefix", "=", "''", ")", "{", "if", "(", "$", "prefix", "!==", "''", ")", "$", "this", "->", "_testQueryStarts", "(", "$", "sqlQuery", ",", "$", "prefix", ")", ";", "$", "statement", "=", "$", "this", "->", "_executeQuery", "(", "$", "sqlQuery", ",", "$", "params", ")", ";", "return", "$", "statement", "->", "rowCount", "(", ")", ";", "}" ]
Execute given SQL query. Please DON'T use instead of other functions example - use this if you need something like "TRUNCATE TABLE `users`" use it VERY CAREFULLY! @param string $sqlQuery @param array $params @param string $prefix prefix to check SQL query against @return int affected rows count
[ "Execute", "given", "SQL", "query", ".", "Please", "DON", "T", "use", "instead", "of", "other", "functions" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L96-L103
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor.beginTransaction
public function beginTransaction() { $this->checkConnection(); try { $this->_pdo->beginTransaction(); $this->_lastCheckTime = time(); } catch (\PDOException $e) { $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e); } }
php
public function beginTransaction() { $this->checkConnection(); try { $this->_pdo->beginTransaction(); $this->_lastCheckTime = time(); } catch (\PDOException $e) { $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e); } }
[ "public", "function", "beginTransaction", "(", ")", "{", "$", "this", "->", "checkConnection", "(", ")", ";", "try", "{", "$", "this", "->", "_pdo", "->", "beginTransaction", "(", ")", ";", "$", "this", "->", "_lastCheckTime", "=", "time", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "$", "this", "->", "_error", "(", "$", "e", "->", "getMessage", "(", ")", ",", "FQDBException", "::", "PDO_CODE", ",", "$", "e", ")", ";", "}", "}" ]
starts transaction
[ "starts", "transaction" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L109-L119
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor.commitTransaction
public function commitTransaction() { try { $this->_pdo->commit(); $this->_lastCheckTime = time(); } catch (\PDOException $e) { $this->rollbackTransaction(); $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e); } }
php
public function commitTransaction() { try { $this->_pdo->commit(); $this->_lastCheckTime = time(); } catch (\PDOException $e) { $this->rollbackTransaction(); $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e); } }
[ "public", "function", "commitTransaction", "(", ")", "{", "try", "{", "$", "this", "->", "_pdo", "->", "commit", "(", ")", ";", "$", "this", "->", "_lastCheckTime", "=", "time", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "$", "this", "->", "rollbackTransaction", "(", ")", ";", "$", "this", "->", "_error", "(", "$", "e", "->", "getMessage", "(", ")", ",", "FQDBException", "::", "PDO_CODE", ",", "$", "e", ")", ";", "}", "}" ]
commits transaction
[ "commits", "transaction" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L124-L133
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor.rollbackTransaction
public function rollbackTransaction() { try { $this->_pdo->rollBack(); $this->_lastCheckTime = time(); } catch (\PDOException $e) { $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e); } }
php
public function rollbackTransaction() { try { $this->_pdo->rollBack(); $this->_lastCheckTime = time(); } catch (\PDOException $e) { $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e); } }
[ "public", "function", "rollbackTransaction", "(", ")", "{", "try", "{", "$", "this", "->", "_pdo", "->", "rollBack", "(", ")", ";", "$", "this", "->", "_lastCheckTime", "=", "time", "(", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "$", "this", "->", "_error", "(", "$", "e", "->", "getMessage", "(", ")", ",", "FQDBException", "::", "PDO_CODE", ",", "$", "e", ")", ";", "}", "}" ]
rollbacks transaction
[ "rollbacks", "transaction" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L138-L146
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor.checkConnection
private function checkConnection() { if ($this->_databaseServer !== self::DB_MYSQL) { return; } $interval = (time() - (int)$this->_lastCheckTime); if ($interval >= self::MYSQL_CONNECTION_TIMEOUT) { $this->connect(); } }
php
private function checkConnection() { if ($this->_databaseServer !== self::DB_MYSQL) { return; } $interval = (time() - (int)$this->_lastCheckTime); if ($interval >= self::MYSQL_CONNECTION_TIMEOUT) { $this->connect(); } }
[ "private", "function", "checkConnection", "(", ")", "{", "if", "(", "$", "this", "->", "_databaseServer", "!==", "self", "::", "DB_MYSQL", ")", "{", "return", ";", "}", "$", "interval", "=", "(", "time", "(", ")", "-", "(", "int", ")", "$", "this", "->", "_lastCheckTime", ")", ";", "if", "(", "$", "interval", ">=", "self", "::", "MYSQL_CONNECTION_TIMEOUT", ")", "{", "$", "this", "->", "connect", "(", ")", ";", "}", "}" ]
if last query was too long time ago - reconnect
[ "if", "last", "query", "was", "too", "long", "time", "ago", "-", "reconnect" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L201-L212
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor._getWarnings
private function _getWarnings($sqlQueryString, $options = []) { if ($this->_databaseServer === self::DB_MYSQL) { $stm = $this->_pdo->query('SHOW WARNINGS'); $sqlWarnings = $stm->fetchAll(\PDO::FETCH_ASSOC); } else { $sqlWarnings = [['Message' => 'WarningReporting not impl. for ' . $this->_pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)]]; } if (count($sqlWarnings) > 0) { $warnings = "Query:\n{$sqlQueryString}\n"; if (!empty($options)) { $warnings .= "Params: ("; foreach ($options as $key => $value) { $warnings .= $key . '=' . json_encode($value) . ', '; } $warnings = substr($warnings, 0, -2) . ")\n"; } $warnings .= "Produced Warnings:"; foreach ($sqlWarnings as $warn) { $warnings .= "\n* " . $warn['Message']; } return $warnings; } return ''; }
php
private function _getWarnings($sqlQueryString, $options = []) { if ($this->_databaseServer === self::DB_MYSQL) { $stm = $this->_pdo->query('SHOW WARNINGS'); $sqlWarnings = $stm->fetchAll(\PDO::FETCH_ASSOC); } else { $sqlWarnings = [['Message' => 'WarningReporting not impl. for ' . $this->_pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)]]; } if (count($sqlWarnings) > 0) { $warnings = "Query:\n{$sqlQueryString}\n"; if (!empty($options)) { $warnings .= "Params: ("; foreach ($options as $key => $value) { $warnings .= $key . '=' . json_encode($value) . ', '; } $warnings = substr($warnings, 0, -2) . ")\n"; } $warnings .= "Produced Warnings:"; foreach ($sqlWarnings as $warn) { $warnings .= "\n* " . $warn['Message']; } return $warnings; } return ''; }
[ "private", "function", "_getWarnings", "(", "$", "sqlQueryString", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "_databaseServer", "===", "self", "::", "DB_MYSQL", ")", "{", "$", "stm", "=", "$", "this", "->", "_pdo", "->", "query", "(", "'SHOW WARNINGS'", ")", ";", "$", "sqlWarnings", "=", "$", "stm", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}", "else", "{", "$", "sqlWarnings", "=", "[", "[", "'Message'", "=>", "'WarningReporting not impl. for '", ".", "$", "this", "->", "_pdo", "->", "getAttribute", "(", "\\", "PDO", "::", "ATTR_DRIVER_NAME", ")", "]", "]", ";", "}", "if", "(", "count", "(", "$", "sqlWarnings", ")", ">", "0", ")", "{", "$", "warnings", "=", "\"Query:\\n{$sqlQueryString}\\n\"", ";", "if", "(", "!", "empty", "(", "$", "options", ")", ")", "{", "$", "warnings", ".=", "\"Params: (\"", ";", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "warnings", ".=", "$", "key", ".", "'='", ".", "json_encode", "(", "$", "value", ")", ".", "', '", ";", "}", "$", "warnings", "=", "substr", "(", "$", "warnings", ",", "0", ",", "-", "2", ")", ".", "\")\\n\"", ";", "}", "$", "warnings", ".=", "\"Produced Warnings:\"", ";", "foreach", "(", "$", "sqlWarnings", "as", "$", "warn", ")", "{", "$", "warnings", ".=", "\"\\n* \"", ".", "$", "warn", "[", "'Message'", "]", ";", "}", "return", "$", "warnings", ";", "}", "return", "''", ";", "}" ]
gathers Warning info from \PDO @param string $sqlQueryString SQL query string with placeholders @param array $options options passed to query @return string
[ "gathers", "Warning", "info", "from", "\\", "PDO" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L220-L254
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor._prepareStatement
private function _prepareStatement($sqlQueryString, $options) { $statementNum = 0; foreach ($options as $placeholder => $value) { if (is_object($value) && ($value instanceof SQLArgs || $value instanceof SQLArgsArray)) { $args = $value->toArray(); if (!is_array($args)) { $this->_error(FQDBException::INTERNAL_ASSERTION_FAIL, FQDBException::FQDB_CODE); } $statementNum++; $valueInStatementNum = 0; $whereInStatement = []; foreach ($args as $inStatementValue) { $valueInStatementNum++; $whereInStatement[':where_in_statement_' . $statementNum . '_' . $valueInStatementNum] = $inStatementValue; } $sqlQueryString = str_replace($placeholder, implode(', ', array_keys($whereInStatement)), $sqlQueryString); $options = array_merge($options, $whereInStatement); unset($options[$placeholder]); } } return [ $sqlQueryString, $options ]; }
php
private function _prepareStatement($sqlQueryString, $options) { $statementNum = 0; foreach ($options as $placeholder => $value) { if (is_object($value) && ($value instanceof SQLArgs || $value instanceof SQLArgsArray)) { $args = $value->toArray(); if (!is_array($args)) { $this->_error(FQDBException::INTERNAL_ASSERTION_FAIL, FQDBException::FQDB_CODE); } $statementNum++; $valueInStatementNum = 0; $whereInStatement = []; foreach ($args as $inStatementValue) { $valueInStatementNum++; $whereInStatement[':where_in_statement_' . $statementNum . '_' . $valueInStatementNum] = $inStatementValue; } $sqlQueryString = str_replace($placeholder, implode(', ', array_keys($whereInStatement)), $sqlQueryString); $options = array_merge($options, $whereInStatement); unset($options[$placeholder]); } } return [ $sqlQueryString, $options ]; }
[ "private", "function", "_prepareStatement", "(", "$", "sqlQueryString", ",", "$", "options", ")", "{", "$", "statementNum", "=", "0", ";", "foreach", "(", "$", "options", "as", "$", "placeholder", "=>", "$", "value", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", "&&", "(", "$", "value", "instanceof", "SQLArgs", "||", "$", "value", "instanceof", "SQLArgsArray", ")", ")", "{", "$", "args", "=", "$", "value", "->", "toArray", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "args", ")", ")", "{", "$", "this", "->", "_error", "(", "FQDBException", "::", "INTERNAL_ASSERTION_FAIL", ",", "FQDBException", "::", "FQDB_CODE", ")", ";", "}", "$", "statementNum", "++", ";", "$", "valueInStatementNum", "=", "0", ";", "$", "whereInStatement", "=", "[", "]", ";", "foreach", "(", "$", "args", "as", "$", "inStatementValue", ")", "{", "$", "valueInStatementNum", "++", ";", "$", "whereInStatement", "[", "':where_in_statement_'", ".", "$", "statementNum", ".", "'_'", ".", "$", "valueInStatementNum", "]", "=", "$", "inStatementValue", ";", "}", "$", "sqlQueryString", "=", "str_replace", "(", "$", "placeholder", ",", "implode", "(", "', '", ",", "array_keys", "(", "$", "whereInStatement", ")", ")", ",", "$", "sqlQueryString", ")", ";", "$", "options", "=", "array_merge", "(", "$", "options", ",", "$", "whereInStatement", ")", ";", "unset", "(", "$", "options", "[", "$", "placeholder", "]", ")", ";", "}", "}", "return", "[", "$", "sqlQueryString", ",", "$", "options", "]", ";", "}" ]
Find WHERE IN statements and converts sqlQueryString and $options to format needed for WHERE IN statement run @param string $sqlQueryString @param array $options placeholders values @return array queryString options
[ "Find", "WHERE", "IN", "statements", "and", "converts", "sqlQueryString", "and", "$options", "to", "format", "needed", "for", "WHERE", "IN", "statement", "run" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L264-L295
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor._executeQuery
protected function _executeQuery($sqlQueryString, $options, $needsLastInsertId = false) { $this->checkConnection(); try { list($sqlQueryString, $options) = $this->_prepareStatement($sqlQueryString, $options); $statement = $this->_pdo->prepare($sqlQueryString); $this->_preExecuteOptionsCheck($sqlQueryString, $options); $this->bindOptionsToStatement($options, $statement); $statement->execute(); //options are already bound to query $this->_lastCheckTime = time(); if ($needsLastInsertId) $lastInsertId = $this->_pdo->lastInsertId(); // if table has no PRI KEY, there will be 0 } catch (\PDOException $e) { $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e, [$sqlQueryString, $options]); return 0; // for static analysis } $this->reportWarnings($sqlQueryString, $options); return isset($lastInsertId) ? $lastInsertId : $statement; }
php
protected function _executeQuery($sqlQueryString, $options, $needsLastInsertId = false) { $this->checkConnection(); try { list($sqlQueryString, $options) = $this->_prepareStatement($sqlQueryString, $options); $statement = $this->_pdo->prepare($sqlQueryString); $this->_preExecuteOptionsCheck($sqlQueryString, $options); $this->bindOptionsToStatement($options, $statement); $statement->execute(); //options are already bound to query $this->_lastCheckTime = time(); if ($needsLastInsertId) $lastInsertId = $this->_pdo->lastInsertId(); // if table has no PRI KEY, there will be 0 } catch (\PDOException $e) { $this->_error($e->getMessage(), FQDBException::PDO_CODE, $e, [$sqlQueryString, $options]); return 0; // for static analysis } $this->reportWarnings($sqlQueryString, $options); return isset($lastInsertId) ? $lastInsertId : $statement; }
[ "protected", "function", "_executeQuery", "(", "$", "sqlQueryString", ",", "$", "options", ",", "$", "needsLastInsertId", "=", "false", ")", "{", "$", "this", "->", "checkConnection", "(", ")", ";", "try", "{", "list", "(", "$", "sqlQueryString", ",", "$", "options", ")", "=", "$", "this", "->", "_prepareStatement", "(", "$", "sqlQueryString", ",", "$", "options", ")", ";", "$", "statement", "=", "$", "this", "->", "_pdo", "->", "prepare", "(", "$", "sqlQueryString", ")", ";", "$", "this", "->", "_preExecuteOptionsCheck", "(", "$", "sqlQueryString", ",", "$", "options", ")", ";", "$", "this", "->", "bindOptionsToStatement", "(", "$", "options", ",", "$", "statement", ")", ";", "$", "statement", "->", "execute", "(", ")", ";", "//options are already bound to query", "$", "this", "->", "_lastCheckTime", "=", "time", "(", ")", ";", "if", "(", "$", "needsLastInsertId", ")", "$", "lastInsertId", "=", "$", "this", "->", "_pdo", "->", "lastInsertId", "(", ")", ";", "// if table has no PRI KEY, there will be 0", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "$", "this", "->", "_error", "(", "$", "e", "->", "getMessage", "(", ")", ",", "FQDBException", "::", "PDO_CODE", ",", "$", "e", ",", "[", "$", "sqlQueryString", ",", "$", "options", "]", ")", ";", "return", "0", ";", "// for static analysis", "}", "$", "this", "->", "reportWarnings", "(", "$", "sqlQueryString", ",", "$", "options", ")", ";", "return", "isset", "(", "$", "lastInsertId", ")", "?", "$", "lastInsertId", ":", "$", "statement", ";", "}" ]
executes prepared \PDO query @param $sqlQueryString @param $options @param bool $needsLastInsertId @return int|\PDOStatement|string
[ "executes", "prepared", "\\", "PDO", "query" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L348-L376
readdle/fqdb
src/Readdle/Database/FQDBExecutor.php
FQDBExecutor._error
protected function _error($message, $code, $exception = null, $context = []) { if (isset($this->_errorHandler)) { call_user_func($this->_errorHandler, $message, $code, $exception, $context); trigger_error('FQDB error handler function should die() or throw another exception!', E_ERROR); } else { throw new FQDBException($message, $code, $exception); } }
php
protected function _error($message, $code, $exception = null, $context = []) { if (isset($this->_errorHandler)) { call_user_func($this->_errorHandler, $message, $code, $exception, $context); trigger_error('FQDB error handler function should die() or throw another exception!', E_ERROR); } else { throw new FQDBException($message, $code, $exception); } }
[ "protected", "function", "_error", "(", "$", "message", ",", "$", "code", ",", "$", "exception", "=", "null", ",", "$", "context", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_errorHandler", ")", ")", "{", "call_user_func", "(", "$", "this", "->", "_errorHandler", ",", "$", "message", ",", "$", "code", ",", "$", "exception", ",", "$", "context", ")", ";", "trigger_error", "(", "'FQDB error handler function should die() or throw another exception!'", ",", "E_ERROR", ")", ";", "}", "else", "{", "throw", "new", "FQDBException", "(", "$", "message", ",", "$", "code", ",", "$", "exception", ")", ";", "}", "}" ]
handle Errors @param string $message error text @param int $code code 0 - FQDB, 1 - PDO @param \Exception $exception previous Exception @param array $context @throws \Readdle\Database\FQDBException if its not
[ "handle", "Errors" ]
train
https://github.com/readdle/fqdb/blob/4ef2e8f3343a7c8fbb309c243be502a160c42083/src/Readdle/Database/FQDBExecutor.php#L428-L436
bestit/commercetools-order-export-bundle
src/Event/PrepareOrderExportEvent.php
PrepareOrderExportEvent.addExportData
public function addExportData($key, $data = null): PrepareOrderExportEvent { if (is_array($key)) { $this->exportData = array_merge($this->exportData, $key); } else { $this->exportData[$key] = $data; } return $this; }
php
public function addExportData($key, $data = null): PrepareOrderExportEvent { if (is_array($key)) { $this->exportData = array_merge($this->exportData, $key); } else { $this->exportData[$key] = $data; } return $this; }
[ "public", "function", "addExportData", "(", "$", "key", ",", "$", "data", "=", "null", ")", ":", "PrepareOrderExportEvent", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "$", "this", "->", "exportData", "=", "array_merge", "(", "$", "this", "->", "exportData", ",", "$", "key", ")", ";", "}", "else", "{", "$", "this", "->", "exportData", "[", "$", "key", "]", "=", "$", "data", ";", "}", "return", "$", "this", ";", "}" ]
Adds an exportable data. @param string|array $key @param null $data @return PrepareOrderExportEvent
[ "Adds", "an", "exportable", "data", "." ]
train
https://github.com/bestit/commercetools-order-export-bundle/blob/44bd0dedff6edab5ecf5803dcf6d24ffe0dbf845/src/Event/PrepareOrderExportEvent.php#L26-L35
movoin/one-swoole
src/Protocol/Protocols/HttpProtocol.php
HttpProtocol.onRequest
public function onRequest(Request $request, Response $response) { try { // 处理 406 $responder = $this->getResponder(); if ($responder->getAcceptHandler($request) === null) { throw ProtocolException::notAcceptable( $request->getHeaderLine('Accept'), $request->getProtocol() ); } $response = $this->handle($request, $response); } catch (MiddlewareException $e) { // {{ log $this->logger->error( sprintf('中间件 %s 发生异常', $e->getMiddleware()), [ 'error' => $e->getMessage(), 'errno' => $e->getCode() ] ); // }} $response = $responder( $request, $response, new Payload( 500, $e->getMessage() ) ); } catch (ProtocolException $e) { // {{ log $this->logger->error( sprintf('处理 %s 请求发生异常', strtoupper($e->getProtocol())), [ 'error' => $e->getMessage(), 'errno' => $e->getCode(), 'uri' => $request->getRequestTarget(), ] ); // }} $response = $e->makeResponse($request, $response, $responder); } catch (Exception $e) { // {{ log $this->logger->error( '系统错误', [ 'error' => $e->getMessage(), 'errno' => $e->getCode() ] ); // }} $response = $responder( $request, $response, new Payload( 500, $e->getMessage() ) ); } unset($responder); return $response->end(); }
php
public function onRequest(Request $request, Response $response) { try { // 处理 406 $responder = $this->getResponder(); if ($responder->getAcceptHandler($request) === null) { throw ProtocolException::notAcceptable( $request->getHeaderLine('Accept'), $request->getProtocol() ); } $response = $this->handle($request, $response); } catch (MiddlewareException $e) { // {{ log $this->logger->error( sprintf('中间件 %s 发生异常', $e->getMiddleware()), [ 'error' => $e->getMessage(), 'errno' => $e->getCode() ] ); // }} $response = $responder( $request, $response, new Payload( 500, $e->getMessage() ) ); } catch (ProtocolException $e) { // {{ log $this->logger->error( sprintf('处理 %s 请求发生异常', strtoupper($e->getProtocol())), [ 'error' => $e->getMessage(), 'errno' => $e->getCode(), 'uri' => $request->getRequestTarget(), ] ); // }} $response = $e->makeResponse($request, $response, $responder); } catch (Exception $e) { // {{ log $this->logger->error( '系统错误', [ 'error' => $e->getMessage(), 'errno' => $e->getCode() ] ); // }} $response = $responder( $request, $response, new Payload( 500, $e->getMessage() ) ); } unset($responder); return $response->end(); }
[ "public", "function", "onRequest", "(", "Request", "$", "request", ",", "Response", "$", "response", ")", "{", "try", "{", "// 处理 406", "$", "responder", "=", "$", "this", "->", "getResponder", "(", ")", ";", "if", "(", "$", "responder", "->", "getAcceptHandler", "(", "$", "request", ")", "===", "null", ")", "{", "throw", "ProtocolException", "::", "notAcceptable", "(", "$", "request", "->", "getHeaderLine", "(", "'Accept'", ")", ",", "$", "request", "->", "getProtocol", "(", ")", ")", ";", "}", "$", "response", "=", "$", "this", "->", "handle", "(", "$", "request", ",", "$", "response", ")", ";", "}", "catch", "(", "MiddlewareException", "$", "e", ")", "{", "// {{ log", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'中间件 %s 发生异常', $e->getMiddl", "e", "a", "r", "e(", ")),", "", "", "", "", "[", "'error'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "'errno'", "=>", "$", "e", "->", "getCode", "(", ")", "]", ")", ";", "// }}", "$", "response", "=", "$", "responder", "(", "$", "request", ",", "$", "response", ",", "new", "Payload", "(", "500", ",", "$", "e", "->", "getMessage", "(", ")", ")", ")", ";", "}", "catch", "(", "ProtocolException", "$", "e", ")", "{", "// {{ log", "$", "this", "->", "logger", "->", "error", "(", "sprintf", "(", "'处理 %s 请求发生异常', strtoupper($e-", ">", "etProtocol", "(", ")", ")", "),", "", "", "", "", "", "", "[", "'error'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "'errno'", "=>", "$", "e", "->", "getCode", "(", ")", ",", "'uri'", "=>", "$", "request", "->", "getRequestTarget", "(", ")", ",", "]", ")", ";", "// }}", "$", "response", "=", "$", "e", "->", "makeResponse", "(", "$", "request", ",", "$", "response", ",", "$", "responder", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "// {{ log", "$", "this", "->", "logger", "->", "error", "(", "'系统错误',", "", "[", "'error'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "'errno'", "=>", "$", "e", "->", "getCode", "(", ")", "]", ")", ";", "// }}", "$", "response", "=", "$", "responder", "(", "$", "request", ",", "$", "response", ",", "new", "Payload", "(", "500", ",", "$", "e", "->", "getMessage", "(", ")", ")", ")", ";", "}", "unset", "(", "$", "responder", ")", ";", "return", "$", "response", "->", "end", "(", ")", ";", "}" ]
响应 HTTP 请求 @param \One\Protocol\Contracts\Request $request @param \One\Protocol\Contracts\Response $response
[ "响应", "HTTP", "请求" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Protocols/HttpProtocol.php#L41-L111
movoin/one-swoole
src/Protocol/Protocols/HttpProtocol.php
HttpProtocol.dispatch
protected function dispatch(Request $request): array { $route = $this->router->match($request); $status = array_shift($route); if (Router::FOUND === $status) { return $route; } if (Router::METHOD_NOT_ALLOWED === $status) { throw ProtocolException::methodNotAllowed( $request->getMethod(), $request->getRequestTarget(), $request->getProtocol() ); } unset($status, $route); throw ProtocolException::notFound($request->getRequestTarget()); }
php
protected function dispatch(Request $request): array { $route = $this->router->match($request); $status = array_shift($route); if (Router::FOUND === $status) { return $route; } if (Router::METHOD_NOT_ALLOWED === $status) { throw ProtocolException::methodNotAllowed( $request->getMethod(), $request->getRequestTarget(), $request->getProtocol() ); } unset($status, $route); throw ProtocolException::notFound($request->getRequestTarget()); }
[ "protected", "function", "dispatch", "(", "Request", "$", "request", ")", ":", "array", "{", "$", "route", "=", "$", "this", "->", "router", "->", "match", "(", "$", "request", ")", ";", "$", "status", "=", "array_shift", "(", "$", "route", ")", ";", "if", "(", "Router", "::", "FOUND", "===", "$", "status", ")", "{", "return", "$", "route", ";", "}", "if", "(", "Router", "::", "METHOD_NOT_ALLOWED", "===", "$", "status", ")", "{", "throw", "ProtocolException", "::", "methodNotAllowed", "(", "$", "request", "->", "getMethod", "(", ")", ",", "$", "request", "->", "getRequestTarget", "(", ")", ",", "$", "request", "->", "getProtocol", "(", ")", ")", ";", "}", "unset", "(", "$", "status", ",", "$", "route", ")", ";", "throw", "ProtocolException", "::", "notFound", "(", "$", "request", "->", "getRequestTarget", "(", ")", ")", ";", "}" ]
解析请求 @param \One\Protocol\Contracts\Request $request @return array @throws \One\Protocol\Exceptions\ProtocolException
[ "解析请求" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Protocols/HttpProtocol.php#L121-L141
movoin/one-swoole
src/Protocol/Protocols/HttpProtocol.php
HttpProtocol.getResponder
protected function getResponder(): Responder { if ($this->responder === null) { $this->responder = new HttpResponder; } return $this->responder; }
php
protected function getResponder(): Responder { if ($this->responder === null) { $this->responder = new HttpResponder; } return $this->responder; }
[ "protected", "function", "getResponder", "(", ")", ":", "Responder", "{", "if", "(", "$", "this", "->", "responder", "===", "null", ")", "{", "$", "this", "->", "responder", "=", "new", "HttpResponder", ";", "}", "return", "$", "this", "->", "responder", ";", "}" ]
获得 Responder 对象 @return \One\Protocol\Contracts\Responder
[ "获得", "Responder", "对象" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Protocols/HttpProtocol.php#L148-L155
Eye4web/E4WZfcUserRedirectUrl
src/E4W/ZfcUser/RedirectUrl/Controller/RedirectCallback.php
RedirectCallback.getRedirectUrlFromRequest
private function getRedirectUrlFromRequest() { $request = $this->application->getRequest(); $redirect = $request->getQuery('redirect'); if ($redirect && $this->urlWhitelisted($redirect)) { return $redirect; } $redirect = $request->getPost('redirect'); if ($redirect && $this->urlWhitelisted($redirect)) { return $redirect; } return false; }
php
private function getRedirectUrlFromRequest() { $request = $this->application->getRequest(); $redirect = $request->getQuery('redirect'); if ($redirect && $this->urlWhitelisted($redirect)) { return $redirect; } $redirect = $request->getPost('redirect'); if ($redirect && $this->urlWhitelisted($redirect)) { return $redirect; } return false; }
[ "private", "function", "getRedirectUrlFromRequest", "(", ")", "{", "$", "request", "=", "$", "this", "->", "application", "->", "getRequest", "(", ")", ";", "$", "redirect", "=", "$", "request", "->", "getQuery", "(", "'redirect'", ")", ";", "if", "(", "$", "redirect", "&&", "$", "this", "->", "urlWhitelisted", "(", "$", "redirect", ")", ")", "{", "return", "$", "redirect", ";", "}", "$", "redirect", "=", "$", "request", "->", "getPost", "(", "'redirect'", ")", ";", "if", "(", "$", "redirect", "&&", "$", "this", "->", "urlWhitelisted", "(", "$", "redirect", ")", ")", "{", "return", "$", "redirect", ";", "}", "return", "false", ";", "}" ]
Return the redirect from param. First checks GET then POST @return string
[ "Return", "the", "redirect", "from", "param", ".", "First", "checks", "GET", "then", "POST" ]
train
https://github.com/Eye4web/E4WZfcUserRedirectUrl/blob/e757f4a127b9c48a4e14fbaf4fc0bf271735874e/src/E4W/ZfcUser/RedirectUrl/Controller/RedirectCallback.php#L78-L92
Eye4web/E4WZfcUserRedirectUrl
src/E4W/ZfcUser/RedirectUrl/Controller/RedirectCallback.php
RedirectCallback.urlWhitelisted
private function urlWhitelisted($url) { $always_allowed = array('localhost'); $whitelisted_domains = array_merge($this->options->getWhitelist(), $always_allowed); // Add http if missing(to satisfy parse_url()) if (strpos($url, "/") !== 0 && strpos($url, "http") !== 0) { $url = 'http://' . $url; } $domain = parse_url($url, PHP_URL_HOST); if (strpos($url, "/") === 0 || in_array($domain, $whitelisted_domains)) { return true; } foreach ($whitelisted_domains as $whitelisted_domain) { $whitelisted_domain = '.' . $whitelisted_domain; if (strpos($domain, $whitelisted_domain) === (strlen($domain) - strlen($whitelisted_domain))) { return true; } } return false; }
php
private function urlWhitelisted($url) { $always_allowed = array('localhost'); $whitelisted_domains = array_merge($this->options->getWhitelist(), $always_allowed); // Add http if missing(to satisfy parse_url()) if (strpos($url, "/") !== 0 && strpos($url, "http") !== 0) { $url = 'http://' . $url; } $domain = parse_url($url, PHP_URL_HOST); if (strpos($url, "/") === 0 || in_array($domain, $whitelisted_domains)) { return true; } foreach ($whitelisted_domains as $whitelisted_domain) { $whitelisted_domain = '.' . $whitelisted_domain; if (strpos($domain, $whitelisted_domain) === (strlen($domain) - strlen($whitelisted_domain))) { return true; } } return false; }
[ "private", "function", "urlWhitelisted", "(", "$", "url", ")", "{", "$", "always_allowed", "=", "array", "(", "'localhost'", ")", ";", "$", "whitelisted_domains", "=", "array_merge", "(", "$", "this", "->", "options", "->", "getWhitelist", "(", ")", ",", "$", "always_allowed", ")", ";", "// Add http if missing(to satisfy parse_url())", "if", "(", "strpos", "(", "$", "url", ",", "\"/\"", ")", "!==", "0", "&&", "strpos", "(", "$", "url", ",", "\"http\"", ")", "!==", "0", ")", "{", "$", "url", "=", "'http://'", ".", "$", "url", ";", "}", "$", "domain", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ";", "if", "(", "strpos", "(", "$", "url", ",", "\"/\"", ")", "===", "0", "||", "in_array", "(", "$", "domain", ",", "$", "whitelisted_domains", ")", ")", "{", "return", "true", ";", "}", "foreach", "(", "$", "whitelisted_domains", "as", "$", "whitelisted_domain", ")", "{", "$", "whitelisted_domain", "=", "'.'", ".", "$", "whitelisted_domain", ";", "if", "(", "strpos", "(", "$", "domain", ",", "$", "whitelisted_domain", ")", "===", "(", "strlen", "(", "$", "domain", ")", "-", "strlen", "(", "$", "whitelisted_domain", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if a $url is in whitelist / and localhost are always allowed partly snatched from https://gist.github.com/mjangda/1623788 @param $url @return bool
[ "Checks", "if", "a", "$url", "is", "in", "whitelist", "/", "and", "localhost", "are", "always", "allowed" ]
train
https://github.com/Eye4web/E4WZfcUserRedirectUrl/blob/e757f4a127b9c48a4e14fbaf4fc0bf271735874e/src/E4W/ZfcUser/RedirectUrl/Controller/RedirectCallback.php#L103-L126
Eye4web/E4WZfcUserRedirectUrl
src/E4W/ZfcUser/RedirectUrl/Controller/RedirectCallback.php
RedirectCallback.getRedirect
private function getRedirect($currentRoute, $redirect = false) { $useRedirect = $this->zfcUserOptions->getUseRedirectParameterIfPresent(); $urlAllowed = ($redirect && $this->urlWhitelisted($redirect)); if ($useRedirect && $urlAllowed) { return $redirect; } switch ($currentRoute) { case 'zfcuser/register': case 'zfcuser/login': $route = $this->zfcUserOptions->getLoginRedirectRoute(); return $this->router->assemble(array(), array('name' => $route)); break; case 'zfcuser/logout': $route = $this->zfcUserOptions->getLogoutRedirectRoute(); return $this->router->assemble(array(), array('name' => $route)); break; default: return $this->router->assemble(array(), array('name' => 'zfcuser')); } }
php
private function getRedirect($currentRoute, $redirect = false) { $useRedirect = $this->zfcUserOptions->getUseRedirectParameterIfPresent(); $urlAllowed = ($redirect && $this->urlWhitelisted($redirect)); if ($useRedirect && $urlAllowed) { return $redirect; } switch ($currentRoute) { case 'zfcuser/register': case 'zfcuser/login': $route = $this->zfcUserOptions->getLoginRedirectRoute(); return $this->router->assemble(array(), array('name' => $route)); break; case 'zfcuser/logout': $route = $this->zfcUserOptions->getLogoutRedirectRoute(); return $this->router->assemble(array(), array('name' => $route)); break; default: return $this->router->assemble(array(), array('name' => 'zfcuser')); } }
[ "private", "function", "getRedirect", "(", "$", "currentRoute", ",", "$", "redirect", "=", "false", ")", "{", "$", "useRedirect", "=", "$", "this", "->", "zfcUserOptions", "->", "getUseRedirectParameterIfPresent", "(", ")", ";", "$", "urlAllowed", "=", "(", "$", "redirect", "&&", "$", "this", "->", "urlWhitelisted", "(", "$", "redirect", ")", ")", ";", "if", "(", "$", "useRedirect", "&&", "$", "urlAllowed", ")", "{", "return", "$", "redirect", ";", "}", "switch", "(", "$", "currentRoute", ")", "{", "case", "'zfcuser/register'", ":", "case", "'zfcuser/login'", ":", "$", "route", "=", "$", "this", "->", "zfcUserOptions", "->", "getLoginRedirectRoute", "(", ")", ";", "return", "$", "this", "->", "router", "->", "assemble", "(", "array", "(", ")", ",", "array", "(", "'name'", "=>", "$", "route", ")", ")", ";", "break", ";", "case", "'zfcuser/logout'", ":", "$", "route", "=", "$", "this", "->", "zfcUserOptions", "->", "getLogoutRedirectRoute", "(", ")", ";", "return", "$", "this", "->", "router", "->", "assemble", "(", "array", "(", ")", ",", "array", "(", "'name'", "=>", "$", "route", ")", ")", ";", "break", ";", "default", ":", "return", "$", "this", "->", "router", "->", "assemble", "(", "array", "(", ")", ",", "array", "(", "'name'", "=>", "'zfcuser'", ")", ")", ";", "}", "}" ]
Returns the url to redirect to based on current url. If $redirect is set and the option to use redirect is set to true, it will return the $redirect url after verifying that the url is in the whitelist. @param string $currentRoute @param bool $redirect @return mixed
[ "Returns", "the", "url", "to", "redirect", "to", "based", "on", "current", "url", ".", "If", "$redirect", "is", "set", "and", "the", "option", "to", "use", "redirect", "is", "set", "to", "true", "it", "will", "return", "the", "$redirect", "url", "after", "verifying", "that", "the", "url", "is", "in", "the", "whitelist", "." ]
train
https://github.com/Eye4web/E4WZfcUserRedirectUrl/blob/e757f4a127b9c48a4e14fbaf4fc0bf271735874e/src/E4W/ZfcUser/RedirectUrl/Controller/RedirectCallback.php#L137-L158
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.factoryUser
public function factoryUser($user,$password,$name,$group,$role,$status,$email=null,$iduser=null,$extra=[]) { $this->user=$user; $this->password=$password; $this->fullName=$name; $this->group=$group; $this->role=$role; $this->status=$status; $this->email=$email; $this->iduser=$iduser; $this->extraFields=$extra; }
php
public function factoryUser($user,$password,$name,$group,$role,$status,$email=null,$iduser=null,$extra=[]) { $this->user=$user; $this->password=$password; $this->fullName=$name; $this->group=$group; $this->role=$role; $this->status=$status; $this->email=$email; $this->iduser=$iduser; $this->extraFields=$extra; }
[ "public", "function", "factoryUser", "(", "$", "user", ",", "$", "password", ",", "$", "name", ",", "$", "group", ",", "$", "role", ",", "$", "status", ",", "$", "email", "=", "null", ",", "$", "iduser", "=", "null", ",", "$", "extra", "=", "[", "]", ")", "{", "$", "this", "->", "user", "=", "$", "user", ";", "$", "this", "->", "password", "=", "$", "password", ";", "$", "this", "->", "fullName", "=", "$", "name", ";", "$", "this", "->", "group", "=", "$", "group", ";", "$", "this", "->", "role", "=", "$", "role", ";", "$", "this", "->", "status", "=", "$", "status", ";", "$", "this", "->", "email", "=", "$", "email", ";", "$", "this", "->", "iduser", "=", "$", "iduser", ";", "$", "this", "->", "extraFields", "=", "$", "extra", ";", "}" ]
It sets the current user. @param string $user @param string $password @param string $name @param string[] $group @param string $role @param int $status 0=disabled,1=enabled @param string $email @param string $iduser @param array $extra
[ "It", "sets", "the", "current", "user", "." ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L112-L122
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.genUID
private function genUID() { // HTTP_CLIENT_IP and HTTP_X_FORWARDE‌​D_FOR can be forged. // REMOTE_ADDR is the same for all clients connected to a proxy. $ip=@$_SERVER['HTTP_CLIENT_IP'].@$_SERVER['HTTP_X_FORWARDE‌​D_FOR'].@$_SERVER['REMOTE_ADDR']; // HTTP_USER_AGENT could be forge. $browser=@$_SERVER['HTTP_USER_AGENT']; return md5($ip.$browser); }
php
private function genUID() { // HTTP_CLIENT_IP and HTTP_X_FORWARDE‌​D_FOR can be forged. // REMOTE_ADDR is the same for all clients connected to a proxy. $ip=@$_SERVER['HTTP_CLIENT_IP'].@$_SERVER['HTTP_X_FORWARDE‌​D_FOR'].@$_SERVER['REMOTE_ADDR']; // HTTP_USER_AGENT could be forge. $browser=@$_SERVER['HTTP_USER_AGENT']; return md5($ip.$browser); }
[ "private", "function", "genUID", "(", ")", "{", "// HTTP_CLIENT_IP and HTTP_X_FORWARDE‌​D_FOR can be forged.", "// REMOTE_ADDR is the same for all clients connected to a proxy.", "$", "ip", "=", "@", "$", "_SERVER", "[", "'HTTP_CLIENT_IP'", "]", ".", "@", "$", "_SERVER", "[", "'HTTP_X_FORWARDE‌​D_FOR'].@$", "_", "S", "E", "R", "VER['RE", "M", "OTE_ADDR'];", "", "", "// HTTP_USER_AGENT could be forge.", "$", "browser", "=", "@", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ";", "return", "md5", "(", "$", "ip", ".", "$", "browser", ")", ";", "}" ]
It generates an unique UID between the current IP and the user agent. @return string
[ "It", "generates", "an", "unique", "UID", "between", "the", "current", "IP", "and", "the", "user", "agent", "." ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L128-L135
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.serialize
public function serialize() { $r=['user'=>$this->user ,'name'=>$this->fullName ,'uid'=>$this->uid ,'group'=>$this->group ,'role'=>$this->role]; /* optional fields */ if ($this->email!==null) $r['email']=$this->email; if ($this->iduser!==null) $r['iduser']=$this->iduser; $r['extrafields']=$this->extraFields; return $r; }
php
public function serialize() { $r=['user'=>$this->user ,'name'=>$this->fullName ,'uid'=>$this->uid ,'group'=>$this->group ,'role'=>$this->role]; /* optional fields */ if ($this->email!==null) $r['email']=$this->email; if ($this->iduser!==null) $r['iduser']=$this->iduser; $r['extrafields']=$this->extraFields; return $r; }
[ "public", "function", "serialize", "(", ")", "{", "$", "r", "=", "[", "'user'", "=>", "$", "this", "->", "user", ",", "'name'", "=>", "$", "this", "->", "fullName", ",", "'uid'", "=>", "$", "this", "->", "uid", ",", "'group'", "=>", "$", "this", "->", "group", ",", "'role'", "=>", "$", "this", "->", "role", "]", ";", "/* optional fields */", "if", "(", "$", "this", "->", "email", "!==", "null", ")", "$", "r", "[", "'email'", "]", "=", "$", "this", "->", "email", ";", "if", "(", "$", "this", "->", "iduser", "!==", "null", ")", "$", "r", "[", "'iduser'", "]", "=", "$", "this", "->", "iduser", ";", "$", "r", "[", "'extrafields'", "]", "=", "$", "this", "->", "extraFields", ";", "return", "$", "r", ";", "}" ]
Returns an associative array with the current user @return array=['user'='','name'=>'','uid'=>'','group'=>[],'role'=>'' ,'email'=>'','iduser'=>'','extrafields'=>[]]
[ "Returns", "an", "associative", "array", "with", "the", "current", "user" ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L142-L155
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.deserialize
public function deserialize($array) { $this->user=@$array['user']; $this->fullName=@$array['name']; $this->uid=@$array['uid']; $this->group=@$array['group']; $this->role=@$array['role']; $this->status=@$array['status']; /* optional fields */ $this->email=@$array['email']; $this->iduser=@$array['iduser']; $this->extraFields=@$array['extrafields']; }
php
public function deserialize($array) { $this->user=@$array['user']; $this->fullName=@$array['name']; $this->uid=@$array['uid']; $this->group=@$array['group']; $this->role=@$array['role']; $this->status=@$array['status']; /* optional fields */ $this->email=@$array['email']; $this->iduser=@$array['iduser']; $this->extraFields=@$array['extrafields']; }
[ "public", "function", "deserialize", "(", "$", "array", ")", "{", "$", "this", "->", "user", "=", "@", "$", "array", "[", "'user'", "]", ";", "$", "this", "->", "fullName", "=", "@", "$", "array", "[", "'name'", "]", ";", "$", "this", "->", "uid", "=", "@", "$", "array", "[", "'uid'", "]", ";", "$", "this", "->", "group", "=", "@", "$", "array", "[", "'group'", "]", ";", "$", "this", "->", "role", "=", "@", "$", "array", "[", "'role'", "]", ";", "$", "this", "->", "status", "=", "@", "$", "array", "[", "'status'", "]", ";", "/* optional fields */", "$", "this", "->", "email", "=", "@", "$", "array", "[", "'email'", "]", ";", "$", "this", "->", "iduser", "=", "@", "$", "array", "[", "'iduser'", "]", ";", "$", "this", "->", "extraFields", "=", "@", "$", "array", "[", "'extrafields'", "]", ";", "}" ]
Set the current user by using an associative array @param $array=['user'=>'','name'=>'','uid'=>'','group'=>[],role=>'' ,'status'=>0,'email'=>'','iduser'=>0,'extrafields'=>[]]
[ "Set", "the", "current", "user", "by", "using", "an", "associative", "array" ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L177-L188
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.login
public function login($user,$password,$storeCookie=false) { $this->user=$user; $this->password=$this->encrypt($password); $this->uid=$this->genUID(); //$this->other=$other; if (call_user_func($this->loginFn,$this)) { $this->fixSession($storeCookie && $this->useCookie); return true; } else { @session_destroy(); @session_write_close(); $this->isLogged=false; return false; } }
php
public function login($user,$password,$storeCookie=false) { $this->user=$user; $this->password=$this->encrypt($password); $this->uid=$this->genUID(); //$this->other=$other; if (call_user_func($this->loginFn,$this)) { $this->fixSession($storeCookie && $this->useCookie); return true; } else { @session_destroy(); @session_write_close(); $this->isLogged=false; return false; } }
[ "public", "function", "login", "(", "$", "user", ",", "$", "password", ",", "$", "storeCookie", "=", "false", ")", "{", "$", "this", "->", "user", "=", "$", "user", ";", "$", "this", "->", "password", "=", "$", "this", "->", "encrypt", "(", "$", "password", ")", ";", "$", "this", "->", "uid", "=", "$", "this", "->", "genUID", "(", ")", ";", "//$this->other=$other;", "if", "(", "call_user_func", "(", "$", "this", "->", "loginFn", ",", "$", "this", ")", ")", "{", "$", "this", "->", "fixSession", "(", "$", "storeCookie", "&&", "$", "this", "->", "useCookie", ")", ";", "return", "true", ";", "}", "else", "{", "@", "session_destroy", "(", ")", ";", "@", "session_write_close", "(", ")", ";", "$", "this", "->", "isLogged", "=", "false", ";", "return", "false", ";", "}", "}" ]
It's used when the user log with an user and password. So it must be used only in the login screen. After that, the user is stored in the session. @param string $user @param string $password Not encrypted password @param bool $storeCookie @return bool
[ "It", "s", "used", "when", "the", "user", "log", "with", "an", "user", "and", "password", ".", "So", "it", "must", "be", "used", "only", "in", "the", "login", "screen", ".", "After", "that", "the", "user", "is", "stored", "in", "the", "session", "." ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L262-L276
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.logout
public function logout() { $this->user=""; $this->password=""; $this->isLogged=false; if ($this->useCookie) { unset($_COOKIE['phpcookiesess']); setcookie('phpcookiesess', null, -1, '/'); } @session_destroy(); @session_write_close(); }
php
public function logout() { $this->user=""; $this->password=""; $this->isLogged=false; if ($this->useCookie) { unset($_COOKIE['phpcookiesess']); setcookie('phpcookiesess', null, -1, '/'); } @session_destroy(); @session_write_close(); }
[ "public", "function", "logout", "(", ")", "{", "$", "this", "->", "user", "=", "\"\"", ";", "$", "this", "->", "password", "=", "\"\"", ";", "$", "this", "->", "isLogged", "=", "false", ";", "if", "(", "$", "this", "->", "useCookie", ")", "{", "unset", "(", "$", "_COOKIE", "[", "'phpcookiesess'", "]", ")", ";", "setcookie", "(", "'phpcookiesess'", ",", "null", ",", "-", "1", ",", "'/'", ")", ";", "}", "@", "session_destroy", "(", ")", ";", "@", "session_write_close", "(", ")", ";", "}" ]
Logout and the session is destroyed. It doesn't redirect to the home page.
[ "Logout", "and", "the", "session", "is", "destroyed", ".", "It", "doesn", "t", "redirect", "to", "the", "home", "page", "." ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L289-L299
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.isLogged
public function isLogged() { if (!$this->isLogged) return false; if ($this->genUID()!=$this->uid) return false; // uid doesn't correspond. return true; }
php
public function isLogged() { if (!$this->isLogged) return false; if ($this->genUID()!=$this->uid) return false; // uid doesn't correspond. return true; }
[ "public", "function", "isLogged", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isLogged", ")", "return", "false", ";", "if", "(", "$", "this", "->", "genUID", "(", ")", "!=", "$", "this", "->", "uid", ")", "return", "false", ";", "// uid doesn't correspond.", "return", "true", ";", "}" ]
Returns true if the user is logged. False if not. It also returns false if the UID doesn't correspond. @return bool
[ "Returns", "true", "if", "the", "user", "is", "logged", ".", "False", "if", "not", ".", "It", "also", "returns", "false", "if", "the", "UID", "doesn", "t", "correspond", "." ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L305-L309
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.isAllowed
public function isAllowed($where="",$when="",$id="") { if ($this->genUID()!=$this->uid) return false; // uid doesn't correspond. // module1,edit,20 // allowed to edit module1 when id 1 return call_user_func($this->isAllowedFn,$this,$where,$when,$id); }
php
public function isAllowed($where="",$when="",$id="") { if ($this->genUID()!=$this->uid) return false; // uid doesn't correspond. // module1,edit,20 // allowed to edit module1 when id 1 return call_user_func($this->isAllowedFn,$this,$where,$when,$id); }
[ "public", "function", "isAllowed", "(", "$", "where", "=", "\"\"", ",", "$", "when", "=", "\"\"", ",", "$", "id", "=", "\"\"", ")", "{", "if", "(", "$", "this", "->", "genUID", "(", ")", "!=", "$", "this", "->", "uid", ")", "return", "false", ";", "// uid doesn't correspond.", "// module1,edit,20", "// allowed to edit module1 when id 1", "return", "call_user_func", "(", "$", "this", "->", "isAllowedFn", ",", "$", "this", ",", "$", "where", ",", "$", "when", ",", "$", "id", ")", ";", "}" ]
Returns true if the user is allowed to do an operation $when on $where with $id. @param string $where It could indicates a module, instance of type of object. @param string $when It could be an action or verb (edit,list,print) @param string $id It could be used to identify an element. Sometimes permissions are tied with a specific element. @return boolean It could be used to identify an element. Sometimes permissions are tied with a specific element.
[ "Returns", "true", "if", "the", "user", "is", "allowed", "to", "do", "an", "operation", "$when", "on", "$where", "with", "$id", "." ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L317-L322
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.getPermission
public function getPermission($where="",$when="",$id="") { if ($this->genUID()!=$this->uid) return false; // uid doesn't correspond. // module1,edit,20 // allowed to edit module1 when id 1 return call_user_func($this->getPermissionFn,$this,$where,$when,$id); }
php
public function getPermission($where="",$when="",$id="") { if ($this->genUID()!=$this->uid) return false; // uid doesn't correspond. // module1,edit,20 // allowed to edit module1 when id 1 return call_user_func($this->getPermissionFn,$this,$where,$when,$id); }
[ "public", "function", "getPermission", "(", "$", "where", "=", "\"\"", ",", "$", "when", "=", "\"\"", ",", "$", "id", "=", "\"\"", ")", "{", "if", "(", "$", "this", "->", "genUID", "(", ")", "!=", "$", "this", "->", "uid", ")", "return", "false", ";", "// uid doesn't correspond.", "// module1,edit,20", "// allowed to edit module1 when id 1", "return", "call_user_func", "(", "$", "this", "->", "getPermissionFn", ",", "$", "this", ",", "$", "where", ",", "$", "when", ",", "$", "id", ")", ";", "}" ]
Returns a nivel of permission SecurityOne::NOTALLOWED|READ|WRITE|READWRITE|ADMIN @param string $where It could indicates a module, instance of type of object. @param string $when It could be an action or verb (edit,list,print) @param string $id It could be used to identify an element. Sometimes permissions are tied with a specific element. @return int SecurityOne::NOTALLOWED|READ|WRITE|READWRITE|ADMIN
[ "Returns", "a", "nivel", "of", "permission", "SecurityOne", "::", "NOTALLOWED|READ|WRITE|READWRITE|ADMIN" ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L331-L336
EFTEC/SecurityOne
lib/SecurityOne.php
SecurityOne.getCurrent
public function getCurrent($closeSession=false) { if (session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE) { $b=@session_start(); if (!$b) return false; // session is not open and I am unable to open it } $obj=@$_SESSION['_user']; if ($obj!==null) $this->deserialize($obj); if ($closeSession) @session_write_close(); return $obj; }
php
public function getCurrent($closeSession=false) { if (session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE) { $b=@session_start(); if (!$b) return false; // session is not open and I am unable to open it } $obj=@$_SESSION['_user']; if ($obj!==null) $this->deserialize($obj); if ($closeSession) @session_write_close(); return $obj; }
[ "public", "function", "getCurrent", "(", "$", "closeSession", "=", "false", ")", "{", "if", "(", "session_status", "(", ")", "===", "PHP_SESSION_ACTIVE", "?", "TRUE", ":", "FALSE", ")", "{", "$", "b", "=", "@", "session_start", "(", ")", ";", "if", "(", "!", "$", "b", ")", "return", "false", ";", "// session is not open and I am unable to open it", "}", "$", "obj", "=", "@", "$", "_SESSION", "[", "'_user'", "]", ";", "if", "(", "$", "obj", "!==", "null", ")", "$", "this", "->", "deserialize", "(", "$", "obj", ")", ";", "if", "(", "$", "closeSession", ")", "@", "session_write_close", "(", ")", ";", "return", "$", "obj", ";", "}" ]
Load current user. It returns an array @param bool $closeSession @return bool
[ "Load", "current", "user", ".", "It", "returns", "an", "array" ]
train
https://github.com/EFTEC/SecurityOne/blob/509412cd8d71dcadce763efa4655c6dfe2dffe13/lib/SecurityOne.php#L343-L354
drpdigital/json-api-parser
src/ResolvedCollection.php
ResolvedCollection.getByClass
public function getByClass($className) { $types = array_unique(Arr::wrap(Arr::get($this->classMapping, $className, []))); $resolved = array_map([$this, 'get'], $types); return $this->firstOrAll(Arr::collapse($resolved)); }
php
public function getByClass($className) { $types = array_unique(Arr::wrap(Arr::get($this->classMapping, $className, []))); $resolved = array_map([$this, 'get'], $types); return $this->firstOrAll(Arr::collapse($resolved)); }
[ "public", "function", "getByClass", "(", "$", "className", ")", "{", "$", "types", "=", "array_unique", "(", "Arr", "::", "wrap", "(", "Arr", "::", "get", "(", "$", "this", "->", "classMapping", ",", "$", "className", ",", "[", "]", ")", ")", ")", ";", "$", "resolved", "=", "array_map", "(", "[", "$", "this", ",", "'get'", "]", ",", "$", "types", ")", ";", "return", "$", "this", "->", "firstOrAll", "(", "Arr", "::", "collapse", "(", "$", "resolved", ")", ")", ";", "}" ]
Get the resolved resource by type. This will return an array of that resource if multiple resources of that type were resolved. If only 1 item in the array then that 1 item will be returned instead. @param string $className @return mixed|array
[ "Get", "the", "resolved", "resource", "by", "type", "." ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/ResolvedCollection.php#L23-L29
drpdigital/json-api-parser
src/ResolvedCollection.php
ResolvedCollection.add
public function add($key, $value) { parent::add($key, $value); if (is_object($value) === false) { return; } $this->classMapping[get_class($value)][] = $key; }
php
public function add($key, $value) { parent::add($key, $value); if (is_object($value) === false) { return; } $this->classMapping[get_class($value)][] = $key; }
[ "public", "function", "add", "(", "$", "key", ",", "$", "value", ")", "{", "parent", "::", "add", "(", "$", "key", ",", "$", "value", ")", ";", "if", "(", "is_object", "(", "$", "value", ")", "===", "false", ")", "{", "return", ";", "}", "$", "this", "->", "classMapping", "[", "get_class", "(", "$", "value", ")", "]", "[", "]", "=", "$", "key", ";", "}" ]
Add resolved resource to the collection. @param string $key @param mixed $value
[ "Add", "resolved", "resource", "to", "the", "collection", "." ]
train
https://github.com/drpdigital/json-api-parser/blob/b1ceefc0c19ec326129126253114c121e97ca943/src/ResolvedCollection.php#L37-L46
vardius/list-bundle
ListView/ListView.php
ListView.render
public function render(ListDataEvent $event, bool $ui = true):string { $data = $this->getData($event, !$ui); $params = array_merge( $data, [ 'columns' => $this->getColumns(), 'actions' => $this->getActions(), 'ui' => $ui, ] ); return $this->container->get('vardius_list.view.renderer')->renderView($this->getView(), $params); }
php
public function render(ListDataEvent $event, bool $ui = true):string { $data = $this->getData($event, !$ui); $params = array_merge( $data, [ 'columns' => $this->getColumns(), 'actions' => $this->getActions(), 'ui' => $ui, ] ); return $this->container->get('vardius_list.view.renderer')->renderView($this->getView(), $params); }
[ "public", "function", "render", "(", "ListDataEvent", "$", "event", ",", "bool", "$", "ui", "=", "true", ")", ":", "string", "{", "$", "data", "=", "$", "this", "->", "getData", "(", "$", "event", ",", "!", "$", "ui", ")", ";", "$", "params", "=", "array_merge", "(", "$", "data", ",", "[", "'columns'", "=>", "$", "this", "->", "getColumns", "(", ")", ",", "'actions'", "=>", "$", "this", "->", "getActions", "(", ")", ",", "'ui'", "=>", "$", "ui", ",", "]", ")", ";", "return", "$", "this", "->", "container", "->", "get", "(", "'vardius_list.view.renderer'", ")", "->", "renderView", "(", "$", "this", "->", "getView", "(", ")", ",", "$", "params", ")", ";", "}" ]
Render list data The ui parameter tells us if user interface is enable (buttons, links etc.) @param ListDataEvent $event @param bool $ui @return string
[ "Render", "list", "data", "The", "ui", "parameter", "tells", "us", "if", "user", "interface", "is", "enable", "(", "buttons", "links", "etc", ".", ")" ]
train
https://github.com/vardius/list-bundle/blob/70d3079ce22eed7dad7c467fee532aa2f18c68c9/ListView/ListView.php#L181-L194
alexpts/psr15-middlewares
src/StaticHeaderDefault.php
StaticHeaderDefault.withStaticHeaders
protected function withStaticHeaders(ResponseInterface $response, array $headers): ResponseInterface { foreach ($headers as $name => $header) { if (!$response->hasHeader($name)) { $response = $response->withHeader($name, $header); } } return $response; }
php
protected function withStaticHeaders(ResponseInterface $response, array $headers): ResponseInterface { foreach ($headers as $name => $header) { if (!$response->hasHeader($name)) { $response = $response->withHeader($name, $header); } } return $response; }
[ "protected", "function", "withStaticHeaders", "(", "ResponseInterface", "$", "response", ",", "array", "$", "headers", ")", ":", "ResponseInterface", "{", "foreach", "(", "$", "headers", "as", "$", "name", "=>", "$", "header", ")", "{", "if", "(", "!", "$", "response", "->", "hasHeader", "(", "$", "name", ")", ")", "{", "$", "response", "=", "$", "response", "->", "withHeader", "(", "$", "name", ",", "$", "header", ")", ";", "}", "}", "return", "$", "response", ";", "}" ]
@param ResponseInterface $response @param array $headers @return ResponseInterface @throws \InvalidArgumentException
[ "@param", "ResponseInterface", "$response", "@param", "array", "$headers" ]
train
https://github.com/alexpts/psr15-middlewares/blob/bff2887d5af01c54d9288fd19c20f0f593b69358/src/StaticHeaderDefault.php#L18-L27
comelyio/comely
src/Comely/Kernel/Comely.php
Comely.PascalCase
public static function PascalCase(string $name): string { // Return an empty String if input is an empty String if (empty($name)) { return ""; } $words = preg_split("/[^a-zA-Z0-9]+/", strtolower($name), 0, PREG_SPLIT_NO_EMPTY); return implode("", array_map(function ($word) { return ucfirst($word); }, $words)); }
php
public static function PascalCase(string $name): string { // Return an empty String if input is an empty String if (empty($name)) { return ""; } $words = preg_split("/[^a-zA-Z0-9]+/", strtolower($name), 0, PREG_SPLIT_NO_EMPTY); return implode("", array_map(function ($word) { return ucfirst($word); }, $words)); }
[ "public", "static", "function", "PascalCase", "(", "string", "$", "name", ")", ":", "string", "{", "// Return an empty String if input is an empty String", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "return", "\"\"", ";", "}", "$", "words", "=", "preg_split", "(", "\"/[^a-zA-Z0-9]+/\"", ",", "strtolower", "(", "$", "name", ")", ",", "0", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "return", "implode", "(", "\"\"", ",", "array_map", "(", "function", "(", "$", "word", ")", "{", "return", "ucfirst", "(", "$", "word", ")", ";", "}", ",", "$", "words", ")", ")", ";", "}" ]
Converts given string (i.e. snake_case) to PascalCase @param string $name @return string
[ "Converts", "given", "string", "(", "i", ".", "e", ".", "snake_case", ")", "to", "PascalCase" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/Kernel/Comely.php#L50-L61
comelyio/comely
src/Comely/Kernel/Comely.php
Comely.camelCase
public static function camelCase(string $name): string { // Return an empty String if input is an empty String if (empty($name)) { return ""; } // Convert to PascalCase first and then convert PascalCase to camelCase $pascal = self::pascalCase($name); return sprintf("%s%s", strtolower($pascal[0]), substr($pascal, 1)); }
php
public static function camelCase(string $name): string { // Return an empty String if input is an empty String if (empty($name)) { return ""; } // Convert to PascalCase first and then convert PascalCase to camelCase $pascal = self::pascalCase($name); return sprintf("%s%s", strtolower($pascal[0]), substr($pascal, 1)); }
[ "public", "static", "function", "camelCase", "(", "string", "$", "name", ")", ":", "string", "{", "// Return an empty String if input is an empty String", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "return", "\"\"", ";", "}", "// Convert to PascalCase first and then convert PascalCase to camelCase", "$", "pascal", "=", "self", "::", "pascalCase", "(", "$", "name", ")", ";", "return", "sprintf", "(", "\"%s%s\"", ",", "strtolower", "(", "$", "pascal", "[", "0", "]", ")", ",", "substr", "(", "$", "pascal", ",", "1", ")", ")", ";", "}" ]
Converts given string (i.e. snake_case) to camelCase @param string $name @return string
[ "Converts", "given", "string", "(", "i", ".", "e", ".", "snake_case", ")", "to", "camelCase" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/Kernel/Comely.php#L69-L79
comelyio/comely
src/Comely/Kernel/Comely.php
Comely.snake_case
public static function snake_case(string $name): string { // Return an empty String if input is an empty String if (empty($name)) { return ""; } // Convert PascalCase word to camelCase $name = sprintf("%s%s", strtolower($name[0]), substr($name, 1)); // Split words $words = preg_split("/([A-Z0-9]+)/", $name, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $wordsCount = count($words); $snake = $words[0]; // Iterate through words for ($i = 1; $i < $wordsCount; $i++) { if ($i % 2 != 0) { // Add an underscore on an odd $i $snake .= "_"; } // Add word to snake $snake .= $words[$i]; } // Return lowercase snake return strtolower($snake); }
php
public static function snake_case(string $name): string { // Return an empty String if input is an empty String if (empty($name)) { return ""; } // Convert PascalCase word to camelCase $name = sprintf("%s%s", strtolower($name[0]), substr($name, 1)); // Split words $words = preg_split("/([A-Z0-9]+)/", $name, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $wordsCount = count($words); $snake = $words[0]; // Iterate through words for ($i = 1; $i < $wordsCount; $i++) { if ($i % 2 != 0) { // Add an underscore on an odd $i $snake .= "_"; } // Add word to snake $snake .= $words[$i]; } // Return lowercase snake return strtolower($snake); }
[ "public", "static", "function", "snake_case", "(", "string", "$", "name", ")", ":", "string", "{", "// Return an empty String if input is an empty String", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "return", "\"\"", ";", "}", "// Convert PascalCase word to camelCase", "$", "name", "=", "sprintf", "(", "\"%s%s\"", ",", "strtolower", "(", "$", "name", "[", "0", "]", ")", ",", "substr", "(", "$", "name", ",", "1", ")", ")", ";", "// Split words", "$", "words", "=", "preg_split", "(", "\"/([A-Z0-9]+)/\"", ",", "$", "name", ",", "0", ",", "PREG_SPLIT_NO_EMPTY", "|", "PREG_SPLIT_DELIM_CAPTURE", ")", ";", "$", "wordsCount", "=", "count", "(", "$", "words", ")", ";", "$", "snake", "=", "$", "words", "[", "0", "]", ";", "// Iterate through words", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "$", "wordsCount", ";", "$", "i", "++", ")", "{", "if", "(", "$", "i", "%", "2", "!=", "0", ")", "{", "// Add an underscore on an odd $i", "$", "snake", ".=", "\"_\"", ";", "}", "// Add word to snake", "$", "snake", ".=", "$", "words", "[", "$", "i", "]", ";", "}", "// Return lowercase snake", "return", "strtolower", "(", "$", "snake", ")", ";", "}" ]
Converts given string (i.e. PascalCase or camelCase) to snake_case @param string $name @return string
[ "Converts", "given", "string", "(", "i", ".", "e", ".", "PascalCase", "or", "camelCase", ")", "to", "snake_case" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/Kernel/Comely.php#L87-L115
opis/storages
session/Database.php
Database.read
public function read($id) { try { $result = $this->db->from($this->table) ->where($this->columns['id'])->eq($id) ->column($this->columns['data']); return $result === false ? '' : $result; } catch (PDOException $e) { return ''; } }
php
public function read($id) { try { $result = $this->db->from($this->table) ->where($this->columns['id'])->eq($id) ->column($this->columns['data']); return $result === false ? '' : $result; } catch (PDOException $e) { return ''; } }
[ "public", "function", "read", "(", "$", "id", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "db", "->", "from", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "columns", "[", "'id'", "]", ")", "->", "eq", "(", "$", "id", ")", "->", "column", "(", "$", "this", "->", "columns", "[", "'data'", "]", ")", ";", "return", "$", "result", "===", "false", "?", "''", ":", "$", "result", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "return", "''", ";", "}", "}" ]
Returns session data. @param string $id Session id @return string
[ "Returns", "session", "data", "." ]
train
https://github.com/opis/storages/blob/548dd631239c7cd75c04d17878b677e646540fde/session/Database.php#L111-L122
opis/storages
session/Database.php
Database.write
public function write($id, $data) { try { $result = $this->db->from($this->table) ->where($this->columns['id'])->eq($id) ->count(); if ($result != 0) { return (bool) $this->db->update($this->table) ->where($this->columns['id'])->eq($id) ->set(array( $this->columns['data'] => $data, $this->columns['expires'] => time() + $this->maxLifetime, )); } else { return $this->db->insert(array( $this->columns['id'] => $id, $this->columns['data'] => $data, $this->columns['expires'] => time() + $this->maxLifetime )) ->into($this->table); } } catch (PDOException $e) { return false; } }
php
public function write($id, $data) { try { $result = $this->db->from($this->table) ->where($this->columns['id'])->eq($id) ->count(); if ($result != 0) { return (bool) $this->db->update($this->table) ->where($this->columns['id'])->eq($id) ->set(array( $this->columns['data'] => $data, $this->columns['expires'] => time() + $this->maxLifetime, )); } else { return $this->db->insert(array( $this->columns['id'] => $id, $this->columns['data'] => $data, $this->columns['expires'] => time() + $this->maxLifetime )) ->into($this->table); } } catch (PDOException $e) { return false; } }
[ "public", "function", "write", "(", "$", "id", ",", "$", "data", ")", "{", "try", "{", "$", "result", "=", "$", "this", "->", "db", "->", "from", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "columns", "[", "'id'", "]", ")", "->", "eq", "(", "$", "id", ")", "->", "count", "(", ")", ";", "if", "(", "$", "result", "!=", "0", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "db", "->", "update", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "columns", "[", "'id'", "]", ")", "->", "eq", "(", "$", "id", ")", "->", "set", "(", "array", "(", "$", "this", "->", "columns", "[", "'data'", "]", "=>", "$", "data", ",", "$", "this", "->", "columns", "[", "'expires'", "]", "=>", "time", "(", ")", "+", "$", "this", "->", "maxLifetime", ",", ")", ")", ";", "}", "else", "{", "return", "$", "this", "->", "db", "->", "insert", "(", "array", "(", "$", "this", "->", "columns", "[", "'id'", "]", "=>", "$", "id", ",", "$", "this", "->", "columns", "[", "'data'", "]", "=>", "$", "data", ",", "$", "this", "->", "columns", "[", "'expires'", "]", "=>", "time", "(", ")", "+", "$", "this", "->", "maxLifetime", ")", ")", "->", "into", "(", "$", "this", "->", "table", ")", ";", "}", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Writes data to the session. @param string $id Session id @param string $data Session data @return boolean
[ "Writes", "data", "to", "the", "session", "." ]
train
https://github.com/opis/storages/blob/548dd631239c7cd75c04d17878b677e646540fde/session/Database.php#L132-L157
opis/storages
session/Database.php
Database.destroy
public function destroy($id) { try { return (bool) $this->db->from($this->table) ->where($this->columns['id'])->eq($id) ->delete(); } catch (PDOException $e) { return false; } }
php
public function destroy($id) { try { return (bool) $this->db->from($this->table) ->where($this->columns['id'])->eq($id) ->delete(); } catch (PDOException $e) { return false; } }
[ "public", "function", "destroy", "(", "$", "id", ")", "{", "try", "{", "return", "(", "bool", ")", "$", "this", "->", "db", "->", "from", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "columns", "[", "'id'", "]", ")", "->", "eq", "(", "$", "id", ")", "->", "delete", "(", ")", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Destroys the session. @param string $id Session id @return boolean
[ "Destroys", "the", "session", "." ]
train
https://github.com/opis/storages/blob/548dd631239c7cd75c04d17878b677e646540fde/session/Database.php#L165-L174
opis/storages
session/Database.php
Database.gc
public function gc($maxLifetime) { try { return (bool) $this->db->from($this->table) ->where($this->columns['expires'])->lt(time()) ->delete(); } catch (PDOException $e) { return false; } }
php
public function gc($maxLifetime) { try { return (bool) $this->db->from($this->table) ->where($this->columns['expires'])->lt(time()) ->delete(); } catch (PDOException $e) { return false; } }
[ "public", "function", "gc", "(", "$", "maxLifetime", ")", "{", "try", "{", "return", "(", "bool", ")", "$", "this", "->", "db", "->", "from", "(", "$", "this", "->", "table", ")", "->", "where", "(", "$", "this", "->", "columns", "[", "'expires'", "]", ")", "->", "lt", "(", "time", "(", ")", ")", "->", "delete", "(", ")", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Garbage collector. @param int $maxLifetime Lifetime in secods @return boolean
[ "Garbage", "collector", "." ]
train
https://github.com/opis/storages/blob/548dd631239c7cd75c04d17878b677e646540fde/session/Database.php#L183-L192
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/TransfersEngine.php
TransfersEngine.add
public function add($url, $parentID = 0, $extract = \false, $callbackUrl = '') { $data = [ 'url' => $url, 'save_parent_id' => $parentID, 'extract' => ($extract ? 'True' : 'False'), 'callback_url' => $callbackUrl ]; return $this->post('transfers/add', $data, \false); }
php
public function add($url, $parentID = 0, $extract = \false, $callbackUrl = '') { $data = [ 'url' => $url, 'save_parent_id' => $parentID, 'extract' => ($extract ? 'True' : 'False'), 'callback_url' => $callbackUrl ]; return $this->post('transfers/add', $data, \false); }
[ "public", "function", "add", "(", "$", "url", ",", "$", "parentID", "=", "0", ",", "$", "extract", "=", "\\", "false", ",", "$", "callbackUrl", "=", "''", ")", "{", "$", "data", "=", "[", "'url'", "=>", "$", "url", ",", "'save_parent_id'", "=>", "$", "parentID", ",", "'extract'", "=>", "(", "$", "extract", "?", "'True'", ":", "'False'", ")", ",", "'callback_url'", "=>", "$", "callbackUrl", "]", ";", "return", "$", "this", "->", "post", "(", "'transfers/add'", ",", "$", "data", ",", "\\", "false", ")", ";", "}" ]
Adds a new transfer to the queue. @param string $url URL of the file/torrent @param int $parentID ID of the target folder. 0 = root @param bool $extract Extract file when download complete @param string $callbackUrl put.io will POST the metadata of the file to the given URL when file is ready. @return array
[ "Adds", "a", "new", "transfer", "to", "the", "queue", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/TransfersEngine.php#L44-L54
nicoSWD/put.io-api-v2
src/PutIO/Engines/PutIO/TransfersEngine.php
TransfersEngine.cancel
public function cancel($transferIDs) { if (is_array($transferIDs)) { $transferIDs = implode(',', $transferIDs); } $data = [ 'transfer_ids' => $transferIDs ]; return $this->post('transfers/cancel', $data, \true); }
php
public function cancel($transferIDs) { if (is_array($transferIDs)) { $transferIDs = implode(',', $transferIDs); } $data = [ 'transfer_ids' => $transferIDs ]; return $this->post('transfers/cancel', $data, \true); }
[ "public", "function", "cancel", "(", "$", "transferIDs", ")", "{", "if", "(", "is_array", "(", "$", "transferIDs", ")", ")", "{", "$", "transferIDs", "=", "implode", "(", "','", ",", "$", "transferIDs", ")", ";", "}", "$", "data", "=", "[", "'transfer_ids'", "=>", "$", "transferIDs", "]", ";", "return", "$", "this", "->", "post", "(", "'transfers/cancel'", ",", "$", "data", ",", "\\", "true", ")", ";", "}" ]
Cancels given transfers. @param int|array $transferIDs Transfer IDs you want to cancel. @return boolean
[ "Cancels", "given", "transfers", "." ]
train
https://github.com/nicoSWD/put.io-api-v2/blob/d91bedd91ea75793512a921bfd9aa83e86a6f0a7/src/PutIO/Engines/PutIO/TransfersEngine.php#L88-L99
jan-dolata/crude-crud
src/Engine/Traits/WithFileTrait.php
WithFileTrait.uploadFilesById
public function uploadFilesById($id, $files) { $crudeName = $this->getCalledClassName(); $model = $this->getById($id); $fileAttrName = $this->getFileAttrName(); $model = (new CrudeFiles)->upload($model, $crudeName, $files, $fileAttrName); return $this->updateById($id, [$fileAttrName => $model->files]); }
php
public function uploadFilesById($id, $files) { $crudeName = $this->getCalledClassName(); $model = $this->getById($id); $fileAttrName = $this->getFileAttrName(); $model = (new CrudeFiles)->upload($model, $crudeName, $files, $fileAttrName); return $this->updateById($id, [$fileAttrName => $model->files]); }
[ "public", "function", "uploadFilesById", "(", "$", "id", ",", "$", "files", ")", "{", "$", "crudeName", "=", "$", "this", "->", "getCalledClassName", "(", ")", ";", "$", "model", "=", "$", "this", "->", "getById", "(", "$", "id", ")", ";", "$", "fileAttrName", "=", "$", "this", "->", "getFileAttrName", "(", ")", ";", "$", "model", "=", "(", "new", "CrudeFiles", ")", "->", "upload", "(", "$", "model", ",", "$", "crudeName", ",", "$", "files", ",", "$", "fileAttrName", ")", ";", "return", "$", "this", "->", "updateById", "(", "$", "id", ",", "[", "$", "fileAttrName", "=>", "$", "model", "->", "files", "]", ")", ";", "}" ]
Upload files @param integer $id - model id @param array $files @return Model
[ "Upload", "files" ]
train
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Engine/Traits/WithFileTrait.php#L23-L33
jan-dolata/crude-crud
src/Engine/Traits/WithFileTrait.php
WithFileTrait.deleteFileByFileLog
public function deleteFileByFileLog(FileLog $log) { $id = $log->model_id; $fileAttrName = $this->getFileAttrName(); $model = $this->getById($id); $model = (new CrudeFiles)->delete($model, $log, $fileAttrName); return $this->updateById($id, [$fileAttrName => $model->files]); }
php
public function deleteFileByFileLog(FileLog $log) { $id = $log->model_id; $fileAttrName = $this->getFileAttrName(); $model = $this->getById($id); $model = (new CrudeFiles)->delete($model, $log, $fileAttrName); return $this->updateById($id, [$fileAttrName => $model->files]); }
[ "public", "function", "deleteFileByFileLog", "(", "FileLog", "$", "log", ")", "{", "$", "id", "=", "$", "log", "->", "model_id", ";", "$", "fileAttrName", "=", "$", "this", "->", "getFileAttrName", "(", ")", ";", "$", "model", "=", "$", "this", "->", "getById", "(", "$", "id", ")", ";", "$", "model", "=", "(", "new", "CrudeFiles", ")", "->", "delete", "(", "$", "model", ",", "$", "log", ",", "$", "fileAttrName", ")", ";", "return", "$", "this", "->", "updateById", "(", "$", "id", ",", "[", "$", "fileAttrName", "=>", "$", "model", "->", "files", "]", ")", ";", "}" ]
Delete files @param integer $id - model id @param FileLog $log @return Model
[ "Delete", "files" ]
train
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Engine/Traits/WithFileTrait.php#L41-L51
pickles2/px2-sitemapexcel
php/pickles-sitemap-excel.php
pickles_sitemap_excel.convert_all
public function convert_all(){ $sitemap_files = array(); $tmp_sitemap_files = $this->px->fs()->ls( $this->realpath_sitemap_dir ); foreach( $tmp_sitemap_files as $filename ){ if( preg_match( '/^\\~\\$/', $filename ) ){ // エクセルの編集中のキャッシュファイルのファイル名だからスルー continue; } if( preg_match( '/^\\.\\~lock\\./', $filename ) ){ // Libre Office, Open Office の編集中のキャッシュファイルのファイル名だからスルー continue; } $extless_basename = $this->px->fs()->trim_extension($filename); $extension = $this->px->fs()->get_extension($filename); $extension = strtolower($extension); if( $extension != 'xlsx' && $extension != 'xlsm' && $extension != 'csv' ){ // 知らない拡張子はスキップ continue; } if( !array_key_exists($extless_basename, $sitemap_files) || !is_array($sitemap_files[$extless_basename]) ){ $sitemap_files[$extless_basename] = array(); } $sitemap_files[$extless_basename][$extension] = $filename; } // var_dump($sitemap_files); $is_detect_update = false; foreach( $sitemap_files as $extless_basename=>$extensions ){ $infos = $this->preprocess_of_update_detection($extless_basename, $extensions); if( $infos['master_format'] == 'pass' ){ // `pass` の場合は、変換を行わずスキップ。 continue; } if( $infos['detected_update'] == 'xlsx2csv' ){ // XLSX または XLSM がマスターになる場合 $is_detect_update = true; break; }elseif( $infos['detected_update'] == 'csv2xlsx' ){ // CSV がマスターになる場合 if( $infos['xlsx_ext'] == 'xlsx' ){ // xlsx以外の場合だけ上書きする。 // xlsx以外の場合(=xlsmの場合) は、上書きしない。 $is_detect_update = true; break; } } } if( !$is_detect_update ){ // ここで更新が検出されなければ、 // あとの処理は実行しない。 return; } if( $this->locker->lock() ){ foreach( $sitemap_files as $extless_basename=>$extensions ){ $this->locker->update(); $infos = $this->preprocess_of_update_detection($extless_basename, $extensions); if( $infos['master_format'] == 'pass' ){ // `pass` の場合は、変換を行わずスキップ。 continue; } if( $infos['detected_update'] == 'xlsx2csv' ){ // XLSX または XLSM がマスターになる場合 $result = $this->xlsx2csv( $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']], $this->realpath_sitemap_dir.$infos['extensions']['csv'] ); touch( $this->realpath_sitemap_dir.$infos['extensions']['csv'], filemtime( $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']] ) ); }elseif( $infos['detected_update'] == 'csv2xlsx' ){ // CSV がマスターになる場合 if( $infos['xlsx_ext'] == 'xlsx' ){ // xlsx以外の場合だけ上書きする。 // xlsx以外の場合(=xlsmの場合) は、上書きしない。 $result = $this->csv2xlsx( $this->realpath_sitemap_dir.$infos['extensions']['csv'], $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']] ); touch( $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']], filemtime( $this->realpath_sitemap_dir.$infos['extensions']['csv'] ) ); } } } $this->locker->unlock(); } return; }
php
public function convert_all(){ $sitemap_files = array(); $tmp_sitemap_files = $this->px->fs()->ls( $this->realpath_sitemap_dir ); foreach( $tmp_sitemap_files as $filename ){ if( preg_match( '/^\\~\\$/', $filename ) ){ // エクセルの編集中のキャッシュファイルのファイル名だからスルー continue; } if( preg_match( '/^\\.\\~lock\\./', $filename ) ){ // Libre Office, Open Office の編集中のキャッシュファイルのファイル名だからスルー continue; } $extless_basename = $this->px->fs()->trim_extension($filename); $extension = $this->px->fs()->get_extension($filename); $extension = strtolower($extension); if( $extension != 'xlsx' && $extension != 'xlsm' && $extension != 'csv' ){ // 知らない拡張子はスキップ continue; } if( !array_key_exists($extless_basename, $sitemap_files) || !is_array($sitemap_files[$extless_basename]) ){ $sitemap_files[$extless_basename] = array(); } $sitemap_files[$extless_basename][$extension] = $filename; } // var_dump($sitemap_files); $is_detect_update = false; foreach( $sitemap_files as $extless_basename=>$extensions ){ $infos = $this->preprocess_of_update_detection($extless_basename, $extensions); if( $infos['master_format'] == 'pass' ){ // `pass` の場合は、変換を行わずスキップ。 continue; } if( $infos['detected_update'] == 'xlsx2csv' ){ // XLSX または XLSM がマスターになる場合 $is_detect_update = true; break; }elseif( $infos['detected_update'] == 'csv2xlsx' ){ // CSV がマスターになる場合 if( $infos['xlsx_ext'] == 'xlsx' ){ // xlsx以外の場合だけ上書きする。 // xlsx以外の場合(=xlsmの場合) は、上書きしない。 $is_detect_update = true; break; } } } if( !$is_detect_update ){ // ここで更新が検出されなければ、 // あとの処理は実行しない。 return; } if( $this->locker->lock() ){ foreach( $sitemap_files as $extless_basename=>$extensions ){ $this->locker->update(); $infos = $this->preprocess_of_update_detection($extless_basename, $extensions); if( $infos['master_format'] == 'pass' ){ // `pass` の場合は、変換を行わずスキップ。 continue; } if( $infos['detected_update'] == 'xlsx2csv' ){ // XLSX または XLSM がマスターになる場合 $result = $this->xlsx2csv( $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']], $this->realpath_sitemap_dir.$infos['extensions']['csv'] ); touch( $this->realpath_sitemap_dir.$infos['extensions']['csv'], filemtime( $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']] ) ); }elseif( $infos['detected_update'] == 'csv2xlsx' ){ // CSV がマスターになる場合 if( $infos['xlsx_ext'] == 'xlsx' ){ // xlsx以外の場合だけ上書きする。 // xlsx以外の場合(=xlsmの場合) は、上書きしない。 $result = $this->csv2xlsx( $this->realpath_sitemap_dir.$infos['extensions']['csv'], $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']] ); touch( $this->realpath_sitemap_dir.$infos['extensions'][$infos['xlsx_ext']], filemtime( $this->realpath_sitemap_dir.$infos['extensions']['csv'] ) ); } } } $this->locker->unlock(); } return; }
[ "public", "function", "convert_all", "(", ")", "{", "$", "sitemap_files", "=", "array", "(", ")", ";", "$", "tmp_sitemap_files", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "ls", "(", "$", "this", "->", "realpath_sitemap_dir", ")", ";", "foreach", "(", "$", "tmp_sitemap_files", "as", "$", "filename", ")", "{", "if", "(", "preg_match", "(", "'/^\\\\~\\\\$/'", ",", "$", "filename", ")", ")", "{", "// エクセルの編集中のキャッシュファイルのファイル名だからスルー\r", "continue", ";", "}", "if", "(", "preg_match", "(", "'/^\\\\.\\\\~lock\\\\./'", ",", "$", "filename", ")", ")", "{", "// Libre Office, Open Office の編集中のキャッシュファイルのファイル名だからスルー\r", "continue", ";", "}", "$", "extless_basename", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "trim_extension", "(", "$", "filename", ")", ";", "$", "extension", "=", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "get_extension", "(", "$", "filename", ")", ";", "$", "extension", "=", "strtolower", "(", "$", "extension", ")", ";", "if", "(", "$", "extension", "!=", "'xlsx'", "&&", "$", "extension", "!=", "'xlsm'", "&&", "$", "extension", "!=", "'csv'", ")", "{", "// 知らない拡張子はスキップ\r", "continue", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "extless_basename", ",", "$", "sitemap_files", ")", "||", "!", "is_array", "(", "$", "sitemap_files", "[", "$", "extless_basename", "]", ")", ")", "{", "$", "sitemap_files", "[", "$", "extless_basename", "]", "=", "array", "(", ")", ";", "}", "$", "sitemap_files", "[", "$", "extless_basename", "]", "[", "$", "extension", "]", "=", "$", "filename", ";", "}", "// var_dump($sitemap_files);\r", "$", "is_detect_update", "=", "false", ";", "foreach", "(", "$", "sitemap_files", "as", "$", "extless_basename", "=>", "$", "extensions", ")", "{", "$", "infos", "=", "$", "this", "->", "preprocess_of_update_detection", "(", "$", "extless_basename", ",", "$", "extensions", ")", ";", "if", "(", "$", "infos", "[", "'master_format'", "]", "==", "'pass'", ")", "{", "// `pass` の場合は、変換を行わずスキップ。\r", "continue", ";", "}", "if", "(", "$", "infos", "[", "'detected_update'", "]", "==", "'xlsx2csv'", ")", "{", "// XLSX または XLSM がマスターになる場合\r", "$", "is_detect_update", "=", "true", ";", "break", ";", "}", "elseif", "(", "$", "infos", "[", "'detected_update'", "]", "==", "'csv2xlsx'", ")", "{", "// CSV がマスターになる場合\r", "if", "(", "$", "infos", "[", "'xlsx_ext'", "]", "==", "'xlsx'", ")", "{", "// xlsx以外の場合だけ上書きする。\r", "// xlsx以外の場合(=xlsmの場合) は、上書きしない。\r", "$", "is_detect_update", "=", "true", ";", "break", ";", "}", "}", "}", "if", "(", "!", "$", "is_detect_update", ")", "{", "// ここで更新が検出されなければ、\r", "// あとの処理は実行しない。\r", "return", ";", "}", "if", "(", "$", "this", "->", "locker", "->", "lock", "(", ")", ")", "{", "foreach", "(", "$", "sitemap_files", "as", "$", "extless_basename", "=>", "$", "extensions", ")", "{", "$", "this", "->", "locker", "->", "update", "(", ")", ";", "$", "infos", "=", "$", "this", "->", "preprocess_of_update_detection", "(", "$", "extless_basename", ",", "$", "extensions", ")", ";", "if", "(", "$", "infos", "[", "'master_format'", "]", "==", "'pass'", ")", "{", "// `pass` の場合は、変換を行わずスキップ。\r", "continue", ";", "}", "if", "(", "$", "infos", "[", "'detected_update'", "]", "==", "'xlsx2csv'", ")", "{", "// XLSX または XLSM がマスターになる場合\r", "$", "result", "=", "$", "this", "->", "xlsx2csv", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "$", "infos", "[", "'xlsx_ext'", "]", "]", ",", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "'csv'", "]", ")", ";", "touch", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "'csv'", "]", ",", "filemtime", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "$", "infos", "[", "'xlsx_ext'", "]", "]", ")", ")", ";", "}", "elseif", "(", "$", "infos", "[", "'detected_update'", "]", "==", "'csv2xlsx'", ")", "{", "// CSV がマスターになる場合\r", "if", "(", "$", "infos", "[", "'xlsx_ext'", "]", "==", "'xlsx'", ")", "{", "// xlsx以外の場合だけ上書きする。\r", "// xlsx以外の場合(=xlsmの場合) は、上書きしない。\r", "$", "result", "=", "$", "this", "->", "csv2xlsx", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "'csv'", "]", ",", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "$", "infos", "[", "'xlsx_ext'", "]", "]", ")", ";", "touch", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "$", "infos", "[", "'xlsx_ext'", "]", "]", ",", "filemtime", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "infos", "[", "'extensions'", "]", "[", "'csv'", "]", ")", ")", ";", "}", "}", "}", "$", "this", "->", "locker", "->", "unlock", "(", ")", ";", "}", "return", ";", "}" ]
すべてのファイルを変換する
[ "すべてのファイルを変換する" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/pickles-sitemap-excel.php#L74-L178
pickles2/px2-sitemapexcel
php/pickles-sitemap-excel.php
pickles_sitemap_excel.preprocess_of_update_detection
private function preprocess_of_update_detection($extless_basename, $extensions){ $master_format = $this->get_master_format_of($extless_basename); // var_dump($master_format); // ファイルが既存しない場合、ファイル名がセットされていないので、 // 明示的にセットする。 if( !array_key_exists('xlsx', $extensions) && !array_key_exists('xlsm', $extensions) ){ // xlsx も xlsm も存在しない場合、xlsx をデフォルトとする。 $extensions['xlsx'] = $extless_basename.'.xlsx'; } if( !array_key_exists('csv', $extensions) ){ $extensions['csv'] = $extless_basename.'.csv'; } $xlsx_ext = 'xlsx'; if( !array_key_exists('xlsx', $extensions) && array_key_exists('xlsm', $extensions) ){ // xlsm が存在し、かつ xlsx が存在しない場合、 // xlsx の代わりに xlsm を扱う。 $xlsx_ext = 'xlsm'; } $detected_update = false; if( ($master_format == 'timestamp' || $master_format == 'xlsx') && true === $this->px->fs()->is_newer_a_than_b( $this->realpath_sitemap_dir.$extensions[$xlsx_ext], $this->realpath_sitemap_dir.$extensions['csv'] ) ){ // XLSX または XLSM がマスターになる場合 $detected_update = 'xlsx2csv'; }elseif( ($master_format == 'timestamp' || $master_format == 'csv') && true === $this->px->fs()->is_newer_a_than_b( $this->realpath_sitemap_dir.$extensions['csv'], $this->realpath_sitemap_dir.$extensions[$xlsx_ext] ) ){ // CSV がマスターになる場合 $detected_update = 'csv2xlsx'; } return array( 'master_format' => $master_format, 'extensions' => $extensions, 'xlsx_ext' => $xlsx_ext, 'detected_update' => $detected_update, ); }
php
private function preprocess_of_update_detection($extless_basename, $extensions){ $master_format = $this->get_master_format_of($extless_basename); // var_dump($master_format); // ファイルが既存しない場合、ファイル名がセットされていないので、 // 明示的にセットする。 if( !array_key_exists('xlsx', $extensions) && !array_key_exists('xlsm', $extensions) ){ // xlsx も xlsm も存在しない場合、xlsx をデフォルトとする。 $extensions['xlsx'] = $extless_basename.'.xlsx'; } if( !array_key_exists('csv', $extensions) ){ $extensions['csv'] = $extless_basename.'.csv'; } $xlsx_ext = 'xlsx'; if( !array_key_exists('xlsx', $extensions) && array_key_exists('xlsm', $extensions) ){ // xlsm が存在し、かつ xlsx が存在しない場合、 // xlsx の代わりに xlsm を扱う。 $xlsx_ext = 'xlsm'; } $detected_update = false; if( ($master_format == 'timestamp' || $master_format == 'xlsx') && true === $this->px->fs()->is_newer_a_than_b( $this->realpath_sitemap_dir.$extensions[$xlsx_ext], $this->realpath_sitemap_dir.$extensions['csv'] ) ){ // XLSX または XLSM がマスターになる場合 $detected_update = 'xlsx2csv'; }elseif( ($master_format == 'timestamp' || $master_format == 'csv') && true === $this->px->fs()->is_newer_a_than_b( $this->realpath_sitemap_dir.$extensions['csv'], $this->realpath_sitemap_dir.$extensions[$xlsx_ext] ) ){ // CSV がマスターになる場合 $detected_update = 'csv2xlsx'; } return array( 'master_format' => $master_format, 'extensions' => $extensions, 'xlsx_ext' => $xlsx_ext, 'detected_update' => $detected_update, ); }
[ "private", "function", "preprocess_of_update_detection", "(", "$", "extless_basename", ",", "$", "extensions", ")", "{", "$", "master_format", "=", "$", "this", "->", "get_master_format_of", "(", "$", "extless_basename", ")", ";", "// var_dump($master_format);\r", "// ファイルが既存しない場合、ファイル名がセットされていないので、\r", "// 明示的にセットする。\r", "if", "(", "!", "array_key_exists", "(", "'xlsx'", ",", "$", "extensions", ")", "&&", "!", "array_key_exists", "(", "'xlsm'", ",", "$", "extensions", ")", ")", "{", "// xlsx も xlsm も存在しない場合、xlsx をデフォルトとする。\r", "$", "extensions", "[", "'xlsx'", "]", "=", "$", "extless_basename", ".", "'.xlsx'", ";", "}", "if", "(", "!", "array_key_exists", "(", "'csv'", ",", "$", "extensions", ")", ")", "{", "$", "extensions", "[", "'csv'", "]", "=", "$", "extless_basename", ".", "'.csv'", ";", "}", "$", "xlsx_ext", "=", "'xlsx'", ";", "if", "(", "!", "array_key_exists", "(", "'xlsx'", ",", "$", "extensions", ")", "&&", "array_key_exists", "(", "'xlsm'", ",", "$", "extensions", ")", ")", "{", "// xlsm が存在し、かつ xlsx が存在しない場合、\r", "// xlsx の代わりに xlsm を扱う。\r", "$", "xlsx_ext", "=", "'xlsm'", ";", "}", "$", "detected_update", "=", "false", ";", "if", "(", "(", "$", "master_format", "==", "'timestamp'", "||", "$", "master_format", "==", "'xlsx'", ")", "&&", "true", "===", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "is_newer_a_than_b", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "extensions", "[", "$", "xlsx_ext", "]", ",", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "extensions", "[", "'csv'", "]", ")", ")", "{", "// XLSX または XLSM がマスターになる場合\r", "$", "detected_update", "=", "'xlsx2csv'", ";", "}", "elseif", "(", "(", "$", "master_format", "==", "'timestamp'", "||", "$", "master_format", "==", "'csv'", ")", "&&", "true", "===", "$", "this", "->", "px", "->", "fs", "(", ")", "->", "is_newer_a_than_b", "(", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "extensions", "[", "'csv'", "]", ",", "$", "this", "->", "realpath_sitemap_dir", ".", "$", "extensions", "[", "$", "xlsx_ext", "]", ")", ")", "{", "// CSV がマスターになる場合\r", "$", "detected_update", "=", "'csv2xlsx'", ";", "}", "return", "array", "(", "'master_format'", "=>", "$", "master_format", ",", "'extensions'", "=>", "$", "extensions", ",", "'xlsx_ext'", "=>", "$", "xlsx_ext", ",", "'detected_update'", "=>", "$", "detected_update", ",", ")", ";", "}" ]
更新抽出のための前処理 @param string $extless_basename 拡張子を除いたファイル名 @param string $extensions 拡張子ごとの実ファイル名一覧 @return array 整理された各情報
[ "更新抽出のための前処理" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/pickles-sitemap-excel.php#L186-L228
pickles2/px2-sitemapexcel
php/pickles-sitemap-excel.php
pickles_sitemap_excel.get_master_format_of
private function get_master_format_of( $extless_basename ){ $rtn = $this->plugin_conf['master_format']; if( strlen(@$this->plugin_conf['files_master_format'][$extless_basename]) ){ $rtn = $this->plugin_conf['files_master_format'][$extless_basename]; } $rtn = strtolower($rtn); return $rtn; }
php
private function get_master_format_of( $extless_basename ){ $rtn = $this->plugin_conf['master_format']; if( strlen(@$this->plugin_conf['files_master_format'][$extless_basename]) ){ $rtn = $this->plugin_conf['files_master_format'][$extless_basename]; } $rtn = strtolower($rtn); return $rtn; }
[ "private", "function", "get_master_format_of", "(", "$", "extless_basename", ")", "{", "$", "rtn", "=", "$", "this", "->", "plugin_conf", "[", "'master_format'", "]", ";", "if", "(", "strlen", "(", "@", "$", "this", "->", "plugin_conf", "[", "'files_master_format'", "]", "[", "$", "extless_basename", "]", ")", ")", "{", "$", "rtn", "=", "$", "this", "->", "plugin_conf", "[", "'files_master_format'", "]", "[", "$", "extless_basename", "]", ";", "}", "$", "rtn", "=", "strtolower", "(", "$", "rtn", ")", ";", "return", "$", "rtn", ";", "}" ]
ファイルの master format を調べる @param string $extless_basename 調べる対象の拡張子を含まないファイル名 @return string master format 名
[ "ファイルの", "master", "format", "を調べる" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/pickles-sitemap-excel.php#L235-L242
pickles2/px2-sitemapexcel
php/pickles-sitemap-excel.php
pickles_sitemap_excel.xlsx2csv
public function xlsx2csv($path_xlsx, $path_csv){ $result = @(new xlsx2csv($this->px, $this))->convert( $path_xlsx, $path_csv ); return $result; }
php
public function xlsx2csv($path_xlsx, $path_csv){ $result = @(new xlsx2csv($this->px, $this))->convert( $path_xlsx, $path_csv ); return $result; }
[ "public", "function", "xlsx2csv", "(", "$", "path_xlsx", ",", "$", "path_csv", ")", "{", "$", "result", "=", "@", "(", "new", "xlsx2csv", "(", "$", "this", "->", "px", ",", "$", "this", ")", ")", "->", "convert", "(", "$", "path_xlsx", ",", "$", "path_csv", ")", ";", "return", "$", "result", ";", "}" ]
サイトマップXLSX を サイトマップCSV に変換 このメソッドは、変換後のファイルを生成するのみです。 タイムスタンプの調整等は行いません。 @param string $path_xlsx Excelファイルのパス @param string $path_csv CSVファイルのパス @return boolean 実行結果
[ "サイトマップXLSX", "を", "サイトマップCSV", "に変換" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/pickles-sitemap-excel.php#L254-L257
pickles2/px2-sitemapexcel
php/pickles-sitemap-excel.php
pickles_sitemap_excel.csv2xlsx
public function csv2xlsx($path_csv, $path_xlsx){ $result = @(new csv2xlsx($this->px, $this))->convert( $path_csv, $path_xlsx ); return $result; }
php
public function csv2xlsx($path_csv, $path_xlsx){ $result = @(new csv2xlsx($this->px, $this))->convert( $path_csv, $path_xlsx ); return $result; }
[ "public", "function", "csv2xlsx", "(", "$", "path_csv", ",", "$", "path_xlsx", ")", "{", "$", "result", "=", "@", "(", "new", "csv2xlsx", "(", "$", "this", "->", "px", ",", "$", "this", ")", ")", "->", "convert", "(", "$", "path_csv", ",", "$", "path_xlsx", ")", ";", "return", "$", "result", ";", "}" ]
サイトマップCSV を サイトマップXLSX に変換 このメソッドは、変換後のファイルを生成するのみです。 タイムスタンプの調整等は行いません。 @param string $path_csv CSVファイルのパス @param string $path_xlsx Excelファイルのパス @return boolean 実行結果
[ "サイトマップCSV", "を", "サイトマップXLSX", "に変換" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/pickles-sitemap-excel.php#L269-L272
pickles2/px2-sitemapexcel
php/pickles-sitemap-excel.php
pickles_sitemap_excel.get_sitemap_definition
public function get_sitemap_definition(){ $col = 'A'; $num = 0; $rtn = array(); $rtn['path'] = array('num'=>$num++,'col'=>$col++,'key'=>'path','name'=>'ページのパス'); $rtn['content'] = array('num'=>$num++,'col'=>$col++,'key'=>'content','name'=>'コンテンツファイルの格納先'); $rtn['id'] = array('num'=>$num++,'col'=>$col++,'key'=>'id','name'=>'ページID'); $rtn['title'] = array('num'=>$num++,'col'=>$col++,'key'=>'title','name'=>'ページタイトル'); $rtn['title_breadcrumb'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_breadcrumb','name'=>'ページタイトル(パン屑表示用)'); $rtn['title_h1'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_h1','name'=>'ページタイトル(H1表示用)'); $rtn['title_label'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_label','name'=>'ページタイトル(リンク表示用)'); $rtn['title_full'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_full','name'=>'ページタイトル(タイトルタグ用)'); $rtn['logical_path'] = array('num'=>$num++,'col'=>$col++,'key'=>'logical_path','name'=>'論理構造上のパス'); $rtn['list_flg'] = array('num'=>$num++,'col'=>$col++,'key'=>'list_flg','name'=>'一覧表示フラグ'); $rtn['layout'] = array('num'=>$num++,'col'=>$col++,'key'=>'layout','name'=>'レイアウト'); $rtn['orderby'] = array('num'=>$num++,'col'=>$col++,'key'=>'orderby','name'=>'表示順'); $rtn['keywords'] = array('num'=>$num++,'col'=>$col++,'key'=>'keywords','name'=>'metaキーワード'); $rtn['description'] = array('num'=>$num++,'col'=>$col++,'key'=>'description','name'=>'metaディスクリプション'); $rtn['category_top_flg'] = array('num'=>$num++,'col'=>$col++,'key'=>'category_top_flg','name'=>'カテゴリトップフラグ'); $rtn['role'] = array('num'=>$num++,'col'=>$col++,'key'=>'role','name'=>'ロール'); $rtn['proc_type'] = array('num'=>$num++,'col'=>$col++,'key'=>'proc_type','name'=>'コンテンツの処理方法'); return $rtn; }
php
public function get_sitemap_definition(){ $col = 'A'; $num = 0; $rtn = array(); $rtn['path'] = array('num'=>$num++,'col'=>$col++,'key'=>'path','name'=>'ページのパス'); $rtn['content'] = array('num'=>$num++,'col'=>$col++,'key'=>'content','name'=>'コンテンツファイルの格納先'); $rtn['id'] = array('num'=>$num++,'col'=>$col++,'key'=>'id','name'=>'ページID'); $rtn['title'] = array('num'=>$num++,'col'=>$col++,'key'=>'title','name'=>'ページタイトル'); $rtn['title_breadcrumb'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_breadcrumb','name'=>'ページタイトル(パン屑表示用)'); $rtn['title_h1'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_h1','name'=>'ページタイトル(H1表示用)'); $rtn['title_label'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_label','name'=>'ページタイトル(リンク表示用)'); $rtn['title_full'] = array('num'=>$num++,'col'=>$col++,'key'=>'title_full','name'=>'ページタイトル(タイトルタグ用)'); $rtn['logical_path'] = array('num'=>$num++,'col'=>$col++,'key'=>'logical_path','name'=>'論理構造上のパス'); $rtn['list_flg'] = array('num'=>$num++,'col'=>$col++,'key'=>'list_flg','name'=>'一覧表示フラグ'); $rtn['layout'] = array('num'=>$num++,'col'=>$col++,'key'=>'layout','name'=>'レイアウト'); $rtn['orderby'] = array('num'=>$num++,'col'=>$col++,'key'=>'orderby','name'=>'表示順'); $rtn['keywords'] = array('num'=>$num++,'col'=>$col++,'key'=>'keywords','name'=>'metaキーワード'); $rtn['description'] = array('num'=>$num++,'col'=>$col++,'key'=>'description','name'=>'metaディスクリプション'); $rtn['category_top_flg'] = array('num'=>$num++,'col'=>$col++,'key'=>'category_top_flg','name'=>'カテゴリトップフラグ'); $rtn['role'] = array('num'=>$num++,'col'=>$col++,'key'=>'role','name'=>'ロール'); $rtn['proc_type'] = array('num'=>$num++,'col'=>$col++,'key'=>'proc_type','name'=>'コンテンツの処理方法'); return $rtn; }
[ "public", "function", "get_sitemap_definition", "(", ")", "{", "$", "col", "=", "'A'", ";", "$", "num", "=", "0", ";", "$", "rtn", "=", "array", "(", ")", ";", "$", "rtn", "[", "'path'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'path'", ",", "'name'", "=>", "'ページのパス');\r", "", "", "$", "rtn", "[", "'content'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'content'", ",", "'name'", "=>", "'コンテンツファイルの格納先');\r", "", "", "$", "rtn", "[", "'id'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'id'", ",", "'name'", "=>", "'ページID');\r", "", "", "$", "rtn", "[", "'title'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'title'", ",", "'name'", "=>", "'ページタイトル');\r", "", "", "$", "rtn", "[", "'title_breadcrumb'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'title_breadcrumb'", ",", "'name'", "=>", "'ページタイトル(パン屑表示用)');\r", "", "", "$", "rtn", "[", "'title_h1'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'title_h1'", ",", "'name'", "=>", "'ページタイトル(H1表示用)');\r", "", "", "$", "rtn", "[", "'title_label'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'title_label'", ",", "'name'", "=>", "'ページタイトル(リンク表示用)');\r", "", "", "$", "rtn", "[", "'title_full'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'title_full'", ",", "'name'", "=>", "'ページタイトル(タイトルタグ用)');\r", "", "", "$", "rtn", "[", "'logical_path'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'logical_path'", ",", "'name'", "=>", "'論理構造上のパス');\r", "", "", "$", "rtn", "[", "'list_flg'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'list_flg'", ",", "'name'", "=>", "'一覧表示フラグ');\r", "", "", "$", "rtn", "[", "'layout'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'layout'", ",", "'name'", "=>", "'レイアウト');\r", "", "", "$", "rtn", "[", "'orderby'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'orderby'", ",", "'name'", "=>", "'表示順');\r", "", "", "$", "rtn", "[", "'keywords'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'keywords'", ",", "'name'", "=>", "'metaキーワード');\r", "", "", "$", "rtn", "[", "'description'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'description'", ",", "'name'", "=>", "'metaディスクリプション');\r", "", "", "$", "rtn", "[", "'category_top_flg'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'category_top_flg'", ",", "'name'", "=>", "'カテゴリトップフラグ');\r", "", "", "$", "rtn", "[", "'role'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'role'", ",", "'name'", "=>", "'ロール');\r", "", "", "$", "rtn", "[", "'proc_type'", "]", "=", "array", "(", "'num'", "=>", "$", "num", "++", ",", "'col'", "=>", "$", "col", "++", ",", "'key'", "=>", "'proc_type'", ",", "'name'", "=>", "'コンテンツの処理方法');\r", "", "", "return", "$", "rtn", ";", "}" ]
サイトマップCSVの定義を取得する @return array サイトマップCSV定義配列
[ "サイトマップCSVの定義を取得する" ]
train
https://github.com/pickles2/px2-sitemapexcel/blob/fbfa207ee9b2e4bd977aadf69a935d3fade51fea/php/pickles-sitemap-excel.php#L278-L300
VDMi/Guzzle-oAuth
src/GuzzleOauth/Consumer/Facebook.php
Facebook.normalizeAccessToken
protected function normalizeAccessToken($access_token) { if (!isset($access_token['expires_in']) && isset($access_token['expires'])) { $access_token['expires_in'] = $access_token['expires']; unset($access_token['expires']); } return parent::normalizeAccessToken($access_token); }
php
protected function normalizeAccessToken($access_token) { if (!isset($access_token['expires_in']) && isset($access_token['expires'])) { $access_token['expires_in'] = $access_token['expires']; unset($access_token['expires']); } return parent::normalizeAccessToken($access_token); }
[ "protected", "function", "normalizeAccessToken", "(", "$", "access_token", ")", "{", "if", "(", "!", "isset", "(", "$", "access_token", "[", "'expires_in'", "]", ")", "&&", "isset", "(", "$", "access_token", "[", "'expires'", "]", ")", ")", "{", "$", "access_token", "[", "'expires_in'", "]", "=", "$", "access_token", "[", "'expires'", "]", ";", "unset", "(", "$", "access_token", "[", "'expires'", "]", ")", ";", "}", "return", "parent", "::", "normalizeAccessToken", "(", "$", "access_token", ")", ";", "}" ]
Facebook does it differently... again!
[ "Facebook", "does", "it", "differently", "...", "again!" ]
train
https://github.com/VDMi/Guzzle-oAuth/blob/e2b2561e4e402e13ba605082bf768b29942f90cb/src/GuzzleOauth/Consumer/Facebook.php#L33-L39
opis/utils
lib/ArrayHandler.php
ArrayHandler.get
public function get($path, $default = null) { $path = explode($this->separator, $path); $item = &$this->item; foreach ($path as $key) { if (!is_array($item)) { return $default; } if (!array_key_exists($key, $item)) { return $default; } $item = &$item[$key]; } return $item; }
php
public function get($path, $default = null) { $path = explode($this->separator, $path); $item = &$this->item; foreach ($path as $key) { if (!is_array($item)) { return $default; } if (!array_key_exists($key, $item)) { return $default; } $item = &$item[$key]; } return $item; }
[ "public", "function", "get", "(", "$", "path", ",", "$", "default", "=", "null", ")", "{", "$", "path", "=", "explode", "(", "$", "this", "->", "separator", ",", "$", "path", ")", ";", "$", "item", "=", "&", "$", "this", "->", "item", ";", "foreach", "(", "$", "path", "as", "$", "key", ")", "{", "if", "(", "!", "is_array", "(", "$", "item", ")", ")", "{", "return", "$", "default", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "item", ")", ")", "{", "return", "$", "default", ";", "}", "$", "item", "=", "&", "$", "item", "[", "$", "key", "]", ";", "}", "return", "$", "item", ";", "}" ]
Get the value stored under the specified path @access public @param string $path Value's path @param mixed $default Default value that will be returned @return mixed
[ "Get", "the", "value", "stored", "under", "the", "specified", "path" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L69-L88
opis/utils
lib/ArrayHandler.php
ArrayHandler.set
public function set($path, $value, $constraint = null) { if ($constraint === null) { $constraint = $this->constraint; } if ($constraint) { $value = json_decode(json_encode($value), true); } if (is_null($path)) { $this->item[] = $value; return; } $path = explode($this->separator, $path); $last = array_pop($path); $item = &$this->item; foreach ($path as $key) { if (!array_key_exists($key, $item) || !is_array($item[$key])) { $item[$key] = array(); } $item = &$item[$key]; } $item[$last] = $value; }
php
public function set($path, $value, $constraint = null) { if ($constraint === null) { $constraint = $this->constraint; } if ($constraint) { $value = json_decode(json_encode($value), true); } if (is_null($path)) { $this->item[] = $value; return; } $path = explode($this->separator, $path); $last = array_pop($path); $item = &$this->item; foreach ($path as $key) { if (!array_key_exists($key, $item) || !is_array($item[$key])) { $item[$key] = array(); } $item = &$item[$key]; } $item[$last] = $value; }
[ "public", "function", "set", "(", "$", "path", ",", "$", "value", ",", "$", "constraint", "=", "null", ")", "{", "if", "(", "$", "constraint", "===", "null", ")", "{", "$", "constraint", "=", "$", "this", "->", "constraint", ";", "}", "if", "(", "$", "constraint", ")", "{", "$", "value", "=", "json_decode", "(", "json_encode", "(", "$", "value", ")", ",", "true", ")", ";", "}", "if", "(", "is_null", "(", "$", "path", ")", ")", "{", "$", "this", "->", "item", "[", "]", "=", "$", "value", ";", "return", ";", "}", "$", "path", "=", "explode", "(", "$", "this", "->", "separator", ",", "$", "path", ")", ";", "$", "last", "=", "array_pop", "(", "$", "path", ")", ";", "$", "item", "=", "&", "$", "this", "->", "item", ";", "foreach", "(", "$", "path", "as", "$", "key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "item", ")", "||", "!", "is_array", "(", "$", "item", "[", "$", "key", "]", ")", ")", "{", "$", "item", "[", "$", "key", "]", "=", "array", "(", ")", ";", "}", "$", "item", "=", "&", "$", "item", "[", "$", "key", "]", ";", "}", "$", "item", "[", "$", "last", "]", "=", "$", "value", ";", "}" ]
Store a value @access public @param string $path Where to store @param mixed $value The value being stored @param boolean $constraint (optional) Constraint
[ "Store", "a", "value" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L113-L141
opis/utils
lib/ArrayHandler.php
ArrayHandler.remove
public function remove($path) { $path = explode($this->separator, $path); $last = array_pop($path); $item = &$this->item; foreach ($path as $key) { if (array_key_exists($key, $item) && is_array($item[$key])) { $item = &$item[$key]; continue; } return false; } if (array_key_exists($last, $item)) { unset($item[$last]); return true; } return false; }
php
public function remove($path) { $path = explode($this->separator, $path); $last = array_pop($path); $item = &$this->item; foreach ($path as $key) { if (array_key_exists($key, $item) && is_array($item[$key])) { $item = &$item[$key]; continue; } return false; } if (array_key_exists($last, $item)) { unset($item[$last]); return true; } return false; }
[ "public", "function", "remove", "(", "$", "path", ")", "{", "$", "path", "=", "explode", "(", "$", "this", "->", "separator", ",", "$", "path", ")", ";", "$", "last", "=", "array_pop", "(", "$", "path", ")", ";", "$", "item", "=", "&", "$", "this", "->", "item", ";", "foreach", "(", "$", "path", "as", "$", "key", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "item", ")", "&&", "is_array", "(", "$", "item", "[", "$", "key", "]", ")", ")", "{", "$", "item", "=", "&", "$", "item", "[", "$", "key", "]", ";", "continue", ";", "}", "return", "false", ";", "}", "if", "(", "array_key_exists", "(", "$", "last", ",", "$", "item", ")", ")", "{", "unset", "(", "$", "item", "[", "$", "last", "]", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Remove a path @access public @param string $path Path to be removed @return boolean
[ "Remove", "a", "path" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L152-L173
opis/utils
lib/ArrayHandler.php
ArrayHandler.unserialize
public function unserialize($data) { $data = unserialize($data); $this->item = $data['item']; $this->separator = $data['separator']; $this->constraint = $data['constraint']; }
php
public function unserialize($data) { $data = unserialize($data); $this->item = $data['item']; $this->separator = $data['separator']; $this->constraint = $data['constraint']; }
[ "public", "function", "unserialize", "(", "$", "data", ")", "{", "$", "data", "=", "unserialize", "(", "$", "data", ")", ";", "$", "this", "->", "item", "=", "$", "data", "[", "'item'", "]", ";", "$", "this", "->", "separator", "=", "$", "data", "[", "'separator'", "]", ";", "$", "this", "->", "constraint", "=", "$", "data", "[", "'constraint'", "]", ";", "}" ]
Method inherited from Serializable @access public @param string $data
[ "Method", "inherited", "from", "Serializable" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L243-L250
opis/utils
lib/ArrayHandler.php
ArrayHandler.isArray
public function isArray($path) { $value = $this->get($path, $this); if ($value === $this || !is_array($value)) { return false; } return array_keys($value) === range(0, count($value) - 1); }
php
public function isArray($path) { $value = $this->get($path, $this); if ($value === $this || !is_array($value)) { return false; } return array_keys($value) === range(0, count($value) - 1); }
[ "public", "function", "isArray", "(", "$", "path", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "path", ",", "$", "this", ")", ";", "if", "(", "$", "value", "===", "$", "this", "||", "!", "is_array", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "return", "array_keys", "(", "$", "value", ")", "===", "range", "(", "0", ",", "count", "(", "$", "value", ")", "-", "1", ")", ";", "}" ]
Check if the value stored under the specified path is a JSON array @access public @param string $path The path to check @return boolean
[ "Check", "if", "the", "value", "stored", "under", "the", "specified", "path", "is", "a", "JSON", "array" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L261-L270
opis/utils
lib/ArrayHandler.php
ArrayHandler.isString
public function isString($path) { $value = $this->get($path, $this); return $value === $this ? false : is_string($value); }
php
public function isString($path) { $value = $this->get($path, $this); return $value === $this ? false : is_string($value); }
[ "public", "function", "isString", "(", "$", "path", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "path", ",", "$", "this", ")", ";", "return", "$", "value", "===", "$", "this", "?", "false", ":", "is_string", "(", "$", "value", ")", ";", "}" ]
Check if the value stored under the specified path is a string @access public @param string $path The path to check @return boolean
[ "Check", "if", "the", "value", "stored", "under", "the", "specified", "path", "is", "a", "string" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L301-L306
opis/utils
lib/ArrayHandler.php
ArrayHandler.isNumber
public function isNumber($path) { $value = $this->get($path, $this); return $value === $this ? false : is_numeric($value); }
php
public function isNumber($path) { $value = $this->get($path, $this); return $value === $this ? false : is_numeric($value); }
[ "public", "function", "isNumber", "(", "$", "path", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "path", ",", "$", "this", ")", ";", "return", "$", "value", "===", "$", "this", "?", "false", ":", "is_numeric", "(", "$", "value", ")", ";", "}" ]
Check if the value stored under the specified path is a number @access public @param string $path The path to check @return boolean
[ "Check", "if", "the", "value", "stored", "under", "the", "specified", "path", "is", "a", "number" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L317-L322
opis/utils
lib/ArrayHandler.php
ArrayHandler.isNull
public function isNull($path) { $value = $this->get($path, $this); return $value === $this ? false : is_null($value); }
php
public function isNull($path) { $value = $this->get($path, $this); return $value === $this ? false : is_null($value); }
[ "public", "function", "isNull", "(", "$", "path", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "path", ",", "$", "this", ")", ";", "return", "$", "value", "===", "$", "this", "?", "false", ":", "is_null", "(", "$", "value", ")", ";", "}" ]
Check if the value stored under the specified path is a `null` value @access public @param string $path The path to check @return boolean
[ "Check", "if", "the", "value", "stored", "under", "the", "specified", "path", "is", "a", "null", "value" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L333-L338
opis/utils
lib/ArrayHandler.php
ArrayHandler.isBoolean
public function isBoolean($path) { $value = $this->get($path, $this); return $value === $this ? false : is_bool($value); }
php
public function isBoolean($path) { $value = $this->get($path, $this); return $value === $this ? false : is_bool($value); }
[ "public", "function", "isBoolean", "(", "$", "path", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "path", ",", "$", "this", ")", ";", "return", "$", "value", "===", "$", "this", "?", "false", ":", "is_bool", "(", "$", "value", ")", ";", "}" ]
Check if the value stored under the specified path is a boolean value @access public @param string $path The path to check @return boolean
[ "Check", "if", "the", "value", "stored", "under", "the", "specified", "path", "is", "a", "boolean", "value" ]
train
https://github.com/opis/utils/blob/239cd3dc3760eb746838011e712592700fe5d58c/lib/ArrayHandler.php#L349-L354
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.attributeUseMethod
public function attributeUseMethod(string $attribute, string $setter, string $getter): ObjectInterface { $this->attributes[$attribute] = new Type\Method($setter, $getter); return $this; }
php
public function attributeUseMethod(string $attribute, string $setter, string $getter): ObjectInterface { $this->attributes[$attribute] = new Type\Method($setter, $getter); return $this; }
[ "public", "function", "attributeUseMethod", "(", "string", "$", "attribute", ",", "string", "$", "setter", ",", "string", "$", "getter", ")", ":", "ObjectInterface", "{", "$", "this", "->", "attributes", "[", "$", "attribute", "]", "=", "new", "Type", "\\", "Method", "(", "$", "setter", ",", "$", "getter", ")", ";", "return", "$", "this", ";", "}" ]
@param string $attribute @param string $setter @param string $getter @return ObjectInterface
[ "@param", "string", "$attribute", "@param", "string", "$setter", "@param", "string", "$getter" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L85-L90
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.attributeUseObject
public function attributeUseObject( string $attribute, ClassName $className, string $setter, string $getter ): ObjectInterface { $this->attributes[$attribute] = new Type\Object($className, $setter, $getter); return $this; }
php
public function attributeUseObject( string $attribute, ClassName $className, string $setter, string $getter ): ObjectInterface { $this->attributes[$attribute] = new Type\Object($className, $setter, $getter); return $this; }
[ "public", "function", "attributeUseObject", "(", "string", "$", "attribute", ",", "ClassName", "$", "className", ",", "string", "$", "setter", ",", "string", "$", "getter", ")", ":", "ObjectInterface", "{", "$", "this", "->", "attributes", "[", "$", "attribute", "]", "=", "new", "Type", "\\", "Object", "(", "$", "className", ",", "$", "setter", ",", "$", "getter", ")", ";", "return", "$", "this", ";", "}" ]
@param string $attribute @param ClassName $className @param string $setter @param string $getter @return ObjectInterface
[ "@param", "string", "$attribute", "@param", "ClassName", "$className", "@param", "string", "$setter", "@param", "string", "$getter" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L100-L109
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.attributeUseCollectionObject
public function attributeUseCollectionObject( string $attribute, ClassName $className, string $setter, string $getter ): ObjectInterface { $this->attributes[$attribute] = new Type\Collection\Object($className, $setter, $getter); return $this; }
php
public function attributeUseCollectionObject( string $attribute, ClassName $className, string $setter, string $getter ): ObjectInterface { $this->attributes[$attribute] = new Type\Collection\Object($className, $setter, $getter); return $this; }
[ "public", "function", "attributeUseCollectionObject", "(", "string", "$", "attribute", ",", "ClassName", "$", "className", ",", "string", "$", "setter", ",", "string", "$", "getter", ")", ":", "ObjectInterface", "{", "$", "this", "->", "attributes", "[", "$", "attribute", "]", "=", "new", "Type", "\\", "Collection", "\\", "Object", "(", "$", "className", ",", "$", "setter", ",", "$", "getter", ")", ";", "return", "$", "this", ";", "}" ]
@param string $attribute @param ClassName $className @param string $setter @param string $getter @return ObjectInterface
[ "@param", "string", "$attribute", "@param", "ClassName", "$className", "@param", "string", "$setter", "@param", "string", "$getter" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L119-L128
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.attributeUseIdentifiedObject
public function attributeUseIdentifiedObject(string $attribute, string $setter, string $getter): ObjectInterface { $this->attributes[$attribute] = new Type\IdentifiedObject($setter, $getter); return $this; }
php
public function attributeUseIdentifiedObject(string $attribute, string $setter, string $getter): ObjectInterface { $this->attributes[$attribute] = new Type\IdentifiedObject($setter, $getter); return $this; }
[ "public", "function", "attributeUseIdentifiedObject", "(", "string", "$", "attribute", ",", "string", "$", "setter", ",", "string", "$", "getter", ")", ":", "ObjectInterface", "{", "$", "this", "->", "attributes", "[", "$", "attribute", "]", "=", "new", "Type", "\\", "IdentifiedObject", "(", "$", "setter", ",", "$", "getter", ")", ";", "return", "$", "this", ";", "}" ]
@param string $attribute @param string $setter @param string $getter @return ObjectInterface
[ "@param", "string", "$attribute", "@param", "string", "$setter", "@param", "string", "$getter" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L137-L142
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.attributeUseCollectionIdentifiedObject
public function attributeUseCollectionIdentifiedObject( string $attribute, string $setter, string $getter ): ObjectInterface { $this->attributes[$attribute] = new Type\Collection\IdentifiedObject($setter, $getter); return $this; }
php
public function attributeUseCollectionIdentifiedObject( string $attribute, string $setter, string $getter ): ObjectInterface { $this->attributes[$attribute] = new Type\Collection\IdentifiedObject($setter, $getter); return $this; }
[ "public", "function", "attributeUseCollectionIdentifiedObject", "(", "string", "$", "attribute", ",", "string", "$", "setter", ",", "string", "$", "getter", ")", ":", "ObjectInterface", "{", "$", "this", "->", "attributes", "[", "$", "attribute", "]", "=", "new", "Type", "\\", "Collection", "\\", "IdentifiedObject", "(", "$", "setter", ",", "$", "getter", ")", ";", "return", "$", "this", ";", "}" ]
@param string $attribute @param string $setter @param string $getter @return ObjectInterface
[ "@param", "string", "$attribute", "@param", "string", "$setter", "@param", "string", "$getter" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L151-L159
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.attributeUseHandler
public function attributeUseHandler( string $attribute, Type\HandlerDeserializerInterface $deserialize, Type\HandlerSerializerInterface $serialize ): ObjectInterface { $this->attributes[$attribute] = new Type\Handler($deserialize, $serialize); return $this; }
php
public function attributeUseHandler( string $attribute, Type\HandlerDeserializerInterface $deserialize, Type\HandlerSerializerInterface $serialize ): ObjectInterface { $this->attributes[$attribute] = new Type\Handler($deserialize, $serialize); return $this; }
[ "public", "function", "attributeUseHandler", "(", "string", "$", "attribute", ",", "Type", "\\", "HandlerDeserializerInterface", "$", "deserialize", ",", "Type", "\\", "HandlerSerializerInterface", "$", "serialize", ")", ":", "ObjectInterface", "{", "$", "this", "->", "attributes", "[", "$", "attribute", "]", "=", "new", "Type", "\\", "Handler", "(", "$", "deserialize", ",", "$", "serialize", ")", ";", "return", "$", "this", ";", "}" ]
@param string $attribute @param Type\HandlerDeserializerInterface $deserialize @param Type\HandlerSerializerInterface $serialize @return ObjectInterface
[ "@param", "string", "$attribute", "@param", "Type", "\\", "HandlerDeserializerInterface", "$deserialize", "@param", "Type", "\\", "HandlerSerializerInterface", "$serialize" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L168-L176
blackprism/serializer
src/Blackprism/Serializer/Configuration/Object.php
Object.registerToConfiguration
public function registerToConfiguration(Configuration $configuration): ObjectInterface { $configuration->addConfigurationObject($this->className, $this); return $this; }
php
public function registerToConfiguration(Configuration $configuration): ObjectInterface { $configuration->addConfigurationObject($this->className, $this); return $this; }
[ "public", "function", "registerToConfiguration", "(", "Configuration", "$", "configuration", ")", ":", "ObjectInterface", "{", "$", "configuration", "->", "addConfigurationObject", "(", "$", "this", "->", "className", ",", "$", "this", ")", ";", "return", "$", "this", ";", "}" ]
@param Configuration $configuration @return ObjectInterface
[ "@param", "Configuration", "$configuration" ]
train
https://github.com/blackprism/serializer/blob/f5bd6ebeec802d2ad747daba7c9211b252ee4776/src/Blackprism/Serializer/Configuration/Object.php#L183-L188