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
raoul2000/yii2-twbsmaxlength-widget
TwbsMaxlength.php
TwbsMaxlength.registerClientScript
public function registerClientScript() { $view = $this->getView(); TwbsMaxlengthAsset::register($view); $options = empty($this->clientOptions) ? "{}" : Json::encode($this->clientOptions); if( isset($this->selector)) { $js = "jQuery(\"{$this->selector}\").maxlength(" . $options . ")"; } else { $js = "jQuery(\"#{$this->options['id']}\").maxlength(" . $options . ")"; } $view->registerJs($js); }
php
public function registerClientScript() { $view = $this->getView(); TwbsMaxlengthAsset::register($view); $options = empty($this->clientOptions) ? "{}" : Json::encode($this->clientOptions); if( isset($this->selector)) { $js = "jQuery(\"{$this->selector}\").maxlength(" . $options . ")"; } else { $js = "jQuery(\"#{$this->options['id']}\").maxlength(" . $options . ")"; } $view->registerJs($js); }
[ "public", "function", "registerClientScript", "(", ")", "{", "$", "view", "=", "$", "this", "->", "getView", "(", ")", ";", "TwbsMaxlengthAsset", "::", "register", "(", "$", "view", ")", ";", "$", "options", "=", "empty", "(", "$", "this", "->", "clientOptions", ")", "?", "\"{}\"", ":", "Json", "::", "encode", "(", "$", "this", "->", "clientOptions", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "selector", ")", ")", "{", "$", "js", "=", "\"jQuery(\\\"{$this->selector}\\\").maxlength(\"", ".", "$", "options", ".", "\")\"", ";", "}", "else", "{", "$", "js", "=", "\"jQuery(\\\"#{$this->options['id']}\\\").maxlength(\"", ".", "$", "options", ".", "\")\"", ";", "}", "$", "view", "->", "registerJs", "(", "$", "js", ")", ";", "}" ]
Generates and registers javascript to start the plugin.
[ "Generates", "and", "registers", "javascript", "to", "start", "the", "plugin", "." ]
train
https://github.com/raoul2000/yii2-twbsmaxlength-widget/blob/87ba6bf179a8db398bff0aaee6701a1e6dfc8b3b/TwbsMaxlength.php#L128-L140
raoul2000/yii2-twbsmaxlength-widget
TwbsMaxlength.php
TwbsMaxlength.apply
public static function apply($field, $clientOptions, $render = true) { if ( isset($field->inputOptions['maxlength'])) { $maxLength = $field->inputOptions['maxlength']; } else { $maxLength = static::getMaxLength($field->model, Html::getAttributeName($field->attribute)); } if ( ! empty($maxLength) ) { $field->inputOptions['maxlength'] = $maxLength; $id = Html::getInputId($field->model, $field->attribute); static::widget( [ 'selector' => '#'.$id, 'clientOptions' => $clientOptions ]); } if ( $render ) { echo $field; } return $field; }
php
public static function apply($field, $clientOptions, $render = true) { if ( isset($field->inputOptions['maxlength'])) { $maxLength = $field->inputOptions['maxlength']; } else { $maxLength = static::getMaxLength($field->model, Html::getAttributeName($field->attribute)); } if ( ! empty($maxLength) ) { $field->inputOptions['maxlength'] = $maxLength; $id = Html::getInputId($field->model, $field->attribute); static::widget( [ 'selector' => '#'.$id, 'clientOptions' => $clientOptions ]); } if ( $render ) { echo $field; } return $field; }
[ "public", "static", "function", "apply", "(", "$", "field", ",", "$", "clientOptions", ",", "$", "render", "=", "true", ")", "{", "if", "(", "isset", "(", "$", "field", "->", "inputOptions", "[", "'maxlength'", "]", ")", ")", "{", "$", "maxLength", "=", "$", "field", "->", "inputOptions", "[", "'maxlength'", "]", ";", "}", "else", "{", "$", "maxLength", "=", "static", "::", "getMaxLength", "(", "$", "field", "->", "model", ",", "Html", "::", "getAttributeName", "(", "$", "field", "->", "attribute", ")", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "maxLength", ")", ")", "{", "$", "field", "->", "inputOptions", "[", "'maxlength'", "]", "=", "$", "maxLength", ";", "$", "id", "=", "Html", "::", "getInputId", "(", "$", "field", "->", "model", ",", "$", "field", "->", "attribute", ")", ";", "static", "::", "widget", "(", "[", "'selector'", "=>", "'#'", ".", "$", "id", ",", "'clientOptions'", "=>", "$", "clientOptions", "]", ")", ";", "}", "if", "(", "$", "render", ")", "{", "echo", "$", "field", ";", "}", "return", "$", "field", ";", "}" ]
Add the maxlength attribute to an ActiveField. The plugin requires that the max number of characters is specified as the HTML5 attribute "maxlength". This method adds this attribute if it is not already defined into the HTML attributes of an ActiveField. The value is retrieved from the StringValidator settings that is attached to the model attribute. Note that if maxlength can't be defined, the plugin is not registred for the view. Note that this method is deprecated and should be replaced by ActiveField widget initialization as explained in the README file. @deprecated since Yii2 2.0.3 it is possible to set the maxlength HTML attribute of a text input [Read more](http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#textInput%28%29-detail) @param yii\widgets\ActiveField $field @param array $clientOptions Bootstrap maxlength plugin options @param boolean $render when true, the $field is output @return yii\widgets\ActiveField the field containing the "maxlength" option (if it could be obtained)
[ "Add", "the", "maxlength", "attribute", "to", "an", "ActiveField", "." ]
train
https://github.com/raoul2000/yii2-twbsmaxlength-widget/blob/87ba6bf179a8db398bff0aaee6701a1e6dfc8b3b/TwbsMaxlength.php#L161-L180
raoul2000/yii2-twbsmaxlength-widget
TwbsMaxlength.php
TwbsMaxlength.getMaxLength
public static function getMaxLength($model, $attribute, $defaultValue = null) { $maxLength = null; foreach ($model->getActiveValidators($attribute) as $validator) { if ( $validator instanceof yii\validators\StringValidator) { $maxLength = $validator->max; break; } } return $maxLength !== null ? $maxLength : $defaultValue; }
php
public static function getMaxLength($model, $attribute, $defaultValue = null) { $maxLength = null; foreach ($model->getActiveValidators($attribute) as $validator) { if ( $validator instanceof yii\validators\StringValidator) { $maxLength = $validator->max; break; } } return $maxLength !== null ? $maxLength : $defaultValue; }
[ "public", "static", "function", "getMaxLength", "(", "$", "model", ",", "$", "attribute", ",", "$", "defaultValue", "=", "null", ")", "{", "$", "maxLength", "=", "null", ";", "foreach", "(", "$", "model", "->", "getActiveValidators", "(", "$", "attribute", ")", "as", "$", "validator", ")", "{", "if", "(", "$", "validator", "instanceof", "yii", "\\", "validators", "\\", "StringValidator", ")", "{", "$", "maxLength", "=", "$", "validator", "->", "max", ";", "break", ";", "}", "}", "return", "$", "maxLength", "!==", "null", "?", "$", "maxLength", ":", "$", "defaultValue", ";", "}" ]
Find the maxlength parameter for an attribute's model. This method searches for a yii\validators\StringValidator among all the active validators (based on the current model scenario). If it founds one, it returns the max length parameter value. If no such value can be found because it is not defined or because no StringValidator is active, $defaultValue is returned. @param yii\base\Model $model @param string $attribute the attribute name @return integer | null the maxlength setting @see yii\validators\StringValidator
[ "Find", "the", "maxlength", "parameter", "for", "an", "attribute", "s", "model", "." ]
train
https://github.com/raoul2000/yii2-twbsmaxlength-widget/blob/87ba6bf179a8db398bff0aaee6701a1e6dfc8b3b/TwbsMaxlength.php#L194-L204
link0/profiler
src/Link0/Profiler/ProfileFactory.php
ProfileFactory.create
public function create($profileData = array(), $applicationData = array(), $serverData = array()) { $profile = Profile::create(); $profile->setProfileData($profileData); $profile->setApplicationData($applicationData); $profile->setServerData($serverData); return $profile; }
php
public function create($profileData = array(), $applicationData = array(), $serverData = array()) { $profile = Profile::create(); $profile->setProfileData($profileData); $profile->setApplicationData($applicationData); $profile->setServerData($serverData); return $profile; }
[ "public", "function", "create", "(", "$", "profileData", "=", "array", "(", ")", ",", "$", "applicationData", "=", "array", "(", ")", ",", "$", "serverData", "=", "array", "(", ")", ")", "{", "$", "profile", "=", "Profile", "::", "create", "(", ")", ";", "$", "profile", "->", "setProfileData", "(", "$", "profileData", ")", ";", "$", "profile", "->", "setApplicationData", "(", "$", "applicationData", ")", ";", "$", "profile", "->", "setServerData", "(", "$", "serverData", ")", ";", "return", "$", "profile", ";", "}" ]
@param array $profileData @param array $applicationData OPTIONAL @param array $serverData OPTIONAL @return ProfileInterface
[ "@param", "array", "$profileData", "@param", "array", "$applicationData", "OPTIONAL", "@param", "array", "$serverData", "OPTIONAL" ]
train
https://github.com/link0/profiler/blob/0573073ff029743734de747619ab65ab2476052d/src/Link0/Profiler/ProfileFactory.php#L24-L32
acasademont/wurfl
WURFL/Xml/Utils.php
WURFL_Xml_Utils.getZippedFile
private static function getZippedFile($filename) { if (!self::zipModuleLoaded()) { throw new WURFL_WURFLException("The ZipArchive extension is not loaded. Load the extension or use the flat wurfl.xml file"); } $tmpDir = WURFL_FileUtils::getTempDir(); $zip = new ZipArchive(); if ($zip->open($filename) !== true) { throw new WURFL_WURFLException("The Zip file <$filename> could not be opened"); } $zippedFile = $zip->statIndex(0); $wurflFile = $zippedFile['name']; //$wurflFile = md5(uniqid(rand(), true)); //$zip->extractTo($tmpDir, $wurflFile); $zip->extractTo($tmpDir); $zip->close(); return WURFL_FileUtils::cleanFilename($tmpDir.DIRECTORY_SEPARATOR.$wurflFile); }
php
private static function getZippedFile($filename) { if (!self::zipModuleLoaded()) { throw new WURFL_WURFLException("The ZipArchive extension is not loaded. Load the extension or use the flat wurfl.xml file"); } $tmpDir = WURFL_FileUtils::getTempDir(); $zip = new ZipArchive(); if ($zip->open($filename) !== true) { throw new WURFL_WURFLException("The Zip file <$filename> could not be opened"); } $zippedFile = $zip->statIndex(0); $wurflFile = $zippedFile['name']; //$wurflFile = md5(uniqid(rand(), true)); //$zip->extractTo($tmpDir, $wurflFile); $zip->extractTo($tmpDir); $zip->close(); return WURFL_FileUtils::cleanFilename($tmpDir.DIRECTORY_SEPARATOR.$wurflFile); }
[ "private", "static", "function", "getZippedFile", "(", "$", "filename", ")", "{", "if", "(", "!", "self", "::", "zipModuleLoaded", "(", ")", ")", "{", "throw", "new", "WURFL_WURFLException", "(", "\"The ZipArchive extension is not loaded. Load the extension or use the flat wurfl.xml file\"", ")", ";", "}", "$", "tmpDir", "=", "WURFL_FileUtils", "::", "getTempDir", "(", ")", ";", "$", "zip", "=", "new", "ZipArchive", "(", ")", ";", "if", "(", "$", "zip", "->", "open", "(", "$", "filename", ")", "!==", "true", ")", "{", "throw", "new", "WURFL_WURFLException", "(", "\"The Zip file <$filename> could not be opened\"", ")", ";", "}", "$", "zippedFile", "=", "$", "zip", "->", "statIndex", "(", "0", ")", ";", "$", "wurflFile", "=", "$", "zippedFile", "[", "'name'", "]", ";", "//$wurflFile = md5(uniqid(rand(), true)); ", "//$zip->extractTo($tmpDir, $wurflFile);", "$", "zip", "->", "extractTo", "(", "$", "tmpDir", ")", ";", "$", "zip", "->", "close", "(", ")", ";", "return", "WURFL_FileUtils", "::", "cleanFilename", "(", "$", "tmpDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "wurflFile", ")", ";", "}" ]
Returns a XML Resource filename for the uncompressed contents of the provided zipped $filename @param string $filename of zipped XML data @throws WURFL_WURFLException ZipArchive extension is not loaded or the ZIP file is corrupt @return string Full filename and path of extracted XML file
[ "Returns", "a", "XML", "Resource", "filename", "for", "the", "uncompressed", "contents", "of", "the", "provided", "zipped", "$filename" ]
train
https://github.com/acasademont/wurfl/blob/0f4fb6e06b452ba95ad1d15e7d8226d0974b60c2/WURFL/Xml/Utils.php#L52-L74
tokenly/bitcoin-payer
src/Tokenly/BitcoinPayer/Provider/BitcoinPayerServiceProvider.php
BitcoinPayerServiceProvider.register
public function register() { $this->bindConfig(); $this->app->bind('Nbobtc\Bitcoind\Bitcoind', function($app) { $bitcoind_client = $app->make('Nbobtc\Bitcoind\Client'); $bitcoind = new Bitcoind($bitcoind_client); return $bitcoind; }); $this->app->bind('Nbobtc\Bitcoind\Client', function($app) { $url_pieces = parse_url(Config::get('bitcoin-payer.connection_string')); $rpc_user = Config::get('bitcoin-payer.rpc_user'); $rpc_password = Config::get('bitcoin-payer.rpc_password'); $connection_string = "{$url_pieces['scheme']}://{$rpc_user}:{$rpc_password}@{$url_pieces['host']}:{$url_pieces['port']}"; $bitcoind_client = new Client($connection_string); return $bitcoind_client; }); $this->app->bind('Tokenly\BitcoinPayer\BitcoinPayer', function($app) { $bitcoind_client = $app->make('Nbobtc\Bitcoind\Client'); $bitcoind = $app->make('Nbobtc\Bitcoind\Bitcoind'); $cache_table_provider = function() { return DB::table('address_txos_cache'); }; $sender = new BitcoinPayer($bitcoind, $bitcoind_client, $cache_table_provider); return $sender; }); }
php
public function register() { $this->bindConfig(); $this->app->bind('Nbobtc\Bitcoind\Bitcoind', function($app) { $bitcoind_client = $app->make('Nbobtc\Bitcoind\Client'); $bitcoind = new Bitcoind($bitcoind_client); return $bitcoind; }); $this->app->bind('Nbobtc\Bitcoind\Client', function($app) { $url_pieces = parse_url(Config::get('bitcoin-payer.connection_string')); $rpc_user = Config::get('bitcoin-payer.rpc_user'); $rpc_password = Config::get('bitcoin-payer.rpc_password'); $connection_string = "{$url_pieces['scheme']}://{$rpc_user}:{$rpc_password}@{$url_pieces['host']}:{$url_pieces['port']}"; $bitcoind_client = new Client($connection_string); return $bitcoind_client; }); $this->app->bind('Tokenly\BitcoinPayer\BitcoinPayer', function($app) { $bitcoind_client = $app->make('Nbobtc\Bitcoind\Client'); $bitcoind = $app->make('Nbobtc\Bitcoind\Bitcoind'); $cache_table_provider = function() { return DB::table('address_txos_cache'); }; $sender = new BitcoinPayer($bitcoind, $bitcoind_client, $cache_table_provider); return $sender; }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "bindConfig", "(", ")", ";", "$", "this", "->", "app", "->", "bind", "(", "'Nbobtc\\Bitcoind\\Bitcoind'", ",", "function", "(", "$", "app", ")", "{", "$", "bitcoind_client", "=", "$", "app", "->", "make", "(", "'Nbobtc\\Bitcoind\\Client'", ")", ";", "$", "bitcoind", "=", "new", "Bitcoind", "(", "$", "bitcoind_client", ")", ";", "return", "$", "bitcoind", ";", "}", ")", ";", "$", "this", "->", "app", "->", "bind", "(", "'Nbobtc\\Bitcoind\\Client'", ",", "function", "(", "$", "app", ")", "{", "$", "url_pieces", "=", "parse_url", "(", "Config", "::", "get", "(", "'bitcoin-payer.connection_string'", ")", ")", ";", "$", "rpc_user", "=", "Config", "::", "get", "(", "'bitcoin-payer.rpc_user'", ")", ";", "$", "rpc_password", "=", "Config", "::", "get", "(", "'bitcoin-payer.rpc_password'", ")", ";", "$", "connection_string", "=", "\"{$url_pieces['scheme']}://{$rpc_user}:{$rpc_password}@{$url_pieces['host']}:{$url_pieces['port']}\"", ";", "$", "bitcoind_client", "=", "new", "Client", "(", "$", "connection_string", ")", ";", "return", "$", "bitcoind_client", ";", "}", ")", ";", "$", "this", "->", "app", "->", "bind", "(", "'Tokenly\\BitcoinPayer\\BitcoinPayer'", ",", "function", "(", "$", "app", ")", "{", "$", "bitcoind_client", "=", "$", "app", "->", "make", "(", "'Nbobtc\\Bitcoind\\Client'", ")", ";", "$", "bitcoind", "=", "$", "app", "->", "make", "(", "'Nbobtc\\Bitcoind\\Bitcoind'", ")", ";", "$", "cache_table_provider", "=", "function", "(", ")", "{", "return", "DB", "::", "table", "(", "'address_txos_cache'", ")", ";", "}", ";", "$", "sender", "=", "new", "BitcoinPayer", "(", "$", "bitcoind", ",", "$", "bitcoind_client", ",", "$", "cache_table_provider", ")", ";", "return", "$", "sender", ";", "}", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/tokenly/bitcoin-payer/blob/73d4b5b6a33e89e3a29cca99a464283046d31e6b/src/Tokenly/BitcoinPayer/Provider/BitcoinPayerServiceProvider.php#L29-L58
drunomics/service-utils
src/Core/Entity/EntityTypeManagerTrait.php
EntityTypeManagerTrait.getEntityTypeManager
public function getEntityTypeManager() { if (empty($this->entityTypeManager)) { $this->entityTypeManager = \Drupal::entityTypeManager(); } return $this->entityTypeManager; }
php
public function getEntityTypeManager() { if (empty($this->entityTypeManager)) { $this->entityTypeManager = \Drupal::entityTypeManager(); } return $this->entityTypeManager; }
[ "public", "function", "getEntityTypeManager", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "entityTypeManager", ")", ")", "{", "$", "this", "->", "entityTypeManager", "=", "\\", "Drupal", "::", "entityTypeManager", "(", ")", ";", "}", "return", "$", "this", "->", "entityTypeManager", ";", "}" ]
Gets the entity type manager. @return \Drupal\Core\Entity\EntityTypeManagerInterface The entity type manager.
[ "Gets", "the", "entity", "type", "manager", "." ]
train
https://github.com/drunomics/service-utils/blob/56761750043132365ef4ae5d9e0cf4263459328f/src/Core/Entity/EntityTypeManagerTrait.php#L38-L43
axelitus/php-base
src/Num.php
Num.parse
public static function parse($value, $default = null) { if (!is_string($value) || !is_numeric($value)) { return $default; } if(Int::extIs($value)){ return Int::parse($value); } else { return Float::parse($value); } }
php
public static function parse($value, $default = null) { if (!is_string($value) || !is_numeric($value)) { return $default; } if(Int::extIs($value)){ return Int::parse($value); } else { return Float::parse($value); } }
[ "public", "static", "function", "parse", "(", "$", "value", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", "||", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "$", "default", ";", "}", "if", "(", "Int", "::", "extIs", "(", "$", "value", ")", ")", "{", "return", "Int", "::", "parse", "(", "$", "value", ")", ";", "}", "else", "{", "return", "Float", "::", "parse", "(", "$", "value", ")", ";", "}", "}" ]
Parses a string numeric value into an integer or a float. @param string $value The value to parse. @param null $default The default return value if the given value is not a string or is not numeric. @return mixed Returns the parsed value or the default value.
[ "Parses", "a", "string", "numeric", "value", "into", "an", "integer", "or", "a", "float", "." ]
train
https://github.com/axelitus/php-base/blob/c2da680c1f0c3ee93ae6a8be5adaacd0caf7d075/src/Num.php#L68-L79
axelitus/php-base
src/Num.php
Num.compare
public static function compare($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 - $num2); }
php
public static function compare($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 - $num2); }
[ "public", "static", "function", "compare", "(", "$", "num1", ",", "$", "num2", ")", "{", "if", "(", "!", "static", "::", "is", "(", "$", "num1", ")", "||", "!", "static", "::", "is", "(", "$", "num2", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The \\$num1 and \\$num2 parameters must be numeric.\"", ")", ";", "}", "return", "(", "$", "num1", "-", "$", "num2", ")", ";", "}" ]
Compares two numeric values. The returning value contains the actual value difference. @param int|float $num1 The left operand. @param int|float $num2 The right operand. @return int Returns <0 if $num1<$num2, =0 if $num1 == $num2, >0 if $num1>$num2 @throws \InvalidArgumentException
[ "Compares", "two", "numeric", "values", "." ]
train
https://github.com/axelitus/php-base/blob/c2da680c1f0c3ee93ae6a8be5adaacd0caf7d075/src/Num.php#L128-L135
axelitus/php-base
src/Num.php
Num.add
public static function add($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 + $num2); }
php
public static function add($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 + $num2); }
[ "public", "static", "function", "add", "(", "$", "num1", ",", "$", "num2", ")", "{", "if", "(", "!", "static", "::", "is", "(", "$", "num1", ")", "||", "!", "static", "::", "is", "(", "$", "num2", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The \\$num1 and \\$num2 parameters must be numeric.\"", ")", ";", "}", "return", "(", "$", "num1", "+", "$", "num2", ")", ";", "}" ]
Adds a number to another number. @param int|float $num1 The left operand. @param int|float $num2 The right operand. @return int|float The result of the operation. @throws \InvalidArgumentException
[ "Adds", "a", "number", "to", "another", "number", "." ]
train
https://github.com/axelitus/php-base/blob/c2da680c1f0c3ee93ae6a8be5adaacd0caf7d075/src/Num.php#L234-L241
axelitus/php-base
src/Num.php
Num.sub
public static function sub($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 - $num2); }
php
public static function sub($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 - $num2); }
[ "public", "static", "function", "sub", "(", "$", "num1", ",", "$", "num2", ")", "{", "if", "(", "!", "static", "::", "is", "(", "$", "num1", ")", "||", "!", "static", "::", "is", "(", "$", "num2", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The \\$num1 and \\$num2 parameters must be numeric.\"", ")", ";", "}", "return", "(", "$", "num1", "-", "$", "num2", ")", ";", "}" ]
Subtracts a number from another number. @param int|float $num1 The left operand. @param int|float $num2 The right operand. @return int|float The result of the operation. @throws \InvalidArgumentException
[ "Subtracts", "a", "number", "from", "another", "number", "." ]
train
https://github.com/axelitus/php-base/blob/c2da680c1f0c3ee93ae6a8be5adaacd0caf7d075/src/Num.php#L252-L259
axelitus/php-base
src/Num.php
Num.mul
public static function mul($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 * $num2); }
php
public static function mul($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } return ($num1 * $num2); }
[ "public", "static", "function", "mul", "(", "$", "num1", ",", "$", "num2", ")", "{", "if", "(", "!", "static", "::", "is", "(", "$", "num1", ")", "||", "!", "static", "::", "is", "(", "$", "num2", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The \\$num1 and \\$num2 parameters must be numeric.\"", ")", ";", "}", "return", "(", "$", "num1", "*", "$", "num2", ")", ";", "}" ]
Multiplies a number by another number. @param int|float $num1 The left operand. @param int|float $num2 The right operand. @return int|float The result of the operation. @throws \InvalidArgumentException
[ "Multiplies", "a", "number", "by", "another", "number", "." ]
train
https://github.com/axelitus/php-base/blob/c2da680c1f0c3ee93ae6a8be5adaacd0caf7d075/src/Num.php#L270-L277
axelitus/php-base
src/Num.php
Num.div
public static function div($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } if ($num2 == 0) { throw new \InvalidArgumentException("Cannot divide by zero. The \$num2 parameter cannot be zero."); } return ($num1 / $num2); }
php
public static function div($num1, $num2) { if (!static::is($num1) || !static::is($num2)) { throw new \InvalidArgumentException("The \$num1 and \$num2 parameters must be numeric."); } if ($num2 == 0) { throw new \InvalidArgumentException("Cannot divide by zero. The \$num2 parameter cannot be zero."); } return ($num1 / $num2); }
[ "public", "static", "function", "div", "(", "$", "num1", ",", "$", "num2", ")", "{", "if", "(", "!", "static", "::", "is", "(", "$", "num1", ")", "||", "!", "static", "::", "is", "(", "$", "num2", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"The \\$num1 and \\$num2 parameters must be numeric.\"", ")", ";", "}", "if", "(", "$", "num2", "==", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Cannot divide by zero. The \\$num2 parameter cannot be zero.\"", ")", ";", "}", "return", "(", "$", "num1", "/", "$", "num2", ")", ";", "}" ]
Divides a number by another number. @param int|float $num1 The left operand. @param int|float $num2 The right operand. @return int|float The result of the operation. @throws \InvalidArgumentException
[ "Divides", "a", "number", "by", "another", "number", "." ]
train
https://github.com/axelitus/php-base/blob/c2da680c1f0c3ee93ae6a8be5adaacd0caf7d075/src/Num.php#L288-L299
stubbles/stubbles-webapp-core
src/main/php/auth/token/TokenFilter.php
TokenFilter.apply
public function apply(Value $value): array { if ($value->isEmpty()) { return $this->filtered(new Token(null)); } $value = $value->value(); if (strtolower(trim(substr($value, 0, 7))) === 'bearer') { return $this->filtered(new Token(substr($value, 7))); } return $this->filtered(new Token($value)); }
php
public function apply(Value $value): array { if ($value->isEmpty()) { return $this->filtered(new Token(null)); } $value = $value->value(); if (strtolower(trim(substr($value, 0, 7))) === 'bearer') { return $this->filtered(new Token(substr($value, 7))); } return $this->filtered(new Token($value)); }
[ "public", "function", "apply", "(", "Value", "$", "value", ")", ":", "array", "{", "if", "(", "$", "value", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "this", "->", "filtered", "(", "new", "Token", "(", "null", ")", ")", ";", "}", "$", "value", "=", "$", "value", "->", "value", "(", ")", ";", "if", "(", "strtolower", "(", "trim", "(", "substr", "(", "$", "value", ",", "0", ",", "7", ")", ")", ")", "===", "'bearer'", ")", "{", "return", "$", "this", "->", "filtered", "(", "new", "Token", "(", "substr", "(", "$", "value", ",", "7", ")", ")", ")", ";", "}", "return", "$", "this", "->", "filtered", "(", "new", "Token", "(", "$", "value", ")", ")", ";", "}" ]
apply filter on given value @param \stubbles\values\Value $value @return array
[ "apply", "filter", "on", "given", "value" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/auth/token/TokenFilter.php#L31-L43
nkt/flame
src/QueryBuilder/SelectQuery.php
SelectQuery.from
public function from($table, $alias = null) { if ($alias === null) { $this->from[] = $this->grammar->buildId($table); } else { $this->from[] = $this->grammar->buildIdWithAlias($table, $alias); } return $this; }
php
public function from($table, $alias = null) { if ($alias === null) { $this->from[] = $this->grammar->buildId($table); } else { $this->from[] = $this->grammar->buildIdWithAlias($table, $alias); } return $this; }
[ "public", "function", "from", "(", "$", "table", ",", "$", "alias", "=", "null", ")", "{", "if", "(", "$", "alias", "===", "null", ")", "{", "$", "this", "->", "from", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildId", "(", "$", "table", ")", ";", "}", "else", "{", "$", "this", "->", "from", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildIdWithAlias", "(", "$", "table", ",", "$", "alias", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $table @param string $alias @return static
[ "@param", "string", "$table", "@param", "string", "$alias" ]
train
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/SelectQuery.php#L71-L80
nkt/flame
src/QueryBuilder/SelectQuery.php
SelectQuery.column
public function column($name, $alias = null) { if ($alias === null) { $this->columns[] = $this->grammar->buildId($name); } else { $this->columns[] = $this->grammar->buildIdWithAlias($name, $alias); } return $this; }
php
public function column($name, $alias = null) { if ($alias === null) { $this->columns[] = $this->grammar->buildId($name); } else { $this->columns[] = $this->grammar->buildIdWithAlias($name, $alias); } return $this; }
[ "public", "function", "column", "(", "$", "name", ",", "$", "alias", "=", "null", ")", "{", "if", "(", "$", "alias", "===", "null", ")", "{", "$", "this", "->", "columns", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildId", "(", "$", "name", ")", ";", "}", "else", "{", "$", "this", "->", "columns", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildIdWithAlias", "(", "$", "name", ",", "$", "alias", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $name @param string $alias @return static
[ "@param", "string", "$name", "@param", "string", "$alias" ]
train
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/SelectQuery.php#L88-L97
nkt/flame
src/QueryBuilder/SelectQuery.php
SelectQuery.columns
public function columns($column) { foreach (func_get_args() as $column) { $this->columns[] = $this->grammar->buildId($column); } return $this; }
php
public function columns($column) { foreach (func_get_args() as $column) { $this->columns[] = $this->grammar->buildId($column); } return $this; }
[ "public", "function", "columns", "(", "$", "column", ")", "{", "foreach", "(", "func_get_args", "(", ")", "as", "$", "column", ")", "{", "$", "this", "->", "columns", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildId", "(", "$", "column", ")", ";", "}", "return", "$", "this", ";", "}" ]
@param string $column,... @return static
[ "@param", "string", "$column", "..." ]
train
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/SelectQuery.php#L104-L111
nkt/flame
src/QueryBuilder/SelectQuery.php
SelectQuery.orderBy
public function orderBy($column, $asc = true) { if ($asc) { $this->orders[] = $this->grammar->buildId($column) . ' ASC'; } else { $this->orders[] = $this->grammar->buildId($column) . ' DESC'; } return $this; }
php
public function orderBy($column, $asc = true) { if ($asc) { $this->orders[] = $this->grammar->buildId($column) . ' ASC'; } else { $this->orders[] = $this->grammar->buildId($column) . ' DESC'; } return $this; }
[ "public", "function", "orderBy", "(", "$", "column", ",", "$", "asc", "=", "true", ")", "{", "if", "(", "$", "asc", ")", "{", "$", "this", "->", "orders", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildId", "(", "$", "column", ")", ".", "' ASC'", ";", "}", "else", "{", "$", "this", "->", "orders", "[", "]", "=", "$", "this", "->", "grammar", "->", "buildId", "(", "$", "column", ")", ".", "' DESC'", ";", "}", "return", "$", "this", ";", "}" ]
@param string $column @param bool $asc @return static
[ "@param", "string", "$column", "@param", "bool", "$asc" ]
train
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/SelectQuery.php#L143-L152
nkt/flame
src/QueryBuilder/SelectQuery.php
SelectQuery.union
public function union(SelectQuery $select, $all = false) { $this->unions[] = "\nUNION" . ($all ? ' ALL' : '') . "\n" . $select; return $this; }
php
public function union(SelectQuery $select, $all = false) { $this->unions[] = "\nUNION" . ($all ? ' ALL' : '') . "\n" . $select; return $this; }
[ "public", "function", "union", "(", "SelectQuery", "$", "select", ",", "$", "all", "=", "false", ")", "{", "$", "this", "->", "unions", "[", "]", "=", "\"\\nUNION\"", ".", "(", "$", "all", "?", "' ALL'", ":", "''", ")", ".", "\"\\n\"", ".", "$", "select", ";", "return", "$", "this", ";", "}" ]
@param SelectQuery $select @param bool $all @return static
[ "@param", "SelectQuery", "$select", "@param", "bool", "$all" ]
train
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/SelectQuery.php#L184-L189
goblindegook/Syllables
src/Shortcode.php
Shortcode.output
final public function output( $atts, $content = null, $tag = null ) { if ( empty( $tag ) ) { $tag = $this->get_tag(); } $output = $this->render( $atts, $content, $tag ); /** * Filters the shortcode content. * * @param string $output This shortcode's rendered content. * @param array $atts The attributes used to invoke this shortcode. * @param string $content This shortcode's raw inner content. * @param string $tag This shortcode tag. * @return string This shortcode's filtered content. */ return \apply_filters( 'syllables/shortcode/output', $output, $atts, $content, $tag ); }
php
final public function output( $atts, $content = null, $tag = null ) { if ( empty( $tag ) ) { $tag = $this->get_tag(); } $output = $this->render( $atts, $content, $tag ); /** * Filters the shortcode content. * * @param string $output This shortcode's rendered content. * @param array $atts The attributes used to invoke this shortcode. * @param string $content This shortcode's raw inner content. * @param string $tag This shortcode tag. * @return string This shortcode's filtered content. */ return \apply_filters( 'syllables/shortcode/output', $output, $atts, $content, $tag ); }
[ "final", "public", "function", "output", "(", "$", "atts", ",", "$", "content", "=", "null", ",", "$", "tag", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "tag", ")", ")", "{", "$", "tag", "=", "$", "this", "->", "get_tag", "(", ")", ";", "}", "$", "output", "=", "$", "this", "->", "render", "(", "$", "atts", ",", "$", "content", ",", "$", "tag", ")", ";", "/**\n\t\t * Filters the shortcode content.\n\t\t *\n\t\t * @param string $output This shortcode's rendered content.\n\t\t * @param array $atts The attributes used to invoke this shortcode.\n\t\t * @param string $content This shortcode's raw inner content.\n\t\t * @param string $tag This shortcode tag.\n\t\t * @return string This shortcode's filtered content.\n\t\t */", "return", "\\", "apply_filters", "(", "'syllables/shortcode/output'", ",", "$", "output", ",", "$", "atts", ",", "$", "content", ",", "$", "tag", ")", ";", "}" ]
Callback that outputs the shortcode. @param array $atts The shortcode's attributes. @param string|null $content (Optional) Content enclosed in shortcode. @param string|null $tag (Optional) Shortcode tag. @return string The rendered shortcode. @uses \apply_filters()
[ "Callback", "that", "outputs", "the", "shortcode", "." ]
train
https://github.com/goblindegook/Syllables/blob/1a98cd15e37595a85b242242f88fee38c4e36acc/src/Shortcode.php#L91-L108
goblindegook/Syllables
src/Shortcode.php
Shortcode.render
public function render( $atts, $content = null, $tag = null ) { if ( is_callable( $this->callback ) ) { $content = call_user_func( $this->callback, $atts, $content, $tag ); } /** * Filters the shortcode content. * * @param string $content This shortcode's rendered content. * @param array $atts The attributes used to invoke this shortcode. * @param string $tag This shortcode tag. * @return string This shortcode's filtered content. * * @deprecated since 0.3.2. Use the `syllables/shortcode/output` filter hook. */ return \apply_filters( 'syllables/shortcode/render', $content, $atts, $tag ); }
php
public function render( $atts, $content = null, $tag = null ) { if ( is_callable( $this->callback ) ) { $content = call_user_func( $this->callback, $atts, $content, $tag ); } /** * Filters the shortcode content. * * @param string $content This shortcode's rendered content. * @param array $atts The attributes used to invoke this shortcode. * @param string $tag This shortcode tag. * @return string This shortcode's filtered content. * * @deprecated since 0.3.2. Use the `syllables/shortcode/output` filter hook. */ return \apply_filters( 'syllables/shortcode/render', $content, $atts, $tag ); }
[ "public", "function", "render", "(", "$", "atts", ",", "$", "content", "=", "null", ",", "$", "tag", "=", "null", ")", "{", "if", "(", "is_callable", "(", "$", "this", "->", "callback", ")", ")", "{", "$", "content", "=", "call_user_func", "(", "$", "this", "->", "callback", ",", "$", "atts", ",", "$", "content", ",", "$", "tag", ")", ";", "}", "/**\n\t\t * Filters the shortcode content.\n\t\t *\n\t\t * @param string $content This shortcode's rendered content.\n\t\t * @param array $atts The attributes used to invoke this shortcode.\n\t\t * @param string $tag This shortcode tag.\n\t\t * @return string This shortcode's filtered content.\n\t\t *\n\t\t * @deprecated since 0.3.2. Use the `syllables/shortcode/output` filter hook.\n\t\t */", "return", "\\", "apply_filters", "(", "'syllables/shortcode/render'", ",", "$", "content", ",", "$", "atts", ",", "$", "tag", ")", ";", "}" ]
Renders the hooked shortcode. @param array $atts The shortcode's attributes. @param string|null $content (Optional) Content enclosed in shortcode. @param string|null $tag (Optional) Shortcode tag. @return string The rendered shortcode. @uses \apply_filters()
[ "Renders", "the", "hooked", "shortcode", "." ]
train
https://github.com/goblindegook/Syllables/blob/1a98cd15e37595a85b242242f88fee38c4e36acc/src/Shortcode.php#L120-L137
Agares/MicroORM
src/EntityMapper.php
EntityMapper.mapEntityFields
private function mapEntityFields(array $fields, \ReflectionClass $entityReflection, $entityInstance, array $fieldsDefinition) { foreach ($fieldsDefinition as $fieldName => $definition) { $typeName = $definition->getTypeName(); if (!isset($this->typeMappers[$typeName])) { throw new UnknownFieldTypeException($typeName); } $fieldReflection = $entityReflection->getProperty($definition->getFieldName()); $fieldReflection->setAccessible(true); $fieldReflection->setValue($entityInstance, $this->typeMappers[$typeName]->fromString($fieldName, $fields)); $fieldReflection->setAccessible(false); } }
php
private function mapEntityFields(array $fields, \ReflectionClass $entityReflection, $entityInstance, array $fieldsDefinition) { foreach ($fieldsDefinition as $fieldName => $definition) { $typeName = $definition->getTypeName(); if (!isset($this->typeMappers[$typeName])) { throw new UnknownFieldTypeException($typeName); } $fieldReflection = $entityReflection->getProperty($definition->getFieldName()); $fieldReflection->setAccessible(true); $fieldReflection->setValue($entityInstance, $this->typeMappers[$typeName]->fromString($fieldName, $fields)); $fieldReflection->setAccessible(false); } }
[ "private", "function", "mapEntityFields", "(", "array", "$", "fields", ",", "\\", "ReflectionClass", "$", "entityReflection", ",", "$", "entityInstance", ",", "array", "$", "fieldsDefinition", ")", "{", "foreach", "(", "$", "fieldsDefinition", "as", "$", "fieldName", "=>", "$", "definition", ")", "{", "$", "typeName", "=", "$", "definition", "->", "getTypeName", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "typeMappers", "[", "$", "typeName", "]", ")", ")", "{", "throw", "new", "UnknownFieldTypeException", "(", "$", "typeName", ")", ";", "}", "$", "fieldReflection", "=", "$", "entityReflection", "->", "getProperty", "(", "$", "definition", "->", "getFieldName", "(", ")", ")", ";", "$", "fieldReflection", "->", "setAccessible", "(", "true", ")", ";", "$", "fieldReflection", "->", "setValue", "(", "$", "entityInstance", ",", "$", "this", "->", "typeMappers", "[", "$", "typeName", "]", "->", "fromString", "(", "$", "fieldName", ",", "$", "fields", ")", ")", ";", "$", "fieldReflection", "->", "setAccessible", "(", "false", ")", ";", "}", "}" ]
@param array $fields @param \ReflectionClass $entityReflection @param mixed $entityInstance @param EntityFieldDefinition[] $fieldsDefinition @throws UnknownFieldTypeException
[ "@param", "array", "$fields", "@param", "\\", "ReflectionClass", "$entityReflection", "@param", "mixed", "$entityInstance", "@param", "EntityFieldDefinition", "[]", "$fieldsDefinition" ]
train
https://github.com/Agares/MicroORM/blob/2852bdff07d91c436725b574cf6dea4e4dab7060/src/EntityMapper.php#L56-L70
contao-bootstrap/buttons
src/Netzmacht/Bootstrap/Buttons/Button.php
Button.generate
public function generate() { return sprintf( '<%s %s>%s</%s>%s', $this->tag, parent::generate(), $this->label, $this->tag, PHP_EOL ); }
php
public function generate() { return sprintf( '<%s %s>%s</%s>%s', $this->tag, parent::generate(), $this->label, $this->tag, PHP_EOL ); }
[ "public", "function", "generate", "(", ")", "{", "return", "sprintf", "(", "'<%s %s>%s</%s>%s'", ",", "$", "this", "->", "tag", ",", "parent", "::", "generate", "(", ")", ",", "$", "this", "->", "label", ",", "$", "this", "->", "tag", ",", "PHP_EOL", ")", ";", "}" ]
Generate the button. @return string
[ "Generate", "the", "button", "." ]
train
https://github.com/contao-bootstrap/buttons/blob/f573a24c19ec059aae528a12ba46dfc993844201/src/Netzmacht/Bootstrap/Buttons/Button.php#L106-L116
ejsmont-artur/phpProxyBuilder
src/PhpProxyBuilder/Adapter/Log/SimpleErrorLog.php
SimpleErrorLog.logDebug
public function logDebug($message, $attachment = null) { error_log($message . print_r($attachment, true), $this->messageType , $this->destination); }
php
public function logDebug($message, $attachment = null) { error_log($message . print_r($attachment, true), $this->messageType , $this->destination); }
[ "public", "function", "logDebug", "(", "$", "message", ",", "$", "attachment", "=", "null", ")", "{", "error_log", "(", "$", "message", ".", "print_r", "(", "$", "attachment", ",", "true", ")", ",", "$", "this", "->", "messageType", ",", "$", "this", "->", "destination", ")", ";", "}" ]
Log message as debug level @param string $message @param mixed $attachment optional array or structure of data to be attached @return void
[ "Log", "message", "as", "debug", "level" ]
train
https://github.com/ejsmont-artur/phpProxyBuilder/blob/ef7ec14e5d18eeba7a93e3617a0fdb5b146d6480/src/PhpProxyBuilder/Adapter/Log/SimpleErrorLog.php#L62-L64
bocharsky-bw/FileNamingResolver
src/NamingStrategy/DatetimeNamingStrategy.php
DatetimeNamingStrategy.provideName
public function provideName(FileInfo $srcFileInfo) { $datetime = \DateTime::createFromFormat('U.u', microtime(true)); $pathSuffix = FileInfo::purifyPath($datetime->format($this->dirFormat)); $dstFileInfo = $srcFileInfo ->changePath($srcFileInfo->getPath().FileInfo::SEPARATOR_DIRECTORY.$pathSuffix) ->changeBasename($datetime->format($this->fileFormat)) ; return $dstFileInfo; }
php
public function provideName(FileInfo $srcFileInfo) { $datetime = \DateTime::createFromFormat('U.u', microtime(true)); $pathSuffix = FileInfo::purifyPath($datetime->format($this->dirFormat)); $dstFileInfo = $srcFileInfo ->changePath($srcFileInfo->getPath().FileInfo::SEPARATOR_DIRECTORY.$pathSuffix) ->changeBasename($datetime->format($this->fileFormat)) ; return $dstFileInfo; }
[ "public", "function", "provideName", "(", "FileInfo", "$", "srcFileInfo", ")", "{", "$", "datetime", "=", "\\", "DateTime", "::", "createFromFormat", "(", "'U.u'", ",", "microtime", "(", "true", ")", ")", ";", "$", "pathSuffix", "=", "FileInfo", "::", "purifyPath", "(", "$", "datetime", "->", "format", "(", "$", "this", "->", "dirFormat", ")", ")", ";", "$", "dstFileInfo", "=", "$", "srcFileInfo", "->", "changePath", "(", "$", "srcFileInfo", "->", "getPath", "(", ")", ".", "FileInfo", "::", "SEPARATOR_DIRECTORY", ".", "$", "pathSuffix", ")", "->", "changeBasename", "(", "$", "datetime", "->", "format", "(", "$", "this", "->", "fileFormat", ")", ")", ";", "return", "$", "dstFileInfo", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/bocharsky-bw/FileNamingResolver/blob/0a0fe86fee0e7acf1ab43a84c1abd51954ce2fbe/src/NamingStrategy/DatetimeNamingStrategy.php#L45-L56
baleen/cli
src/CommandBus/Config/InitHandler.php
InitHandler.handle
public function handle(InitMessage $message) { $output = $message->getOutput(); $configStorage = $message->getConfigStorage(); if ($configStorage->isInitialized($message->getConfig())) { $output->writeln(sprintf( '%s is already initialised!', $message->getCliCommand()->getApplication()->getName() )); return; } $result = $configStorage->write($message->getConfig()); if ($result !== false) { $msg = sprintf('Config file created at "<info>%s</info>".', $message->getConfig()->getFileName()); } else { $msg = sprintf( '<error>Error: Could not create and write file "<info>%s</info>". '. 'Please check file and directory permissions.</error>', $message->getConfig()->getFileName() ); } $output->writeln($msg); }
php
public function handle(InitMessage $message) { $output = $message->getOutput(); $configStorage = $message->getConfigStorage(); if ($configStorage->isInitialized($message->getConfig())) { $output->writeln(sprintf( '%s is already initialised!', $message->getCliCommand()->getApplication()->getName() )); return; } $result = $configStorage->write($message->getConfig()); if ($result !== false) { $msg = sprintf('Config file created at "<info>%s</info>".', $message->getConfig()->getFileName()); } else { $msg = sprintf( '<error>Error: Could not create and write file "<info>%s</info>". '. 'Please check file and directory permissions.</error>', $message->getConfig()->getFileName() ); } $output->writeln($msg); }
[ "public", "function", "handle", "(", "InitMessage", "$", "message", ")", "{", "$", "output", "=", "$", "message", "->", "getOutput", "(", ")", ";", "$", "configStorage", "=", "$", "message", "->", "getConfigStorage", "(", ")", ";", "if", "(", "$", "configStorage", "->", "isInitialized", "(", "$", "message", "->", "getConfig", "(", ")", ")", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'%s is already initialised!'", ",", "$", "message", "->", "getCliCommand", "(", ")", "->", "getApplication", "(", ")", "->", "getName", "(", ")", ")", ")", ";", "return", ";", "}", "$", "result", "=", "$", "configStorage", "->", "write", "(", "$", "message", "->", "getConfig", "(", ")", ")", ";", "if", "(", "$", "result", "!==", "false", ")", "{", "$", "msg", "=", "sprintf", "(", "'Config file created at \"<info>%s</info>\".'", ",", "$", "message", "->", "getConfig", "(", ")", "->", "getFileName", "(", ")", ")", ";", "}", "else", "{", "$", "msg", "=", "sprintf", "(", "'<error>Error: Could not create and write file \"<info>%s</info>\". '", ".", "'Please check file and directory permissions.</error>'", ",", "$", "message", "->", "getConfig", "(", ")", "->", "getFileName", "(", ")", ")", ";", "}", "$", "output", "->", "writeln", "(", "$", "msg", ")", ";", "}" ]
Handle an InitMessage. Creates an end-user configuration file using default values. If the file already exists it simply exists without doing anything. @param InitMessage $message
[ "Handle", "an", "InitMessage", ".", "Creates", "an", "end", "-", "user", "configuration", "file", "using", "default", "values", ".", "If", "the", "file", "already", "exists", "it", "simply", "exists", "without", "doing", "anything", "." ]
train
https://github.com/baleen/cli/blob/2ecbc7179c5800c9075fd93204ef25da375536ed/src/CommandBus/Config/InitHandler.php#L36-L62
pageon/SlackWebhookMonolog
src/Slack/Payload.php
Payload.setIcon
private function setIcon() { if (!$this->slackConfig->getCustomUser()->hasIcon()) { return; } $iconType = 'icon_' . $this->slackConfig->getCustomUser()->getIcon()->getType(); $this->payload[$iconType] = $this->slackConfig->getCustomUser()->getIcon(); }
php
private function setIcon() { if (!$this->slackConfig->getCustomUser()->hasIcon()) { return; } $iconType = 'icon_' . $this->slackConfig->getCustomUser()->getIcon()->getType(); $this->payload[$iconType] = $this->slackConfig->getCustomUser()->getIcon(); }
[ "private", "function", "setIcon", "(", ")", "{", "if", "(", "!", "$", "this", "->", "slackConfig", "->", "getCustomUser", "(", ")", "->", "hasIcon", "(", ")", ")", "{", "return", ";", "}", "$", "iconType", "=", "'icon_'", ".", "$", "this", "->", "slackConfig", "->", "getCustomUser", "(", ")", "->", "getIcon", "(", ")", "->", "getType", "(", ")", ";", "$", "this", "->", "payload", "[", "$", "iconType", "]", "=", "$", "this", "->", "slackConfig", "->", "getCustomUser", "(", ")", "->", "getIcon", "(", ")", ";", "}" ]
Set a custom icon if available.
[ "Set", "a", "custom", "icon", "if", "available", "." ]
train
https://github.com/pageon/SlackWebhookMonolog/blob/6755060ddd6429620fd4c7decbb95f05463fc36b/src/Slack/Payload.php#L93-L101
pageon/SlackWebhookMonolog
src/Slack/Payload.php
Payload.setUsername
private function setUsername() { if (!$this->slackConfig->getCustomUser()->hasUsername()) { return; } $this->payload['username'] = $this->slackConfig->getCustomUser()->getUsername(); }
php
private function setUsername() { if (!$this->slackConfig->getCustomUser()->hasUsername()) { return; } $this->payload['username'] = $this->slackConfig->getCustomUser()->getUsername(); }
[ "private", "function", "setUsername", "(", ")", "{", "if", "(", "!", "$", "this", "->", "slackConfig", "->", "getCustomUser", "(", ")", "->", "hasUsername", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "payload", "[", "'username'", "]", "=", "$", "this", "->", "slackConfig", "->", "getCustomUser", "(", ")", "->", "getUsername", "(", ")", ";", "}" ]
Set a custom username if available.
[ "Set", "a", "custom", "username", "if", "available", "." ]
train
https://github.com/pageon/SlackWebhookMonolog/blob/6755060ddd6429620fd4c7decbb95f05463fc36b/src/Slack/Payload.php#L106-L113
pageon/SlackWebhookMonolog
src/Slack/Payload.php
Payload.setChannel
private function setChannel() { if (!$this->slackConfig->getWebhook()->hasCustomChannel()) { return; } $this->payload['channel'] = $this->slackConfig->getWebhook()->getCustomChannel(); }
php
private function setChannel() { if (!$this->slackConfig->getWebhook()->hasCustomChannel()) { return; } $this->payload['channel'] = $this->slackConfig->getWebhook()->getCustomChannel(); }
[ "private", "function", "setChannel", "(", ")", "{", "if", "(", "!", "$", "this", "->", "slackConfig", "->", "getWebhook", "(", ")", "->", "hasCustomChannel", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "payload", "[", "'channel'", "]", "=", "$", "this", "->", "slackConfig", "->", "getWebhook", "(", ")", "->", "getCustomChannel", "(", ")", ";", "}" ]
Set a custom channel if available.
[ "Set", "a", "custom", "channel", "if", "available", "." ]
train
https://github.com/pageon/SlackWebhookMonolog/blob/6755060ddd6429620fd4c7decbb95f05463fc36b/src/Slack/Payload.php#L118-L125
pageon/SlackWebhookMonolog
src/Slack/Payload.php
Payload.setErrorData
private function setErrorData() { if (!isset($this->record['context']['error'])) { return; } $this->errorData = $this->record['context']['error']; // remove the error from the context so we can use it for for other things. unset($this->record['context']['error']); }
php
private function setErrorData() { if (!isset($this->record['context']['error'])) { return; } $this->errorData = $this->record['context']['error']; // remove the error from the context so we can use it for for other things. unset($this->record['context']['error']); }
[ "private", "function", "setErrorData", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "record", "[", "'context'", "]", "[", "'error'", "]", ")", ")", "{", "return", ";", "}", "$", "this", "->", "errorData", "=", "$", "this", "->", "record", "[", "'context'", "]", "[", "'error'", "]", ";", "// remove the error from the context so we can use it for for other things.", "unset", "(", "$", "this", "->", "record", "[", "'context'", "]", "[", "'error'", "]", ")", ";", "}" ]
If available set the error data.
[ "If", "available", "set", "the", "error", "data", "." ]
train
https://github.com/pageon/SlackWebhookMonolog/blob/6755060ddd6429620fd4c7decbb95f05463fc36b/src/Slack/Payload.php#L130-L140
nicolasmure/NmureEncryptor
src/Formatter/HexFormatter.php
HexFormatter.parse
public function parse($input, $ivLength) { $input = hex2bin($input); return array( self::KEY_IV => substr($input, 0, $ivLength), self::KEY_DATA => substr($input, $ivLength, strlen($input)), ); }
php
public function parse($input, $ivLength) { $input = hex2bin($input); return array( self::KEY_IV => substr($input, 0, $ivLength), self::KEY_DATA => substr($input, $ivLength, strlen($input)), ); }
[ "public", "function", "parse", "(", "$", "input", ",", "$", "ivLength", ")", "{", "$", "input", "=", "hex2bin", "(", "$", "input", ")", ";", "return", "array", "(", "self", "::", "KEY_IV", "=>", "substr", "(", "$", "input", ",", "0", ",", "$", "ivLength", ")", ",", "self", "::", "KEY_DATA", "=>", "substr", "(", "$", "input", ",", "$", "ivLength", ",", "strlen", "(", "$", "input", ")", ")", ",", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/nicolasmure/NmureEncryptor/blob/571b5311e7230f5a1241706edacbb2346624634d/src/Formatter/HexFormatter.php#L20-L28
DeprecatedPackages/CodingStandard
src/ZenifyCodingStandard/Sniffs/Namespaces/UseDeclarationSniff.php
UseDeclarationSniff.shouldIgnoreUse
private function shouldIgnoreUse(PHP_CodeSniffer_File $file, $position) : bool { $tokens = $file->getTokens(); // Ignore USE keywords inside closures. $next = $file->findNext(T_WHITESPACE, ($position + 1), NULL, TRUE); if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) { return TRUE; } // Ignore USE keywords for traits. if ($file->hasCondition($position, [T_CLASS, T_TRAIT]) === TRUE) { return TRUE; } return FALSE; }
php
private function shouldIgnoreUse(PHP_CodeSniffer_File $file, $position) : bool { $tokens = $file->getTokens(); // Ignore USE keywords inside closures. $next = $file->findNext(T_WHITESPACE, ($position + 1), NULL, TRUE); if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) { return TRUE; } // Ignore USE keywords for traits. if ($file->hasCondition($position, [T_CLASS, T_TRAIT]) === TRUE) { return TRUE; } return FALSE; }
[ "private", "function", "shouldIgnoreUse", "(", "PHP_CodeSniffer_File", "$", "file", ",", "$", "position", ")", ":", "bool", "{", "$", "tokens", "=", "$", "file", "->", "getTokens", "(", ")", ";", "// Ignore USE keywords inside closures.", "$", "next", "=", "$", "file", "->", "findNext", "(", "T_WHITESPACE", ",", "(", "$", "position", "+", "1", ")", ",", "NULL", ",", "TRUE", ")", ";", "if", "(", "$", "tokens", "[", "$", "next", "]", "[", "'code'", "]", "===", "T_OPEN_PARENTHESIS", ")", "{", "return", "TRUE", ";", "}", "// Ignore USE keywords for traits.", "if", "(", "$", "file", "->", "hasCondition", "(", "$", "position", ",", "[", "T_CLASS", ",", "T_TRAIT", "]", ")", "===", "TRUE", ")", "{", "return", "TRUE", ";", "}", "return", "FALSE", ";", "}" ]
Check if this use statement is part of the namespace block. @param PHP_CodeSniffer_File $file @param int|bool $position
[ "Check", "if", "this", "use", "statement", "is", "part", "of", "the", "namespace", "block", "." ]
train
https://github.com/DeprecatedPackages/CodingStandard/blob/071a296bca199c8b7341e7c9e2f20f33d81b230e/src/ZenifyCodingStandard/Sniffs/Namespaces/UseDeclarationSniff.php#L84-L100
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php
LoginLogQuery.filterById
public function filterById($id = null, $comparison = null) { if (is_array($id)) { $useMinMax = false; if (isset($id['min'])) { $this->addUsingAlias(LoginLogTableMap::COL_ID, $id['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($id['max'])) { $this->addUsingAlias(LoginLogTableMap::COL_ID, $id['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(LoginLogTableMap::COL_ID, $id, $comparison); }
php
public function filterById($id = null, $comparison = null) { if (is_array($id)) { $useMinMax = false; if (isset($id['min'])) { $this->addUsingAlias(LoginLogTableMap::COL_ID, $id['min'], Criteria::GREATER_EQUAL); $useMinMax = true; } if (isset($id['max'])) { $this->addUsingAlias(LoginLogTableMap::COL_ID, $id['max'], Criteria::LESS_EQUAL); $useMinMax = true; } if ($useMinMax) { return $this; } if (null === $comparison) { $comparison = Criteria::IN; } } return $this->addUsingAlias(LoginLogTableMap::COL_ID, $id, $comparison); }
[ "public", "function", "filterById", "(", "$", "id", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "id", ")", ")", "{", "$", "useMinMax", "=", "false", ";", "if", "(", "isset", "(", "$", "id", "[", "'min'", "]", ")", ")", "{", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_ID", ",", "$", "id", "[", "'min'", "]", ",", "Criteria", "::", "GREATER_EQUAL", ")", ";", "$", "useMinMax", "=", "true", ";", "}", "if", "(", "isset", "(", "$", "id", "[", "'max'", "]", ")", ")", "{", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_ID", ",", "$", "id", "[", "'max'", "]", ",", "Criteria", "::", "LESS_EQUAL", ")", ";", "$", "useMinMax", "=", "true", ";", "}", "if", "(", "$", "useMinMax", ")", "{", "return", "$", "this", ";", "}", "if", "(", "null", "===", "$", "comparison", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_ID", ",", "$", "id", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the id column Example usage: <code> $query->filterById(1234); // WHERE id = 1234 $query->filterById(array(12, 34)); // WHERE id IN (12, 34) $query->filterById(array('min' => 12)); // WHERE id > 12 </code> @param mixed $id The value to use as filter. Use scalar values for equality. Use array values for in_array() equivalent. Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return $this|ChildLoginLogQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "id", "column" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php#L270-L291
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php
LoginLogQuery.filterByType
public function filterByType($type = null, $comparison = null) { if (null === $comparison) { if (is_array($type)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $type)) { $type = str_replace('*', '%', $type); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(LoginLogTableMap::COL_TYPE, $type, $comparison); }
php
public function filterByType($type = null, $comparison = null) { if (null === $comparison) { if (is_array($type)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $type)) { $type = str_replace('*', '%', $type); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(LoginLogTableMap::COL_TYPE, $type, $comparison); }
[ "public", "function", "filterByType", "(", "$", "type", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "type", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "type", ")", ")", "{", "$", "type", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "type", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_TYPE", ",", "$", "type", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the type column Example usage: <code> $query->filterByType('fooValue'); // WHERE type = 'fooValue' $query->filterByType('%fooValue%'); // WHERE type LIKE '%fooValue%' </code> @param string $type The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return $this|ChildLoginLogQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "type", "column" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php#L308-L320
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php
LoginLogQuery.filterByClientAddress
public function filterByClientAddress($clientAddress = null, $comparison = null) { if (null === $comparison) { if (is_array($clientAddress)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $clientAddress)) { $clientAddress = str_replace('*', '%', $clientAddress); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(LoginLogTableMap::COL_CLIENT_ADDRESS, $clientAddress, $comparison); }
php
public function filterByClientAddress($clientAddress = null, $comparison = null) { if (null === $comparison) { if (is_array($clientAddress)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $clientAddress)) { $clientAddress = str_replace('*', '%', $clientAddress); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(LoginLogTableMap::COL_CLIENT_ADDRESS, $clientAddress, $comparison); }
[ "public", "function", "filterByClientAddress", "(", "$", "clientAddress", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "clientAddress", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "clientAddress", ")", ")", "{", "$", "clientAddress", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "clientAddress", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_CLIENT_ADDRESS", ",", "$", "clientAddress", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the client_address column Example usage: <code> $query->filterByClientAddress('fooValue'); // WHERE client_address = 'fooValue' $query->filterByClientAddress('%fooValue%'); // WHERE client_address LIKE '%fooValue%' </code> @param string $clientAddress The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return $this|ChildLoginLogQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "client_address", "column" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php#L467-L479
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php
LoginLogQuery.filterByClientIp
public function filterByClientIp($clientIp = null, $comparison = null) { if (null === $comparison) { if (is_array($clientIp)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $clientIp)) { $clientIp = str_replace('*', '%', $clientIp); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(LoginLogTableMap::COL_CLIENT_IP, $clientIp, $comparison); }
php
public function filterByClientIp($clientIp = null, $comparison = null) { if (null === $comparison) { if (is_array($clientIp)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $clientIp)) { $clientIp = str_replace('*', '%', $clientIp); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(LoginLogTableMap::COL_CLIENT_IP, $clientIp, $comparison); }
[ "public", "function", "filterByClientIp", "(", "$", "clientIp", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "clientIp", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "clientIp", ")", ")", "{", "$", "clientIp", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "clientIp", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_CLIENT_IP", ",", "$", "clientIp", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the client_ip column Example usage: <code> $query->filterByClientIp('fooValue'); // WHERE client_ip = 'fooValue' $query->filterByClientIp('%fooValue%'); // WHERE client_ip LIKE '%fooValue%' </code> @param string $clientIp The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return $this|ChildLoginLogQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "client_ip", "column" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php#L496-L508
phpalchemy/cerberus
src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php
LoginLogQuery.prune
public function prune($loginLog = null) { if ($loginLog) { $this->addUsingAlias(LoginLogTableMap::COL_ID, $loginLog->getId(), Criteria::NOT_EQUAL); } return $this; }
php
public function prune($loginLog = null) { if ($loginLog) { $this->addUsingAlias(LoginLogTableMap::COL_ID, $loginLog->getId(), Criteria::NOT_EQUAL); } return $this; }
[ "public", "function", "prune", "(", "$", "loginLog", "=", "null", ")", "{", "if", "(", "$", "loginLog", ")", "{", "$", "this", "->", "addUsingAlias", "(", "LoginLogTableMap", "::", "COL_ID", ",", "$", "loginLog", "->", "getId", "(", ")", ",", "Criteria", "::", "NOT_EQUAL", ")", ";", "}", "return", "$", "this", ";", "}" ]
Exclude object from result @param ChildLoginLog $loginLog Object to remove from the list of results @return $this|ChildLoginLogQuery The current query, for fluid interface
[ "Exclude", "object", "from", "result" ]
train
https://github.com/phpalchemy/cerberus/blob/3424a360c9bded71eb5b570bc114a7759cb23ec6/src/Alchemy/Component/Cerberus/Model/Base/LoginLogQuery.php#L575-L582
withfatpanda/illuminate-wordpress
src/WordPress/Models/PostBuilder.php
PostBuilder.with
function with($meta, $operator = null, $value = null) { list($value, $operator) = $this->prepareValueAndOperator( $value, $operator, func_num_args() == 2 ); static $count; if (empty($count)) { $count = 0; } if (!is_array($meta)) { $meta = [ $meta => $value ]; } foreach($meta as $key => $value) { $alias = '_with_condition_'.(++$count); $this->query->join("postmeta as {$alias}", "{$alias}.post_id", '=', 'ID'); $this->query->where("{$alias}.meta_key", '_' . $key); $this->query->where("{$alias}.meta_value", $operator, $value); } return $this; }
php
function with($meta, $operator = null, $value = null) { list($value, $operator) = $this->prepareValueAndOperator( $value, $operator, func_num_args() == 2 ); static $count; if (empty($count)) { $count = 0; } if (!is_array($meta)) { $meta = [ $meta => $value ]; } foreach($meta as $key => $value) { $alias = '_with_condition_'.(++$count); $this->query->join("postmeta as {$alias}", "{$alias}.post_id", '=', 'ID'); $this->query->where("{$alias}.meta_key", '_' . $key); $this->query->where("{$alias}.meta_value", $operator, $value); } return $this; }
[ "function", "with", "(", "$", "meta", ",", "$", "operator", "=", "null", ",", "$", "value", "=", "null", ")", "{", "list", "(", "$", "value", ",", "$", "operator", ")", "=", "$", "this", "->", "prepareValueAndOperator", "(", "$", "value", ",", "$", "operator", ",", "func_num_args", "(", ")", "==", "2", ")", ";", "static", "$", "count", ";", "if", "(", "empty", "(", "$", "count", ")", ")", "{", "$", "count", "=", "0", ";", "}", "if", "(", "!", "is_array", "(", "$", "meta", ")", ")", "{", "$", "meta", "=", "[", "$", "meta", "=>", "$", "value", "]", ";", "}", "foreach", "(", "$", "meta", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "alias", "=", "'_with_condition_'", ".", "(", "++", "$", "count", ")", ";", "$", "this", "->", "query", "->", "join", "(", "\"postmeta as {$alias}\"", ",", "\"{$alias}.post_id\"", ",", "'='", ",", "'ID'", ")", ";", "$", "this", "->", "query", "->", "where", "(", "\"{$alias}.meta_key\"", ",", "'_'", ".", "$", "key", ")", ";", "$", "this", "->", "query", "->", "where", "(", "\"{$alias}.meta_value\"", ",", "$", "operator", ",", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add one or more meta data conditions to the query.
[ "Add", "one", "or", "more", "meta", "data", "conditions", "to", "the", "query", "." ]
train
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Models/PostBuilder.php#L11-L35
gdbots/pbjx-bundle-php
src/Controller/PbjxReceiveController.php
PbjxReceiveController.receiveAction
public function receiveAction(Request $request): JsonResponse { if (!$this->enabled) { throw new AccessDeniedHttpException( 'The receive endpoint is not enabled.', null, Code::UNIMPLEMENTED ); } $token = $request->headers->get('x-pbjx-token'); if (empty($token)) { throw new AccessDeniedHttpException( 'The receive endpoint requires the "x-pbjx-token" header.', null, Code::PERMISSION_DENIED ); } try { $this->signer->validate($request->getContent(), $request->getUri(), $token); } catch (\Throwable $e) { throw new AccessDeniedHttpException($e->getMessage(), $e, Code::PERMISSION_DENIED); } $handle = $request->getContent(true); $data = [ 'lines' => [ 'total' => 0, 'ok' => 0, 'failed' => 0, 'ignored' => 0, ], 'results' => [], ]; while (($line = fgets($handle)) !== false) { ++$data['lines']['total']; $line = trim($line); if (empty($line)) { ++$data['lines']['ignored']; $data['results'][] = [ 'ok' => false, 'code' => Code::INVALID_ARGUMENT, 'error_name' => 'InvalidArgumentException', 'error_message' => 'empty line', ]; continue; } $message = null; $result = []; try { $envelope = TransportEnvelope::fromString($line); $message = $envelope->getMessage(); $this->receiveMessage($message); ++$data['lines']['ok']; $result['ok'] = true; $result['code'] = Code::OK; $result['message_ref'] = $message->generateMessageRef()->toString(); } catch (\Throwable $e) { ++$data['lines']['failed']; $this->handleException($result, $e); if ($message instanceof Message) { $result['message_ref'] = $message->generateMessageRef()->toString(); } } $data['results'][] = $result; } return JsonResponse::create($data); }
php
public function receiveAction(Request $request): JsonResponse { if (!$this->enabled) { throw new AccessDeniedHttpException( 'The receive endpoint is not enabled.', null, Code::UNIMPLEMENTED ); } $token = $request->headers->get('x-pbjx-token'); if (empty($token)) { throw new AccessDeniedHttpException( 'The receive endpoint requires the "x-pbjx-token" header.', null, Code::PERMISSION_DENIED ); } try { $this->signer->validate($request->getContent(), $request->getUri(), $token); } catch (\Throwable $e) { throw new AccessDeniedHttpException($e->getMessage(), $e, Code::PERMISSION_DENIED); } $handle = $request->getContent(true); $data = [ 'lines' => [ 'total' => 0, 'ok' => 0, 'failed' => 0, 'ignored' => 0, ], 'results' => [], ]; while (($line = fgets($handle)) !== false) { ++$data['lines']['total']; $line = trim($line); if (empty($line)) { ++$data['lines']['ignored']; $data['results'][] = [ 'ok' => false, 'code' => Code::INVALID_ARGUMENT, 'error_name' => 'InvalidArgumentException', 'error_message' => 'empty line', ]; continue; } $message = null; $result = []; try { $envelope = TransportEnvelope::fromString($line); $message = $envelope->getMessage(); $this->receiveMessage($message); ++$data['lines']['ok']; $result['ok'] = true; $result['code'] = Code::OK; $result['message_ref'] = $message->generateMessageRef()->toString(); } catch (\Throwable $e) { ++$data['lines']['failed']; $this->handleException($result, $e); if ($message instanceof Message) { $result['message_ref'] = $message->generateMessageRef()->toString(); } } $data['results'][] = $result; } return JsonResponse::create($data); }
[ "public", "function", "receiveAction", "(", "Request", "$", "request", ")", ":", "JsonResponse", "{", "if", "(", "!", "$", "this", "->", "enabled", ")", "{", "throw", "new", "AccessDeniedHttpException", "(", "'The receive endpoint is not enabled.'", ",", "null", ",", "Code", "::", "UNIMPLEMENTED", ")", ";", "}", "$", "token", "=", "$", "request", "->", "headers", "->", "get", "(", "'x-pbjx-token'", ")", ";", "if", "(", "empty", "(", "$", "token", ")", ")", "{", "throw", "new", "AccessDeniedHttpException", "(", "'The receive endpoint requires the \"x-pbjx-token\" header.'", ",", "null", ",", "Code", "::", "PERMISSION_DENIED", ")", ";", "}", "try", "{", "$", "this", "->", "signer", "->", "validate", "(", "$", "request", "->", "getContent", "(", ")", ",", "$", "request", "->", "getUri", "(", ")", ",", "$", "token", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "throw", "new", "AccessDeniedHttpException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", ",", "Code", "::", "PERMISSION_DENIED", ")", ";", "}", "$", "handle", "=", "$", "request", "->", "getContent", "(", "true", ")", ";", "$", "data", "=", "[", "'lines'", "=>", "[", "'total'", "=>", "0", ",", "'ok'", "=>", "0", ",", "'failed'", "=>", "0", ",", "'ignored'", "=>", "0", ",", "]", ",", "'results'", "=>", "[", "]", ",", "]", ";", "while", "(", "(", "$", "line", "=", "fgets", "(", "$", "handle", ")", ")", "!==", "false", ")", "{", "++", "$", "data", "[", "'lines'", "]", "[", "'total'", "]", ";", "$", "line", "=", "trim", "(", "$", "line", ")", ";", "if", "(", "empty", "(", "$", "line", ")", ")", "{", "++", "$", "data", "[", "'lines'", "]", "[", "'ignored'", "]", ";", "$", "data", "[", "'results'", "]", "[", "]", "=", "[", "'ok'", "=>", "false", ",", "'code'", "=>", "Code", "::", "INVALID_ARGUMENT", ",", "'error_name'", "=>", "'InvalidArgumentException'", ",", "'error_message'", "=>", "'empty line'", ",", "]", ";", "continue", ";", "}", "$", "message", "=", "null", ";", "$", "result", "=", "[", "]", ";", "try", "{", "$", "envelope", "=", "TransportEnvelope", "::", "fromString", "(", "$", "line", ")", ";", "$", "message", "=", "$", "envelope", "->", "getMessage", "(", ")", ";", "$", "this", "->", "receiveMessage", "(", "$", "message", ")", ";", "++", "$", "data", "[", "'lines'", "]", "[", "'ok'", "]", ";", "$", "result", "[", "'ok'", "]", "=", "true", ";", "$", "result", "[", "'code'", "]", "=", "Code", "::", "OK", ";", "$", "result", "[", "'message_ref'", "]", "=", "$", "message", "->", "generateMessageRef", "(", ")", "->", "toString", "(", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "++", "$", "data", "[", "'lines'", "]", "[", "'failed'", "]", ";", "$", "this", "->", "handleException", "(", "$", "result", ",", "$", "e", ")", ";", "if", "(", "$", "message", "instanceof", "Message", ")", "{", "$", "result", "[", "'message_ref'", "]", "=", "$", "message", "->", "generateMessageRef", "(", ")", "->", "toString", "(", ")", ";", "}", "}", "$", "data", "[", "'results'", "]", "[", "]", "=", "$", "result", ";", "}", "return", "JsonResponse", "::", "create", "(", "$", "data", ")", ";", "}" ]
@param Request $request @return JsonResponse @throws \Throwable
[ "@param", "Request", "$request" ]
train
https://github.com/gdbots/pbjx-bundle-php/blob/f3c0088583879fc92f13247a0752634bd8696eac/src/Controller/PbjxReceiveController.php#L65-L141
gdbots/pbjx-bundle-php
src/Controller/PbjxReceiveController.php
PbjxReceiveController.receiveMessage
private function receiveMessage(Message $message): void { if ($message instanceof Command) { $this->locator->getCommandBus()->receiveCommand($message); return; } if ($message instanceof Event) { $this->locator->getEventBus()->receiveEvent($message); return; } throw new BadRequestHttpException( 'The receive endpoint cannot process requests.', null, Code::INVALID_ARGUMENT ); }
php
private function receiveMessage(Message $message): void { if ($message instanceof Command) { $this->locator->getCommandBus()->receiveCommand($message); return; } if ($message instanceof Event) { $this->locator->getEventBus()->receiveEvent($message); return; } throw new BadRequestHttpException( 'The receive endpoint cannot process requests.', null, Code::INVALID_ARGUMENT ); }
[ "private", "function", "receiveMessage", "(", "Message", "$", "message", ")", ":", "void", "{", "if", "(", "$", "message", "instanceof", "Command", ")", "{", "$", "this", "->", "locator", "->", "getCommandBus", "(", ")", "->", "receiveCommand", "(", "$", "message", ")", ";", "return", ";", "}", "if", "(", "$", "message", "instanceof", "Event", ")", "{", "$", "this", "->", "locator", "->", "getEventBus", "(", ")", "->", "receiveEvent", "(", "$", "message", ")", ";", "return", ";", "}", "throw", "new", "BadRequestHttpException", "(", "'The receive endpoint cannot process requests.'", ",", "null", ",", "Code", "::", "INVALID_ARGUMENT", ")", ";", "}" ]
@param Message $message @throws BadRequestHttpException
[ "@param", "Message", "$message" ]
train
https://github.com/gdbots/pbjx-bundle-php/blob/f3c0088583879fc92f13247a0752634bd8696eac/src/Controller/PbjxReceiveController.php#L148-L165
movoin/one-swoole
src/Protocol/Message/Headers.php
Headers.get
public function get(string $key, $default = null) { if ($this->has($key)) { return parent::get($key)['value']; } return $default; }
php
public function get(string $key, $default = null) { if ($this->has($key)) { return parent::get($key)['value']; } return $default; }
[ "public", "function", "get", "(", "string", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "$", "this", "->", "has", "(", "$", "key", ")", ")", "{", "return", "parent", "::", "get", "(", "$", "key", ")", "[", "'value'", "]", ";", "}", "return", "$", "default", ";", "}" ]
返回指定数据项 @param string $key @param mixed $default @return mixed
[ "返回指定数据项" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Message/Headers.php#L53-L60
movoin/one-swoole
src/Protocol/Message/Headers.php
Headers.set
public function set(string $key, $value) { if (! is_array($value)) { $value = [$value]; } parent::set($key, [ 'value' => $value, 'originalKey' => $key ]); }
php
public function set(string $key, $value) { if (! is_array($value)) { $value = [$value]; } parent::set($key, [ 'value' => $value, 'originalKey' => $key ]); }
[ "public", "function", "set", "(", "string", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "[", "$", "value", "]", ";", "}", "parent", "::", "set", "(", "$", "key", ",", "[", "'value'", "=>", "$", "value", ",", "'originalKey'", "=>", "$", "key", "]", ")", ";", "}" ]
设置数据项 @param string $key @param mixed $value
[ "设置数据项" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Message/Headers.php#L85-L95
movoin/one-swoole
src/Protocol/Message/Headers.php
Headers.normalizeKey
public function normalizeKey(string $key): string { $key = strtr(strtolower(trim($key)), '_', '-'); if (strpos($key, 'http-') === 0) { $key = substr($key, 5); } return $key; }
php
public function normalizeKey(string $key): string { $key = strtr(strtolower(trim($key)), '_', '-'); if (strpos($key, 'http-') === 0) { $key = substr($key, 5); } return $key; }
[ "public", "function", "normalizeKey", "(", "string", "$", "key", ")", ":", "string", "{", "$", "key", "=", "strtr", "(", "strtolower", "(", "trim", "(", "$", "key", ")", ")", ",", "'_'", ",", "'-'", ")", ";", "if", "(", "strpos", "(", "$", "key", ",", "'http-'", ")", "===", "0", ")", "{", "$", "key", "=", "substr", "(", "$", "key", ",", "5", ")", ";", "}", "return", "$", "key", ";", "}" ]
标准化键名 @param string $key @return string
[ "标准化键名" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Protocol/Message/Headers.php#L119-L128
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.parseShiritoriLine
protected function parseShiritoriLine(Dictionary $dictionary, string $line) { $fields = explode(',', $line); if (isset($fields[1]) && $this->isNumeric($fields[1])) { throw new SyntaxException(sprintf(_('2列目に数値「%s」は含められません。'), $fields[1])); } $fieldsAsMultiDimensionalArray['text'][] = array_shift($fields); $answerPattern = []; $mode = '|'; foreach ($fields as $field) { if ($this->isNumeric($field)) { // レベル $int = $this->convertToInt($field); if ($int > 0) { $weight = round(1 / $int, self::SCALE); if ($weight > 0) { $fieldsAsMultiDimensionalArray['weight'][0] = $weight; } } continue; } if ($field !== '' && $field[0] === '@') { // 解説 $fieldsAsMultiDimensionalArray['description'][0] = substr($field, 1); continue; } if (in_array($field, ['[', '|', ']'])) { // モード変更 $mode = $field; continue; } if (preg_match('/^[ぁ-わをんー]*$/u', $field) !== 1) { throw new SyntaxException(sprintf(_('「%s」には、しりとり辞書で使用可能なひらがな以外が含まれています。'), $field)); } $answerPattern[$mode][] = $field; } if (empty($answerPattern['|'])) { throw new SyntaxException(sprintf(_('行「%s」には読み方が設定されていません。'), $line)); } foreach ($answerPattern['|'] as $infix) { // 接頭辞の付加 if (isset($answerPattern['['])) { foreach ($answerPattern['['] as $prefix) { $answersWithPrefix[] = $prefix . $infix; } } else { $answersWithPrefix[] = $infix; } // 接尾辞の付加 if (isset($answerPattern[']'])) { foreach ($answerPattern[']'] as $suffix) { foreach ($answersWithPrefix as $answer) { $answersWithPrefixAndSuffix[] = $answer . $suffix; } } } else { $answersWithPrefixAndSuffix = $answersWithPrefix; } } // 重複、空行の削除 $fieldsAsMultiDimensionalArray['answer'] = array_filter(array_unique($answersWithPrefixAndSuffix)); if ($fieldsAsMultiDimensionalArray['answer']) { foreach ($fieldsAsMultiDimensionalArray['answer'] as $answer) { if (preg_match('/^([んー])|([っゎんー]ー)$/u', $answer, $matches) === 1) { if ($matches[1] !== '') { throw new SyntaxException(sprintf(_('読み方を「%s」で始めることはできません。'), $matches[1])); } else { throw new SyntaxException(sprintf(_('読み方を「%s」で終わらせることはできません。'), $matches[2])); } } } if ($fieldsAsMultiDimensionalArray['text'][0] === '') { $fieldsAsMultiDimensionalArray['text'][0] = $fieldsAsMultiDimensionalArray['answer'][0]; } $dictionary->addWord($fieldsAsMultiDimensionalArray); $words = $dictionary->getWords(); $this->wholeText .= implode('', $words[count($words) - 1]['answer']); } }
php
protected function parseShiritoriLine(Dictionary $dictionary, string $line) { $fields = explode(',', $line); if (isset($fields[1]) && $this->isNumeric($fields[1])) { throw new SyntaxException(sprintf(_('2列目に数値「%s」は含められません。'), $fields[1])); } $fieldsAsMultiDimensionalArray['text'][] = array_shift($fields); $answerPattern = []; $mode = '|'; foreach ($fields as $field) { if ($this->isNumeric($field)) { // レベル $int = $this->convertToInt($field); if ($int > 0) { $weight = round(1 / $int, self::SCALE); if ($weight > 0) { $fieldsAsMultiDimensionalArray['weight'][0] = $weight; } } continue; } if ($field !== '' && $field[0] === '@') { // 解説 $fieldsAsMultiDimensionalArray['description'][0] = substr($field, 1); continue; } if (in_array($field, ['[', '|', ']'])) { // モード変更 $mode = $field; continue; } if (preg_match('/^[ぁ-わをんー]*$/u', $field) !== 1) { throw new SyntaxException(sprintf(_('「%s」には、しりとり辞書で使用可能なひらがな以外が含まれています。'), $field)); } $answerPattern[$mode][] = $field; } if (empty($answerPattern['|'])) { throw new SyntaxException(sprintf(_('行「%s」には読み方が設定されていません。'), $line)); } foreach ($answerPattern['|'] as $infix) { // 接頭辞の付加 if (isset($answerPattern['['])) { foreach ($answerPattern['['] as $prefix) { $answersWithPrefix[] = $prefix . $infix; } } else { $answersWithPrefix[] = $infix; } // 接尾辞の付加 if (isset($answerPattern[']'])) { foreach ($answerPattern[']'] as $suffix) { foreach ($answersWithPrefix as $answer) { $answersWithPrefixAndSuffix[] = $answer . $suffix; } } } else { $answersWithPrefixAndSuffix = $answersWithPrefix; } } // 重複、空行の削除 $fieldsAsMultiDimensionalArray['answer'] = array_filter(array_unique($answersWithPrefixAndSuffix)); if ($fieldsAsMultiDimensionalArray['answer']) { foreach ($fieldsAsMultiDimensionalArray['answer'] as $answer) { if (preg_match('/^([んー])|([っゎんー]ー)$/u', $answer, $matches) === 1) { if ($matches[1] !== '') { throw new SyntaxException(sprintf(_('読み方を「%s」で始めることはできません。'), $matches[1])); } else { throw new SyntaxException(sprintf(_('読み方を「%s」で終わらせることはできません。'), $matches[2])); } } } if ($fieldsAsMultiDimensionalArray['text'][0] === '') { $fieldsAsMultiDimensionalArray['text'][0] = $fieldsAsMultiDimensionalArray['answer'][0]; } $dictionary->addWord($fieldsAsMultiDimensionalArray); $words = $dictionary->getWords(); $this->wholeText .= implode('', $words[count($words) - 1]['answer']); } }
[ "protected", "function", "parseShiritoriLine", "(", "Dictionary", "$", "dictionary", ",", "string", "$", "line", ")", "{", "$", "fields", "=", "explode", "(", "','", ",", "$", "line", ")", ";", "if", "(", "isset", "(", "$", "fields", "[", "1", "]", ")", "&&", "$", "this", "->", "isNumeric", "(", "$", "fields", "[", "1", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'2列目に数値「%s」は含められません。'), $fields[1]));", "", "", "", "", "", "", "", "", "", "", "}", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "]", "=", "array_shift", "(", "$", "fields", ")", ";", "$", "answerPattern", "=", "[", "]", ";", "$", "mode", "=", "'|'", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "$", "this", "->", "isNumeric", "(", "$", "field", ")", ")", "{", "// レベル", "$", "int", "=", "$", "this", "->", "convertToInt", "(", "$", "field", ")", ";", "if", "(", "$", "int", ">", "0", ")", "{", "$", "weight", "=", "round", "(", "1", "/", "$", "int", ",", "self", "::", "SCALE", ")", ";", "if", "(", "$", "weight", ">", "0", ")", "{", "$", "fieldsAsMultiDimensionalArray", "[", "'weight'", "]", "[", "0", "]", "=", "$", "weight", ";", "}", "}", "continue", ";", "}", "if", "(", "$", "field", "!==", "''", "&&", "$", "field", "[", "0", "]", "===", "'@'", ")", "{", "// 解説", "$", "fieldsAsMultiDimensionalArray", "[", "'description'", "]", "[", "0", "]", "=", "substr", "(", "$", "field", ",", "1", ")", ";", "continue", ";", "}", "if", "(", "in_array", "(", "$", "field", ",", "[", "'['", ",", "'|'", ",", "']'", "]", ")", ")", "{", "// モード変更", "$", "mode", "=", "$", "field", ";", "continue", ";", "}", "if", "(", "preg_match", "(", "'/^[ぁ-わをんー]*$/u', $field) ", "!", "=", " 1) {", "", "", "", "", "", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」には、しりとり辞書で使用可能なひらがな以外が含まれています。'), $field));", "", "", "", "", "", "", "", "}", "$", "answerPattern", "[", "$", "mode", "]", "[", "]", "=", "$", "field", ";", "}", "if", "(", "empty", "(", "$", "answerPattern", "[", "'|'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'行「%s」には読み方が設定されていません。'), $line));", "", "", "", "", "", "", "", "}", "foreach", "(", "$", "answerPattern", "[", "'|'", "]", "as", "$", "infix", ")", "{", "// 接頭辞の付加", "if", "(", "isset", "(", "$", "answerPattern", "[", "'['", "]", ")", ")", "{", "foreach", "(", "$", "answerPattern", "[", "'['", "]", "as", "$", "prefix", ")", "{", "$", "answersWithPrefix", "[", "]", "=", "$", "prefix", ".", "$", "infix", ";", "}", "}", "else", "{", "$", "answersWithPrefix", "[", "]", "=", "$", "infix", ";", "}", "// 接尾辞の付加", "if", "(", "isset", "(", "$", "answerPattern", "[", "']'", "]", ")", ")", "{", "foreach", "(", "$", "answerPattern", "[", "']'", "]", "as", "$", "suffix", ")", "{", "foreach", "(", "$", "answersWithPrefix", "as", "$", "answer", ")", "{", "$", "answersWithPrefixAndSuffix", "[", "]", "=", "$", "answer", ".", "$", "suffix", ";", "}", "}", "}", "else", "{", "$", "answersWithPrefixAndSuffix", "=", "$", "answersWithPrefix", ";", "}", "}", "// 重複、空行の削除", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "=", "array_filter", "(", "array_unique", "(", "$", "answersWithPrefixAndSuffix", ")", ")", ";", "if", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", ")", "{", "foreach", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "as", "$", "answer", ")", "{", "if", "(", "preg_match", "(", "'/^([んー])|([っゎんー]ー)$/u', $answer, $ma", "t", "h", "es) ==", "=", "1", ") {", "", "", "", "", "", "if", "(", "$", "matches", "[", "1", "]", "!==", "''", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'読み方を「%s」で始めることはできません。'), $matches[1]));", "", "", "", "", "", "", "", "", "", "", "}", "else", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'読み方を「%s」で終わらせることはできません。'), $matches[2]));", "", "", "", "", "", "", "", "", "", "", "}", "}", "}", "if", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "0", "]", "===", "''", ")", "{", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "0", "]", "=", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "[", "0", "]", ";", "}", "$", "dictionary", "->", "addWord", "(", "$", "fieldsAsMultiDimensionalArray", ")", ";", "$", "words", "=", "$", "dictionary", "->", "getWords", "(", ")", ";", "$", "this", "->", "wholeText", ".=", "implode", "(", "''", ",", "$", "words", "[", "count", "(", "$", "words", ")", "-", "1", "]", "[", "'answer'", "]", ")", ";", "}", "}" ]
しりとり辞書の行を解析します。 プレフィックス、サフィックスの組み合わせの結果がすべて空文字列になる時はnullを返します。 @param Dictionary $dictionary @param string $line @throws SyntaxException 2つ目のフィールド数値の場合。読み方が設定されていない場合。 読み方にしりとり辞書で使用可能なひらがな以外が含まれている、「ん」「ー」で始まる、「っー」「ゎー」「んー」「ーー」で終わる場合。
[ "しりとり辞書の行を解析します。", "プレフィックス、サフィックスの組み合わせの結果がすべて空文字列になる時はnullを返します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L64-L156
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.parseQuizLines
protected function parseQuizLines(Dictionary $dictioanry, string $question, string $answer) { $line = "$question\n$answer"; $specifics = new URLSearchParams(); $questionFields = explode(',', $question, 5); $answerFields = explode(',', $answer); if (!$this->isNumeric($questionFields[1])) { throw new SyntaxException(sprintf(_('出題の種類「%s」は数値として認識できません。'), $questionFields[1])); } elseif (!$this->isNumeric($answerFields[1])) { throw new SyntaxException(sprintf(_('解答の種類「%s」は数値として認識できません。'), $answerFields[1])); } /** @var int 出題の種類。 */ $questionType = $this->convertToInt($questionFields[1]); switch ($questionType) { case 1: // 音声ファイルを再生 case 2: // 画像ファイルを表示 if (empty($questionFields[3])) { throw new SyntaxException(_('ファイルが指定されていません。')); } // ファイル名 $fieldsAsMultiDimensionalArray[$questionType === 1 ? 'audio' : 'image'][] = $this->decodeCommaInTaggingEntity($questionFields[3]); // 問題オプション if (isset($questionFields[4])) { foreach (explode(',', $questionFields[4]) as $option) { $option = explode('=', $option, 2); $name = $option[0]; $value = $option[1] ?? ''; if (!$this->isNumeric($value)) { throw new SyntaxException(sprintf(_('問題オプション %1$s の値「%2$s」は数値として認識できません。'), $name, $value)); } $int = $this->convertToInt($value); switch ($name) { case 'start': case 'media_start': $specifics->set('start', $int / self::SECONDS_TO_MILISECONDS); break; case 'repeat': $specifics->set('repeat', $int); break; case 'length': $specifics->set('length', $int / self::SECONDS_TO_MILISECONDS); break; case 'speed': $specifics->set('speed', $int / self::DECIMAL_TO_PERCENT); break; case 'zoom_start': $specifics->set('magnification', $int); break; case 'zoom_end': $specifics->set('last-magnification', $int); break; case 'mozaic': if ($int === 1) { $specifics->set('pixelization', ''); } else { $specifics->delete('pixelization'); } break; case 'score': $specifics->set('score', $int); break; case 'finalscore': $specifics->set('last-score', $int); break; } } } break; case 3: // Wikipediaクイズ case 4: // アンサイクロペディアクイズ $this->logInconvertibleError("$question\n$answer"); return; } // 問題文 if (isset($questionFields[2])) { $fieldsAsMultiDimensionalArray['question'][] = $this->parseQuestionSentence($questionFields[2]); } /** @var int 解答の種類。 */ $answerType = $this->convertToInt($answerFields[1]); if (in_array($answerType, [1, 2, 3])) { $fieldsAsMultiDimensionalArray['type'][] = 'selection'; if ($answerType === 3) { $specifics->set('require-all-right', ''); } } else { $answerType = 0; } $mode = '|'; $answerValidator = new \esperecyan\dictionary_php\validator\AnswerValidator(); foreach (array_slice($answerFields, 2) as $i => $field) { if (isset($field[0]) && $field[0] === '\\' && isset($field[1]) && $field[1] !== '\\') { // 解答オプション if ($field === '\\norandom') { // 選択肢をシャッフルしない if (in_array($answerType, [1, 3])) { $specifics->set('no-random', ''); } } elseif ($field === '\\seikai') { // 直前の選択肢を正解扱いに if (in_array($answerType, [1, 3])) { if (empty($fieldsAsMultiDimensionalArray['option'])) { throw new SyntaxException(_('\\seikai の前には選択肢が必要です。')); } $fieldsAsMultiDimensionalArray['answer'][] = end($fieldsAsMultiDimensionalArray['option']); } } elseif (preg_match('/^\\\\explain=(.+)$/u', $field, $matches) === 1) { // 解説 $fieldsAsMultiDimensionalArray['description'][] = $this->parseQuestionSentence($matches[1]); } elseif ($answerType === 0 && preg_match('/^\\\\bonus=(.*)$/u', $field, $matches) === 1) { // ボーナスポイント if (!$this->isNumeric($matches[1])) { throw new SyntaxException(sprintf(_('解答オプション \\bonus の値「%s」は数値として認識できません。'), $matches[1])); } if (empty($answerPattenAndBonuses['|'])) { throw new SyntaxException(sprintf(_('解答オプション「%s」の前には解答本体が必要です。'), $field)); } $bonus = $this->convertToInt($matches[1]); if ($bonus !== 0) { $answerPattenAndBonuses['|'][count($answerPattenAndBonuses['|']) - 1]['bonus'] = $bonus; } } continue; } switch ($answerType) { case 0: // 記述形式 if ($field === '[[' || $field === '||') { // 正規表現 if (empty($answerPattenAndBonuses['|'])) { throw new SyntaxException(sprintf(_('「%s」の前には解答本体が必要です。'), $field)); } $end = count($answerPattenAndBonuses['|']) - 1; $answerPattenAndBonuses['|'][$end]['regexp'] = ($field === '||' ? '.*' : '') . preg_quote($answerPattenAndBonuses['|'][$end]['body'], '/') . '.*'; } elseif (in_array($field, ['[', '|', ']'])) { // モード変更 $mode = $field; } elseif ($mode === '|') { $answerPattenAndBonuses['|'][]['body'] = $field; } else { $answerPattenAndBonuses[$mode][] = $field; } break; case 1: // 選択形式 case 3: // 全選択形式 $fieldsAsMultiDimensionalArray['option'][] = $answerValidator->isRegExp($field) ? trim($field, '/') : $field; break; case 2: // 並べ替え形式 if ($i % 2 === 0) { $numbersAndOptions[] = [$answerValidator->isRegExp($field) ? trim($field, '/') : $field]; } else { $number = $this->isNumeric($field) ? $this->convertToInt($field) : 0; if ($number > 0) { array_unshift($numbersAndOptions[count($numbersAndOptions) - 1], $number); } else { // 順番が0以下であれば選択肢自体を削除 array_pop($numbersAndOptions); } } break; } } switch ($answerType) { case 0: // 記述形式 $noRegExpAnswerExisted = false; foreach ($answerPattenAndBonuses['|'] as $infix) { // 接頭辞の付加 if (isset($answerPattenAndBonuses['['])) { foreach ($answerPattenAndBonuses['['] as $prefix) { $tmpInfix = $infix; $tmpInfix['body'] = $prefix . $tmpInfix['body']; if (isset($tmpInfix['regexp'])) { $tmpInfix['regexp'] = preg_quote($prefix, '/') . $tmpInfix['regexp']; } $answersAndBonusesWithPrefix[] = $tmpInfix; } } else { $answersAndBonusesWithPrefix[] = $infix; } // 接尾辞の付加 if (isset($answerPattenAndBonuses[']'])) { foreach ($answerPattenAndBonuses[']'] as $suffix) { foreach ($answersAndBonusesWithPrefix as $answer) { $answer['body'] .= $suffix; if (isset($answer['regexp'])) { $answer['regexp'] .= preg_quote($prefix, '/'); } $answersAndBonusesWithPrefixAndSuffix[] = $answer; } } } else { $answersAndBonusesWithPrefixAndSuffix = $answersAndBonusesWithPrefix; } unset($answersAndBonusesWithPrefix); foreach ($answersAndBonusesWithPrefixAndSuffix as &$answer) { if ($answerValidator->isRegExp($answer['body'])) { $answer['body'] = trim($answer['body'], '/'); if ($answer['body'] === '') { unset($answer['body']); } } if (isset($answer['regexp']) || isset($answer['body'])) { $fieldsAsMultiDimensionalArray['answer'][] = isset($answer['regexp']) ? "/$answer[regexp]/" : $answer['body']; if (isset($answer['regexp'])) { if (!isset($noRegExpAnswerAndBonus)) { $noRegExpAnswerAndBonus = [ 'answer' => $answer['body'], 'bonus' => isset($answer['bonus']) ? (string)$answer['bonus'] : '', ]; } } else { $noRegExpAnswerExisted = true; } $bonuses[] = isset($answer['bonus']) ? (string)$answer['bonus'] : ''; } } unset($answersAndBonusesWithPrefixAndSuffix); } if (!$noRegExpAnswerExisted) { // answerフィールドがすべて正規表現なら if (isset($noRegExpAnswerAndBonus)) { array_unshift($fieldsAsMultiDimensionalArray['answer'], $noRegExpAnswerAndBonus['answer']); array_unshift($bonuses, $noRegExpAnswerAndBonus['bonus']); } else { $this->logInconvertibleError($line); return; } } // specificsフィールドのbonusの設定 if (isset($bonuses)) { foreach (array_reverse($bonuses, true) as $i => $bonus) { if ($bonus) { $lastBonusPosition = $i; break; } } } if (isset($lastBonusPosition)) { foreach (array_slice($bonuses, 0, $lastBonusPosition + 1) as $bonus) { $specifics->append('bonus', $bonus); } } $fieldsAsMultiDimensionalArray['text'][] = $fieldsAsMultiDimensionalArray['answer'][0]; if (count($fieldsAsMultiDimensionalArray['answer']) === 1) { unset($fieldsAsMultiDimensionalArray['answer']); } break; case 1: // 選択形式 case 3: // 全選択形式 if (empty($fieldsAsMultiDimensionalArray['answer'])) { throw new SyntaxException(_('\\seikai が設定されていません。')); } $fieldsAsMultiDimensionalArray['text'][] = count($fieldsAsMultiDimensionalArray['answer']) === 1 ? $fieldsAsMultiDimensionalArray['answer'][0] : '「' . implode('」' . ($answerType === 1 ? 'か' : 'と') . '「', $fieldsAsMultiDimensionalArray['answer']) . '」'; break; case 2: // 並べ替え形式 if (isset($numbersAndOptions)) { if (count(end($numbersAndOptions)) === 1) { // 順番が指定されていない選択肢を削除 array_pop($numbersAndOptions); } sort($numbersAndOptions); $fieldsAsMultiDimensionalArray['option'] = array_column($numbersAndOptions, 1); $fieldsAsMultiDimensionalArray['text'][] = implode(' → ', $fieldsAsMultiDimensionalArray['option']); } break; } $encoded = (string)$specifics; if ($encoded !== '') { $fieldsAsMultiDimensionalArray['specifics'][] = $encoded; } try { $dictioanry->addWord($fieldsAsMultiDimensionalArray); if ($answerType === 0) { // 記述形式 $words = $dictioanry->getWords(); $word = $words[count($words) - 1]; if (isset($word['answer'])) { foreach ($word['answer'] as $answer) { $this->wholeText .= $answerValidator->isRegExp($answer) ? preg_replace('#^/|\\.\\*|/$#u', '', $answer) : $answer; } } else { $this->wholeText .= $word['text'][0]; } } } catch (SyntaxException $e) { $this->logInconvertibleError($line, $e); } }
php
protected function parseQuizLines(Dictionary $dictioanry, string $question, string $answer) { $line = "$question\n$answer"; $specifics = new URLSearchParams(); $questionFields = explode(',', $question, 5); $answerFields = explode(',', $answer); if (!$this->isNumeric($questionFields[1])) { throw new SyntaxException(sprintf(_('出題の種類「%s」は数値として認識できません。'), $questionFields[1])); } elseif (!$this->isNumeric($answerFields[1])) { throw new SyntaxException(sprintf(_('解答の種類「%s」は数値として認識できません。'), $answerFields[1])); } /** @var int 出題の種類。 */ $questionType = $this->convertToInt($questionFields[1]); switch ($questionType) { case 1: // 音声ファイルを再生 case 2: // 画像ファイルを表示 if (empty($questionFields[3])) { throw new SyntaxException(_('ファイルが指定されていません。')); } // ファイル名 $fieldsAsMultiDimensionalArray[$questionType === 1 ? 'audio' : 'image'][] = $this->decodeCommaInTaggingEntity($questionFields[3]); // 問題オプション if (isset($questionFields[4])) { foreach (explode(',', $questionFields[4]) as $option) { $option = explode('=', $option, 2); $name = $option[0]; $value = $option[1] ?? ''; if (!$this->isNumeric($value)) { throw new SyntaxException(sprintf(_('問題オプション %1$s の値「%2$s」は数値として認識できません。'), $name, $value)); } $int = $this->convertToInt($value); switch ($name) { case 'start': case 'media_start': $specifics->set('start', $int / self::SECONDS_TO_MILISECONDS); break; case 'repeat': $specifics->set('repeat', $int); break; case 'length': $specifics->set('length', $int / self::SECONDS_TO_MILISECONDS); break; case 'speed': $specifics->set('speed', $int / self::DECIMAL_TO_PERCENT); break; case 'zoom_start': $specifics->set('magnification', $int); break; case 'zoom_end': $specifics->set('last-magnification', $int); break; case 'mozaic': if ($int === 1) { $specifics->set('pixelization', ''); } else { $specifics->delete('pixelization'); } break; case 'score': $specifics->set('score', $int); break; case 'finalscore': $specifics->set('last-score', $int); break; } } } break; case 3: // Wikipediaクイズ case 4: // アンサイクロペディアクイズ $this->logInconvertibleError("$question\n$answer"); return; } // 問題文 if (isset($questionFields[2])) { $fieldsAsMultiDimensionalArray['question'][] = $this->parseQuestionSentence($questionFields[2]); } /** @var int 解答の種類。 */ $answerType = $this->convertToInt($answerFields[1]); if (in_array($answerType, [1, 2, 3])) { $fieldsAsMultiDimensionalArray['type'][] = 'selection'; if ($answerType === 3) { $specifics->set('require-all-right', ''); } } else { $answerType = 0; } $mode = '|'; $answerValidator = new \esperecyan\dictionary_php\validator\AnswerValidator(); foreach (array_slice($answerFields, 2) as $i => $field) { if (isset($field[0]) && $field[0] === '\\' && isset($field[1]) && $field[1] !== '\\') { // 解答オプション if ($field === '\\norandom') { // 選択肢をシャッフルしない if (in_array($answerType, [1, 3])) { $specifics->set('no-random', ''); } } elseif ($field === '\\seikai') { // 直前の選択肢を正解扱いに if (in_array($answerType, [1, 3])) { if (empty($fieldsAsMultiDimensionalArray['option'])) { throw new SyntaxException(_('\\seikai の前には選択肢が必要です。')); } $fieldsAsMultiDimensionalArray['answer'][] = end($fieldsAsMultiDimensionalArray['option']); } } elseif (preg_match('/^\\\\explain=(.+)$/u', $field, $matches) === 1) { // 解説 $fieldsAsMultiDimensionalArray['description'][] = $this->parseQuestionSentence($matches[1]); } elseif ($answerType === 0 && preg_match('/^\\\\bonus=(.*)$/u', $field, $matches) === 1) { // ボーナスポイント if (!$this->isNumeric($matches[1])) { throw new SyntaxException(sprintf(_('解答オプション \\bonus の値「%s」は数値として認識できません。'), $matches[1])); } if (empty($answerPattenAndBonuses['|'])) { throw new SyntaxException(sprintf(_('解答オプション「%s」の前には解答本体が必要です。'), $field)); } $bonus = $this->convertToInt($matches[1]); if ($bonus !== 0) { $answerPattenAndBonuses['|'][count($answerPattenAndBonuses['|']) - 1]['bonus'] = $bonus; } } continue; } switch ($answerType) { case 0: // 記述形式 if ($field === '[[' || $field === '||') { // 正規表現 if (empty($answerPattenAndBonuses['|'])) { throw new SyntaxException(sprintf(_('「%s」の前には解答本体が必要です。'), $field)); } $end = count($answerPattenAndBonuses['|']) - 1; $answerPattenAndBonuses['|'][$end]['regexp'] = ($field === '||' ? '.*' : '') . preg_quote($answerPattenAndBonuses['|'][$end]['body'], '/') . '.*'; } elseif (in_array($field, ['[', '|', ']'])) { // モード変更 $mode = $field; } elseif ($mode === '|') { $answerPattenAndBonuses['|'][]['body'] = $field; } else { $answerPattenAndBonuses[$mode][] = $field; } break; case 1: // 選択形式 case 3: // 全選択形式 $fieldsAsMultiDimensionalArray['option'][] = $answerValidator->isRegExp($field) ? trim($field, '/') : $field; break; case 2: // 並べ替え形式 if ($i % 2 === 0) { $numbersAndOptions[] = [$answerValidator->isRegExp($field) ? trim($field, '/') : $field]; } else { $number = $this->isNumeric($field) ? $this->convertToInt($field) : 0; if ($number > 0) { array_unshift($numbersAndOptions[count($numbersAndOptions) - 1], $number); } else { // 順番が0以下であれば選択肢自体を削除 array_pop($numbersAndOptions); } } break; } } switch ($answerType) { case 0: // 記述形式 $noRegExpAnswerExisted = false; foreach ($answerPattenAndBonuses['|'] as $infix) { // 接頭辞の付加 if (isset($answerPattenAndBonuses['['])) { foreach ($answerPattenAndBonuses['['] as $prefix) { $tmpInfix = $infix; $tmpInfix['body'] = $prefix . $tmpInfix['body']; if (isset($tmpInfix['regexp'])) { $tmpInfix['regexp'] = preg_quote($prefix, '/') . $tmpInfix['regexp']; } $answersAndBonusesWithPrefix[] = $tmpInfix; } } else { $answersAndBonusesWithPrefix[] = $infix; } // 接尾辞の付加 if (isset($answerPattenAndBonuses[']'])) { foreach ($answerPattenAndBonuses[']'] as $suffix) { foreach ($answersAndBonusesWithPrefix as $answer) { $answer['body'] .= $suffix; if (isset($answer['regexp'])) { $answer['regexp'] .= preg_quote($prefix, '/'); } $answersAndBonusesWithPrefixAndSuffix[] = $answer; } } } else { $answersAndBonusesWithPrefixAndSuffix = $answersAndBonusesWithPrefix; } unset($answersAndBonusesWithPrefix); foreach ($answersAndBonusesWithPrefixAndSuffix as &$answer) { if ($answerValidator->isRegExp($answer['body'])) { $answer['body'] = trim($answer['body'], '/'); if ($answer['body'] === '') { unset($answer['body']); } } if (isset($answer['regexp']) || isset($answer['body'])) { $fieldsAsMultiDimensionalArray['answer'][] = isset($answer['regexp']) ? "/$answer[regexp]/" : $answer['body']; if (isset($answer['regexp'])) { if (!isset($noRegExpAnswerAndBonus)) { $noRegExpAnswerAndBonus = [ 'answer' => $answer['body'], 'bonus' => isset($answer['bonus']) ? (string)$answer['bonus'] : '', ]; } } else { $noRegExpAnswerExisted = true; } $bonuses[] = isset($answer['bonus']) ? (string)$answer['bonus'] : ''; } } unset($answersAndBonusesWithPrefixAndSuffix); } if (!$noRegExpAnswerExisted) { // answerフィールドがすべて正規表現なら if (isset($noRegExpAnswerAndBonus)) { array_unshift($fieldsAsMultiDimensionalArray['answer'], $noRegExpAnswerAndBonus['answer']); array_unshift($bonuses, $noRegExpAnswerAndBonus['bonus']); } else { $this->logInconvertibleError($line); return; } } // specificsフィールドのbonusの設定 if (isset($bonuses)) { foreach (array_reverse($bonuses, true) as $i => $bonus) { if ($bonus) { $lastBonusPosition = $i; break; } } } if (isset($lastBonusPosition)) { foreach (array_slice($bonuses, 0, $lastBonusPosition + 1) as $bonus) { $specifics->append('bonus', $bonus); } } $fieldsAsMultiDimensionalArray['text'][] = $fieldsAsMultiDimensionalArray['answer'][0]; if (count($fieldsAsMultiDimensionalArray['answer']) === 1) { unset($fieldsAsMultiDimensionalArray['answer']); } break; case 1: // 選択形式 case 3: // 全選択形式 if (empty($fieldsAsMultiDimensionalArray['answer'])) { throw new SyntaxException(_('\\seikai が設定されていません。')); } $fieldsAsMultiDimensionalArray['text'][] = count($fieldsAsMultiDimensionalArray['answer']) === 1 ? $fieldsAsMultiDimensionalArray['answer'][0] : '「' . implode('」' . ($answerType === 1 ? 'か' : 'と') . '「', $fieldsAsMultiDimensionalArray['answer']) . '」'; break; case 2: // 並べ替え形式 if (isset($numbersAndOptions)) { if (count(end($numbersAndOptions)) === 1) { // 順番が指定されていない選択肢を削除 array_pop($numbersAndOptions); } sort($numbersAndOptions); $fieldsAsMultiDimensionalArray['option'] = array_column($numbersAndOptions, 1); $fieldsAsMultiDimensionalArray['text'][] = implode(' → ', $fieldsAsMultiDimensionalArray['option']); } break; } $encoded = (string)$specifics; if ($encoded !== '') { $fieldsAsMultiDimensionalArray['specifics'][] = $encoded; } try { $dictioanry->addWord($fieldsAsMultiDimensionalArray); if ($answerType === 0) { // 記述形式 $words = $dictioanry->getWords(); $word = $words[count($words) - 1]; if (isset($word['answer'])) { foreach ($word['answer'] as $answer) { $this->wholeText .= $answerValidator->isRegExp($answer) ? preg_replace('#^/|\\.\\*|/$#u', '', $answer) : $answer; } } else { $this->wholeText .= $word['text'][0]; } } } catch (SyntaxException $e) { $this->logInconvertibleError($line, $e); } }
[ "protected", "function", "parseQuizLines", "(", "Dictionary", "$", "dictioanry", ",", "string", "$", "question", ",", "string", "$", "answer", ")", "{", "$", "line", "=", "\"$question\\n$answer\"", ";", "$", "specifics", "=", "new", "URLSearchParams", "(", ")", ";", "$", "questionFields", "=", "explode", "(", "','", ",", "$", "question", ",", "5", ")", ";", "$", "answerFields", "=", "explode", "(", "','", ",", "$", "answer", ")", ";", "if", "(", "!", "$", "this", "->", "isNumeric", "(", "$", "questionFields", "[", "1", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'出題の種類「%s」は数値として認識できません。'), $questionFields[1]));", "", "", "", "", "", "", "", "", "", "", "}", "elseif", "(", "!", "$", "this", "->", "isNumeric", "(", "$", "answerFields", "[", "1", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'解答の種類「%s」は数値として認識できません。'), $answerFields[1]));", "", "", "", "", "", "", "", "", "", "", "}", "/** @var int 出題の種類。 */", "$", "questionType", "=", "$", "this", "->", "convertToInt", "(", "$", "questionFields", "[", "1", "]", ")", ";", "switch", "(", "$", "questionType", ")", "{", "case", "1", ":", "// 音声ファイルを再生", "case", "2", ":", "// 画像ファイルを表示", "if", "(", "empty", "(", "$", "questionFields", "[", "3", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'ファイルが指定されていません。'));", "", "", "", "}", "// ファイル名", "$", "fieldsAsMultiDimensionalArray", "[", "$", "questionType", "===", "1", "?", "'audio'", ":", "'image'", "]", "[", "]", "=", "$", "this", "->", "decodeCommaInTaggingEntity", "(", "$", "questionFields", "[", "3", "]", ")", ";", "// 問題オプション", "if", "(", "isset", "(", "$", "questionFields", "[", "4", "]", ")", ")", "{", "foreach", "(", "explode", "(", "','", ",", "$", "questionFields", "[", "4", "]", ")", "as", "$", "option", ")", "{", "$", "option", "=", "explode", "(", "'='", ",", "$", "option", ",", "2", ")", ";", "$", "name", "=", "$", "option", "[", "0", "]", ";", "$", "value", "=", "$", "option", "[", "1", "]", "??", "''", ";", "if", "(", "!", "$", "this", "->", "isNumeric", "(", "$", "value", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'問題オプション %1$s の値「%2$s」は数値として認識できません。'), $name, $value));", "", "", "", "", "", "", "", "", "", "", "}", "$", "int", "=", "$", "this", "->", "convertToInt", "(", "$", "value", ")", ";", "switch", "(", "$", "name", ")", "{", "case", "'start'", ":", "case", "'media_start'", ":", "$", "specifics", "->", "set", "(", "'start'", ",", "$", "int", "/", "self", "::", "SECONDS_TO_MILISECONDS", ")", ";", "break", ";", "case", "'repeat'", ":", "$", "specifics", "->", "set", "(", "'repeat'", ",", "$", "int", ")", ";", "break", ";", "case", "'length'", ":", "$", "specifics", "->", "set", "(", "'length'", ",", "$", "int", "/", "self", "::", "SECONDS_TO_MILISECONDS", ")", ";", "break", ";", "case", "'speed'", ":", "$", "specifics", "->", "set", "(", "'speed'", ",", "$", "int", "/", "self", "::", "DECIMAL_TO_PERCENT", ")", ";", "break", ";", "case", "'zoom_start'", ":", "$", "specifics", "->", "set", "(", "'magnification'", ",", "$", "int", ")", ";", "break", ";", "case", "'zoom_end'", ":", "$", "specifics", "->", "set", "(", "'last-magnification'", ",", "$", "int", ")", ";", "break", ";", "case", "'mozaic'", ":", "if", "(", "$", "int", "===", "1", ")", "{", "$", "specifics", "->", "set", "(", "'pixelization'", ",", "''", ")", ";", "}", "else", "{", "$", "specifics", "->", "delete", "(", "'pixelization'", ")", ";", "}", "break", ";", "case", "'score'", ":", "$", "specifics", "->", "set", "(", "'score'", ",", "$", "int", ")", ";", "break", ";", "case", "'finalscore'", ":", "$", "specifics", "->", "set", "(", "'last-score'", ",", "$", "int", ")", ";", "break", ";", "}", "}", "}", "break", ";", "case", "3", ":", "// Wikipediaクイズ", "case", "4", ":", "// アンサイクロペディアクイズ", "$", "this", "->", "logInconvertibleError", "(", "\"$question\\n$answer\"", ")", ";", "return", ";", "}", "// 問題文", "if", "(", "isset", "(", "$", "questionFields", "[", "2", "]", ")", ")", "{", "$", "fieldsAsMultiDimensionalArray", "[", "'question'", "]", "[", "]", "=", "$", "this", "->", "parseQuestionSentence", "(", "$", "questionFields", "[", "2", "]", ")", ";", "}", "/** @var int 解答の種類。 */", "$", "answerType", "=", "$", "this", "->", "convertToInt", "(", "$", "answerFields", "[", "1", "]", ")", ";", "if", "(", "in_array", "(", "$", "answerType", ",", "[", "1", ",", "2", ",", "3", "]", ")", ")", "{", "$", "fieldsAsMultiDimensionalArray", "[", "'type'", "]", "[", "]", "=", "'selection'", ";", "if", "(", "$", "answerType", "===", "3", ")", "{", "$", "specifics", "->", "set", "(", "'require-all-right'", ",", "''", ")", ";", "}", "}", "else", "{", "$", "answerType", "=", "0", ";", "}", "$", "mode", "=", "'|'", ";", "$", "answerValidator", "=", "new", "\\", "esperecyan", "\\", "dictionary_php", "\\", "validator", "\\", "AnswerValidator", "(", ")", ";", "foreach", "(", "array_slice", "(", "$", "answerFields", ",", "2", ")", "as", "$", "i", "=>", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "field", "[", "0", "]", ")", "&&", "$", "field", "[", "0", "]", "===", "'\\\\'", "&&", "isset", "(", "$", "field", "[", "1", "]", ")", "&&", "$", "field", "[", "1", "]", "!==", "'\\\\'", ")", "{", "// 解答オプション", "if", "(", "$", "field", "===", "'\\\\norandom'", ")", "{", "// 選択肢をシャッフルしない", "if", "(", "in_array", "(", "$", "answerType", ",", "[", "1", ",", "3", "]", ")", ")", "{", "$", "specifics", "->", "set", "(", "'no-random'", ",", "''", ")", ";", "}", "}", "elseif", "(", "$", "field", "===", "'\\\\seikai'", ")", "{", "// 直前の選択肢を正解扱いに", "if", "(", "in_array", "(", "$", "answerType", ",", "[", "1", ",", "3", "]", ")", ")", "{", "if", "(", "empty", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'option'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'\\\\seikai の前には選択肢が必要です。'));", "", "", "", "}", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "[", "]", "=", "end", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'option'", "]", ")", ";", "}", "}", "elseif", "(", "preg_match", "(", "'/^\\\\\\\\explain=(.+)$/u'", ",", "$", "field", ",", "$", "matches", ")", "===", "1", ")", "{", "// 解説", "$", "fieldsAsMultiDimensionalArray", "[", "'description'", "]", "[", "]", "=", "$", "this", "->", "parseQuestionSentence", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "elseif", "(", "$", "answerType", "===", "0", "&&", "preg_match", "(", "'/^\\\\\\\\bonus=(.*)$/u'", ",", "$", "field", ",", "$", "matches", ")", "===", "1", ")", "{", "// ボーナスポイント", "if", "(", "!", "$", "this", "->", "isNumeric", "(", "$", "matches", "[", "1", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'解答オプション \\\\bonus の値「%s」は数値として認識できません。'), $matches[1]));", "", "", "", "", "", "", "", "", "", "", "}", "if", "(", "empty", "(", "$", "answerPattenAndBonuses", "[", "'|'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'解答オプション「%s」の前には解答本体が必要です。'), $field));", "", "", "", "", "", "", "", "}", "$", "bonus", "=", "$", "this", "->", "convertToInt", "(", "$", "matches", "[", "1", "]", ")", ";", "if", "(", "$", "bonus", "!==", "0", ")", "{", "$", "answerPattenAndBonuses", "[", "'|'", "]", "[", "count", "(", "$", "answerPattenAndBonuses", "[", "'|'", "]", ")", "-", "1", "]", "[", "'bonus'", "]", "=", "$", "bonus", ";", "}", "}", "continue", ";", "}", "switch", "(", "$", "answerType", ")", "{", "case", "0", ":", "// 記述形式", "if", "(", "$", "field", "===", "'[['", "||", "$", "field", "===", "'||'", ")", "{", "// 正規表現", "if", "(", "empty", "(", "$", "answerPattenAndBonuses", "[", "'|'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」の前には解答本体が必要です。'), $field));", "", "", "", "", "", "", "", "}", "$", "end", "=", "count", "(", "$", "answerPattenAndBonuses", "[", "'|'", "]", ")", "-", "1", ";", "$", "answerPattenAndBonuses", "[", "'|'", "]", "[", "$", "end", "]", "[", "'regexp'", "]", "=", "(", "$", "field", "===", "'||'", "?", "'.*'", ":", "''", ")", ".", "preg_quote", "(", "$", "answerPattenAndBonuses", "[", "'|'", "]", "[", "$", "end", "]", "[", "'body'", "]", ",", "'/'", ")", ".", "'.*'", ";", "}", "elseif", "(", "in_array", "(", "$", "field", ",", "[", "'['", ",", "'|'", ",", "']'", "]", ")", ")", "{", "// モード変更", "$", "mode", "=", "$", "field", ";", "}", "elseif", "(", "$", "mode", "===", "'|'", ")", "{", "$", "answerPattenAndBonuses", "[", "'|'", "]", "[", "]", "[", "'body'", "]", "=", "$", "field", ";", "}", "else", "{", "$", "answerPattenAndBonuses", "[", "$", "mode", "]", "[", "]", "=", "$", "field", ";", "}", "break", ";", "case", "1", ":", "// 選択形式", "case", "3", ":", "// 全選択形式", "$", "fieldsAsMultiDimensionalArray", "[", "'option'", "]", "[", "]", "=", "$", "answerValidator", "->", "isRegExp", "(", "$", "field", ")", "?", "trim", "(", "$", "field", ",", "'/'", ")", ":", "$", "field", ";", "break", ";", "case", "2", ":", "// 並べ替え形式", "if", "(", "$", "i", "%", "2", "===", "0", ")", "{", "$", "numbersAndOptions", "[", "]", "=", "[", "$", "answerValidator", "->", "isRegExp", "(", "$", "field", ")", "?", "trim", "(", "$", "field", ",", "'/'", ")", ":", "$", "field", "]", ";", "}", "else", "{", "$", "number", "=", "$", "this", "->", "isNumeric", "(", "$", "field", ")", "?", "$", "this", "->", "convertToInt", "(", "$", "field", ")", ":", "0", ";", "if", "(", "$", "number", ">", "0", ")", "{", "array_unshift", "(", "$", "numbersAndOptions", "[", "count", "(", "$", "numbersAndOptions", ")", "-", "1", "]", ",", "$", "number", ")", ";", "}", "else", "{", "// 順番が0以下であれば選択肢自体を削除", "array_pop", "(", "$", "numbersAndOptions", ")", ";", "}", "}", "break", ";", "}", "}", "switch", "(", "$", "answerType", ")", "{", "case", "0", ":", "// 記述形式", "$", "noRegExpAnswerExisted", "=", "false", ";", "foreach", "(", "$", "answerPattenAndBonuses", "[", "'|'", "]", "as", "$", "infix", ")", "{", "// 接頭辞の付加", "if", "(", "isset", "(", "$", "answerPattenAndBonuses", "[", "'['", "]", ")", ")", "{", "foreach", "(", "$", "answerPattenAndBonuses", "[", "'['", "]", "as", "$", "prefix", ")", "{", "$", "tmpInfix", "=", "$", "infix", ";", "$", "tmpInfix", "[", "'body'", "]", "=", "$", "prefix", ".", "$", "tmpInfix", "[", "'body'", "]", ";", "if", "(", "isset", "(", "$", "tmpInfix", "[", "'regexp'", "]", ")", ")", "{", "$", "tmpInfix", "[", "'regexp'", "]", "=", "preg_quote", "(", "$", "prefix", ",", "'/'", ")", ".", "$", "tmpInfix", "[", "'regexp'", "]", ";", "}", "$", "answersAndBonusesWithPrefix", "[", "]", "=", "$", "tmpInfix", ";", "}", "}", "else", "{", "$", "answersAndBonusesWithPrefix", "[", "]", "=", "$", "infix", ";", "}", "// 接尾辞の付加", "if", "(", "isset", "(", "$", "answerPattenAndBonuses", "[", "']'", "]", ")", ")", "{", "foreach", "(", "$", "answerPattenAndBonuses", "[", "']'", "]", "as", "$", "suffix", ")", "{", "foreach", "(", "$", "answersAndBonusesWithPrefix", "as", "$", "answer", ")", "{", "$", "answer", "[", "'body'", "]", ".=", "$", "suffix", ";", "if", "(", "isset", "(", "$", "answer", "[", "'regexp'", "]", ")", ")", "{", "$", "answer", "[", "'regexp'", "]", ".=", "preg_quote", "(", "$", "prefix", ",", "'/'", ")", ";", "}", "$", "answersAndBonusesWithPrefixAndSuffix", "[", "]", "=", "$", "answer", ";", "}", "}", "}", "else", "{", "$", "answersAndBonusesWithPrefixAndSuffix", "=", "$", "answersAndBonusesWithPrefix", ";", "}", "unset", "(", "$", "answersAndBonusesWithPrefix", ")", ";", "foreach", "(", "$", "answersAndBonusesWithPrefixAndSuffix", "as", "&", "$", "answer", ")", "{", "if", "(", "$", "answerValidator", "->", "isRegExp", "(", "$", "answer", "[", "'body'", "]", ")", ")", "{", "$", "answer", "[", "'body'", "]", "=", "trim", "(", "$", "answer", "[", "'body'", "]", ",", "'/'", ")", ";", "if", "(", "$", "answer", "[", "'body'", "]", "===", "''", ")", "{", "unset", "(", "$", "answer", "[", "'body'", "]", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "answer", "[", "'regexp'", "]", ")", "||", "isset", "(", "$", "answer", "[", "'body'", "]", ")", ")", "{", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "[", "]", "=", "isset", "(", "$", "answer", "[", "'regexp'", "]", ")", "?", "\"/$answer[regexp]/\"", ":", "$", "answer", "[", "'body'", "]", ";", "if", "(", "isset", "(", "$", "answer", "[", "'regexp'", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "noRegExpAnswerAndBonus", ")", ")", "{", "$", "noRegExpAnswerAndBonus", "=", "[", "'answer'", "=>", "$", "answer", "[", "'body'", "]", ",", "'bonus'", "=>", "isset", "(", "$", "answer", "[", "'bonus'", "]", ")", "?", "(", "string", ")", "$", "answer", "[", "'bonus'", "]", ":", "''", ",", "]", ";", "}", "}", "else", "{", "$", "noRegExpAnswerExisted", "=", "true", ";", "}", "$", "bonuses", "[", "]", "=", "isset", "(", "$", "answer", "[", "'bonus'", "]", ")", "?", "(", "string", ")", "$", "answer", "[", "'bonus'", "]", ":", "''", ";", "}", "}", "unset", "(", "$", "answersAndBonusesWithPrefixAndSuffix", ")", ";", "}", "if", "(", "!", "$", "noRegExpAnswerExisted", ")", "{", "// answerフィールドがすべて正規表現なら", "if", "(", "isset", "(", "$", "noRegExpAnswerAndBonus", ")", ")", "{", "array_unshift", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", ",", "$", "noRegExpAnswerAndBonus", "[", "'answer'", "]", ")", ";", "array_unshift", "(", "$", "bonuses", ",", "$", "noRegExpAnswerAndBonus", "[", "'bonus'", "]", ")", ";", "}", "else", "{", "$", "this", "->", "logInconvertibleError", "(", "$", "line", ")", ";", "return", ";", "}", "}", "// specificsフィールドのbonusの設定", "if", "(", "isset", "(", "$", "bonuses", ")", ")", "{", "foreach", "(", "array_reverse", "(", "$", "bonuses", ",", "true", ")", "as", "$", "i", "=>", "$", "bonus", ")", "{", "if", "(", "$", "bonus", ")", "{", "$", "lastBonusPosition", "=", "$", "i", ";", "break", ";", "}", "}", "}", "if", "(", "isset", "(", "$", "lastBonusPosition", ")", ")", "{", "foreach", "(", "array_slice", "(", "$", "bonuses", ",", "0", ",", "$", "lastBonusPosition", "+", "1", ")", "as", "$", "bonus", ")", "{", "$", "specifics", "->", "append", "(", "'bonus'", ",", "$", "bonus", ")", ";", "}", "}", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "]", "=", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "[", "0", "]", ";", "if", "(", "count", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", ")", "===", "1", ")", "{", "unset", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", ")", ";", "}", "break", ";", "case", "1", ":", "// 選択形式", "case", "3", ":", "// 全選択形式", "if", "(", "empty", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'\\\\seikai が設定されていません。'));", "", "", "", "}", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "]", "=", "count", "(", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", ")", "===", "1", "?", "$", "fieldsAsMultiDimensionalArray", "[", "'answer'", "]", "[", "0", "]", ":", "'「' .", "i", "plode('", "」", "' . (", "a", "s", "w", "erType ===", "1 ?", "'", "'", ": 'と'", " ", " '「',", " ", "f", "eldsA", "s", "u", "ltiDimensionalArray['answer']", ")", " . '」';", "", "", "", "", "", "break", ";", "case", "2", ":", "// 並べ替え形式", "if", "(", "isset", "(", "$", "numbersAndOptions", ")", ")", "{", "if", "(", "count", "(", "end", "(", "$", "numbersAndOptions", ")", ")", "===", "1", ")", "{", "// 順番が指定されていない選択肢を削除", "array_pop", "(", "$", "numbersAndOptions", ")", ";", "}", "sort", "(", "$", "numbersAndOptions", ")", ";", "$", "fieldsAsMultiDimensionalArray", "[", "'option'", "]", "=", "array_column", "(", "$", "numbersAndOptions", ",", "1", ")", ";", "$", "fieldsAsMultiDimensionalArray", "[", "'text'", "]", "[", "]", "=", "implode", "(", "' → ', ", "$", "i", "eldsAsMultiDimensionalArray['", "o", "ption'])", ";", "", "", "}", "break", ";", "}", "$", "encoded", "=", "(", "string", ")", "$", "specifics", ";", "if", "(", "$", "encoded", "!==", "''", ")", "{", "$", "fieldsAsMultiDimensionalArray", "[", "'specifics'", "]", "[", "]", "=", "$", "encoded", ";", "}", "try", "{", "$", "dictioanry", "->", "addWord", "(", "$", "fieldsAsMultiDimensionalArray", ")", ";", "if", "(", "$", "answerType", "===", "0", ")", "{", "// 記述形式", "$", "words", "=", "$", "dictioanry", "->", "getWords", "(", ")", ";", "$", "word", "=", "$", "words", "[", "count", "(", "$", "words", ")", "-", "1", "]", ";", "if", "(", "isset", "(", "$", "word", "[", "'answer'", "]", ")", ")", "{", "foreach", "(", "$", "word", "[", "'answer'", "]", "as", "$", "answer", ")", "{", "$", "this", "->", "wholeText", ".=", "$", "answerValidator", "->", "isRegExp", "(", "$", "answer", ")", "?", "preg_replace", "(", "'#^/|\\\\.\\\\*|/$#u'", ",", "''", ",", "$", "answer", ")", ":", "$", "answer", ";", "}", "}", "else", "{", "$", "this", "->", "wholeText", ".=", "$", "word", "[", "'text'", "]", "[", "0", "]", ";", "}", "}", "}", "catch", "(", "SyntaxException", "$", "e", ")", "{", "$", "this", "->", "logInconvertibleError", "(", "$", "line", ",", "$", "e", ")", ";", "}", "}" ]
Q&Aを解析します。 @param Dictionary $dictioanry @param string $question @param string $answer
[ "Q&Aを解析します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L180-L508
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.decodeCommaInTaggingEntity
protected function decodeCommaInTaggingEntity(string $fileLocation): string { return preg_replace_callback( '/^(tag:)((?:"(?:[^"\\\\]|\\\\.)*"|[^"]+@)?[^:]+)/iu', function (array $matches): string { return $matches[1] . str_replace('%2C', ',', $matches[2]); }, $fileLocation ); }
php
protected function decodeCommaInTaggingEntity(string $fileLocation): string { return preg_replace_callback( '/^(tag:)((?:"(?:[^"\\\\]|\\\\.)*"|[^"]+@)?[^:]+)/iu', function (array $matches): string { return $matches[1] . str_replace('%2C', ',', $matches[2]); }, $fileLocation ); }
[ "protected", "function", "decodeCommaInTaggingEntity", "(", "string", "$", "fileLocation", ")", ":", "string", "{", "return", "preg_replace_callback", "(", "'/^(tag:)((?:\"(?:[^\"\\\\\\\\]|\\\\\\\\.)*\"|[^\"]+@)?[^:]+)/iu'", ",", "function", "(", "array", "$", "matches", ")", ":", "string", "{", "return", "$", "matches", "[", "1", "]", ".", "str_replace", "(", "'%2C'", ",", "','", ",", "$", "matches", "[", "2", "]", ")", ";", "}", ",", "$", "fileLocation", ")", ";", "}" ]
tag URLにおけるtaggingEntity中の不正にパーセント符号化された「,」を複号します。 @param string $fileLocation
[ "tag", "URLにおけるtaggingEntity中の不正にパーセント符号化された「", "」を複号します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L514-L523
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.parseQuestionLine
protected function parseQuestionLine(Dictionary $dictionary, string $question = null) { if ($this->answers) { // 未解析の解答が存在する場合 $this->parseQuizLines($dictionary, $this->question, $this->answers); $this->question = null; $this->answers = null; } elseif ($this->question) { // 未解析の問題が存在する場合 throw new SyntaxException($question ? _('「Q,」で始まる行が連続しています。') : _('辞書は「A,」で始まる行で終わらせなければなりません。')); } $this->question = $question; }
php
protected function parseQuestionLine(Dictionary $dictionary, string $question = null) { if ($this->answers) { // 未解析の解答が存在する場合 $this->parseQuizLines($dictionary, $this->question, $this->answers); $this->question = null; $this->answers = null; } elseif ($this->question) { // 未解析の問題が存在する場合 throw new SyntaxException($question ? _('「Q,」で始まる行が連続しています。') : _('辞書は「A,」で始まる行で終わらせなければなりません。')); } $this->question = $question; }
[ "protected", "function", "parseQuestionLine", "(", "Dictionary", "$", "dictionary", ",", "string", "$", "question", "=", "null", ")", "{", "if", "(", "$", "this", "->", "answers", ")", "{", "// 未解析の解答が存在する場合", "$", "this", "->", "parseQuizLines", "(", "$", "dictionary", ",", "$", "this", "->", "question", ",", "$", "this", "->", "answers", ")", ";", "$", "this", "->", "question", "=", "null", ";", "$", "this", "->", "answers", "=", "null", ";", "}", "elseif", "(", "$", "this", "->", "question", ")", "{", "// 未解析の問題が存在する場合", "throw", "new", "SyntaxException", "(", "$", "question", "?", "_", "(", "'「Q,」で始まる行が連続しています。') : _('辞書は「A,」で始まる行で終わらせなければなりませ", "ん", "'", ")", ";", "", "", "", "", "}", "$", "this", "->", "question", "=", "$", "question", ";", "}" ]
問題行を解析します。 @param Dictionary $dictionary @param string $question @throws SyntaxException すでに未解析の問題行が存在していた場合。
[ "問題行を解析します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L531-L543
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.parseAnswerLine
protected function parseAnswerLine(string $answer) { if (is_null($this->question)) { throw new SyntaxException(_('辞書は「Q,」で始めなければなりません。')); } elseif ($this->answers) { $this->answers .= ",$answer"; } else { $this->answers = $answer; } }
php
protected function parseAnswerLine(string $answer) { if (is_null($this->question)) { throw new SyntaxException(_('辞書は「Q,」で始めなければなりません。')); } elseif ($this->answers) { $this->answers .= ",$answer"; } else { $this->answers = $answer; } }
[ "protected", "function", "parseAnswerLine", "(", "string", "$", "answer", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "question", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'辞書は「Q,」で始めなければなりません。'));", "", "", "", "}", "elseif", "(", "$", "this", "->", "answers", ")", "{", "$", "this", "->", "answers", ".=", "\",$answer\"", ";", "}", "else", "{", "$", "this", "->", "answers", "=", "$", "answer", ";", "}", "}" ]
問題行を解析します。 @param string $answer @throws SyntaxException 未解析の問題行が存在していない場合。
[ "問題行を解析します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L550-L559
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.parseLine
protected function parseLine(Dictionary $dictionary, string $line = null) { if (is_null($line)) { if ($this->type === 'Inteligenceω クイズ') { $output = $this->parseQuestionLine($dictionary, null); } } elseif ($line[0] !== '%') { // 空行でなければ if (is_null($this->type)) { // 辞書の種類が与えられてなければ $this->type = stripos($line, 'Q,') === 0 ? 'Inteligenceω クイズ' : 'Inteligenceω しりとり'; } if ($this->type === 'Inteligenceω しりとり') { // しりとり辞書なら $output = $this->parseShiritoriLine($dictionary, $line); } elseif (stripos($line, 'Q,') === 0) { // 問題行なら $output = $this->parseQuestionLine($dictionary, $line); } elseif (stripos($line, 'A,') === 0) { // 解答行なら $this->parseAnswerLine($line); } else { throw new SyntaxException(_('壊れた行が含まれています:') . "\n" . $line); } } return $output ?? null; }
php
protected function parseLine(Dictionary $dictionary, string $line = null) { if (is_null($line)) { if ($this->type === 'Inteligenceω クイズ') { $output = $this->parseQuestionLine($dictionary, null); } } elseif ($line[0] !== '%') { // 空行でなければ if (is_null($this->type)) { // 辞書の種類が与えられてなければ $this->type = stripos($line, 'Q,') === 0 ? 'Inteligenceω クイズ' : 'Inteligenceω しりとり'; } if ($this->type === 'Inteligenceω しりとり') { // しりとり辞書なら $output = $this->parseShiritoriLine($dictionary, $line); } elseif (stripos($line, 'Q,') === 0) { // 問題行なら $output = $this->parseQuestionLine($dictionary, $line); } elseif (stripos($line, 'A,') === 0) { // 解答行なら $this->parseAnswerLine($line); } else { throw new SyntaxException(_('壊れた行が含まれています:') . "\n" . $line); } } return $output ?? null; }
[ "protected", "function", "parseLine", "(", "Dictionary", "$", "dictionary", ",", "string", "$", "line", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "line", ")", ")", "{", "if", "(", "$", "this", "->", "type", "===", "'Inteligenceω クイズ') {", "", "", "$", "output", "=", "$", "this", "->", "parseQuestionLine", "(", "$", "dictionary", ",", "null", ")", ";", "}", "}", "elseif", "(", "$", "line", "[", "0", "]", "!==", "'%'", ")", "{", "// 空行でなければ", "if", "(", "is_null", "(", "$", "this", "->", "type", ")", ")", "{", "// 辞書の種類が与えられてなければ", "$", "this", "->", "type", "=", "stripos", "(", "$", "line", ",", "'Q,'", ")", "===", "0", "?", "'Inteligenceω クイズ' : 'Int", "l", "genceω しりとり';", "", "}", "if", "(", "$", "this", "->", "type", "===", "'Inteligenceω しりとり') {", "", "", "// しりとり辞書なら", "$", "output", "=", "$", "this", "->", "parseShiritoriLine", "(", "$", "dictionary", ",", "$", "line", ")", ";", "}", "elseif", "(", "stripos", "(", "$", "line", ",", "'Q,'", ")", "===", "0", ")", "{", "// 問題行なら", "$", "output", "=", "$", "this", "->", "parseQuestionLine", "(", "$", "dictionary", ",", "$", "line", ")", ";", "}", "elseif", "(", "stripos", "(", "$", "line", ",", "'A,'", ")", "===", "0", ")", "{", "// 解答行なら", "$", "this", "->", "parseAnswerLine", "(", "$", "line", ")", ";", "}", "else", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'壊れた行が含まれています:') . \"\\n\" . $line);", "", "", "", "", "", "", "", "", "}", "}", "return", "$", "output", "??", "null", ";", "}" ]
行を解析します。 @param Dictionary $dictionary @param string|null ファイル終端ならnull。 @throws SyntaxException クイズ辞書で、コメント、問題、解答のいずれでもない行があれば @return Word|null
[ "行を解析します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L568-L596
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.getTitleFromFilename
protected function getTitleFromFilename(string $filename) { $withoutExtension = pathinfo($filename, PATHINFO_FILENAME); return $withoutExtension !== '' ? $withoutExtension : $filename; }
php
protected function getTitleFromFilename(string $filename) { $withoutExtension = pathinfo($filename, PATHINFO_FILENAME); return $withoutExtension !== '' ? $withoutExtension : $filename; }
[ "protected", "function", "getTitleFromFilename", "(", "string", "$", "filename", ")", "{", "$", "withoutExtension", "=", "pathinfo", "(", "$", "filename", ",", "PATHINFO_FILENAME", ")", ";", "return", "$", "withoutExtension", "!==", "''", "?", "$", "withoutExtension", ":", "$", "filename", ";", "}" ]
ファイル名から辞書のタイトルを取得します。 @param string $filename @return string|null
[ "ファイル名から辞書のタイトルを取得します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L603-L607
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.correctArchiveFilenamesEncoding
protected function correctArchiveFilenamesEncoding(ZipFile $archive) { $parser = new GenericDictionaryParser(); foreach ($archive->getListFiles() as $filename) { $corrected = $parser->correctEncoding($filename); if ($filename !== $corrected) { $archive->rename($filename, $corrected); } } }
php
protected function correctArchiveFilenamesEncoding(ZipFile $archive) { $parser = new GenericDictionaryParser(); foreach ($archive->getListFiles() as $filename) { $corrected = $parser->correctEncoding($filename); if ($filename !== $corrected) { $archive->rename($filename, $corrected); } } }
[ "protected", "function", "correctArchiveFilenamesEncoding", "(", "ZipFile", "$", "archive", ")", "{", "$", "parser", "=", "new", "GenericDictionaryParser", "(", ")", ";", "foreach", "(", "$", "archive", "->", "getListFiles", "(", ")", "as", "$", "filename", ")", "{", "$", "corrected", "=", "$", "parser", "->", "correctEncoding", "(", "$", "filename", ")", ";", "if", "(", "$", "filename", "!==", "$", "corrected", ")", "{", "$", "archive", "->", "rename", "(", "$", "filename", ",", "$", "corrected", ")", ";", "}", "}", "}" ]
アーカイブ中のファイル名の符号化方式をUTF-8に矯正します。 @param ZipFile $archive
[ "アーカイブ中のファイル名の符号化方式をUTF", "-", "8に矯正します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L613-L622
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.flattenArchive
protected function flattenArchive(ZipFile $archive) { $validator = new validator\FileLocationValidator(); foreach ($archive->getListFiles() as $filename) { if (\Stringy\StaticStringy::endsWith($filename, '/')) { $archive->deleteFromName($directory); } else { $basename = $validator->getBasename($filename); if ($filename !== $basename) { if (in_array(strtolower($basename), array_map('strtolower', $archive->getListFiles()))) { throw SyntaxException(_('アーカイブ中に同名のファイルを含めることはできません: ') . $basename); } $archive->rename($filename, $basename); } } } }
php
protected function flattenArchive(ZipFile $archive) { $validator = new validator\FileLocationValidator(); foreach ($archive->getListFiles() as $filename) { if (\Stringy\StaticStringy::endsWith($filename, '/')) { $archive->deleteFromName($directory); } else { $basename = $validator->getBasename($filename); if ($filename !== $basename) { if (in_array(strtolower($basename), array_map('strtolower', $archive->getListFiles()))) { throw SyntaxException(_('アーカイブ中に同名のファイルを含めることはできません: ') . $basename); } $archive->rename($filename, $basename); } } } }
[ "protected", "function", "flattenArchive", "(", "ZipFile", "$", "archive", ")", "{", "$", "validator", "=", "new", "validator", "\\", "FileLocationValidator", "(", ")", ";", "foreach", "(", "$", "archive", "->", "getListFiles", "(", ")", "as", "$", "filename", ")", "{", "if", "(", "\\", "Stringy", "\\", "StaticStringy", "::", "endsWith", "(", "$", "filename", ",", "'/'", ")", ")", "{", "$", "archive", "->", "deleteFromName", "(", "$", "directory", ")", ";", "}", "else", "{", "$", "basename", "=", "$", "validator", "->", "getBasename", "(", "$", "filename", ")", ";", "if", "(", "$", "filename", "!==", "$", "basename", ")", "{", "if", "(", "in_array", "(", "strtolower", "(", "$", "basename", ")", ",", "array_map", "(", "'strtolower'", ",", "$", "archive", "->", "getListFiles", "(", ")", ")", ")", ")", "{", "throw", "SyntaxException", "(", "_", "(", "'アーカイブ中に同名のファイルを含めることはできません: ') . $basename);", "", "", "", "", "", "", "}", "$", "archive", "->", "rename", "(", "$", "filename", ",", "$", "basename", ")", ";", "}", "}", "}", "}" ]
アーカイブ中のディレクトリ構造を除去します。 @param ZipFile $archive @throws SyntaxException 同名のファイルが存在する場合。
[ "アーカイブ中のディレクトリ構造を除去します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L629-L645
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.correctArchiveFilenames
protected function correctArchiveFilenames(ZipFile $archive): array { $filenames = []; foreach ($archive->getListFiles() as $filename) { $corrected = (new validator\FilenameValidator(null, $filenames, false))->correct($filename); if ($filename !== $corrected) { $archive->rename($filename, $corrected); $filenames[$filename] = $corrected; } else { $filenames[] = $filename; } set_time_limit(ini_get('max_execution_time')); } return $filenames; }
php
protected function correctArchiveFilenames(ZipFile $archive): array { $filenames = []; foreach ($archive->getListFiles() as $filename) { $corrected = (new validator\FilenameValidator(null, $filenames, false))->correct($filename); if ($filename !== $corrected) { $archive->rename($filename, $corrected); $filenames[$filename] = $corrected; } else { $filenames[] = $filename; } set_time_limit(ini_get('max_execution_time')); } return $filenames; }
[ "protected", "function", "correctArchiveFilenames", "(", "ZipFile", "$", "archive", ")", ":", "array", "{", "$", "filenames", "=", "[", "]", ";", "foreach", "(", "$", "archive", "->", "getListFiles", "(", ")", "as", "$", "filename", ")", "{", "$", "corrected", "=", "(", "new", "validator", "\\", "FilenameValidator", "(", "null", ",", "$", "filenames", ",", "false", ")", ")", "->", "correct", "(", "$", "filename", ")", ";", "if", "(", "$", "filename", "!==", "$", "corrected", ")", "{", "$", "archive", "->", "rename", "(", "$", "filename", ",", "$", "corrected", ")", ";", "$", "filenames", "[", "$", "filename", "]", "=", "$", "corrected", ";", "}", "else", "{", "$", "filenames", "[", "]", "=", "$", "filename", ";", "}", "set_time_limit", "(", "ini_get", "(", "'max_execution_time'", ")", ")", ";", "}", "return", "$", "filenames", ";", "}" ]
アーカイブ中のファイル名を矯正します。 @param ZipFile $archive @return string[] ファイル名の一覧。矯正を行った場合は、キーに矯正前のファイル名を持ちます。
[ "アーカイブ中のファイル名を矯正します。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L652-L668
esperecyan/dictionary-php
src/parser/InteligenceoParser.php
InteligenceoParser.parseArchive
protected function parseArchive(\SplFileInfo $file): \SplFileInfo { $archive = (new ZipFile())->openFile( $file instanceof \SplTempFileObject ? $this->generateTempFile($file) : $file->getRealPath() ); $this->correctArchiveFilenamesEncoding($archive); $this->flattenArchive($archive); $this->filenames = $this->correctArchiveFilenames($archive); $tempDirectoryPath = (new GenericDictionaryParser())->generateTempDirectory(); $archive->extractTo($tempDirectoryPath); $archive->close(); $validator = new \esperecyan\dictionary_php\Validator(); $validator->setLogger($this->logger); foreach (new \FilesystemIterator( $tempDirectoryPath, \FilesystemIterator::KEY_AS_FILENAME ) as $filename => $file) { if ($file->getExtension() === 'txt') { if (isset($quizFile)) { throw new SyntaxException(_('拡張子が「.txt」のファイルが2つ以上含まれています。')); } if (!in_array( (new Finfo(FILEINFO_MIME_TYPE))->file($file), ['text/plain', 'text/csv'] )) { throw new SyntaxException( sprintf(_('「%s」は通常のテキストファイルとして認識できません。'), $filename) ); } $quizFile = $file; } } if (empty($quizFile)) { throw new SyntaxException(_('拡張子が「.txt」のファイルが見つかりません。')); } return $quizFile; }
php
protected function parseArchive(\SplFileInfo $file): \SplFileInfo { $archive = (new ZipFile())->openFile( $file instanceof \SplTempFileObject ? $this->generateTempFile($file) : $file->getRealPath() ); $this->correctArchiveFilenamesEncoding($archive); $this->flattenArchive($archive); $this->filenames = $this->correctArchiveFilenames($archive); $tempDirectoryPath = (new GenericDictionaryParser())->generateTempDirectory(); $archive->extractTo($tempDirectoryPath); $archive->close(); $validator = new \esperecyan\dictionary_php\Validator(); $validator->setLogger($this->logger); foreach (new \FilesystemIterator( $tempDirectoryPath, \FilesystemIterator::KEY_AS_FILENAME ) as $filename => $file) { if ($file->getExtension() === 'txt') { if (isset($quizFile)) { throw new SyntaxException(_('拡張子が「.txt」のファイルが2つ以上含まれています。')); } if (!in_array( (new Finfo(FILEINFO_MIME_TYPE))->file($file), ['text/plain', 'text/csv'] )) { throw new SyntaxException( sprintf(_('「%s」は通常のテキストファイルとして認識できません。'), $filename) ); } $quizFile = $file; } } if (empty($quizFile)) { throw new SyntaxException(_('拡張子が「.txt」のファイルが見つかりません。')); } return $quizFile; }
[ "protected", "function", "parseArchive", "(", "\\", "SplFileInfo", "$", "file", ")", ":", "\\", "SplFileInfo", "{", "$", "archive", "=", "(", "new", "ZipFile", "(", ")", ")", "->", "openFile", "(", "$", "file", "instanceof", "\\", "SplTempFileObject", "?", "$", "this", "->", "generateTempFile", "(", "$", "file", ")", ":", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "$", "this", "->", "correctArchiveFilenamesEncoding", "(", "$", "archive", ")", ";", "$", "this", "->", "flattenArchive", "(", "$", "archive", ")", ";", "$", "this", "->", "filenames", "=", "$", "this", "->", "correctArchiveFilenames", "(", "$", "archive", ")", ";", "$", "tempDirectoryPath", "=", "(", "new", "GenericDictionaryParser", "(", ")", ")", "->", "generateTempDirectory", "(", ")", ";", "$", "archive", "->", "extractTo", "(", "$", "tempDirectoryPath", ")", ";", "$", "archive", "->", "close", "(", ")", ";", "$", "validator", "=", "new", "\\", "esperecyan", "\\", "dictionary_php", "\\", "Validator", "(", ")", ";", "$", "validator", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "foreach", "(", "new", "\\", "FilesystemIterator", "(", "$", "tempDirectoryPath", ",", "\\", "FilesystemIterator", "::", "KEY_AS_FILENAME", ")", "as", "$", "filename", "=>", "$", "file", ")", "{", "if", "(", "$", "file", "->", "getExtension", "(", ")", "===", "'txt'", ")", "{", "if", "(", "isset", "(", "$", "quizFile", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'拡張子が「.txt」のファイルが2つ以上含まれています。'));", "", "", "", "}", "if", "(", "!", "in_array", "(", "(", "new", "Finfo", "(", "FILEINFO_MIME_TYPE", ")", ")", "->", "file", "(", "$", "file", ")", ",", "[", "'text/plain'", ",", "'text/csv'", "]", ")", ")", "{", "throw", "new", "SyntaxException", "(", "sprintf", "(", "_", "(", "'「%s」は通常のテキストファイルとして認識できません。'), $filename)", "", "", "", "", "", ")", ";", "}", "$", "quizFile", "=", "$", "file", ";", "}", "}", "if", "(", "empty", "(", "$", "quizFile", ")", ")", "{", "throw", "new", "SyntaxException", "(", "_", "(", "'拡張子が「.txt」のファイルが見つかりません。'));", "", "", "", "}", "return", "$", "quizFile", ";", "}" ]
ZIPアーカイブを解析し、ファイルの矯正を行います。 @param \SplFileInfo $file @throws SyntaxException @return \SplFileInfo
[ "ZIPアーカイブを解析し、ファイルの矯正を行います。" ]
train
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/parser/InteligenceoParser.php#L676-L716
stubbles/stubbles-webapp-core
src/main/php/response/mimetypes/Json.php
Json.serialize
public function serialize($resource, OutputStream $out): OutputStream { $out->write(json_encode($resource)); return $out; }
php
public function serialize($resource, OutputStream $out): OutputStream { $out->write(json_encode($resource)); return $out; }
[ "public", "function", "serialize", "(", "$", "resource", ",", "OutputStream", "$", "out", ")", ":", "OutputStream", "{", "$", "out", "->", "write", "(", "json_encode", "(", "$", "resource", ")", ")", ";", "return", "$", "out", ";", "}" ]
serializes resource to output stream @param mixed $resource @param \stubbles\streams\OutputStream $out @return \stubbles\streams\OutputStream
[ "serializes", "resource", "to", "output", "stream" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/response/mimetypes/Json.php#L37-L41
CalderaWP/magic-tags
src/magictag.php
magictag.do_magic_tag
public function do_magic_tag($content){ // check for magics preg_match_all("/\{(.+?)\}/", (string) $content, $magics); // on found tags if(!empty($magics[1])){ foreach($magics[1] as $magic_key=>$magic_tag){ $params = explode(':', $magic_tag, 2 ); if( empty( $params[1] ) ){ continue; } // filter a general tag using the second argument as the original tag $filter_value = apply_filters( 'caldera_magic_tag', apply_filters( "caldera_magic_tag-{$params[0]}", $params[1] ) , $magics[0][$magic_key]); // chech the tag changed if( $filter_value !== $params[1] ){ // on a difference in the tag, replace it. $content = str_replace( $magics[0][$magic_key], $filter_value, $content ); } } } // return content converted or not. return $content; }
php
public function do_magic_tag($content){ // check for magics preg_match_all("/\{(.+?)\}/", (string) $content, $magics); // on found tags if(!empty($magics[1])){ foreach($magics[1] as $magic_key=>$magic_tag){ $params = explode(':', $magic_tag, 2 ); if( empty( $params[1] ) ){ continue; } // filter a general tag using the second argument as the original tag $filter_value = apply_filters( 'caldera_magic_tag', apply_filters( "caldera_magic_tag-{$params[0]}", $params[1] ) , $magics[0][$magic_key]); // chech the tag changed if( $filter_value !== $params[1] ){ // on a difference in the tag, replace it. $content = str_replace( $magics[0][$magic_key], $filter_value, $content ); } } } // return content converted or not. return $content; }
[ "public", "function", "do_magic_tag", "(", "$", "content", ")", "{", "// check for magics", "preg_match_all", "(", "\"/\\{(.+?)\\}/\"", ",", "(", "string", ")", "$", "content", ",", "$", "magics", ")", ";", "// on found tags", "if", "(", "!", "empty", "(", "$", "magics", "[", "1", "]", ")", ")", "{", "foreach", "(", "$", "magics", "[", "1", "]", "as", "$", "magic_key", "=>", "$", "magic_tag", ")", "{", "$", "params", "=", "explode", "(", "':'", ",", "$", "magic_tag", ",", "2", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "1", "]", ")", ")", "{", "continue", ";", "}", "// filter a general tag using the second argument as the original tag", "$", "filter_value", "=", "apply_filters", "(", "'caldera_magic_tag'", ",", "apply_filters", "(", "\"caldera_magic_tag-{$params[0]}\"", ",", "$", "params", "[", "1", "]", ")", ",", "$", "magics", "[", "0", "]", "[", "$", "magic_key", "]", ")", ";", "// chech the tag changed", "if", "(", "$", "filter_value", "!==", "$", "params", "[", "1", "]", ")", "{", "// on a difference in the tag, replace it.", "$", "content", "=", "str_replace", "(", "$", "magics", "[", "0", "]", "[", "$", "magic_key", "]", ",", "$", "filter_value", ",", "$", "content", ")", ";", "}", "}", "}", "// return content converted or not.", "return", "$", "content", ";", "}" ]
Renders a magic tag @return string converted string with matched tags replaced
[ "Renders", "a", "magic", "tag" ]
train
https://github.com/CalderaWP/magic-tags/blob/0e46a6d187bff87c027ed8a6a9e09446aa5f3bd9/src/magictag.php#L48-L71
CalderaWP/magic-tags
src/magictag.php
magictag.get_post_value
private function get_post_value( $field, $in_params, $post ){ if( !is_object( $post ) ){ return $in_params; } if ( 'permalink' == $field || 'post_permalink' == $field ) { return esc_url( get_permalink( $post->ID ) ); } //handle auto-generated and <!--more--> tag excerpts @since 1.1.0 if ( 'post_excerpt' == $field && '' == $post->post_excerpt ) { if ( 0 < strpos( $post->post_content, '<!--more-->' ) ){ $excerpt = substr( $post->post_content, 0, strpos( $post->post_content, '<!--more-->') ); } else { /** * This filer is duplicated from WordPress core to respect core setting for excerpt length. * * It is documented in wp-includes/formatting.php */ $excerpt_length = apply_filters( 'excerpt_length', 55 ); $excerpt = wp_trim_words( $post->post_content, $excerpt_length, '' ); } return $excerpt; } //possibly do a post_thumbnail magic tag @since 1.1.0 $maybe_thumbnail = $this->maybe_do_post_thumbnail( $field, $post ); if ( filter_var( $maybe_thumbnail, FILTER_VALIDATE_URL ) ) { return $maybe_thumbnail; } if( isset( $post->{$field} ) ){ return implode( ', ', (array) $post->{$field} ); } return $in_params; }
php
private function get_post_value( $field, $in_params, $post ){ if( !is_object( $post ) ){ return $in_params; } if ( 'permalink' == $field || 'post_permalink' == $field ) { return esc_url( get_permalink( $post->ID ) ); } //handle auto-generated and <!--more--> tag excerpts @since 1.1.0 if ( 'post_excerpt' == $field && '' == $post->post_excerpt ) { if ( 0 < strpos( $post->post_content, '<!--more-->' ) ){ $excerpt = substr( $post->post_content, 0, strpos( $post->post_content, '<!--more-->') ); } else { /** * This filer is duplicated from WordPress core to respect core setting for excerpt length. * * It is documented in wp-includes/formatting.php */ $excerpt_length = apply_filters( 'excerpt_length', 55 ); $excerpt = wp_trim_words( $post->post_content, $excerpt_length, '' ); } return $excerpt; } //possibly do a post_thumbnail magic tag @since 1.1.0 $maybe_thumbnail = $this->maybe_do_post_thumbnail( $field, $post ); if ( filter_var( $maybe_thumbnail, FILTER_VALIDATE_URL ) ) { return $maybe_thumbnail; } if( isset( $post->{$field} ) ){ return implode( ', ', (array) $post->{$field} ); } return $in_params; }
[ "private", "function", "get_post_value", "(", "$", "field", ",", "$", "in_params", ",", "$", "post", ")", "{", "if", "(", "!", "is_object", "(", "$", "post", ")", ")", "{", "return", "$", "in_params", ";", "}", "if", "(", "'permalink'", "==", "$", "field", "||", "'post_permalink'", "==", "$", "field", ")", "{", "return", "esc_url", "(", "get_permalink", "(", "$", "post", "->", "ID", ")", ")", ";", "}", "//handle auto-generated and <!--more--> tag excerpts @since 1.1.0", "if", "(", "'post_excerpt'", "==", "$", "field", "&&", "''", "==", "$", "post", "->", "post_excerpt", ")", "{", "if", "(", "0", "<", "strpos", "(", "$", "post", "->", "post_content", ",", "'<!--more-->'", ")", ")", "{", "$", "excerpt", "=", "substr", "(", "$", "post", "->", "post_content", ",", "0", ",", "strpos", "(", "$", "post", "->", "post_content", ",", "'<!--more-->'", ")", ")", ";", "}", "else", "{", "/**\n\t\t\t\t * This filer is duplicated from WordPress core to respect core setting for excerpt length.\n\t\t\t\t *\n\t\t\t\t * It is documented in wp-includes/formatting.php\n\t\t\t\t */", "$", "excerpt_length", "=", "apply_filters", "(", "'excerpt_length'", ",", "55", ")", ";", "$", "excerpt", "=", "wp_trim_words", "(", "$", "post", "->", "post_content", ",", "$", "excerpt_length", ",", "''", ")", ";", "}", "return", "$", "excerpt", ";", "}", "//possibly do a post_thumbnail magic tag @since 1.1.0", "$", "maybe_thumbnail", "=", "$", "this", "->", "maybe_do_post_thumbnail", "(", "$", "field", ",", "$", "post", ")", ";", "if", "(", "filter_var", "(", "$", "maybe_thumbnail", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "return", "$", "maybe_thumbnail", ";", "}", "if", "(", "isset", "(", "$", "post", "->", "{", "$", "field", "}", ")", ")", "{", "return", "implode", "(", "', '", ",", "(", "array", ")", "$", "post", "->", "{", "$", "field", "}", ")", ";", "}", "return", "$", "in_params", ";", "}" ]
Gets a posts meta value @since 0.0.1 @return string post field value
[ "Gets", "a", "posts", "meta", "value" ]
train
https://github.com/CalderaWP/magic-tags/blob/0e46a6d187bff87c027ed8a6a9e09446aa5f3bd9/src/magictag.php#L80-L123
withfatpanda/illuminate-wordpress
src/WordPress/Models/FieldGroup.php
FieldGroup.buildConfig
function buildConfig(Plugin $plugin) { if (!empty($this->fields)) { $this->config['fields'] = []; foreach($this->fields as $field) { $this->config['fields'][] = $field->buildConfig($plugin); } } if (!is_null($this->id)) { $this->config['id'] = $this->id; } return $this->config; }
php
function buildConfig(Plugin $plugin) { if (!empty($this->fields)) { $this->config['fields'] = []; foreach($this->fields as $field) { $this->config['fields'][] = $field->buildConfig($plugin); } } if (!is_null($this->id)) { $this->config['id'] = $this->id; } return $this->config; }
[ "function", "buildConfig", "(", "Plugin", "$", "plugin", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "fields", ")", ")", "{", "$", "this", "->", "config", "[", "'fields'", "]", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "fields", "as", "$", "field", ")", "{", "$", "this", "->", "config", "[", "'fields'", "]", "[", "]", "=", "$", "field", "->", "buildConfig", "(", "$", "plugin", ")", ";", "}", "}", "if", "(", "!", "is_null", "(", "$", "this", "->", "id", ")", ")", "{", "$", "this", "->", "config", "[", "'id'", "]", "=", "$", "this", "->", "id", ";", "}", "return", "$", "this", "->", "config", ";", "}" ]
Build field group config @return array
[ "Build", "field", "group", "config" ]
train
https://github.com/withfatpanda/illuminate-wordpress/blob/b426ca81a55367459430c974932ee5a941d759d8/src/WordPress/Models/FieldGroup.php#L196-L210
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait.error
public function error($message = '', $jumpUrl = '', $data = []) { return $this->getDispatch()->error($message, $jumpUrl, $data); }
php
public function error($message = '', $jumpUrl = '', $data = []) { return $this->getDispatch()->error($message, $jumpUrl, $data); }
[ "public", "function", "error", "(", "$", "message", "=", "''", ",", "$", "jumpUrl", "=", "''", ",", "$", "data", "=", "[", "]", ")", "{", "return", "$", "this", "->", "getDispatch", "(", ")", "->", "error", "(", "$", "message", ",", "$", "jumpUrl", ",", "$", "data", ")", ";", "}" ]
操作失败后返回结果至客户端 @param string|array $message 提示信息 @param string|array $jumpUrl 页面跳转地址 @param mixed $data - 为整数,则代表页面跳转停留时间,默认为3妙,时间结束后自动跳转至指定的`$jumpUrl`页面 - 为数组,则代表返回给客户端的数据 @return mixed
[ "操作失败后返回结果至客户端" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L101-L104
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait.success
public function success($message = '', $jumpUrl = '', $data = []) { return $this->getDispatch()->success($message, $jumpUrl, $data); }
php
public function success($message = '', $jumpUrl = '', $data = []) { return $this->getDispatch()->success($message, $jumpUrl, $data); }
[ "public", "function", "success", "(", "$", "message", "=", "''", ",", "$", "jumpUrl", "=", "''", ",", "$", "data", "=", "[", "]", ")", "{", "return", "$", "this", "->", "getDispatch", "(", ")", "->", "success", "(", "$", "message", ",", "$", "jumpUrl", ",", "$", "data", ")", ";", "}" ]
操作成功后返回结果至客户端 @param string|array $message 提示信息 @param string|array $jumpUrl 页面跳转地址 @param mixed $data - 为整数,则代表页面跳转停留时间,默认为1妙,时间结束后自动跳转至指定的`$jumpUrl`页面 - 为数组,则代表返回给客户端的数据 @return mixed
[ "操作成功后返回结果至客户端" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L117-L120
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait.normalizeDispatchNamespace
public function normalizeDispatchNamespace($route) { $route = explode('/', $route); foreach ($route as &$part) { if (strpos($part, '-') !== false) { $part = Inflector::variablize($part); } } return ($this->_isDeveloperMode() ? $this->developerDispatchNamespace : $this->dispatchNamespace) . '\\' . str_replace('/', '\\', implode('/', $route)); }
php
public function normalizeDispatchNamespace($route) { $route = explode('/', $route); foreach ($route as &$part) { if (strpos($part, '-') !== false) { $part = Inflector::variablize($part); } } return ($this->_isDeveloperMode() ? $this->developerDispatchNamespace : $this->dispatchNamespace) . '\\' . str_replace('/', '\\', implode('/', $route)); }
[ "public", "function", "normalizeDispatchNamespace", "(", "$", "route", ")", "{", "$", "route", "=", "explode", "(", "'/'", ",", "$", "route", ")", ";", "foreach", "(", "$", "route", "as", "&", "$", "part", ")", "{", "if", "(", "strpos", "(", "$", "part", ",", "'-'", ")", "!==", "false", ")", "{", "$", "part", "=", "Inflector", "::", "variablize", "(", "$", "part", ")", ";", "}", "}", "return", "(", "$", "this", "->", "_isDeveloperMode", "(", ")", "?", "$", "this", "->", "developerDispatchNamespace", ":", "$", "this", "->", "dispatchNamespace", ")", ".", "'\\\\'", ".", "str_replace", "(", "'/'", ",", "'\\\\'", ",", "implode", "(", "'/'", ",", "$", "route", ")", ")", ";", "}" ]
格式化带'-_'字符的调度器路由地址 例如:ConfigManager控制器,路由地址为'config-manager',调度器在处理路由地址时,因命名空间不支持带'-'的命名方式, 因此需要处理该字符窜,操作将返回如`configManager`这样格式的字符窜 @param string $route @return string
[ "格式化带", "-", "_", "字符的调度器路由地址", "例如:ConfigManager控制器,路由地址为", "config", "-", "manager", ",调度器在处理路由地址时,因命名空间不支持带", "-", "的命名方式,", "因此需要处理该字符窜,操作将返回如", "configManager", "这样格式的字符窜" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L201-L212
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait.getDispatch
public function getDispatch($route = null) { // 没有指定调度路由则默认获取主题公共调度器 return $route === null ? $this->getCommonDispatch() : $this->_getDispatchByRoute($route); }
php
public function getDispatch($route = null) { // 没有指定调度路由则默认获取主题公共调度器 return $route === null ? $this->getCommonDispatch() : $this->_getDispatchByRoute($route); }
[ "public", "function", "getDispatch", "(", "$", "route", "=", "null", ")", "{", "// 没有指定调度路由则默认获取主题公共调度器", "return", "$", "route", "===", "null", "?", "$", "this", "->", "getCommonDispatch", "(", ")", ":", "$", "this", "->", "_getDispatchByRoute", "(", "$", "route", ")", ";", "}" ]
根据路由地址获取调度器,默认获取主题公共调度器 该方法和[[run()|runAction()]]方法类似,唯一区别是在获取到指定调度器时不默认执行[[run()]],而是可以自由调用调度器里面的方法, 这样可以有效实现部分代码重用 @param null|string $route 调度路由,支持以下格式:'view', 'comment/view', '/admin/comment/view' @return null|Dispatch
[ "根据路由地址获取调度器,默认获取主题公共调度器" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L238-L242
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait._createDispatchByConfig
private function _createDispatchByConfig($id, $config) { if (!is_array($config)) { $config = ['class' => $config]; } internal: $className = ltrim($config['class'], '\\'); $dispatch = null; if (class_exists($className)) { if (is_subclass_of($className, 'wocenter\core\Dispatch')) { $dispatch = Yii::createObject($config, [ $id, Yii::$app->controller ?: $this, ]); if (get_class($dispatch) !== $className) { $dispatch = null; } } elseif (YII_DEBUG) { throw new InvalidConfigException("Dispatch class must extend from \\wocenter\\core\\Dispatch."); } } // 调度器不存在则调用系统扩展内调度器 elseif ($this->_isDeveloperMode()) { $config['class'] = StringHelper::replace($config['class'], 'developer\\'); if (class_exists($config['class'])) { goto internal; } } if ($dispatch === null) { $this->_generateDispatchFile($className); } Yii::trace('Loading dispatch: ' . $className, __METHOD__); return $dispatch; }
php
private function _createDispatchByConfig($id, $config) { if (!is_array($config)) { $config = ['class' => $config]; } internal: $className = ltrim($config['class'], '\\'); $dispatch = null; if (class_exists($className)) { if (is_subclass_of($className, 'wocenter\core\Dispatch')) { $dispatch = Yii::createObject($config, [ $id, Yii::$app->controller ?: $this, ]); if (get_class($dispatch) !== $className) { $dispatch = null; } } elseif (YII_DEBUG) { throw new InvalidConfigException("Dispatch class must extend from \\wocenter\\core\\Dispatch."); } } // 调度器不存在则调用系统扩展内调度器 elseif ($this->_isDeveloperMode()) { $config['class'] = StringHelper::replace($config['class'], 'developer\\'); if (class_exists($config['class'])) { goto internal; } } if ($dispatch === null) { $this->_generateDispatchFile($className); } Yii::trace('Loading dispatch: ' . $className, __METHOD__); return $dispatch; }
[ "private", "function", "_createDispatchByConfig", "(", "$", "id", ",", "$", "config", ")", "{", "if", "(", "!", "is_array", "(", "$", "config", ")", ")", "{", "$", "config", "=", "[", "'class'", "=>", "$", "config", "]", ";", "}", "internal", ":", "$", "className", "=", "ltrim", "(", "$", "config", "[", "'class'", "]", ",", "'\\\\'", ")", ";", "$", "dispatch", "=", "null", ";", "if", "(", "class_exists", "(", "$", "className", ")", ")", "{", "if", "(", "is_subclass_of", "(", "$", "className", ",", "'wocenter\\core\\Dispatch'", ")", ")", "{", "$", "dispatch", "=", "Yii", "::", "createObject", "(", "$", "config", ",", "[", "$", "id", ",", "Yii", "::", "$", "app", "->", "controller", "?", ":", "$", "this", ",", "]", ")", ";", "if", "(", "get_class", "(", "$", "dispatch", ")", "!==", "$", "className", ")", "{", "$", "dispatch", "=", "null", ";", "}", "}", "elseif", "(", "YII_DEBUG", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"Dispatch class must extend from \\\\wocenter\\\\core\\\\Dispatch.\"", ")", ";", "}", "}", "// 调度器不存在则调用系统扩展内调度器", "elseif", "(", "$", "this", "->", "_isDeveloperMode", "(", ")", ")", "{", "$", "config", "[", "'class'", "]", "=", "StringHelper", "::", "replace", "(", "$", "config", "[", "'class'", "]", ",", "'developer\\\\'", ")", ";", "if", "(", "class_exists", "(", "$", "config", "[", "'class'", "]", ")", ")", "{", "goto", "internal", ";", "}", "}", "if", "(", "$", "dispatch", "===", "null", ")", "{", "$", "this", "->", "_generateDispatchFile", "(", "$", "className", ")", ";", "}", "Yii", "::", "trace", "(", "'Loading dispatch: '", ".", "$", "className", ",", "__METHOD__", ")", ";", "return", "$", "dispatch", ";", "}" ]
根据调度器配置创建调度器 @param string $id 调度器ID @param string|array $config 调度器类名或调度器配置信息 @return null|Dispatch|object @throws Exception @throws InvalidConfigException
[ "根据调度器配置创建调度器" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L254-L292
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait._createDispatch
private function _createDispatch($id, $withConfig = true) { if ($id === '') { $id = $this->defaultAction; } if ($withConfig) { $dispatchMap = $this->dispatches(); // 存在调度配置信息则执行自定义调度,否则终止调度行为 if (in_array($id, $dispatchMap) || isset($dispatchMap[$id])) { // 存在调度配置信息 if (isset($dispatchMap[$id]) && !empty($dispatchMap[$id])) { $config = $dispatchMap[$id]; // 调度配置为数组 if (is_array($config)) { $dispatchOptions = ArrayHelper::remove($config, 'dispatchOptions', []); // 调度配置包含`class`键名则直接使用`class`创建调度器 if (isset($config['class'])) { $classConfig = $config; } else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($dispatchOptions['map'] ?? $id); $classConfig = array_merge( ['class' => $this->normalizeDispatchNamespace($dispatchId)], $config // 使用其他属性初始化调度器 ); } } // 调度配置为类名 elseif (class_exists($config)) { $classConfig = $config; } // 其他字符串则为直接调度器映射 else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($config); $classConfig = $this->normalizeDispatchNamespace($dispatchId); } } // 根据调度器ID直接创建调度器 else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($id); $classConfig = $this->normalizeDispatchNamespace($dispatchId); } } else { return null; } } else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($id); $classConfig = $this->normalizeDispatchNamespace($dispatchId); } return $this->_createDispatchByConfig($id, $classConfig); }
php
private function _createDispatch($id, $withConfig = true) { if ($id === '') { $id = $this->defaultAction; } if ($withConfig) { $dispatchMap = $this->dispatches(); // 存在调度配置信息则执行自定义调度,否则终止调度行为 if (in_array($id, $dispatchMap) || isset($dispatchMap[$id])) { // 存在调度配置信息 if (isset($dispatchMap[$id]) && !empty($dispatchMap[$id])) { $config = $dispatchMap[$id]; // 调度配置为数组 if (is_array($config)) { $dispatchOptions = ArrayHelper::remove($config, 'dispatchOptions', []); // 调度配置包含`class`键名则直接使用`class`创建调度器 if (isset($config['class'])) { $classConfig = $config; } else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($dispatchOptions['map'] ?? $id); $classConfig = array_merge( ['class' => $this->normalizeDispatchNamespace($dispatchId)], $config // 使用其他属性初始化调度器 ); } } // 调度配置为类名 elseif (class_exists($config)) { $classConfig = $config; } // 其他字符串则为直接调度器映射 else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($config); $classConfig = $this->normalizeDispatchNamespace($dispatchId); } } // 根据调度器ID直接创建调度器 else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($id); $classConfig = $this->normalizeDispatchNamespace($dispatchId); } } else { return null; } } else { $dispatchId = $this->id . '/' . $this->normalizeDispatchName($id); $classConfig = $this->normalizeDispatchNamespace($dispatchId); } return $this->_createDispatchByConfig($id, $classConfig); }
[ "private", "function", "_createDispatch", "(", "$", "id", ",", "$", "withConfig", "=", "true", ")", "{", "if", "(", "$", "id", "===", "''", ")", "{", "$", "id", "=", "$", "this", "->", "defaultAction", ";", "}", "if", "(", "$", "withConfig", ")", "{", "$", "dispatchMap", "=", "$", "this", "->", "dispatches", "(", ")", ";", "// 存在调度配置信息则执行自定义调度,否则终止调度行为", "if", "(", "in_array", "(", "$", "id", ",", "$", "dispatchMap", ")", "||", "isset", "(", "$", "dispatchMap", "[", "$", "id", "]", ")", ")", "{", "// 存在调度配置信息", "if", "(", "isset", "(", "$", "dispatchMap", "[", "$", "id", "]", ")", "&&", "!", "empty", "(", "$", "dispatchMap", "[", "$", "id", "]", ")", ")", "{", "$", "config", "=", "$", "dispatchMap", "[", "$", "id", "]", ";", "// 调度配置为数组", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "$", "dispatchOptions", "=", "ArrayHelper", "::", "remove", "(", "$", "config", ",", "'dispatchOptions'", ",", "[", "]", ")", ";", "// 调度配置包含`class`键名则直接使用`class`创建调度器", "if", "(", "isset", "(", "$", "config", "[", "'class'", "]", ")", ")", "{", "$", "classConfig", "=", "$", "config", ";", "}", "else", "{", "$", "dispatchId", "=", "$", "this", "->", "id", ".", "'/'", ".", "$", "this", "->", "normalizeDispatchName", "(", "$", "dispatchOptions", "[", "'map'", "]", "??", "$", "id", ")", ";", "$", "classConfig", "=", "array_merge", "(", "[", "'class'", "=>", "$", "this", "->", "normalizeDispatchNamespace", "(", "$", "dispatchId", ")", "]", ",", "$", "config", "// 使用其他属性初始化调度器", ")", ";", "}", "}", "// 调度配置为类名", "elseif", "(", "class_exists", "(", "$", "config", ")", ")", "{", "$", "classConfig", "=", "$", "config", ";", "}", "// 其他字符串则为直接调度器映射", "else", "{", "$", "dispatchId", "=", "$", "this", "->", "id", ".", "'/'", ".", "$", "this", "->", "normalizeDispatchName", "(", "$", "config", ")", ";", "$", "classConfig", "=", "$", "this", "->", "normalizeDispatchNamespace", "(", "$", "dispatchId", ")", ";", "}", "}", "// 根据调度器ID直接创建调度器", "else", "{", "$", "dispatchId", "=", "$", "this", "->", "id", ".", "'/'", ".", "$", "this", "->", "normalizeDispatchName", "(", "$", "id", ")", ";", "$", "classConfig", "=", "$", "this", "->", "normalizeDispatchNamespace", "(", "$", "dispatchId", ")", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}", "else", "{", "$", "dispatchId", "=", "$", "this", "->", "id", ".", "'/'", ".", "$", "this", "->", "normalizeDispatchName", "(", "$", "id", ")", ";", "$", "classConfig", "=", "$", "this", "->", "normalizeDispatchNamespace", "(", "$", "dispatchId", ")", ";", "}", "return", "$", "this", "->", "_createDispatchByConfig", "(", "$", "id", ",", "$", "classConfig", ")", ";", "}" ]
根据调度器ID创建调度器 @param string $id 调度器ID @param bool $withConfig 是否使用调度器配置。默认使用,即根据`[[dispatches()]]`配置来创建调度器 @return null|Dispatch @throws InvalidConfigException
[ "根据调度器ID创建调度器" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L303-L351
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait._getDispatchByRoute
private function _getDispatchByRoute($route) { $pos = strpos($route, '/'); if ($pos === false) { $parts = [$this, $route]; } elseif ($pos > 0) { $parts = $this->module->createController($route); } else { $parts = Yii::$app->createController($route); } if (is_array($parts)) { /* @var $controller self */ list($controller, $actionID) = $parts; $oldController = Yii::$app->controller; Yii::$app->controller = $controller; } else { throw new InvalidRouteException('Unable to resolve the dispatch request: ' . $route); } $dispatch = $controller->_createDispatch($actionID, false); if ($oldController !== null) { Yii::$app->controller = $oldController; } return $dispatch; }
php
private function _getDispatchByRoute($route) { $pos = strpos($route, '/'); if ($pos === false) { $parts = [$this, $route]; } elseif ($pos > 0) { $parts = $this->module->createController($route); } else { $parts = Yii::$app->createController($route); } if (is_array($parts)) { /* @var $controller self */ list($controller, $actionID) = $parts; $oldController = Yii::$app->controller; Yii::$app->controller = $controller; } else { throw new InvalidRouteException('Unable to resolve the dispatch request: ' . $route); } $dispatch = $controller->_createDispatch($actionID, false); if ($oldController !== null) { Yii::$app->controller = $oldController; } return $dispatch; }
[ "private", "function", "_getDispatchByRoute", "(", "$", "route", ")", "{", "$", "pos", "=", "strpos", "(", "$", "route", ",", "'/'", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "{", "$", "parts", "=", "[", "$", "this", ",", "$", "route", "]", ";", "}", "elseif", "(", "$", "pos", ">", "0", ")", "{", "$", "parts", "=", "$", "this", "->", "module", "->", "createController", "(", "$", "route", ")", ";", "}", "else", "{", "$", "parts", "=", "Yii", "::", "$", "app", "->", "createController", "(", "$", "route", ")", ";", "}", "if", "(", "is_array", "(", "$", "parts", ")", ")", "{", "/* @var $controller self */", "list", "(", "$", "controller", ",", "$", "actionID", ")", "=", "$", "parts", ";", "$", "oldController", "=", "Yii", "::", "$", "app", "->", "controller", ";", "Yii", "::", "$", "app", "->", "controller", "=", "$", "controller", ";", "}", "else", "{", "throw", "new", "InvalidRouteException", "(", "'Unable to resolve the dispatch request: '", ".", "$", "route", ")", ";", "}", "$", "dispatch", "=", "$", "controller", "->", "_createDispatch", "(", "$", "actionID", ",", "false", ")", ";", "if", "(", "$", "oldController", "!==", "null", ")", "{", "Yii", "::", "$", "app", "->", "controller", "=", "$", "oldController", ";", "}", "return", "$", "dispatch", ";", "}" ]
根据路由地址获取调度器 @param string $route 调度路由,支持以下格式:'view', 'comment/view', '/admin/comment/view' @return null|Dispatch @throws InvalidRouteException
[ "根据路由地址获取调度器" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L361-L387
Wonail/wocenter
traits/DispatchTrait.php
DispatchTrait._generateDispatchFile
private function _generateDispatchFile($className) { $file = '@' . str_replace('\\', '/', ltrim($className, '\\')) . '.php'; $file = str_replace('\\', DIRECTORY_SEPARATOR, Yii::getAlias($file)); throw new Exception("请在该路径下创建调度器文件:\r\n{$file}"); }
php
private function _generateDispatchFile($className) { $file = '@' . str_replace('\\', '/', ltrim($className, '\\')) . '.php'; $file = str_replace('\\', DIRECTORY_SEPARATOR, Yii::getAlias($file)); throw new Exception("请在该路径下创建调度器文件:\r\n{$file}"); }
[ "private", "function", "_generateDispatchFile", "(", "$", "className", ")", "{", "$", "file", "=", "'@'", ".", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "ltrim", "(", "$", "className", ",", "'\\\\'", ")", ")", ".", "'.php'", ";", "$", "file", "=", "str_replace", "(", "'\\\\'", ",", "DIRECTORY_SEPARATOR", ",", "Yii", "::", "getAlias", "(", "$", "file", ")", ")", ";", "throw", "new", "Exception", "(", "\"请在该路径下创建调度器文件:\\r\\n{$file}\");", "", "", "}" ]
调度器不存在则抛出友好提示信息 @param string $className 调度器类名 @throws Exception
[ "调度器不存在则抛出友好提示信息" ]
train
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/traits/DispatchTrait.php#L396-L401
phramework/jsonapi
src/Controller/GET.php
GET.handleGET
protected static function handleGET( $parameters, $modelClass, $primaryDataParameters = [], $relationshipParameters = [] ) { $page = $modelClass::parsePage($parameters); $filter = $modelClass::parseFilter($parameters); $sort = $modelClass::parseSort($parameters); $fields = $modelClass::parseFields($parameters); $requestInclude = static::getRequestInclude($parameters, $modelClass); $data = $modelClass::get( $page, $filter, $sort, $fields, ...$primaryDataParameters ); //Get included data $includedData = $modelClass::getIncludedData( $data, $requestInclude, $fields, $relationshipParameters ); $meta = (object) [ 'page' => ( $page === null ? $modelClass::getDefaultPage() : $page ) ]; return static::viewData( $data, (object) [ 'self' => $modelClass::getSelfLink() ], $meta, (empty($requestInclude) ? null : $includedData) ); }
php
protected static function handleGET( $parameters, $modelClass, $primaryDataParameters = [], $relationshipParameters = [] ) { $page = $modelClass::parsePage($parameters); $filter = $modelClass::parseFilter($parameters); $sort = $modelClass::parseSort($parameters); $fields = $modelClass::parseFields($parameters); $requestInclude = static::getRequestInclude($parameters, $modelClass); $data = $modelClass::get( $page, $filter, $sort, $fields, ...$primaryDataParameters ); //Get included data $includedData = $modelClass::getIncludedData( $data, $requestInclude, $fields, $relationshipParameters ); $meta = (object) [ 'page' => ( $page === null ? $modelClass::getDefaultPage() : $page ) ]; return static::viewData( $data, (object) [ 'self' => $modelClass::getSelfLink() ], $meta, (empty($requestInclude) ? null : $includedData) ); }
[ "protected", "static", "function", "handleGET", "(", "$", "parameters", ",", "$", "modelClass", ",", "$", "primaryDataParameters", "=", "[", "]", ",", "$", "relationshipParameters", "=", "[", "]", ")", "{", "$", "page", "=", "$", "modelClass", "::", "parsePage", "(", "$", "parameters", ")", ";", "$", "filter", "=", "$", "modelClass", "::", "parseFilter", "(", "$", "parameters", ")", ";", "$", "sort", "=", "$", "modelClass", "::", "parseSort", "(", "$", "parameters", ")", ";", "$", "fields", "=", "$", "modelClass", "::", "parseFields", "(", "$", "parameters", ")", ";", "$", "requestInclude", "=", "static", "::", "getRequestInclude", "(", "$", "parameters", ",", "$", "modelClass", ")", ";", "$", "data", "=", "$", "modelClass", "::", "get", "(", "$", "page", ",", "$", "filter", ",", "$", "sort", ",", "$", "fields", ",", "...", "$", "primaryDataParameters", ")", ";", "//Get included data", "$", "includedData", "=", "$", "modelClass", "::", "getIncludedData", "(", "$", "data", ",", "$", "requestInclude", ",", "$", "fields", ",", "$", "relationshipParameters", ")", ";", "$", "meta", "=", "(", "object", ")", "[", "'page'", "=>", "(", "$", "page", "===", "null", "?", "$", "modelClass", "::", "getDefaultPage", "(", ")", ":", "$", "page", ")", "]", ";", "return", "static", "::", "viewData", "(", "$", "data", ",", "(", "object", ")", "[", "'self'", "=>", "$", "modelClass", "::", "getSelfLink", "(", ")", "]", ",", "$", "meta", ",", "(", "empty", "(", "$", "requestInclude", ")", "?", "null", ":", "$", "includedData", ")", ")", ";", "}" ]
handles GET requests @param object $parameters Request parameters @param string $modelClass Resource's primary model class name to be used @param array $primaryDataParameters *[Optional]* Array with any additional arguments that the primary data is requiring @param array $relationshipParameters [Optional] Array with any additional argument primary data's relationships are requiring @param boolean $filterable *[Optional]* Default is true, if true allows `filter` URI parameters to be parsed for filtering @param boolean $filterableJSON *[Optional]* Default is false, if true allows `filter` URI parameters to be parsed for filtering for JSON encoded fields @param boolean $sortable *[Optional]* Default is true, if true allows sorting @uses $modelClass::get method to fetch resource collection @throws \Exception @throws RequestException @return boolean @todo Force parsing of relationship data when included
[ "handles", "GET", "requests" ]
train
https://github.com/phramework/jsonapi/blob/af20882a8b6f6e5be9c8e09e5b87f6c23a4b0726/src/Controller/GET.php#L59-L104
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.read
public function read(string $path): string { $location = $this->applyBasePath($path); $content = file_get_contents($location); unset($location); return $content; }
php
public function read(string $path): string { $location = $this->applyBasePath($path); $content = file_get_contents($location); unset($location); return $content; }
[ "public", "function", "read", "(", "string", "$", "path", ")", ":", "string", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "content", "=", "file_get_contents", "(", "$", "location", ")", ";", "unset", "(", "$", "location", ")", ";", "return", "$", "content", ";", "}" ]
读取文件内容 @param string $path @return string
[ "读取文件内容" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L96-L104
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.readStream
public function readStream(string $path) { $location = $this->applyBasePath($path); $stream = @fopen($location, 'rb'); unset($location); return $stream; }
php
public function readStream(string $path) { $location = $this->applyBasePath($path); $stream = @fopen($location, 'rb'); unset($location); return $stream; }
[ "public", "function", "readStream", "(", "string", "$", "path", ")", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "stream", "=", "@", "fopen", "(", "$", "location", ",", "'rb'", ")", ";", "unset", "(", "$", "location", ")", ";", "return", "$", "stream", ";", "}" ]
从文件中读取数据流 @param string $path @return resource
[ "从文件中读取数据流" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L113-L121
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.listContents
public function listContents(string $directory = '', bool $recursive = false): array { $list = []; $location = $this->applyBasePath($directory); if (! is_dir($location)) { return $list; } $iterator = $recursive ? $this->getRecursiveDirectoryIterator($location) : $this->getDirectoryIterator($location); foreach ($iterator as $file) { $path = $this->getFilePath($file); if (preg_match('#(^|/|\\\\)\.{1,2}$#', $path)) { continue; } $list[] = $this->normalizeFileInfo($file); unset($path); } unset($location, $iterator); return array_filter($list); }
php
public function listContents(string $directory = '', bool $recursive = false): array { $list = []; $location = $this->applyBasePath($directory); if (! is_dir($location)) { return $list; } $iterator = $recursive ? $this->getRecursiveDirectoryIterator($location) : $this->getDirectoryIterator($location); foreach ($iterator as $file) { $path = $this->getFilePath($file); if (preg_match('#(^|/|\\\\)\.{1,2}$#', $path)) { continue; } $list[] = $this->normalizeFileInfo($file); unset($path); } unset($location, $iterator); return array_filter($list); }
[ "public", "function", "listContents", "(", "string", "$", "directory", "=", "''", ",", "bool", "$", "recursive", "=", "false", ")", ":", "array", "{", "$", "list", "=", "[", "]", ";", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "directory", ")", ";", "if", "(", "!", "is_dir", "(", "$", "location", ")", ")", "{", "return", "$", "list", ";", "}", "$", "iterator", "=", "$", "recursive", "?", "$", "this", "->", "getRecursiveDirectoryIterator", "(", "$", "location", ")", ":", "$", "this", "->", "getDirectoryIterator", "(", "$", "location", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "$", "path", "=", "$", "this", "->", "getFilePath", "(", "$", "file", ")", ";", "if", "(", "preg_match", "(", "'#(^|/|\\\\\\\\)\\.{1,2}$#'", ",", "$", "path", ")", ")", "{", "continue", ";", "}", "$", "list", "[", "]", "=", "$", "this", "->", "normalizeFileInfo", "(", "$", "file", ")", ";", "unset", "(", "$", "path", ")", ";", "}", "unset", "(", "$", "location", ",", "$", "iterator", ")", ";", "return", "array_filter", "(", "$", "list", ")", ";", "}" ]
返回目录中的内容 @param string $directory @param bool $recursive @return array
[ "返回目录中的内容" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L131-L159
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.update
public function update(string $path, string $contents, array $config = []): bool { $location = $this->applyBasePath($path); $this->ensureDirectory(dirname($location)); if (file_put_contents($location, $contents, $this->writeFlags) === false) { return false; } if (($visibility = Arr::get($config, 'visibility')) !== null) { $this->setVisibility($path, $visibility); } unset($location, $visibility); return true; }
php
public function update(string $path, string $contents, array $config = []): bool { $location = $this->applyBasePath($path); $this->ensureDirectory(dirname($location)); if (file_put_contents($location, $contents, $this->writeFlags) === false) { return false; } if (($visibility = Arr::get($config, 'visibility')) !== null) { $this->setVisibility($path, $visibility); } unset($location, $visibility); return true; }
[ "public", "function", "update", "(", "string", "$", "path", ",", "string", "$", "contents", ",", "array", "$", "config", "=", "[", "]", ")", ":", "bool", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "this", "->", "ensureDirectory", "(", "dirname", "(", "$", "location", ")", ")", ";", "if", "(", "file_put_contents", "(", "$", "location", ",", "$", "contents", ",", "$", "this", "->", "writeFlags", ")", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "(", "$", "visibility", "=", "Arr", "::", "get", "(", "$", "config", ",", "'visibility'", ")", ")", "!==", "null", ")", "{", "$", "this", "->", "setVisibility", "(", "$", "path", ",", "$", "visibility", ")", ";", "}", "unset", "(", "$", "location", ",", "$", "visibility", ")", ";", "return", "true", ";", "}" ]
更新文件内容 @param string $path @param string $contents @param array $config @return bool @throws \One\FileSystem\Exceptions\FileSystemException
[ "更新文件内容" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L234-L250
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.updateStream
public function updateStream(string $path, $resource, array $config = []): bool { $location = $this->applyBasePath($path); $this->ensureDirectory(dirname($location)); $stream = @fopen($location, 'w+b'); if (! $stream) { return false; } stream_copy_to_stream($resource, $stream); if (! fclose($stream)) { return false; } if (($visibility = Arr::get($config, 'visibility')) !== null) { $this->setVisibility($path, $visibility); } unset($location, $stream, $visibility); return true; }
php
public function updateStream(string $path, $resource, array $config = []): bool { $location = $this->applyBasePath($path); $this->ensureDirectory(dirname($location)); $stream = @fopen($location, 'w+b'); if (! $stream) { return false; } stream_copy_to_stream($resource, $stream); if (! fclose($stream)) { return false; } if (($visibility = Arr::get($config, 'visibility')) !== null) { $this->setVisibility($path, $visibility); } unset($location, $stream, $visibility); return true; }
[ "public", "function", "updateStream", "(", "string", "$", "path", ",", "$", "resource", ",", "array", "$", "config", "=", "[", "]", ")", ":", "bool", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "this", "->", "ensureDirectory", "(", "dirname", "(", "$", "location", ")", ")", ";", "$", "stream", "=", "@", "fopen", "(", "$", "location", ",", "'w+b'", ")", ";", "if", "(", "!", "$", "stream", ")", "{", "return", "false", ";", "}", "stream_copy_to_stream", "(", "$", "resource", ",", "$", "stream", ")", ";", "if", "(", "!", "fclose", "(", "$", "stream", ")", ")", "{", "return", "false", ";", "}", "if", "(", "(", "$", "visibility", "=", "Arr", "::", "get", "(", "$", "config", ",", "'visibility'", ")", ")", "!==", "null", ")", "{", "$", "this", "->", "setVisibility", "(", "$", "path", ",", "$", "visibility", ")", ";", "}", "unset", "(", "$", "location", ",", "$", "stream", ",", "$", "visibility", ")", ";", "return", "true", ";", "}" ]
以数据流的方式更新文件内容 @param string $path @param resource $resource @param array $config @return bool @throws \One\FileSystem\Exceptions\FileSystemException
[ "以数据流的方式更新文件内容" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L262-L285
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.getMetaData
public function getMetaData(string $path): array { $location = $this->applyBasePath($path); $info = new SplFileInfo($location); $metadata = $this->normalizeFileInfo($info); unset($location, $info); return $metadata === null ? [] : $metadata; }
php
public function getMetaData(string $path): array { $location = $this->applyBasePath($path); $info = new SplFileInfo($location); $metadata = $this->normalizeFileInfo($info); unset($location, $info); return $metadata === null ? [] : $metadata; }
[ "public", "function", "getMetaData", "(", "string", "$", "path", ")", ":", "array", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "info", "=", "new", "SplFileInfo", "(", "$", "location", ")", ";", "$", "metadata", "=", "$", "this", "->", "normalizeFileInfo", "(", "$", "info", ")", ";", "unset", "(", "$", "location", ",", "$", "info", ")", ";", "return", "$", "metadata", "===", "null", "?", "[", "]", ":", "$", "metadata", ";", "}" ]
获得文件的源数据 @param string $path @return array
[ "获得文件的源数据" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L294-L303
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.getMimeType
public function getMimeType(string $path): string { $location = $this->applyBasePath($path); $finfo = new Finfo(FILEINFO_MIME_TYPE); $mimetype = $finfo->file($location); if (in_array($mimetype, ['application/octet-stream', 'inode/x-empty'])) { $mimetype = MimeType::detectByFilePath($location); } return $mimetype; }
php
public function getMimeType(string $path): string { $location = $this->applyBasePath($path); $finfo = new Finfo(FILEINFO_MIME_TYPE); $mimetype = $finfo->file($location); if (in_array($mimetype, ['application/octet-stream', 'inode/x-empty'])) { $mimetype = MimeType::detectByFilePath($location); } return $mimetype; }
[ "public", "function", "getMimeType", "(", "string", "$", "path", ")", ":", "string", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "finfo", "=", "new", "Finfo", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "mimetype", "=", "$", "finfo", "->", "file", "(", "$", "location", ")", ";", "if", "(", "in_array", "(", "$", "mimetype", ",", "[", "'application/octet-stream'", ",", "'inode/x-empty'", "]", ")", ")", "{", "$", "mimetype", "=", "MimeType", "::", "detectByFilePath", "(", "$", "location", ")", ";", "}", "return", "$", "mimetype", ";", "}" ]
获得文件的类型 @param string $path @return string
[ "获得文件的类型" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L312-L323
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.getVisibility
public function getVisibility(string $path): string { $location = $this->applyBasePath($path); clearstatcache(false, $location); $permission = octdec(substr(sprintf('%o', fileperms($location)), -4)); return $permission & 0044 ? self::VIS_PUB : self::VIS_PRI; }
php
public function getVisibility(string $path): string { $location = $this->applyBasePath($path); clearstatcache(false, $location); $permission = octdec(substr(sprintf('%o', fileperms($location)), -4)); return $permission & 0044 ? self::VIS_PUB : self::VIS_PRI; }
[ "public", "function", "getVisibility", "(", "string", "$", "path", ")", ":", "string", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "clearstatcache", "(", "false", ",", "$", "location", ")", ";", "$", "permission", "=", "octdec", "(", "substr", "(", "sprintf", "(", "'%o'", ",", "fileperms", "(", "$", "location", ")", ")", ",", "-", "4", ")", ")", ";", "return", "$", "permission", "&", "0044", "?", "self", "::", "VIS_PUB", ":", "self", "::", "VIS_PRI", ";", "}" ]
返回文件可见性 @param string $path @return string
[ "返回文件可见性" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L332-L339
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.setVisibility
public function setVisibility(string $path, string $visibility): bool { $location = $this->applyBasePath($path); $type = is_dir($location) ? 'dir' : 'file'; return chmod($location, $this->permissions[$type][$visibility]); }
php
public function setVisibility(string $path, string $visibility): bool { $location = $this->applyBasePath($path); $type = is_dir($location) ? 'dir' : 'file'; return chmod($location, $this->permissions[$type][$visibility]); }
[ "public", "function", "setVisibility", "(", "string", "$", "path", ",", "string", "$", "visibility", ")", ":", "bool", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "type", "=", "is_dir", "(", "$", "location", ")", "?", "'dir'", ":", "'file'", ";", "return", "chmod", "(", "$", "location", ",", "$", "this", "->", "permissions", "[", "$", "type", "]", "[", "$", "visibility", "]", ")", ";", "}" ]
设置文件可见性 @param string $path @param string $visibility @return bool
[ "设置文件可见性" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L349-L355
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.rename
public function rename(string $path, string $newpath): bool { $location = $this->applyBasePath($path); $destination = $this->applyBasePath($newpath); $this->ensureDirectory(dirname($destination)); return rename($location, $destination); }
php
public function rename(string $path, string $newpath): bool { $location = $this->applyBasePath($path); $destination = $this->applyBasePath($newpath); $this->ensureDirectory(dirname($destination)); return rename($location, $destination); }
[ "public", "function", "rename", "(", "string", "$", "path", ",", "string", "$", "newpath", ")", ":", "bool", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "path", ")", ";", "$", "destination", "=", "$", "this", "->", "applyBasePath", "(", "$", "newpath", ")", ";", "$", "this", "->", "ensureDirectory", "(", "dirname", "(", "$", "destination", ")", ")", ";", "return", "rename", "(", "$", "location", ",", "$", "destination", ")", ";", "}" ]
重命名文件 @param string $path @param string $newpath @return bool @throws \One\FileSystem\Exceptions\FileSystemException
[ "重命名文件" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L366-L374
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.createDir
public function createDir(string $dirname, array $config = []): bool { $location = $this->applyBasePath($dirname); if (is_dir($location)) { throw new DirectoryExistsException($dirname); } $umask = umask(0); $visibility = Arr::get($config, 'visibility', 'public'); if (mkdir($location, $this->permissions['dir'][$visibility], true)) { umask($umask); return true; } return false; }
php
public function createDir(string $dirname, array $config = []): bool { $location = $this->applyBasePath($dirname); if (is_dir($location)) { throw new DirectoryExistsException($dirname); } $umask = umask(0); $visibility = Arr::get($config, 'visibility', 'public'); if (mkdir($location, $this->permissions['dir'][$visibility], true)) { umask($umask); return true; } return false; }
[ "public", "function", "createDir", "(", "string", "$", "dirname", ",", "array", "$", "config", "=", "[", "]", ")", ":", "bool", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "dirname", ")", ";", "if", "(", "is_dir", "(", "$", "location", ")", ")", "{", "throw", "new", "DirectoryExistsException", "(", "$", "dirname", ")", ";", "}", "$", "umask", "=", "umask", "(", "0", ")", ";", "$", "visibility", "=", "Arr", "::", "get", "(", "$", "config", ",", "'visibility'", ",", "'public'", ")", ";", "if", "(", "mkdir", "(", "$", "location", ",", "$", "this", "->", "permissions", "[", "'dir'", "]", "[", "$", "visibility", "]", ",", "true", ")", ")", "{", "umask", "(", "$", "umask", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
创建目录 @param string $dirname @param array $config @return bool @throws \One\FileSystem\Exceptions\DirectoryExistsException
[ "创建目录" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L397-L415
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.deleteDir
public function deleteDir(string $dirname): bool { $location = $this->applyBasePath($dirname); if (! is_dir($location)) { throw new DirectoryNotExistsException($dirname); } $contents = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($location, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($contents as $file) { if ($file->isReadable()) { switch ($file->getType()) { case 'dir': rmdir($file->getRealPath()); break; case 'link': unlink($file->getPathname()); break; default: unlink($file->getRealPath()); break; } } } unset($contents); return rmdir($location); }
php
public function deleteDir(string $dirname): bool { $location = $this->applyBasePath($dirname); if (! is_dir($location)) { throw new DirectoryNotExistsException($dirname); } $contents = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($location, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($contents as $file) { if ($file->isReadable()) { switch ($file->getType()) { case 'dir': rmdir($file->getRealPath()); break; case 'link': unlink($file->getPathname()); break; default: unlink($file->getRealPath()); break; } } } unset($contents); return rmdir($location); }
[ "public", "function", "deleteDir", "(", "string", "$", "dirname", ")", ":", "bool", "{", "$", "location", "=", "$", "this", "->", "applyBasePath", "(", "$", "dirname", ")", ";", "if", "(", "!", "is_dir", "(", "$", "location", ")", ")", "{", "throw", "new", "DirectoryNotExistsException", "(", "$", "dirname", ")", ";", "}", "$", "contents", "=", "new", "RecursiveIteratorIterator", "(", "new", "RecursiveDirectoryIterator", "(", "$", "location", ",", "FilesystemIterator", "::", "SKIP_DOTS", ")", ",", "RecursiveIteratorIterator", "::", "CHILD_FIRST", ")", ";", "foreach", "(", "$", "contents", "as", "$", "file", ")", "{", "if", "(", "$", "file", "->", "isReadable", "(", ")", ")", "{", "switch", "(", "$", "file", "->", "getType", "(", ")", ")", "{", "case", "'dir'", ":", "rmdir", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "break", ";", "case", "'link'", ":", "unlink", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "break", ";", "default", ":", "unlink", "(", "$", "file", "->", "getRealPath", "(", ")", ")", ";", "break", ";", "}", "}", "}", "unset", "(", "$", "contents", ")", ";", "return", "rmdir", "(", "$", "location", ")", ";", "}" ]
删除目录 @param string $dirname @return bool @throws \One\FileSystem\Exceptions\DirectoryNotExistsException
[ "删除目录" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L425-L457
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.ensureDirectory
protected function ensureDirectory(string $path) { if (! is_dir($path)) { $umask = umask(0); @mkdir($path, $this->permissions['dir']['public'], true); umask($umask); if (! is_dir($path)) { throw new FileSystemException($path, 'Unable to create "%s" directory'); } } if (! is_readable($path)) { throw new FileSystemException($path, 'Unable to access "%s" directory'); } }
php
protected function ensureDirectory(string $path) { if (! is_dir($path)) { $umask = umask(0); @mkdir($path, $this->permissions['dir']['public'], true); umask($umask); if (! is_dir($path)) { throw new FileSystemException($path, 'Unable to create "%s" directory'); } } if (! is_readable($path)) { throw new FileSystemException($path, 'Unable to access "%s" directory'); } }
[ "protected", "function", "ensureDirectory", "(", "string", "$", "path", ")", "{", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "$", "umask", "=", "umask", "(", "0", ")", ";", "@", "mkdir", "(", "$", "path", ",", "$", "this", "->", "permissions", "[", "'dir'", "]", "[", "'public'", "]", ",", "true", ")", ";", "umask", "(", "$", "umask", ")", ";", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "throw", "new", "FileSystemException", "(", "$", "path", ",", "'Unable to create \"%s\" directory'", ")", ";", "}", "}", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "FileSystemException", "(", "$", "path", ",", "'Unable to access \"%s\" directory'", ")", ";", "}", "}" ]
确认目录存在 @param string $path @throws \One\FileSystem\Exceptions\FileSystemException
[ "确认目录存在" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L466-L481
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.normalizeFileInfo
protected function normalizeFileInfo(SplFileInfo $file) { if (! $file->isLink()) { $normalized = [ 'type' => $file->getType(), 'path' => $this->getFilePath($file), 'timestamp' => $file->getMTime() ]; if ($normalized['type'] === 'file') { $normalized['size'] = $file->getSize(); } return $normalized; } }
php
protected function normalizeFileInfo(SplFileInfo $file) { if (! $file->isLink()) { $normalized = [ 'type' => $file->getType(), 'path' => $this->getFilePath($file), 'timestamp' => $file->getMTime() ]; if ($normalized['type'] === 'file') { $normalized['size'] = $file->getSize(); } return $normalized; } }
[ "protected", "function", "normalizeFileInfo", "(", "SplFileInfo", "$", "file", ")", "{", "if", "(", "!", "$", "file", "->", "isLink", "(", ")", ")", "{", "$", "normalized", "=", "[", "'type'", "=>", "$", "file", "->", "getType", "(", ")", ",", "'path'", "=>", "$", "this", "->", "getFilePath", "(", "$", "file", ")", ",", "'timestamp'", "=>", "$", "file", "->", "getMTime", "(", ")", "]", ";", "if", "(", "$", "normalized", "[", "'type'", "]", "===", "'file'", ")", "{", "$", "normalized", "[", "'size'", "]", "=", "$", "file", "->", "getSize", "(", ")", ";", "}", "return", "$", "normalized", ";", "}", "}" ]
标准化文件信息 @param \SplFileInfo $file @return array|null
[ "标准化文件信息" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L490-L505
movoin/one-swoole
src/FileSystem/Adapters/Local.php
Local.getFilePath
protected function getFilePath(SplFileInfo $file): string { $location = $file->getPathName(); $path = $this->removeBasePath($location); unset($location); return trim(str_replace('\\', '/', $path), '/'); }
php
protected function getFilePath(SplFileInfo $file): string { $location = $file->getPathName(); $path = $this->removeBasePath($location); unset($location); return trim(str_replace('\\', '/', $path), '/'); }
[ "protected", "function", "getFilePath", "(", "SplFileInfo", "$", "file", ")", ":", "string", "{", "$", "location", "=", "$", "file", "->", "getPathName", "(", ")", ";", "$", "path", "=", "$", "this", "->", "removeBasePath", "(", "$", "location", ")", ";", "unset", "(", "$", "location", ")", ";", "return", "trim", "(", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "path", ")", ",", "'/'", ")", ";", "}" ]
从 SplFileInfo 中返回完整文件路径 @param \SplFileInfo $file @return string
[ "从", "SplFileInfo", "中返回完整文件路径" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/FileSystem/Adapters/Local.php#L514-L522
movoin/one-swoole
src/Swoole/Components/Timer/Provider.php
Provider.register
public function register() { $this->bind('timer', function ($server) { $scheduler = new Scheduler; $scheduler->setSwoole($server->getSwoole()); return $scheduler; }); }
php
public function register() { $this->bind('timer', function ($server) { $scheduler = new Scheduler; $scheduler->setSwoole($server->getSwoole()); return $scheduler; }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "bind", "(", "'timer'", ",", "function", "(", "$", "server", ")", "{", "$", "scheduler", "=", "new", "Scheduler", ";", "$", "scheduler", "->", "setSwoole", "(", "$", "server", "->", "getSwoole", "(", ")", ")", ";", "return", "$", "scheduler", ";", "}", ")", ";", "}" ]
注册服务
[ "注册服务" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Components/Timer/Provider.php#L22-L30
jan-dolata/crude-crud
src/Engine/CrudeSetupTrait/ColumnFormat.php
ColumnFormat.setColumnFormat
public function setColumnFormat($attr, $format = null) { $formats = is_array($attr) ? $attr : [$attr => $format]; foreach ($formats as $a => $f) $this->_setSingleColumnFormat($a, $f); return $this; }
php
public function setColumnFormat($attr, $format = null) { $formats = is_array($attr) ? $attr : [$attr => $format]; foreach ($formats as $a => $f) $this->_setSingleColumnFormat($a, $f); return $this; }
[ "public", "function", "setColumnFormat", "(", "$", "attr", ",", "$", "format", "=", "null", ")", "{", "$", "formats", "=", "is_array", "(", "$", "attr", ")", "?", "$", "attr", ":", "[", "$", "attr", "=>", "$", "format", "]", ";", "foreach", "(", "$", "formats", "as", "$", "a", "=>", "$", "f", ")", "$", "this", "->", "_setSingleColumnFormat", "(", "$", "a", ",", "$", "f", ")", ";", "return", "$", "this", ";", "}" ]
Sets the Column cell format rules. @param array $columnFormat the column format @return self
[ "Sets", "the", "Column", "cell", "format", "rules", "." ]
train
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Engine/CrudeSetupTrait/ColumnFormat.php#L31-L41
comelyio/comely
src/Comely/IO/Mailer/Agents/SMTP.php
SMTP.authCredentials
public function authCredentials(string $username, string $password): self { $this->username = $username; $this->password = $password; return $this; }
php
public function authCredentials(string $username, string $password): self { $this->username = $username; $this->password = $password; return $this; }
[ "public", "function", "authCredentials", "(", "string", "$", "username", ",", "string", "$", "password", ")", ":", "self", "{", "$", "this", "->", "username", "=", "$", "username", ";", "$", "this", "->", "password", "=", "$", "password", ";", "return", "$", "this", ";", "}" ]
Set auth. credentials for AUTH LOGIN @param string $username @param string $password @return SMTP
[ "Set", "auth", ".", "credentials", "for", "AUTH", "LOGIN" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Mailer/Agents/SMTP.php#L112-L117
comelyio/comely
src/Comely/IO/Mailer/Agents/SMTP.php
SMTP.connect
private function connect() { if (!$this->stream) { $errorNum = 0; $errorMsg = ""; $context = @stream_context_create($this->streamOptions); $this->stream = @stream_socket_client( sprintf('%1$s:%2$d', $this->host, $this->port), $errorNum, $errorMsg, $this->timeOut, STREAM_CLIENT_CONNECT, $context ); if (!$this->stream) { throw SMTPException::connectionError($errorNum, $errorMsg); } $this->read(); // Read response from server if ($this->lastResponseCode() !== 220) { throw SMTPException::unexpectedResponse("CONNECT", 220, $this->lastResponseCode()); } // Build specs/options available at remote SMTP server $this->smtpServerOptions( $this->command("EHLO", $this->serverName) ); // Use TLS? if ($this->secure === true) { if ($this->options["startTLS"] !== true) { throw SMTPException::tlsNotAvailable(); } $this->command("STARTTLS", null, 220); $tls = @stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if (!$tls) { throw SMTPException::tlsNegotiateFailed(); } $this->command("EHLO", $this->serverName); // Resend EHLO command } // Authenticate if ($this->options["authLogin"] === true) { try { $this->command("AUTH LOGIN", null, 334); $this->command(base64_encode($this->username ?? " "), null, 334); $this->command(base64_encode($this->password ?? " "), null, 235); } catch (SMTPException $e) { throw SMTPException::authFailed($this->lastResponse); } } elseif ($this->options["authPlain"] === true) { // Todo: plain authentication throw SMTPException::authUnavailable(); } else { throw SMTPException::authUnavailable(); } } else { try { if (!stream_get_meta_data($this->stream)["timed_out"]) { throw new SMTPException(__METHOD__, "Timed out"); } $this->command("NOOP", null, 250); } catch (SMTPException $e) { $this->stream = null; $this->connect(); return; } } }
php
private function connect() { if (!$this->stream) { $errorNum = 0; $errorMsg = ""; $context = @stream_context_create($this->streamOptions); $this->stream = @stream_socket_client( sprintf('%1$s:%2$d', $this->host, $this->port), $errorNum, $errorMsg, $this->timeOut, STREAM_CLIENT_CONNECT, $context ); if (!$this->stream) { throw SMTPException::connectionError($errorNum, $errorMsg); } $this->read(); // Read response from server if ($this->lastResponseCode() !== 220) { throw SMTPException::unexpectedResponse("CONNECT", 220, $this->lastResponseCode()); } // Build specs/options available at remote SMTP server $this->smtpServerOptions( $this->command("EHLO", $this->serverName) ); // Use TLS? if ($this->secure === true) { if ($this->options["startTLS"] !== true) { throw SMTPException::tlsNotAvailable(); } $this->command("STARTTLS", null, 220); $tls = @stream_socket_enable_crypto($this->stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); if (!$tls) { throw SMTPException::tlsNegotiateFailed(); } $this->command("EHLO", $this->serverName); // Resend EHLO command } // Authenticate if ($this->options["authLogin"] === true) { try { $this->command("AUTH LOGIN", null, 334); $this->command(base64_encode($this->username ?? " "), null, 334); $this->command(base64_encode($this->password ?? " "), null, 235); } catch (SMTPException $e) { throw SMTPException::authFailed($this->lastResponse); } } elseif ($this->options["authPlain"] === true) { // Todo: plain authentication throw SMTPException::authUnavailable(); } else { throw SMTPException::authUnavailable(); } } else { try { if (!stream_get_meta_data($this->stream)["timed_out"]) { throw new SMTPException(__METHOD__, "Timed out"); } $this->command("NOOP", null, 250); } catch (SMTPException $e) { $this->stream = null; $this->connect(); return; } } }
[ "private", "function", "connect", "(", ")", "{", "if", "(", "!", "$", "this", "->", "stream", ")", "{", "$", "errorNum", "=", "0", ";", "$", "errorMsg", "=", "\"\"", ";", "$", "context", "=", "@", "stream_context_create", "(", "$", "this", "->", "streamOptions", ")", ";", "$", "this", "->", "stream", "=", "@", "stream_socket_client", "(", "sprintf", "(", "'%1$s:%2$d'", ",", "$", "this", "->", "host", ",", "$", "this", "->", "port", ")", ",", "$", "errorNum", ",", "$", "errorMsg", ",", "$", "this", "->", "timeOut", ",", "STREAM_CLIENT_CONNECT", ",", "$", "context", ")", ";", "if", "(", "!", "$", "this", "->", "stream", ")", "{", "throw", "SMTPException", "::", "connectionError", "(", "$", "errorNum", ",", "$", "errorMsg", ")", ";", "}", "$", "this", "->", "read", "(", ")", ";", "// Read response from server", "if", "(", "$", "this", "->", "lastResponseCode", "(", ")", "!==", "220", ")", "{", "throw", "SMTPException", "::", "unexpectedResponse", "(", "\"CONNECT\"", ",", "220", ",", "$", "this", "->", "lastResponseCode", "(", ")", ")", ";", "}", "// Build specs/options available at remote SMTP server", "$", "this", "->", "smtpServerOptions", "(", "$", "this", "->", "command", "(", "\"EHLO\"", ",", "$", "this", "->", "serverName", ")", ")", ";", "// Use TLS?", "if", "(", "$", "this", "->", "secure", "===", "true", ")", "{", "if", "(", "$", "this", "->", "options", "[", "\"startTLS\"", "]", "!==", "true", ")", "{", "throw", "SMTPException", "::", "tlsNotAvailable", "(", ")", ";", "}", "$", "this", "->", "command", "(", "\"STARTTLS\"", ",", "null", ",", "220", ")", ";", "$", "tls", "=", "@", "stream_socket_enable_crypto", "(", "$", "this", "->", "stream", ",", "true", ",", "STREAM_CRYPTO_METHOD_TLS_CLIENT", ")", ";", "if", "(", "!", "$", "tls", ")", "{", "throw", "SMTPException", "::", "tlsNegotiateFailed", "(", ")", ";", "}", "$", "this", "->", "command", "(", "\"EHLO\"", ",", "$", "this", "->", "serverName", ")", ";", "// Resend EHLO command", "}", "// Authenticate", "if", "(", "$", "this", "->", "options", "[", "\"authLogin\"", "]", "===", "true", ")", "{", "try", "{", "$", "this", "->", "command", "(", "\"AUTH LOGIN\"", ",", "null", ",", "334", ")", ";", "$", "this", "->", "command", "(", "base64_encode", "(", "$", "this", "->", "username", "??", "\" \"", ")", ",", "null", ",", "334", ")", ";", "$", "this", "->", "command", "(", "base64_encode", "(", "$", "this", "->", "password", "??", "\" \"", ")", ",", "null", ",", "235", ")", ";", "}", "catch", "(", "SMTPException", "$", "e", ")", "{", "throw", "SMTPException", "::", "authFailed", "(", "$", "this", "->", "lastResponse", ")", ";", "}", "}", "elseif", "(", "$", "this", "->", "options", "[", "\"authPlain\"", "]", "===", "true", ")", "{", "// Todo: plain authentication", "throw", "SMTPException", "::", "authUnavailable", "(", ")", ";", "}", "else", "{", "throw", "SMTPException", "::", "authUnavailable", "(", ")", ";", "}", "}", "else", "{", "try", "{", "if", "(", "!", "stream_get_meta_data", "(", "$", "this", "->", "stream", ")", "[", "\"timed_out\"", "]", ")", "{", "throw", "new", "SMTPException", "(", "__METHOD__", ",", "\"Timed out\"", ")", ";", "}", "$", "this", "->", "command", "(", "\"NOOP\"", ",", "null", ",", "250", ")", ";", "}", "catch", "(", "SMTPException", "$", "e", ")", "{", "$", "this", "->", "stream", "=", "null", ";", "$", "this", "->", "connect", "(", ")", ";", "return", ";", "}", "}", "}" ]
Establish connection to SMTP server or revive existing one
[ "Establish", "connection", "to", "SMTP", "server", "or", "revive", "existing", "one" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Mailer/Agents/SMTP.php#L157-L229
comelyio/comely
src/Comely/IO/Mailer/Agents/SMTP.php
SMTP.command
public function command(string $command, string $args = null, int $expect = 0): string { $sendCommand = $args ? sprintf('%1$s %2$s', $command, $args) : $command; $this->write($sendCommand); $response = $this->read(); $responseCode = $this->lastResponseCode(); if ($expect > 0) { if ($responseCode !== $expect) { throw SMTPException::unexpectedResponse($command, $expect, $responseCode); } } return $response; }
php
public function command(string $command, string $args = null, int $expect = 0): string { $sendCommand = $args ? sprintf('%1$s %2$s', $command, $args) : $command; $this->write($sendCommand); $response = $this->read(); $responseCode = $this->lastResponseCode(); if ($expect > 0) { if ($responseCode !== $expect) { throw SMTPException::unexpectedResponse($command, $expect, $responseCode); } } return $response; }
[ "public", "function", "command", "(", "string", "$", "command", ",", "string", "$", "args", "=", "null", ",", "int", "$", "expect", "=", "0", ")", ":", "string", "{", "$", "sendCommand", "=", "$", "args", "?", "sprintf", "(", "'%1$s %2$s'", ",", "$", "command", ",", "$", "args", ")", ":", "$", "command", ";", "$", "this", "->", "write", "(", "$", "sendCommand", ")", ";", "$", "response", "=", "$", "this", "->", "read", "(", ")", ";", "$", "responseCode", "=", "$", "this", "->", "lastResponseCode", "(", ")", ";", "if", "(", "$", "expect", ">", "0", ")", "{", "if", "(", "$", "responseCode", "!==", "$", "expect", ")", "{", "throw", "SMTPException", "::", "unexpectedResponse", "(", "$", "command", ",", "$", "expect", ",", "$", "responseCode", ")", ";", "}", "}", "return", "$", "response", ";", "}" ]
Send command to server, read response, and make sure response code matches expected code @param string $command @param string|null $args @param int $expect @return string @throws SMTPException
[ "Send", "command", "to", "server", "read", "response", "and", "make", "sure", "response", "code", "matches", "expected", "code" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Mailer/Agents/SMTP.php#L283-L297
comelyio/comely
src/Comely/IO/Mailer/Agents/SMTP.php
SMTP.read
private function read(): string { $this->lastResponse = fread($this->stream, 1024); // Read up to 1KB $this->lastResponseCode = intval(explode(" ", $this->lastResponse)[0]); $this->lastResponseCode = $this->lastResponseCode > 0 ? $this->lastResponseCode : -1; return $this->lastResponse; }
php
private function read(): string { $this->lastResponse = fread($this->stream, 1024); // Read up to 1KB $this->lastResponseCode = intval(explode(" ", $this->lastResponse)[0]); $this->lastResponseCode = $this->lastResponseCode > 0 ? $this->lastResponseCode : -1; return $this->lastResponse; }
[ "private", "function", "read", "(", ")", ":", "string", "{", "$", "this", "->", "lastResponse", "=", "fread", "(", "$", "this", "->", "stream", ",", "1024", ")", ";", "// Read up to 1KB", "$", "this", "->", "lastResponseCode", "=", "intval", "(", "explode", "(", "\" \"", ",", "$", "this", "->", "lastResponse", ")", "[", "0", "]", ")", ";", "$", "this", "->", "lastResponseCode", "=", "$", "this", "->", "lastResponseCode", ">", "0", "?", "$", "this", "->", "lastResponseCode", ":", "-", "1", ";", "return", "$", "this", "->", "lastResponse", ";", "}" ]
Read response from SMTP server @return string
[ "Read", "response", "from", "SMTP", "server" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Mailer/Agents/SMTP.php#L314-L320
comelyio/comely
src/Comely/IO/Mailer/Agents/SMTP.php
SMTP.send
public function send(Message $message, array $emails): int { $this->connect(); // Establish or revive connection $this->command("RSET"); // Reset SMTP buffer $this->command(sprintf('MAIL FROM:<%1$s>', $message->sender()->email), null, 250); // Set mail from $count = 0; foreach ($emails as $email) { $this->write(sprintf('RCPT TO:<%1$s>', $email)); $this->read(); if ($this->lastResponseCode !== 250) { throw SMTPException::invalidRecipient(substr($this->lastResponse, 4)); } $count++; } $messageMime = $message->compile(); $messageMimeSize = strlen($messageMime); if ($this->options["size"] > 0 && $messageMimeSize > $this->options["size"]) { throw SMTPException::exceedsMaximumSize($messageMimeSize, $this->options["size"]); } $this->command("DATA", null, 354); $this->write($messageMime); // Write MIME $this->command(".", null, 250); // End DATA // Keep alive? if (!$this->keepAlive) { $this->write("QUIT"); // Send QUIT command //unset($this->stream); $this->stream = null; // Close stream resource } return $count; }
php
public function send(Message $message, array $emails): int { $this->connect(); // Establish or revive connection $this->command("RSET"); // Reset SMTP buffer $this->command(sprintf('MAIL FROM:<%1$s>', $message->sender()->email), null, 250); // Set mail from $count = 0; foreach ($emails as $email) { $this->write(sprintf('RCPT TO:<%1$s>', $email)); $this->read(); if ($this->lastResponseCode !== 250) { throw SMTPException::invalidRecipient(substr($this->lastResponse, 4)); } $count++; } $messageMime = $message->compile(); $messageMimeSize = strlen($messageMime); if ($this->options["size"] > 0 && $messageMimeSize > $this->options["size"]) { throw SMTPException::exceedsMaximumSize($messageMimeSize, $this->options["size"]); } $this->command("DATA", null, 354); $this->write($messageMime); // Write MIME $this->command(".", null, 250); // End DATA // Keep alive? if (!$this->keepAlive) { $this->write("QUIT"); // Send QUIT command //unset($this->stream); $this->stream = null; // Close stream resource } return $count; }
[ "public", "function", "send", "(", "Message", "$", "message", ",", "array", "$", "emails", ")", ":", "int", "{", "$", "this", "->", "connect", "(", ")", ";", "// Establish or revive connection", "$", "this", "->", "command", "(", "\"RSET\"", ")", ";", "// Reset SMTP buffer", "$", "this", "->", "command", "(", "sprintf", "(", "'MAIL FROM:<%1$s>'", ",", "$", "message", "->", "sender", "(", ")", "->", "email", ")", ",", "null", ",", "250", ")", ";", "// Set mail from", "$", "count", "=", "0", ";", "foreach", "(", "$", "emails", "as", "$", "email", ")", "{", "$", "this", "->", "write", "(", "sprintf", "(", "'RCPT TO:<%1$s>'", ",", "$", "email", ")", ")", ";", "$", "this", "->", "read", "(", ")", ";", "if", "(", "$", "this", "->", "lastResponseCode", "!==", "250", ")", "{", "throw", "SMTPException", "::", "invalidRecipient", "(", "substr", "(", "$", "this", "->", "lastResponse", ",", "4", ")", ")", ";", "}", "$", "count", "++", ";", "}", "$", "messageMime", "=", "$", "message", "->", "compile", "(", ")", ";", "$", "messageMimeSize", "=", "strlen", "(", "$", "messageMime", ")", ";", "if", "(", "$", "this", "->", "options", "[", "\"size\"", "]", ">", "0", "&&", "$", "messageMimeSize", ">", "$", "this", "->", "options", "[", "\"size\"", "]", ")", "{", "throw", "SMTPException", "::", "exceedsMaximumSize", "(", "$", "messageMimeSize", ",", "$", "this", "->", "options", "[", "\"size\"", "]", ")", ";", "}", "$", "this", "->", "command", "(", "\"DATA\"", ",", "null", ",", "354", ")", ";", "$", "this", "->", "write", "(", "$", "messageMime", ")", ";", "// Write MIME", "$", "this", "->", "command", "(", "\".\"", ",", "null", ",", "250", ")", ";", "// End DATA", "// Keep alive?", "if", "(", "!", "$", "this", "->", "keepAlive", ")", "{", "$", "this", "->", "write", "(", "\"QUIT\"", ")", ";", "// Send QUIT command", "//unset($this->stream);", "$", "this", "->", "stream", "=", "null", ";", "// Close stream resource", "}", "return", "$", "count", ";", "}" ]
Send email message(s) @param Message $message @param array $emails @return int @throws SMTPException
[ "Send", "email", "message", "(", "s", ")" ]
train
https://github.com/comelyio/comely/blob/561ea7aef36fea347a1a79d3ee5597d4057ddf82/src/Comely/IO/Mailer/Agents/SMTP.php#L346-L381
movoin/one-swoole
src/Swoole/Provider.php
Provider.log
final protected function log(string $level, string $message, array $context = []) { $this->provider('logger')->log($level, $message, $context); }
php
final protected function log(string $level, string $message, array $context = []) { $this->provider('logger')->log($level, $message, $context); }
[ "final", "protected", "function", "log", "(", "string", "$", "level", ",", "string", "$", "message", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "this", "->", "provider", "(", "'logger'", ")", "->", "log", "(", "$", "level", ",", "$", "message", ",", "$", "context", ")", ";", "}" ]
写入日志 @param string $level @param string $message @param array $context
[ "写入日志" ]
train
https://github.com/movoin/one-swoole/blob/b9b175963ead91416cc50902a04e05ff3ef571de/src/Swoole/Provider.php#L101-L104
stubbles/stubbles-webapp-core
src/main/php/routing/Interceptors.php
Interceptors.preProcess
public function preProcess(Request $request, Response $response): bool { foreach ($this->preInterceptors as $preInterceptor) { if (false === $this->executePreInterceptor($preInterceptor, $request, $response)) { return false; } } return true; }
php
public function preProcess(Request $request, Response $response): bool { foreach ($this->preInterceptors as $preInterceptor) { if (false === $this->executePreInterceptor($preInterceptor, $request, $response)) { return false; } } return true; }
[ "public", "function", "preProcess", "(", "Request", "$", "request", ",", "Response", "$", "response", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "preInterceptors", "as", "$", "preInterceptor", ")", "{", "if", "(", "false", "===", "$", "this", "->", "executePreInterceptor", "(", "$", "preInterceptor", ",", "$", "request", ",", "$", "response", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
apply pre interceptors Returns false if one of the pre interceptors cancels the request. @param \stubbles\webapp\Request $request current request @param \stubbles\webapp\Response $response response to send @return bool
[ "apply", "pre", "interceptors" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/routing/Interceptors.php#L64-L73
stubbles/stubbles-webapp-core
src/main/php/routing/Interceptors.php
Interceptors.executePreInterceptor
private function executePreInterceptor($preInterceptor, Request $request, Response $response) { if (is_callable($preInterceptor)) { return $preInterceptor($request, $response); } if ($preInterceptor instanceof PreInterceptor) { return $preInterceptor->preProcess($request, $response); } $instance = $this->injector->getInstance($preInterceptor); if (!($instance instanceof PreInterceptor)) { $response->write( $response->internalServerError( 'Configured pre interceptor ' . $preInterceptor . ' is not an instance of ' . PreInterceptor::class ) ); return false; } return $instance->preProcess($request, $response); }
php
private function executePreInterceptor($preInterceptor, Request $request, Response $response) { if (is_callable($preInterceptor)) { return $preInterceptor($request, $response); } if ($preInterceptor instanceof PreInterceptor) { return $preInterceptor->preProcess($request, $response); } $instance = $this->injector->getInstance($preInterceptor); if (!($instance instanceof PreInterceptor)) { $response->write( $response->internalServerError( 'Configured pre interceptor ' . $preInterceptor . ' is not an instance of ' . PreInterceptor::class ) ); return false; } return $instance->preProcess($request, $response); }
[ "private", "function", "executePreInterceptor", "(", "$", "preInterceptor", ",", "Request", "$", "request", ",", "Response", "$", "response", ")", "{", "if", "(", "is_callable", "(", "$", "preInterceptor", ")", ")", "{", "return", "$", "preInterceptor", "(", "$", "request", ",", "$", "response", ")", ";", "}", "if", "(", "$", "preInterceptor", "instanceof", "PreInterceptor", ")", "{", "return", "$", "preInterceptor", "->", "preProcess", "(", "$", "request", ",", "$", "response", ")", ";", "}", "$", "instance", "=", "$", "this", "->", "injector", "->", "getInstance", "(", "$", "preInterceptor", ")", ";", "if", "(", "!", "(", "$", "instance", "instanceof", "PreInterceptor", ")", ")", "{", "$", "response", "->", "write", "(", "$", "response", "->", "internalServerError", "(", "'Configured pre interceptor '", ".", "$", "preInterceptor", ".", "' is not an instance of '", ".", "PreInterceptor", "::", "class", ")", ")", ";", "return", "false", ";", "}", "return", "$", "instance", "->", "preProcess", "(", "$", "request", ",", "$", "response", ")", ";", "}" ]
executes pre interceptor @param mixed $preInterceptor @param \stubbles\webapp\Request $request current request @param \stubbles\webapp\Response $response response to send @return bool|null
[ "executes", "pre", "interceptor" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/routing/Interceptors.php#L83-L105
stubbles/stubbles-webapp-core
src/main/php/routing/Interceptors.php
Interceptors.postProcess
public function postProcess(Request $request, Response $response): bool { foreach ($this->postInterceptors as $postInterceptor) { if (false === $this->executePostInterceptor($postInterceptor, $request, $response)) { return false; } } return true; }
php
public function postProcess(Request $request, Response $response): bool { foreach ($this->postInterceptors as $postInterceptor) { if (false === $this->executePostInterceptor($postInterceptor, $request, $response)) { return false; } } return true; }
[ "public", "function", "postProcess", "(", "Request", "$", "request", ",", "Response", "$", "response", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "postInterceptors", "as", "$", "postInterceptor", ")", "{", "if", "(", "false", "===", "$", "this", "->", "executePostInterceptor", "(", "$", "postInterceptor", ",", "$", "request", ",", "$", "response", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
apply post interceptors @param \stubbles\webapp\Request $request current request @param \stubbles\webapp\Response $response response to send @return bool
[ "apply", "post", "interceptors" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/routing/Interceptors.php#L114-L123
stubbles/stubbles-webapp-core
src/main/php/routing/Interceptors.php
Interceptors.executePostInterceptor
private function executePostInterceptor($postInterceptor, Request $request, Response $response) { if (is_callable($postInterceptor)) { return $postInterceptor($request, $response); } if ($postInterceptor instanceof PostInterceptor) { return $postInterceptor->postProcess($request, $response); } $instance = $this->injector->getInstance($postInterceptor); if (!($instance instanceof PostInterceptor)) { $response->write( $response->internalServerError( 'Configured post interceptor ' . $postInterceptor . ' is not an instance of ' . PostInterceptor::class ) ); return false; } return $instance->postProcess($request, $response); }
php
private function executePostInterceptor($postInterceptor, Request $request, Response $response) { if (is_callable($postInterceptor)) { return $postInterceptor($request, $response); } if ($postInterceptor instanceof PostInterceptor) { return $postInterceptor->postProcess($request, $response); } $instance = $this->injector->getInstance($postInterceptor); if (!($instance instanceof PostInterceptor)) { $response->write( $response->internalServerError( 'Configured post interceptor ' . $postInterceptor . ' is not an instance of ' . PostInterceptor::class ) ); return false; } return $instance->postProcess($request, $response); }
[ "private", "function", "executePostInterceptor", "(", "$", "postInterceptor", ",", "Request", "$", "request", ",", "Response", "$", "response", ")", "{", "if", "(", "is_callable", "(", "$", "postInterceptor", ")", ")", "{", "return", "$", "postInterceptor", "(", "$", "request", ",", "$", "response", ")", ";", "}", "if", "(", "$", "postInterceptor", "instanceof", "PostInterceptor", ")", "{", "return", "$", "postInterceptor", "->", "postProcess", "(", "$", "request", ",", "$", "response", ")", ";", "}", "$", "instance", "=", "$", "this", "->", "injector", "->", "getInstance", "(", "$", "postInterceptor", ")", ";", "if", "(", "!", "(", "$", "instance", "instanceof", "PostInterceptor", ")", ")", "{", "$", "response", "->", "write", "(", "$", "response", "->", "internalServerError", "(", "'Configured post interceptor '", ".", "$", "postInterceptor", ".", "' is not an instance of '", ".", "PostInterceptor", "::", "class", ")", ")", ";", "return", "false", ";", "}", "return", "$", "instance", "->", "postProcess", "(", "$", "request", ",", "$", "response", ")", ";", "}" ]
executes post interceptor @param mixed $postInterceptor @param \stubbles\webapp\Request $request current request @param \stubbles\webapp\Response $response response to send @return bool|null
[ "executes", "post", "interceptor" ]
train
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/routing/Interceptors.php#L133-L155
ekyna/GlsUniBox
Renderer/LabelRenderer.php
LabelRenderer.initialize
private function initialize() { if (null === $this->layout) { $this->layout = [ // Control bar 1 Config::T110 => ['s' => 84, 'x' => 28, 'y' => 155], Config::T310 => ['s' => 84, 'x' => 545, 'y' => 155, 'c' => 'white'], Config::T100 => ['s' => 84, 'x' => 662, 'y' => 155], Config::T105 => ['s' => 84, 'x' => 662, 'y' => 155], Config::T101 => ['s' => 84, 'x' => 877, 'y' => 155, 'c' => 'white'], // Control bar 2 Config::T320 => ['s' => 72, 'x' => 28, 'y' => 305], Config::T8951 => ['s' => 32, 'x' => 387, 'y' => 245], Config::T8952 => ['s' => 32, 'x' => 622, 'y' => 245], Config::T330 => ['s' => 48, 'x' => 370, 'y' => 320], Config::T8913 => ['s' => 48, 'x' => 622, 'y' => 320], Config::T200 => ['s' => 52, 'x' => 962, 'y' => 297, 'f' => 'swiss_bold'], // Control bar 3 (barcodes) // Control bar 4 Config::T500 => ['s' => 40, 'x' => 20, 'y' => 780], Config::T540 => ['s' => 20, 'x' => 255, 'y' => 780], Config::T541 => ['s' => 20, 'x' => 390, 'y' => 780], Config::T530 => ['s' => 32, 'x' => 520, 'y' => 780, 'append' => 'KG'], // Bloc 1 Config::T751 => ['s' => 38, 'x' => 30, 'y' => 965], Config::T752 => ['s' => 38, 'x' => 30, 'y' => 1070], // Bloc 2 Config::T860 => ['s' => 30, 'x' => 30, 'y' => 1290], Config::T861 => ['s' => 30, 'x' => 30, 'y' => 1347], Config::T862 => ['s' => 30, 'x' => 30, 'y' => 1404], Config::T863 => ['s' => 30, 'x' => 30, 'y' => 1461], // Bloc 3 // Bloc 4 Config::T8915 => ['s' => 28, 'x' => 1110, 'y' => 1020, 'a' => 270, 'prepend' => 'Client '], Config::T8914 => ['s' => 28, 'x' => 1110, 'y' => 1350, 'a' => 270, 'prepend' => 'ContactId '], Config::T810 => ['s' => 24, 'x' => 1060, 'y' => 830, 'a' => 270], Config::T820 => ['s' => 24, 'x' => 1015, 'y' => 830, 'a' => 270], ]; $this->fonts = [ 'swiss_normal' => __DIR__ . '/../Resources/font/Swiss721CondensedBT.ttf', 'swiss_bold' => __DIR__ . '/../Resources/font/Swiss721BoldCondensedBT.ttf', ]; } $this->image = imagecreatefromgif(__DIR__ . '/../Resources/img/gls-label.gif'); $this->colors = [ 'black' => imagecolorallocate($this->image, 0, 0, 0), 'white' => imagecolorallocate($this->image, 255, 255, 255), ]; }
php
private function initialize() { if (null === $this->layout) { $this->layout = [ // Control bar 1 Config::T110 => ['s' => 84, 'x' => 28, 'y' => 155], Config::T310 => ['s' => 84, 'x' => 545, 'y' => 155, 'c' => 'white'], Config::T100 => ['s' => 84, 'x' => 662, 'y' => 155], Config::T105 => ['s' => 84, 'x' => 662, 'y' => 155], Config::T101 => ['s' => 84, 'x' => 877, 'y' => 155, 'c' => 'white'], // Control bar 2 Config::T320 => ['s' => 72, 'x' => 28, 'y' => 305], Config::T8951 => ['s' => 32, 'x' => 387, 'y' => 245], Config::T8952 => ['s' => 32, 'x' => 622, 'y' => 245], Config::T330 => ['s' => 48, 'x' => 370, 'y' => 320], Config::T8913 => ['s' => 48, 'x' => 622, 'y' => 320], Config::T200 => ['s' => 52, 'x' => 962, 'y' => 297, 'f' => 'swiss_bold'], // Control bar 3 (barcodes) // Control bar 4 Config::T500 => ['s' => 40, 'x' => 20, 'y' => 780], Config::T540 => ['s' => 20, 'x' => 255, 'y' => 780], Config::T541 => ['s' => 20, 'x' => 390, 'y' => 780], Config::T530 => ['s' => 32, 'x' => 520, 'y' => 780, 'append' => 'KG'], // Bloc 1 Config::T751 => ['s' => 38, 'x' => 30, 'y' => 965], Config::T752 => ['s' => 38, 'x' => 30, 'y' => 1070], // Bloc 2 Config::T860 => ['s' => 30, 'x' => 30, 'y' => 1290], Config::T861 => ['s' => 30, 'x' => 30, 'y' => 1347], Config::T862 => ['s' => 30, 'x' => 30, 'y' => 1404], Config::T863 => ['s' => 30, 'x' => 30, 'y' => 1461], // Bloc 3 // Bloc 4 Config::T8915 => ['s' => 28, 'x' => 1110, 'y' => 1020, 'a' => 270, 'prepend' => 'Client '], Config::T8914 => ['s' => 28, 'x' => 1110, 'y' => 1350, 'a' => 270, 'prepend' => 'ContactId '], Config::T810 => ['s' => 24, 'x' => 1060, 'y' => 830, 'a' => 270], Config::T820 => ['s' => 24, 'x' => 1015, 'y' => 830, 'a' => 270], ]; $this->fonts = [ 'swiss_normal' => __DIR__ . '/../Resources/font/Swiss721CondensedBT.ttf', 'swiss_bold' => __DIR__ . '/../Resources/font/Swiss721BoldCondensedBT.ttf', ]; } $this->image = imagecreatefromgif(__DIR__ . '/../Resources/img/gls-label.gif'); $this->colors = [ 'black' => imagecolorallocate($this->image, 0, 0, 0), 'white' => imagecolorallocate($this->image, 255, 255, 255), ]; }
[ "private", "function", "initialize", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "layout", ")", "{", "$", "this", "->", "layout", "=", "[", "// Control bar 1", "Config", "::", "T110", "=>", "[", "'s'", "=>", "84", ",", "'x'", "=>", "28", ",", "'y'", "=>", "155", "]", ",", "Config", "::", "T310", "=>", "[", "'s'", "=>", "84", ",", "'x'", "=>", "545", ",", "'y'", "=>", "155", ",", "'c'", "=>", "'white'", "]", ",", "Config", "::", "T100", "=>", "[", "'s'", "=>", "84", ",", "'x'", "=>", "662", ",", "'y'", "=>", "155", "]", ",", "Config", "::", "T105", "=>", "[", "'s'", "=>", "84", ",", "'x'", "=>", "662", ",", "'y'", "=>", "155", "]", ",", "Config", "::", "T101", "=>", "[", "'s'", "=>", "84", ",", "'x'", "=>", "877", ",", "'y'", "=>", "155", ",", "'c'", "=>", "'white'", "]", ",", "// Control bar 2", "Config", "::", "T320", "=>", "[", "'s'", "=>", "72", ",", "'x'", "=>", "28", ",", "'y'", "=>", "305", "]", ",", "Config", "::", "T8951", "=>", "[", "'s'", "=>", "32", ",", "'x'", "=>", "387", ",", "'y'", "=>", "245", "]", ",", "Config", "::", "T8952", "=>", "[", "'s'", "=>", "32", ",", "'x'", "=>", "622", ",", "'y'", "=>", "245", "]", ",", "Config", "::", "T330", "=>", "[", "'s'", "=>", "48", ",", "'x'", "=>", "370", ",", "'y'", "=>", "320", "]", ",", "Config", "::", "T8913", "=>", "[", "'s'", "=>", "48", ",", "'x'", "=>", "622", ",", "'y'", "=>", "320", "]", ",", "Config", "::", "T200", "=>", "[", "'s'", "=>", "52", ",", "'x'", "=>", "962", ",", "'y'", "=>", "297", ",", "'f'", "=>", "'swiss_bold'", "]", ",", "// Control bar 3 (barcodes)", "// Control bar 4", "Config", "::", "T500", "=>", "[", "'s'", "=>", "40", ",", "'x'", "=>", "20", ",", "'y'", "=>", "780", "]", ",", "Config", "::", "T540", "=>", "[", "'s'", "=>", "20", ",", "'x'", "=>", "255", ",", "'y'", "=>", "780", "]", ",", "Config", "::", "T541", "=>", "[", "'s'", "=>", "20", ",", "'x'", "=>", "390", ",", "'y'", "=>", "780", "]", ",", "Config", "::", "T530", "=>", "[", "'s'", "=>", "32", ",", "'x'", "=>", "520", ",", "'y'", "=>", "780", ",", "'append'", "=>", "'KG'", "]", ",", "// Bloc 1", "Config", "::", "T751", "=>", "[", "'s'", "=>", "38", ",", "'x'", "=>", "30", ",", "'y'", "=>", "965", "]", ",", "Config", "::", "T752", "=>", "[", "'s'", "=>", "38", ",", "'x'", "=>", "30", ",", "'y'", "=>", "1070", "]", ",", "// Bloc 2", "Config", "::", "T860", "=>", "[", "'s'", "=>", "30", ",", "'x'", "=>", "30", ",", "'y'", "=>", "1290", "]", ",", "Config", "::", "T861", "=>", "[", "'s'", "=>", "30", ",", "'x'", "=>", "30", ",", "'y'", "=>", "1347", "]", ",", "Config", "::", "T862", "=>", "[", "'s'", "=>", "30", ",", "'x'", "=>", "30", ",", "'y'", "=>", "1404", "]", ",", "Config", "::", "T863", "=>", "[", "'s'", "=>", "30", ",", "'x'", "=>", "30", ",", "'y'", "=>", "1461", "]", ",", "// Bloc 3", "// Bloc 4", "Config", "::", "T8915", "=>", "[", "'s'", "=>", "28", ",", "'x'", "=>", "1110", ",", "'y'", "=>", "1020", ",", "'a'", "=>", "270", ",", "'prepend'", "=>", "'Client '", "]", ",", "Config", "::", "T8914", "=>", "[", "'s'", "=>", "28", ",", "'x'", "=>", "1110", ",", "'y'", "=>", "1350", ",", "'a'", "=>", "270", ",", "'prepend'", "=>", "'ContactId '", "]", ",", "Config", "::", "T810", "=>", "[", "'s'", "=>", "24", ",", "'x'", "=>", "1060", ",", "'y'", "=>", "830", ",", "'a'", "=>", "270", "]", ",", "Config", "::", "T820", "=>", "[", "'s'", "=>", "24", ",", "'x'", "=>", "1015", ",", "'y'", "=>", "830", ",", "'a'", "=>", "270", "]", ",", "]", ";", "$", "this", "->", "fonts", "=", "[", "'swiss_normal'", "=>", "__DIR__", ".", "'/../Resources/font/Swiss721CondensedBT.ttf'", ",", "'swiss_bold'", "=>", "__DIR__", ".", "'/../Resources/font/Swiss721BoldCondensedBT.ttf'", ",", "]", ";", "}", "$", "this", "->", "image", "=", "imagecreatefromgif", "(", "__DIR__", ".", "'/../Resources/img/gls-label.gif'", ")", ";", "$", "this", "->", "colors", "=", "[", "'black'", "=>", "imagecolorallocate", "(", "$", "this", "->", "image", ",", "0", ",", "0", ",", "0", ")", ",", "'white'", "=>", "imagecolorallocate", "(", "$", "this", "->", "image", ",", "255", ",", "255", ",", "255", ")", ",", "]", ";", "}" ]
Initializes the label.
[ "Initializes", "the", "label", "." ]
train
https://github.com/ekyna/GlsUniBox/blob/b474271ba355c3917074422306dc64abf09584d0/Renderer/LabelRenderer.php#L55-L107
ekyna/GlsUniBox
Renderer/LabelRenderer.php
LabelRenderer.build
private function build(array $data) { foreach ($this->layout as $key => $c) { if (!isset($data[$key]) || 0 === strlen($value = $data[$key])) { continue; } if (isset($c['prepend'])) $value = $c['prepend'] . $value; if (isset($c['append'])) $value .= $c['append']; $angle = isset($c['a']) ? $c['a'] : 0; $color = isset($c['c']) ? $c['c'] : 'black'; $font = isset($c['f']) ? $c['f'] : 'swiss_normal'; $this->text($value, $c['s'], $c['x'], $c['y'], $color, $font, $angle); } // Primary barcode $matrix = imagecreatefromstring($this->getBarcodeDatamatrix($data[Config::T8902])); imagecopy($this->image, $matrix, 57, 398, 0, 0, imagesx($matrix), imagesy($matrix)); imagedestroy($matrix); // Mondial relay if (isset($data[Config::T200]) && $data[Config::T200] === 'SHD') { $this->text('Mondial Relay', 40, 475, 420); // Barcode $barcode = imagecreatefromstring($this->getBarcode128($data[Config::T8913])); imagecopy($this->image, $barcode, 425, 462, 0, 0, imagesx($barcode), imagesy($barcode)); imagedestroy($barcode); $this->text('GLS' . $data[Config::T8913], 32, 500, 670); } // Secondary barcode $matrix = imagecreatefromstring($this->getBarcodeDatamatrix($data[Config::T8903])); imagecopy($this->image, $matrix, 895, 400, 0, 0, imagesx($matrix), imagesy($matrix)); imagedestroy($matrix); // Pages if (isset($data[Config::T8904]) && isset($data[Config::T8905])) { $pages = $data[Config::T8904] . '/' . $data[Config::T8905]; $this->text($pages, 20, 792, 780); } // Service label $service = null; if (isset($data[Config::T750])) { $service = $data[Config::T750]; } elseif (isset($data[Config::T200]) && $data[Config::T200] === 'T13') { $service = '13.00SERVICE'; } if ($service) { $this->text($service, 38, 30, 870); } // Téléphones if (isset($data[Config::T1230])) { $this->text($data[Config::T1230], 38, 30, 1175); } elseif (isset($data[Config::T871])) { $this->text($data[Config::T871], 38, 30, 1175); } // Ref. destinataire if (isset($data[Config::T859]) && !empty($value = $data[Config::T859])) { $this->text('Ref Dest : ' . $value, 22, 600, 1230); } // Pays / Code postal / Ville destinataire $this->text($data[Config::T100] . ' ' . $data[Config::T330] . ' ' . $data[Config::T864], 30, 30, 1518); // Expediteur $this->text('Expediteur', 28, 1110, 810, 'black', 'swiss_bold', 270); // Pays / Code postal / Ville expéditeur $value = $data[Config::T821] . ' ' . $data[Config::T822] . ' ' . $data[Config::T823]; $this->text($value, 28, 925, 830, 'black', 'swiss_normal', 270); }
php
private function build(array $data) { foreach ($this->layout as $key => $c) { if (!isset($data[$key]) || 0 === strlen($value = $data[$key])) { continue; } if (isset($c['prepend'])) $value = $c['prepend'] . $value; if (isset($c['append'])) $value .= $c['append']; $angle = isset($c['a']) ? $c['a'] : 0; $color = isset($c['c']) ? $c['c'] : 'black'; $font = isset($c['f']) ? $c['f'] : 'swiss_normal'; $this->text($value, $c['s'], $c['x'], $c['y'], $color, $font, $angle); } // Primary barcode $matrix = imagecreatefromstring($this->getBarcodeDatamatrix($data[Config::T8902])); imagecopy($this->image, $matrix, 57, 398, 0, 0, imagesx($matrix), imagesy($matrix)); imagedestroy($matrix); // Mondial relay if (isset($data[Config::T200]) && $data[Config::T200] === 'SHD') { $this->text('Mondial Relay', 40, 475, 420); // Barcode $barcode = imagecreatefromstring($this->getBarcode128($data[Config::T8913])); imagecopy($this->image, $barcode, 425, 462, 0, 0, imagesx($barcode), imagesy($barcode)); imagedestroy($barcode); $this->text('GLS' . $data[Config::T8913], 32, 500, 670); } // Secondary barcode $matrix = imagecreatefromstring($this->getBarcodeDatamatrix($data[Config::T8903])); imagecopy($this->image, $matrix, 895, 400, 0, 0, imagesx($matrix), imagesy($matrix)); imagedestroy($matrix); // Pages if (isset($data[Config::T8904]) && isset($data[Config::T8905])) { $pages = $data[Config::T8904] . '/' . $data[Config::T8905]; $this->text($pages, 20, 792, 780); } // Service label $service = null; if (isset($data[Config::T750])) { $service = $data[Config::T750]; } elseif (isset($data[Config::T200]) && $data[Config::T200] === 'T13') { $service = '13.00SERVICE'; } if ($service) { $this->text($service, 38, 30, 870); } // Téléphones if (isset($data[Config::T1230])) { $this->text($data[Config::T1230], 38, 30, 1175); } elseif (isset($data[Config::T871])) { $this->text($data[Config::T871], 38, 30, 1175); } // Ref. destinataire if (isset($data[Config::T859]) && !empty($value = $data[Config::T859])) { $this->text('Ref Dest : ' . $value, 22, 600, 1230); } // Pays / Code postal / Ville destinataire $this->text($data[Config::T100] . ' ' . $data[Config::T330] . ' ' . $data[Config::T864], 30, 30, 1518); // Expediteur $this->text('Expediteur', 28, 1110, 810, 'black', 'swiss_bold', 270); // Pays / Code postal / Ville expéditeur $value = $data[Config::T821] . ' ' . $data[Config::T822] . ' ' . $data[Config::T823]; $this->text($value, 28, 925, 830, 'black', 'swiss_normal', 270); }
[ "private", "function", "build", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "this", "->", "layout", "as", "$", "key", "=>", "$", "c", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "$", "key", "]", ")", "||", "0", "===", "strlen", "(", "$", "value", "=", "$", "data", "[", "$", "key", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "c", "[", "'prepend'", "]", ")", ")", "$", "value", "=", "$", "c", "[", "'prepend'", "]", ".", "$", "value", ";", "if", "(", "isset", "(", "$", "c", "[", "'append'", "]", ")", ")", "$", "value", ".=", "$", "c", "[", "'append'", "]", ";", "$", "angle", "=", "isset", "(", "$", "c", "[", "'a'", "]", ")", "?", "$", "c", "[", "'a'", "]", ":", "0", ";", "$", "color", "=", "isset", "(", "$", "c", "[", "'c'", "]", ")", "?", "$", "c", "[", "'c'", "]", ":", "'black'", ";", "$", "font", "=", "isset", "(", "$", "c", "[", "'f'", "]", ")", "?", "$", "c", "[", "'f'", "]", ":", "'swiss_normal'", ";", "$", "this", "->", "text", "(", "$", "value", ",", "$", "c", "[", "'s'", "]", ",", "$", "c", "[", "'x'", "]", ",", "$", "c", "[", "'y'", "]", ",", "$", "color", ",", "$", "font", ",", "$", "angle", ")", ";", "}", "// Primary barcode", "$", "matrix", "=", "imagecreatefromstring", "(", "$", "this", "->", "getBarcodeDatamatrix", "(", "$", "data", "[", "Config", "::", "T8902", "]", ")", ")", ";", "imagecopy", "(", "$", "this", "->", "image", ",", "$", "matrix", ",", "57", ",", "398", ",", "0", ",", "0", ",", "imagesx", "(", "$", "matrix", ")", ",", "imagesy", "(", "$", "matrix", ")", ")", ";", "imagedestroy", "(", "$", "matrix", ")", ";", "// Mondial relay", "if", "(", "isset", "(", "$", "data", "[", "Config", "::", "T200", "]", ")", "&&", "$", "data", "[", "Config", "::", "T200", "]", "===", "'SHD'", ")", "{", "$", "this", "->", "text", "(", "'Mondial Relay'", ",", "40", ",", "475", ",", "420", ")", ";", "// Barcode", "$", "barcode", "=", "imagecreatefromstring", "(", "$", "this", "->", "getBarcode128", "(", "$", "data", "[", "Config", "::", "T8913", "]", ")", ")", ";", "imagecopy", "(", "$", "this", "->", "image", ",", "$", "barcode", ",", "425", ",", "462", ",", "0", ",", "0", ",", "imagesx", "(", "$", "barcode", ")", ",", "imagesy", "(", "$", "barcode", ")", ")", ";", "imagedestroy", "(", "$", "barcode", ")", ";", "$", "this", "->", "text", "(", "'GLS'", ".", "$", "data", "[", "Config", "::", "T8913", "]", ",", "32", ",", "500", ",", "670", ")", ";", "}", "// Secondary barcode", "$", "matrix", "=", "imagecreatefromstring", "(", "$", "this", "->", "getBarcodeDatamatrix", "(", "$", "data", "[", "Config", "::", "T8903", "]", ")", ")", ";", "imagecopy", "(", "$", "this", "->", "image", ",", "$", "matrix", ",", "895", ",", "400", ",", "0", ",", "0", ",", "imagesx", "(", "$", "matrix", ")", ",", "imagesy", "(", "$", "matrix", ")", ")", ";", "imagedestroy", "(", "$", "matrix", ")", ";", "// Pages", "if", "(", "isset", "(", "$", "data", "[", "Config", "::", "T8904", "]", ")", "&&", "isset", "(", "$", "data", "[", "Config", "::", "T8905", "]", ")", ")", "{", "$", "pages", "=", "$", "data", "[", "Config", "::", "T8904", "]", ".", "'/'", ".", "$", "data", "[", "Config", "::", "T8905", "]", ";", "$", "this", "->", "text", "(", "$", "pages", ",", "20", ",", "792", ",", "780", ")", ";", "}", "// Service label", "$", "service", "=", "null", ";", "if", "(", "isset", "(", "$", "data", "[", "Config", "::", "T750", "]", ")", ")", "{", "$", "service", "=", "$", "data", "[", "Config", "::", "T750", "]", ";", "}", "elseif", "(", "isset", "(", "$", "data", "[", "Config", "::", "T200", "]", ")", "&&", "$", "data", "[", "Config", "::", "T200", "]", "===", "'T13'", ")", "{", "$", "service", "=", "'13.00SERVICE'", ";", "}", "if", "(", "$", "service", ")", "{", "$", "this", "->", "text", "(", "$", "service", ",", "38", ",", "30", ",", "870", ")", ";", "}", "// Téléphones", "if", "(", "isset", "(", "$", "data", "[", "Config", "::", "T1230", "]", ")", ")", "{", "$", "this", "->", "text", "(", "$", "data", "[", "Config", "::", "T1230", "]", ",", "38", ",", "30", ",", "1175", ")", ";", "}", "elseif", "(", "isset", "(", "$", "data", "[", "Config", "::", "T871", "]", ")", ")", "{", "$", "this", "->", "text", "(", "$", "data", "[", "Config", "::", "T871", "]", ",", "38", ",", "30", ",", "1175", ")", ";", "}", "// Ref. destinataire", "if", "(", "isset", "(", "$", "data", "[", "Config", "::", "T859", "]", ")", "&&", "!", "empty", "(", "$", "value", "=", "$", "data", "[", "Config", "::", "T859", "]", ")", ")", "{", "$", "this", "->", "text", "(", "'Ref Dest : '", ".", "$", "value", ",", "22", ",", "600", ",", "1230", ")", ";", "}", "// Pays / Code postal / Ville destinataire", "$", "this", "->", "text", "(", "$", "data", "[", "Config", "::", "T100", "]", ".", "' '", ".", "$", "data", "[", "Config", "::", "T330", "]", ".", "' '", ".", "$", "data", "[", "Config", "::", "T864", "]", ",", "30", ",", "30", ",", "1518", ")", ";", "// Expediteur", "$", "this", "->", "text", "(", "'Expediteur'", ",", "28", ",", "1110", ",", "810", ",", "'black'", ",", "'swiss_bold'", ",", "270", ")", ";", "// Pays / Code postal / Ville expéditeur", "$", "value", "=", "$", "data", "[", "Config", "::", "T821", "]", ".", "' '", ".", "$", "data", "[", "Config", "::", "T822", "]", ".", "' '", ".", "$", "data", "[", "Config", "::", "T823", "]", ";", "$", "this", "->", "text", "(", "$", "value", ",", "28", ",", "925", ",", "830", ",", "'black'", ",", "'swiss_normal'", ",", "270", ")", ";", "}" ]
Writes the fields to the label. @param array $data
[ "Writes", "the", "fields", "to", "the", "label", "." ]
train
https://github.com/ekyna/GlsUniBox/blob/b474271ba355c3917074422306dc64abf09584d0/Renderer/LabelRenderer.php#L114-L191
ekyna/GlsUniBox
Renderer/LabelRenderer.php
LabelRenderer.text
private function text($text, $size, $x, $y, $color = 'black', $font = 'swiss_normal', $angle = 0) { imagettftext($this->image, $size, $angle, $x, $y, $this->colors[$color], $this->fonts[$font], $text); }
php
private function text($text, $size, $x, $y, $color = 'black', $font = 'swiss_normal', $angle = 0) { imagettftext($this->image, $size, $angle, $x, $y, $this->colors[$color], $this->fonts[$font], $text); }
[ "private", "function", "text", "(", "$", "text", ",", "$", "size", ",", "$", "x", ",", "$", "y", ",", "$", "color", "=", "'black'", ",", "$", "font", "=", "'swiss_normal'", ",", "$", "angle", "=", "0", ")", "{", "imagettftext", "(", "$", "this", "->", "image", ",", "$", "size", ",", "$", "angle", ",", "$", "x", ",", "$", "y", ",", "$", "this", "->", "colors", "[", "$", "color", "]", ",", "$", "this", "->", "fonts", "[", "$", "font", "]", ",", "$", "text", ")", ";", "}" ]
Writes the given text. @param string $text @param int $size @param int $x @param int $y @param string $color @param string $font @param int $angle
[ "Writes", "the", "given", "text", "." ]
train
https://github.com/ekyna/GlsUniBox/blob/b474271ba355c3917074422306dc64abf09584d0/Renderer/LabelRenderer.php#L204-L207
ekyna/GlsUniBox
Renderer/LabelRenderer.php
LabelRenderer.getImageData
private function getImageData() { ob_start(); imagegif($this->image); $output = ob_get_contents(); ob_end_clean(); imagedestroy($this->image); return $output; }
php
private function getImageData() { ob_start(); imagegif($this->image); $output = ob_get_contents(); ob_end_clean(); imagedestroy($this->image); return $output; }
[ "private", "function", "getImageData", "(", ")", "{", "ob_start", "(", ")", ";", "imagegif", "(", "$", "this", "->", "image", ")", ";", "$", "output", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "imagedestroy", "(", "$", "this", "->", "image", ")", ";", "return", "$", "output", ";", "}" ]
Returns the image raw data. @return string
[ "Returns", "the", "image", "raw", "data", "." ]
train
https://github.com/ekyna/GlsUniBox/blob/b474271ba355c3917074422306dc64abf09584d0/Renderer/LabelRenderer.php#L214-L223
ekyna/GlsUniBox
Renderer/LabelRenderer.php
LabelRenderer.getBarcodeDatamatrix
public function getBarcodeDatamatrix($data) { $barcode = new Barcode(); $bobj = $barcode->getBarcodeObj( 'DATAMATRIX', $data, 256, 256, 'black', array(0, 0, 0, 0) )->setBackgroundColor('white'); return $bobj->getPngData(); }
php
public function getBarcodeDatamatrix($data) { $barcode = new Barcode(); $bobj = $barcode->getBarcodeObj( 'DATAMATRIX', $data, 256, 256, 'black', array(0, 0, 0, 0) )->setBackgroundColor('white'); return $bobj->getPngData(); }
[ "public", "function", "getBarcodeDatamatrix", "(", "$", "data", ")", "{", "$", "barcode", "=", "new", "Barcode", "(", ")", ";", "$", "bobj", "=", "$", "barcode", "->", "getBarcodeObj", "(", "'DATAMATRIX'", ",", "$", "data", ",", "256", ",", "256", ",", "'black'", ",", "array", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "->", "setBackgroundColor", "(", "'white'", ")", ";", "return", "$", "bobj", "->", "getPngData", "(", ")", ";", "}" ]
Returns the datamatrix from the given data. @param string $data @return string
[ "Returns", "the", "datamatrix", "from", "the", "given", "data", "." ]
train
https://github.com/ekyna/GlsUniBox/blob/b474271ba355c3917074422306dc64abf09584d0/Renderer/LabelRenderer.php#L232-L246
ekyna/GlsUniBox
Renderer/LabelRenderer.php
LabelRenderer.getBarcode128
public function getBarcode128($data) { $barcode = new Barcode(); $bobj = $barcode->getBarcodeObj( 'C128', $data, 380, 135, 'black', array(0, 0, 0, 0) )->setBackgroundColor('white'); return $bobj->getPngData(); }
php
public function getBarcode128($data) { $barcode = new Barcode(); $bobj = $barcode->getBarcodeObj( 'C128', $data, 380, 135, 'black', array(0, 0, 0, 0) )->setBackgroundColor('white'); return $bobj->getPngData(); }
[ "public", "function", "getBarcode128", "(", "$", "data", ")", "{", "$", "barcode", "=", "new", "Barcode", "(", ")", ";", "$", "bobj", "=", "$", "barcode", "->", "getBarcodeObj", "(", "'C128'", ",", "$", "data", ",", "380", ",", "135", ",", "'black'", ",", "array", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "->", "setBackgroundColor", "(", "'white'", ")", ";", "return", "$", "bobj", "->", "getPngData", "(", ")", ";", "}" ]
Returns the barcode from the given data. @param string $data @return string
[ "Returns", "the", "barcode", "from", "the", "given", "data", "." ]
train
https://github.com/ekyna/GlsUniBox/blob/b474271ba355c3917074422306dc64abf09584d0/Renderer/LabelRenderer.php#L255-L269