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
tck/zf-imageresizer
src/TckImageResizer/Util/UrlSafeBase64.php
UrlSafeBase64.decode
public static function decode($data) { $rData = strtr($data, '-_', '+/'); $rMod4 = strlen($rData) % 4; if ($rMod4) { $rData .= substr('====', $rMod4); } return base64_decode($rData); }
php
public static function decode($data) { $rData = strtr($data, '-_', '+/'); $rMod4 = strlen($rData) % 4; if ($rMod4) { $rData .= substr('====', $rMod4); } return base64_decode($rData); }
[ "public", "static", "function", "decode", "(", "$", "data", ")", "{", "$", "rData", "=", "strtr", "(", "$", "data", ",", "'-_'", ",", "'+/'", ")", ";", "$", "rMod4", "=", "strlen", "(", "$", "rData", ")", "%", "4", ";", "if", "(", "$", "rMod4",...
base64 decode @param string $data data to decode @return string decoded data
[ "base64", "decode" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Util/UrlSafeBase64.php#L38-L46
stephweb/daw-php-orm
example/core/Http/Response.php
Response.header
public static function header(string $content, string $type = null) { if ($type) { header($content.': '.$type.'; charset=UTF-8'); } else { header($content); } }
php
public static function header(string $content, string $type = null) { if ($type) { header($content.': '.$type.'; charset=UTF-8'); } else { header($content); } }
[ "public", "static", "function", "header", "(", "string", "$", "content", ",", "string", "$", "type", "=", "null", ")", "{", "if", "(", "$", "type", ")", "{", "header", "(", "$", "content", ".", "': '", ".", "$", "type", ".", "'; charset=UTF-8'", ")",...
Spécifier l'en-tête HTTP de l'affichage d'une vue @param string $content @param string|null $type
[ "Spécifier", "l", "en", "-", "tête", "HTTP", "de", "l", "affichage", "d", "une", "vue" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/example/core/Http/Response.php#L102-L109
stephweb/daw-php-orm
example/core/Http/Response.php
Response.redirect
public static function redirect(string $url, $httpResponseCodeParam = null) { if ($httpResponseCodeParam) { if (array_key_exists($httpResponseCodeParam, self::STATUS_CODE)) { $httpResponseCode = $httpResponseCodeParam; header('Location: '.$url, true, $httpResponseCode); } else { getException('Status code "'.$httpResponseCodeParam.'" not good.'); header('Location: '.$url); } } else { header('Location: '.$url); } exit(); }
php
public static function redirect(string $url, $httpResponseCodeParam = null) { if ($httpResponseCodeParam) { if (array_key_exists($httpResponseCodeParam, self::STATUS_CODE)) { $httpResponseCode = $httpResponseCodeParam; header('Location: '.$url, true, $httpResponseCode); } else { getException('Status code "'.$httpResponseCodeParam.'" not good.'); header('Location: '.$url); } } else { header('Location: '.$url); } exit(); }
[ "public", "static", "function", "redirect", "(", "string", "$", "url", ",", "$", "httpResponseCodeParam", "=", "null", ")", "{", "if", "(", "$", "httpResponseCodeParam", ")", "{", "if", "(", "array_key_exists", "(", "$", "httpResponseCodeParam", ",", "self", ...
Rediriger @param string $url - url vers où regiriger visiteur @param null|int $httpResponseCodeParam - Code de la réponse HTTP
[ "Rediriger" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/example/core/Http/Response.php#L116-L133
accompli/accompli
src/DependencyInjection/AwarenessCompilerPass.php
AwarenessCompilerPass.process
public function process(ContainerBuilder $container) { foreach ($container->getDefinitions() as $definition) { $interfaces = class_implements($definition->getClass()); foreach ($interfaces as $interface) { if (substr($interface, -14) === 'AwareInterface') { $camelCasedServiceId = substr($interface, strrpos($interface, '\\') + 1, -14); $serviceId = Container::underscore($camelCasedServiceId); if ($container->has($serviceId)) { $setterMethod = 'set'.$camelCasedServiceId; $definition->addMethodCall($setterMethod, array(new Reference($serviceId))); } } } } }
php
public function process(ContainerBuilder $container) { foreach ($container->getDefinitions() as $definition) { $interfaces = class_implements($definition->getClass()); foreach ($interfaces as $interface) { if (substr($interface, -14) === 'AwareInterface') { $camelCasedServiceId = substr($interface, strrpos($interface, '\\') + 1, -14); $serviceId = Container::underscore($camelCasedServiceId); if ($container->has($serviceId)) { $setterMethod = 'set'.$camelCasedServiceId; $definition->addMethodCall($setterMethod, array(new Reference($serviceId))); } } } } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "foreach", "(", "$", "container", "->", "getDefinitions", "(", ")", "as", "$", "definition", ")", "{", "$", "interfaces", "=", "class_implements", "(", "$", "definition", "...
Processes awareness interfaces by adding a setter method call to the service definition with a reference to the service. @param ContainerBuilder $container
[ "Processes", "awareness", "interfaces", "by", "adding", "a", "setter", "method", "call", "to", "the", "service", "definition", "with", "a", "reference", "to", "the", "service", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/DependencyInjection/AwarenessCompilerPass.php#L22-L39
schnittstabil/csrf-tokenservice
src/TokenGenerator.php
TokenGenerator.generatePayload
protected function generatePayload($nonce, $iat, $exp) { $payload = new \stdClass(); $payload->nonce = $nonce; $payload->iat = $iat; $payload->ttl = $exp - $iat; $payload->exp = $exp; return $payload; }
php
protected function generatePayload($nonce, $iat, $exp) { $payload = new \stdClass(); $payload->nonce = $nonce; $payload->iat = $iat; $payload->ttl = $exp - $iat; $payload->exp = $exp; return $payload; }
[ "protected", "function", "generatePayload", "(", "$", "nonce", ",", "$", "iat", ",", "$", "exp", ")", "{", "$", "payload", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "payload", "->", "nonce", "=", "$", "nonce", ";", "$", "payload", "->", "ia...
Generate the payload of a CSRF token. @param string $nonce Value used to associate a client session @param int $iat The time that the token was issued, defaults to `time()` @param int $exp The expiration time @return \stdClass
[ "Generate", "the", "payload", "of", "a", "CSRF", "token", "." ]
train
https://github.com/schnittstabil/csrf-tokenservice/blob/22aefee674137e661fe439d08414b6abc1fe0d25/src/TokenGenerator.php#L51-L60
loyals-online/silverstripe-tinymce4
thirdparty/tinymce/tiny_mce_gzip.php
TinyMCE4_Compressor.parseTime
private function parseTime($time) { $multipel = 1; // Hours if (strpos($time, "h") > 0) $multipel = 3600; // Days if (strpos($time, "d") > 0) $multipel = 86400; // Months if (strpos($time, "m") > 0) $multipel = 2592000; // Trim string return intval($time) * $multipel; }
php
private function parseTime($time) { $multipel = 1; // Hours if (strpos($time, "h") > 0) $multipel = 3600; // Days if (strpos($time, "d") > 0) $multipel = 86400; // Months if (strpos($time, "m") > 0) $multipel = 2592000; // Trim string return intval($time) * $multipel; }
[ "private", "function", "parseTime", "(", "$", "time", ")", "{", "$", "multipel", "=", "1", ";", "// Hours\r", "if", "(", "strpos", "(", "$", "time", ",", "\"h\"", ")", ">", "0", ")", "$", "multipel", "=", "3600", ";", "// Days\r", "if", "(", "strpo...
Parses the specified time format into seconds. Supports formats like 10h, 10d, 10m. @param String $time Time format to convert into seconds. @return Int Number of seconds for the specified format.
[ "Parses", "the", "specified", "time", "format", "into", "seconds", ".", "Supports", "formats", "like", "10h", "10d", "10m", "." ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/thirdparty/tinymce/tiny_mce_gzip.php#L292-L309
loyals-online/silverstripe-tinymce4
thirdparty/tinymce/tiny_mce_gzip.php
TinyMCE4_Compressor.getFileContents
private function getFileContents($file) { $content = file_get_contents($file); // Remove UTF-8 BOM if (substr($content, 0, 3) === pack("CCC", 0xef, 0xbb, 0xbf)) $content = substr($content, 3); return $content; }
php
private function getFileContents($file) { $content = file_get_contents($file); // Remove UTF-8 BOM if (substr($content, 0, 3) === pack("CCC", 0xef, 0xbb, 0xbf)) $content = substr($content, 3); return $content; }
[ "private", "function", "getFileContents", "(", "$", "file", ")", "{", "$", "content", "=", "file_get_contents", "(", "$", "file", ")", ";", "// Remove UTF-8 BOM\r", "if", "(", "substr", "(", "$", "content", ",", "0", ",", "3", ")", "===", "pack", "(", ...
Returns the contents of the script file if it exists and removes the UTF-8 BOM header if it exists. @param String $file File to load. @return String File contents or empty string if it doesn't exist.
[ "Returns", "the", "contents", "of", "the", "script", "file", "if", "it", "exists", "and", "removes", "the", "UTF", "-", "8", "BOM", "header", "if", "it", "exists", "." ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/thirdparty/tinymce/tiny_mce_gzip.php#L317-L325
index0h/yii2-phar
src/helpers/FileHelper.php
FileHelper.realPath
public static function realPath($path) { if (self::isPhar($path) === false) { return realpath($path); } preg_match('/^(phar:\/{0,2})?(.*)?/u', $path, $matches); $path = self::resolveRelativeToGlobal($matches[2]); $path = self::resolveDots($path); return self::PHAR_PREFIX . $path; }
php
public static function realPath($path) { if (self::isPhar($path) === false) { return realpath($path); } preg_match('/^(phar:\/{0,2})?(.*)?/u', $path, $matches); $path = self::resolveRelativeToGlobal($matches[2]); $path = self::resolveDots($path); return self::PHAR_PREFIX . $path; }
[ "public", "static", "function", "realPath", "(", "$", "path", ")", "{", "if", "(", "self", "::", "isPhar", "(", "$", "path", ")", "===", "false", ")", "{", "return", "realpath", "(", "$", "path", ")", ";", "}", "preg_match", "(", "'/^(phar:\\/{0,2})?(....
@param string $path Path to convert. @return string
[ "@param", "string", "$path", "Path", "to", "convert", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/helpers/FileHelper.php#L28-L40
index0h/yii2-phar
src/helpers/FileHelper.php
FileHelper.fileMakeTime
public static function fileMakeTime($path) { if (self::isPhar($path) === false) { return filemtime($path); } return filemtime(self::getPharPath($path)); }
php
public static function fileMakeTime($path) { if (self::isPhar($path) === false) { return filemtime($path); } return filemtime(self::getPharPath($path)); }
[ "public", "static", "function", "fileMakeTime", "(", "$", "path", ")", "{", "if", "(", "self", "::", "isPhar", "(", "$", "path", ")", "===", "false", ")", "{", "return", "filemtime", "(", "$", "path", ")", ";", "}", "return", "filemtime", "(", "self"...
@param string $path Path to file/folder. @return int
[ "@param", "string", "$path", "Path", "to", "file", "/", "folder", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/helpers/FileHelper.php#L47-L54
index0h/yii2-phar
src/helpers/FileHelper.php
FileHelper.isDir
public static function isDir($path) { return (self::isPhar($path) === true) ? file_exists($path) : is_dir($path); }
php
public static function isDir($path) { return (self::isPhar($path) === true) ? file_exists($path) : is_dir($path); }
[ "public", "static", "function", "isDir", "(", "$", "path", ")", "{", "return", "(", "self", "::", "isPhar", "(", "$", "path", ")", "===", "true", ")", "?", "file_exists", "(", "$", "path", ")", ":", "is_dir", "(", "$", "path", ")", ";", "}" ]
@param string $path Path to folder. @return bool
[ "@param", "string", "$path", "Path", "to", "folder", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/helpers/FileHelper.php#L61-L64
index0h/yii2-phar
src/helpers/FileHelper.php
FileHelper.getPharPath
protected static function getPharPath($path) { $path = self::realPath($path); return str_replace(self::PHAR_PREFIX, '', $path); }
php
protected static function getPharPath($path) { $path = self::realPath($path); return str_replace(self::PHAR_PREFIX, '', $path); }
[ "protected", "static", "function", "getPharPath", "(", "$", "path", ")", "{", "$", "path", "=", "self", "::", "realPath", "(", "$", "path", ")", ";", "return", "str_replace", "(", "self", "::", "PHAR_PREFIX", ",", "''", ",", "$", "path", ")", ";", "}...
@param string $path Path to file/folder. @return string
[ "@param", "string", "$path", "Path", "to", "file", "/", "folder", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/helpers/FileHelper.php#L81-L85
index0h/yii2-phar
src/helpers/FileHelper.php
FileHelper.resolveRelativeToGlobal
protected static function resolveRelativeToGlobal($path) { // Checks if path is relative. if ((strpos($path, ':') === false) && ((strlen($path) === 0) || ($path[0] !== '/'))) { $path = getcwd() . DIRECTORY_SEPARATOR . $path; } return $path; }
php
protected static function resolveRelativeToGlobal($path) { // Checks if path is relative. if ((strpos($path, ':') === false) && ((strlen($path) === 0) || ($path[0] !== '/'))) { $path = getcwd() . DIRECTORY_SEPARATOR . $path; } return $path; }
[ "protected", "static", "function", "resolveRelativeToGlobal", "(", "$", "path", ")", "{", "// Checks if path is relative.", "if", "(", "(", "strpos", "(", "$", "path", ",", "':'", ")", "===", "false", ")", "&&", "(", "(", "strlen", "(", "$", "path", ")", ...
@param string $path Path without stream prefix. @return string
[ "@param", "string", "$path", "Path", "without", "stream", "prefix", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/helpers/FileHelper.php#L92-L99
phlib/db
src/Adapter/CrudTrait.php
CrudTrait.select
public function select($table, $where = [], array $bind = []) { $table = $this->quote()->identifier($table); $sql = "SELECT * FROM $table"; if (is_array($where)) { $where = $this->createWhereExpression($where); } $sql .= (($where) ? " WHERE {$where}" : ''); return $this->query($sql, $bind); }
php
public function select($table, $where = [], array $bind = []) { $table = $this->quote()->identifier($table); $sql = "SELECT * FROM $table"; if (is_array($where)) { $where = $this->createWhereExpression($where); } $sql .= (($where) ? " WHERE {$where}" : ''); return $this->query($sql, $bind); }
[ "public", "function", "select", "(", "$", "table", ",", "$", "where", "=", "[", "]", ",", "array", "$", "bind", "=", "[", "]", ")", "{", "$", "table", "=", "$", "this", "->", "quote", "(", ")", "->", "identifier", "(", "$", "table", ")", ";", ...
Select data from table. @param string $table @param array|string $where Deprecated usage of parameter as string @param array $bind Deprecated in favour of $where as array @return \PDOStatement
[ "Select", "data", "from", "table", "." ]
train
https://github.com/phlib/db/blob/30c0fce5fb268766265cb03492c4209bcf916a40/src/Adapter/CrudTrait.php#L15-L25
phlib/db
src/Adapter/CrudTrait.php
CrudTrait.insert
public function insert($table, array $data) { $table = $this->quote()->identifier($table); $fields = implode(', ', array_keys($data)); $values = implode(', ', array_map([$this->quote(), 'value'], $data)); $sql = "INSERT INTO $table ($fields) VALUES ($values)"; $stmt = $this->query($sql); return $stmt->rowCount(); }
php
public function insert($table, array $data) { $table = $this->quote()->identifier($table); $fields = implode(', ', array_keys($data)); $values = implode(', ', array_map([$this->quote(), 'value'], $data)); $sql = "INSERT INTO $table ($fields) VALUES ($values)"; $stmt = $this->query($sql); return $stmt->rowCount(); }
[ "public", "function", "insert", "(", "$", "table", ",", "array", "$", "data", ")", "{", "$", "table", "=", "$", "this", "->", "quote", "(", ")", "->", "identifier", "(", "$", "table", ")", ";", "$", "fields", "=", "implode", "(", "', '", ",", "ar...
Insert data to table. @param string $table @param array $data @return int Number of affected rows
[ "Insert", "data", "to", "table", "." ]
train
https://github.com/phlib/db/blob/30c0fce5fb268766265cb03492c4209bcf916a40/src/Adapter/CrudTrait.php#L34-L44
phlib/db
src/Adapter/CrudTrait.php
CrudTrait.update
public function update($table, array $data, $where = [], array $bind = []) { $table = $this->quote()->identifier($table); $fields = []; foreach ($data as $field => $value) { $fields[] = $this->quote()->into("{$field} = ?", $value); } $sql = "UPDATE $table SET " . implode(', ', $fields); if (is_array($where)) { $where = $this->createWhereExpression($where); } $sql .= (($where) ? " WHERE {$where}" : ''); $stmt = $this->query($sql, $bind); return $stmt->rowCount(); }
php
public function update($table, array $data, $where = [], array $bind = []) { $table = $this->quote()->identifier($table); $fields = []; foreach ($data as $field => $value) { $fields[] = $this->quote()->into("{$field} = ?", $value); } $sql = "UPDATE $table SET " . implode(', ', $fields); if (is_array($where)) { $where = $this->createWhereExpression($where); } $sql .= (($where) ? " WHERE {$where}" : ''); $stmt = $this->query($sql, $bind); return $stmt->rowCount(); }
[ "public", "function", "update", "(", "$", "table", ",", "array", "$", "data", ",", "$", "where", "=", "[", "]", ",", "array", "$", "bind", "=", "[", "]", ")", "{", "$", "table", "=", "$", "this", "->", "quote", "(", ")", "->", "identifier", "("...
Update data in table. @param string $table @param array $data @param array|string $where Deprecated usage of parameter as string @param array $bind Deprecated in favour of $where as array @return int Number of affected rows
[ "Update", "data", "in", "table", "." ]
train
https://github.com/phlib/db/blob/30c0fce5fb268766265cb03492c4209bcf916a40/src/Adapter/CrudTrait.php#L55-L71
phlib/db
src/Adapter/CrudTrait.php
CrudTrait.delete
public function delete($table, $where = [], array $bind = []) { $table = $this->quote()->identifier($table); $sql = "DELETE FROM $table"; if (is_array($where)) { $where = $this->createWhereExpression($where); } $sql .= (($where) ? " WHERE {$where}" : ''); $stmt = $this->query($sql, $bind); return $stmt->rowCount(); }
php
public function delete($table, $where = [], array $bind = []) { $table = $this->quote()->identifier($table); $sql = "DELETE FROM $table"; if (is_array($where)) { $where = $this->createWhereExpression($where); } $sql .= (($where) ? " WHERE {$where}" : ''); $stmt = $this->query($sql, $bind); return $stmt->rowCount(); }
[ "public", "function", "delete", "(", "$", "table", ",", "$", "where", "=", "[", "]", ",", "array", "$", "bind", "=", "[", "]", ")", "{", "$", "table", "=", "$", "this", "->", "quote", "(", ")", "->", "identifier", "(", "$", "table", ")", ";", ...
Delete from table. @param string $table @param array|string $where Deprecated usage of parameter as string @param array $bind Deprecated in favour of $where as array @return int Number of affected rows
[ "Delete", "from", "table", "." ]
train
https://github.com/phlib/db/blob/30c0fce5fb268766265cb03492c4209bcf916a40/src/Adapter/CrudTrait.php#L81-L93
phlib/db
src/Adapter/CrudTrait.php
CrudTrait.upsert
public function upsert($table, array $data, array $updateFields) { $table = $this->quote()->identifier($table); $fields = implode(', ', array_map([$this->quote(), 'identifier'], array_keys($data))); $placeHolders = implode(', ', array_fill(0, count($data), '?')); $updateValues = []; foreach ($updateFields as $field) { $field = $this->quote()->identifier($field); $updateValues[] = "$field = VALUES($field)"; } $updates = implode(', ', $updateValues); $sql = "INSERT INTO $table ($fields) VALUES ($placeHolders) ON DUPLICATE KEY UPDATE $updates"; $stmt = $this->query($sql, array_values($data)); return $stmt->rowCount(); }
php
public function upsert($table, array $data, array $updateFields) { $table = $this->quote()->identifier($table); $fields = implode(', ', array_map([$this->quote(), 'identifier'], array_keys($data))); $placeHolders = implode(', ', array_fill(0, count($data), '?')); $updateValues = []; foreach ($updateFields as $field) { $field = $this->quote()->identifier($field); $updateValues[] = "$field = VALUES($field)"; } $updates = implode(', ', $updateValues); $sql = "INSERT INTO $table ($fields) VALUES ($placeHolders) ON DUPLICATE KEY UPDATE $updates"; $stmt = $this->query($sql, array_values($data)); return $stmt->rowCount(); }
[ "public", "function", "upsert", "(", "$", "table", ",", "array", "$", "data", ",", "array", "$", "updateFields", ")", "{", "$", "table", "=", "$", "this", "->", "quote", "(", ")", "->", "identifier", "(", "$", "table", ")", ";", "$", "fields", "=",...
Insert (on duplicate key update) data in table. @param string $table @param array $data @param array $updateFields @return int Number of affected rows
[ "Insert", "(", "on", "duplicate", "key", "update", ")", "data", "in", "table", "." ]
train
https://github.com/phlib/db/blob/30c0fce5fb268766265cb03492c4209bcf916a40/src/Adapter/CrudTrait.php#L103-L119
phlib/db
src/Adapter/CrudTrait.php
CrudTrait.createWhereExpression
private function createWhereExpression(array $where = []) { $criteria = []; foreach ($where as $index => $value) { if (is_int($index)) { $criteria[] = $value; } else { $criteria[] = $this->quote()->into($index, $value); } } return implode(' AND ', $criteria); }
php
private function createWhereExpression(array $where = []) { $criteria = []; foreach ($where as $index => $value) { if (is_int($index)) { $criteria[] = $value; } else { $criteria[] = $this->quote()->into($index, $value); } } return implode(' AND ', $criteria); }
[ "private", "function", "createWhereExpression", "(", "array", "$", "where", "=", "[", "]", ")", "{", "$", "criteria", "=", "[", "]", ";", "foreach", "(", "$", "where", "as", "$", "index", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$",...
Create WHERE expression from given criteria @param array $where @return string
[ "Create", "WHERE", "expression", "from", "given", "criteria" ]
train
https://github.com/phlib/db/blob/30c0fce5fb268766265cb03492c4209bcf916a40/src/Adapter/CrudTrait.php#L127-L138
makinacorpus/drupal-ucms
ucms_site/src/Datasource/SiteAdminDatasource.php
SiteAdminDatasource.getFilters
public function getFilters() { $states = SiteState::getList(SiteState::ARCHIVE); foreach ($states as $key => $label) { $states[$key] = $this->t($label); } return [ (new Filter('state', $this->t("State")))->setChoicesMap($states), // @todo missing site type registry or variable somewhere (new Filter('theme', $this->t("Theme")))->setChoicesMap($this->manager->getAllowedThemesOptionList()), (new Filter('template', $this->t("Template")))->setChoicesMap($this->manager->getTemplateList()), (new Filter('other', $this->t("Other")))->setChoicesMap(['t' => "template"]), new Filter('uid'), ]; }
php
public function getFilters() { $states = SiteState::getList(SiteState::ARCHIVE); foreach ($states as $key => $label) { $states[$key] = $this->t($label); } return [ (new Filter('state', $this->t("State")))->setChoicesMap($states), // @todo missing site type registry or variable somewhere (new Filter('theme', $this->t("Theme")))->setChoicesMap($this->manager->getAllowedThemesOptionList()), (new Filter('template', $this->t("Template")))->setChoicesMap($this->manager->getTemplateList()), (new Filter('other', $this->t("Other")))->setChoicesMap(['t' => "template"]), new Filter('uid'), ]; }
[ "public", "function", "getFilters", "(", ")", "{", "$", "states", "=", "SiteState", "::", "getList", "(", "SiteState", "::", "ARCHIVE", ")", ";", "foreach", "(", "$", "states", "as", "$", "key", "=>", "$", "label", ")", "{", "$", "states", "[", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Datasource/SiteAdminDatasource.php#L51-L67
makinacorpus/drupal-ucms
ucms_site/src/Datasource/SiteAdminDatasource.php
SiteAdminDatasource.getSorts
public function getSorts() { return [ 's.id' => $this->t("identifier"), 's.title' => $this->t("title"), 's.title_admin' => $this->t("administrative title"), 's.http_host' => $this->t("hostname"), 's.state' => $this->t("state"), 's.type' => $this->t("type"), 's.ts_changed' => $this->t("lastest update date"), 's.ts_created' => $this->t("creation date"), 'u.name' => $this->t("owner name"), ]; }
php
public function getSorts() { return [ 's.id' => $this->t("identifier"), 's.title' => $this->t("title"), 's.title_admin' => $this->t("administrative title"), 's.http_host' => $this->t("hostname"), 's.state' => $this->t("state"), 's.type' => $this->t("type"), 's.ts_changed' => $this->t("lastest update date"), 's.ts_created' => $this->t("creation date"), 'u.name' => $this->t("owner name"), ]; }
[ "public", "function", "getSorts", "(", ")", "{", "return", "[", "'s.id'", "=>", "$", "this", "->", "t", "(", "\"identifier\"", ")", ",", "'s.title'", "=>", "$", "this", "->", "t", "(", "\"title\"", ")", ",", "'s.title_admin'", "=>", "$", "this", "->", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Datasource/SiteAdminDatasource.php#L72-L85
makinacorpus/drupal-ucms
ucms_site/src/Datasource/SiteAdminDatasource.php
SiteAdminDatasource.getItems
public function getItems(Query $query) { $q = $this ->db ->select('ucms_site', 's') ->fields('s', ['id']) ->addTag('ucms_site_access') ; $q->leftJoin('users', 'u', "u.uid = s.uid"); if ($query->has('state')) { $q->condition('s.state', $query->get('state')); } if ($query->has('theme')) { $q->condition('s.theme', $query->get('theme')); } if ($query->has('template')) { $q->condition('s.template_id', $query->get('template')); } if ($query->has('uid')) { $q->join('ucms_site_access', 'sa', "sa.site_id = s.id"); $q->condition('sa.uid', $query->get('uid')); } // Quite ugly, but working as of now // @todo find a more elegant way if ($query->has('other')) { $others = $query->get('other'); if (!is_array($others)) { $others = [$others]; } foreach ($others as $value) { switch ($value) { case 't': $q->condition('s.is_template', 1); break; } } } if ($query->hasSortField()) { $q->orderBy($query->getSortField(), $query->getSortOrder()); } $q->orderBy('s.id', $query->getSortOrder()); $search = $query->getSearchString(); if ($search) { $q->condition( db_or() ->condition('s.title', '%' . db_like($search) . '%', 'LIKE') ->condition('s.http_host', '%' . db_like($search) . '%', 'LIKE') ); } $q->groupBy('s.id'); /** @var \MakinaCorpus\Drupal\Calista\Datasource\QueryExtender\DrupalPager $pager */ $pager = $q->extend(DrupalPager::class)->setDatasourceQuery($query); $idList = $pager->execute()->fetchCol(); $items = $this->manager->getStorage()->loadAll($idList); return $this->createResult($items, $pager->getTotalCount()); }
php
public function getItems(Query $query) { $q = $this ->db ->select('ucms_site', 's') ->fields('s', ['id']) ->addTag('ucms_site_access') ; $q->leftJoin('users', 'u', "u.uid = s.uid"); if ($query->has('state')) { $q->condition('s.state', $query->get('state')); } if ($query->has('theme')) { $q->condition('s.theme', $query->get('theme')); } if ($query->has('template')) { $q->condition('s.template_id', $query->get('template')); } if ($query->has('uid')) { $q->join('ucms_site_access', 'sa', "sa.site_id = s.id"); $q->condition('sa.uid', $query->get('uid')); } // Quite ugly, but working as of now // @todo find a more elegant way if ($query->has('other')) { $others = $query->get('other'); if (!is_array($others)) { $others = [$others]; } foreach ($others as $value) { switch ($value) { case 't': $q->condition('s.is_template', 1); break; } } } if ($query->hasSortField()) { $q->orderBy($query->getSortField(), $query->getSortOrder()); } $q->orderBy('s.id', $query->getSortOrder()); $search = $query->getSearchString(); if ($search) { $q->condition( db_or() ->condition('s.title', '%' . db_like($search) . '%', 'LIKE') ->condition('s.http_host', '%' . db_like($search) . '%', 'LIKE') ); } $q->groupBy('s.id'); /** @var \MakinaCorpus\Drupal\Calista\Datasource\QueryExtender\DrupalPager $pager */ $pager = $q->extend(DrupalPager::class)->setDatasourceQuery($query); $idList = $pager->execute()->fetchCol(); $items = $this->manager->getStorage()->loadAll($idList); return $this->createResult($items, $pager->getTotalCount()); }
[ "public", "function", "getItems", "(", "Query", "$", "query", ")", "{", "$", "q", "=", "$", "this", "->", "db", "->", "select", "(", "'ucms_site'", ",", "'s'", ")", "->", "fields", "(", "'s'", ",", "[", "'id'", "]", ")", "->", "addTag", "(", "'uc...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Datasource/SiteAdminDatasource.php#L99-L162
NicolasMahe/Laravel-SlackOutput
src/Helper/ExceptionHelper.php
ExceptionHelper.asArray
static function asArray(Exception $e) { return [ 'exception' => get_class($e), 'code' => $e->getCode(), 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'hash' => self::hash($e), 'status_code' => self::statusCode($e) ]; }
php
static function asArray(Exception $e) { return [ 'exception' => get_class($e), 'code' => $e->getCode(), 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'hash' => self::hash($e), 'status_code' => self::statusCode($e) ]; }
[ "static", "function", "asArray", "(", "Exception", "$", "e", ")", "{", "return", "[", "'exception'", "=>", "get_class", "(", "$", "e", ")", ",", "'code'", "=>", "$", "e", "->", "getCode", "(", ")", ",", "'message'", "=>", "$", "e", "->", "getMessage"...
Return an array from an Exception @param Exception $e @return array
[ "Return", "an", "array", "from", "an", "Exception" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Helper/ExceptionHelper.php#L17-L28
NicolasMahe/Laravel-SlackOutput
src/Helper/ExceptionHelper.php
ExceptionHelper.statusCode
static function statusCode(Exception $e) { return $e instanceof \Symfony\Component\HttpKernel\Exception\HttpException ? $e->getStatusCode() : 500; }
php
static function statusCode(Exception $e) { return $e instanceof \Symfony\Component\HttpKernel\Exception\HttpException ? $e->getStatusCode() : 500; }
[ "static", "function", "statusCode", "(", "Exception", "$", "e", ")", "{", "return", "$", "e", "instanceof", "\\", "Symfony", "\\", "Component", "\\", "HttpKernel", "\\", "Exception", "\\", "HttpException", "?", "$", "e", "->", "getStatusCode", "(", ")", ":...
Get the http status code of an exception @param Exception $e @return int
[ "Get", "the", "http", "status", "code", "of", "an", "exception" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Helper/ExceptionHelper.php#L38-L41
NicolasMahe/Laravel-SlackOutput
src/Helper/ExceptionHelper.php
ExceptionHelper.hash
static function hash(Exception $e) { return $e instanceof \App\Exceptions\JSONException ? $e->getHash() : null; }
php
static function hash(Exception $e) { return $e instanceof \App\Exceptions\JSONException ? $e->getHash() : null; }
[ "static", "function", "hash", "(", "Exception", "$", "e", ")", "{", "return", "$", "e", "instanceof", "\\", "App", "\\", "Exceptions", "\\", "JSONException", "?", "$", "e", "->", "getHash", "(", ")", ":", "null", ";", "}" ]
Get the hash code of an exception @param Exception $e @return null
[ "Get", "the", "hash", "code", "of", "an", "exception" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Helper/ExceptionHelper.php#L51-L54
makinacorpus/drupal-ucms
ucms_tree/src/MenuAccess.php
MenuAccess.isUserWebmaster
public function isUserWebmaster(Menu $menu, AccountInterface $account) { if ($menu->hasSiteId()) { $site = $this->siteManager->getStorage()->findOne($menu->getSiteId()); return $this->siteManager->getAccess()->userIsWebmaster($account, $site); } return false; }
php
public function isUserWebmaster(Menu $menu, AccountInterface $account) { if ($menu->hasSiteId()) { $site = $this->siteManager->getStorage()->findOne($menu->getSiteId()); return $this->siteManager->getAccess()->userIsWebmaster($account, $site); } return false; }
[ "public", "function", "isUserWebmaster", "(", "Menu", "$", "menu", ",", "AccountInterface", "$", "account", ")", "{", "if", "(", "$", "menu", "->", "hasSiteId", "(", ")", ")", "{", "$", "site", "=", "$", "this", "->", "siteManager", "->", "getStorage", ...
Is user webmaster in the menu site @param Menu $menu @param AccountInterface $account @return bool
[ "Is", "user", "webmaster", "in", "the", "menu", "site" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/MenuAccess.php#L53-L62
makinacorpus/drupal-ucms
ucms_tree/src/MenuAccess.php
MenuAccess.canEditMenu
public function canEditMenu(Menu $menu, AccountInterface $account) { return $account->hasPermission(self::PERM_MANAGE_ALL_MENU) || $this->isUserWebmaster($menu, $account); }
php
public function canEditMenu(Menu $menu, AccountInterface $account) { return $account->hasPermission(self::PERM_MANAGE_ALL_MENU) || $this->isUserWebmaster($menu, $account); }
[ "public", "function", "canEditMenu", "(", "Menu", "$", "menu", ",", "AccountInterface", "$", "account", ")", "{", "return", "$", "account", "->", "hasPermission", "(", "self", "::", "PERM_MANAGE_ALL_MENU", ")", "||", "$", "this", "->", "isUserWebmaster", "(", ...
Can user edit the given menu @param Menu $menu @param AccountInterface $account @return bool
[ "Can", "user", "edit", "the", "given", "menu" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/MenuAccess.php#L72-L75
makinacorpus/drupal-ucms
ucms_tree/src/MenuAccess.php
MenuAccess.canDeleteMenu
public function canDeleteMenu(Menu $menu, AccountInterface $account) { if ($menu->isSiteMain()) { return false; } return $account->hasPermission(self::PERM_MANAGE_ALL_MENU) || $this->isUserWebmaster($menu, $account); }
php
public function canDeleteMenu(Menu $menu, AccountInterface $account) { if ($menu->isSiteMain()) { return false; } return $account->hasPermission(self::PERM_MANAGE_ALL_MENU) || $this->isUserWebmaster($menu, $account); }
[ "public", "function", "canDeleteMenu", "(", "Menu", "$", "menu", ",", "AccountInterface", "$", "account", ")", "{", "if", "(", "$", "menu", "->", "isSiteMain", "(", ")", ")", "{", "return", "false", ";", "}", "return", "$", "account", "->", "hasPermissio...
Can user delete the given menu @param Menu $menu @param AccountInterface $account @return bool
[ "Can", "user", "delete", "the", "given", "menu" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/MenuAccess.php#L98-L105
makinacorpus/drupal-ucms
ucms_tree/src/MenuAccess.php
MenuAccess.canAccessMenuAdmin
public function canAccessMenuAdmin(AccountInterface $account, Site $site = null) { if ($account->hasPermission(self::PERM_MANAGE_ALL_MENU)) { return true; } $site = $this->ensureSiteContext($site); if ($site) { return $this->siteManager->getAccess()->userIsWebmaster($account, $site); } else { return $this->siteManager->getAccess()->userIsWebmaster($account); } return false; }
php
public function canAccessMenuAdmin(AccountInterface $account, Site $site = null) { if ($account->hasPermission(self::PERM_MANAGE_ALL_MENU)) { return true; } $site = $this->ensureSiteContext($site); if ($site) { return $this->siteManager->getAccess()->userIsWebmaster($account, $site); } else { return $this->siteManager->getAccess()->userIsWebmaster($account); } return false; }
[ "public", "function", "canAccessMenuAdmin", "(", "AccountInterface", "$", "account", ",", "Site", "$", "site", "=", "null", ")", "{", "if", "(", "$", "account", "->", "hasPermission", "(", "self", "::", "PERM_MANAGE_ALL_MENU", ")", ")", "{", "return", "true"...
Can user access to the menu admin in the current context @param AccountInterface $account @param Site $site @return bool
[ "Can", "user", "access", "to", "the", "menu", "admin", "in", "the", "current", "context" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/MenuAccess.php#L115-L130
makinacorpus/drupal-ucms
ucms_tree/src/MenuAccess.php
MenuAccess.canCreateMenu
public function canCreateMenu(AccountInterface $account, Site $site = null) { $site = $this->ensureSiteContext($site); return $account->hasPermission(self::PERM_MANAGE_ALL_MENU) || $this->siteManager->getAccess()->userIsWebmaster($account, $site); }
php
public function canCreateMenu(AccountInterface $account, Site $site = null) { $site = $this->ensureSiteContext($site); return $account->hasPermission(self::PERM_MANAGE_ALL_MENU) || $this->siteManager->getAccess()->userIsWebmaster($account, $site); }
[ "public", "function", "canCreateMenu", "(", "AccountInterface", "$", "account", ",", "Site", "$", "site", "=", "null", ")", "{", "$", "site", "=", "$", "this", "->", "ensureSiteContext", "(", "$", "site", ")", ";", "return", "$", "account", "->", "hasPer...
Can user create a menu in the given context @param AccountInterface $account @param Site $site @return bool
[ "Can", "user", "create", "a", "menu", "in", "the", "given", "context" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/MenuAccess.php#L140-L145
runcmf/runbb
src/RunBB/Core/AdminUtils.php
AdminUtils.breadcrumbsAdmin
public static function breadcrumbsAdmin(array $links) { foreach ($links as $name => $url) { if ($name != '' && $url != '') { $tmp[] = '<span><a href="' . $url . '">'.Utils::escape($name).'</a></span>'; } else { $tmp[] = '<span>'.__('Deleted').'</span>'; return implode(' » ', $tmp); } } return implode(' » ', $tmp); }
php
public static function breadcrumbsAdmin(array $links) { foreach ($links as $name => $url) { if ($name != '' && $url != '') { $tmp[] = '<span><a href="' . $url . '">'.Utils::escape($name).'</a></span>'; } else { $tmp[] = '<span>'.__('Deleted').'</span>'; return implode(' » ', $tmp); } } return implode(' » ', $tmp); }
[ "public", "static", "function", "breadcrumbsAdmin", "(", "array", "$", "links", ")", "{", "foreach", "(", "$", "links", "as", "$", "name", "=>", "$", "url", ")", "{", "if", "(", "$", "name", "!=", "''", "&&", "$", "url", "!=", "''", ")", "{", "$"...
Generate breadcrumbs from an array of name and URLs
[ "Generate", "breadcrumbs", "from", "an", "array", "of", "name", "and", "URLs" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/AdminUtils.php#L62-L73
runcmf/runbb
src/RunBB/Core/AdminUtils.php
AdminUtils.deleteFolder
public static function deleteFolder($dirPath) { $it = new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { if ($file->isDir()) { rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dirPath); }
php
public static function deleteFolder($dirPath) { $it = new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::CHILD_FIRST ); foreach ($files as $file) { if ($file->isDir()) { rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dirPath); }
[ "public", "static", "function", "deleteFolder", "(", "$", "dirPath", ")", "{", "$", "it", "=", "new", "RecursiveDirectoryIterator", "(", "$", "dirPath", ",", "RecursiveDirectoryIterator", "::", "SKIP_DOTS", ")", ";", "$", "files", "=", "new", "RecursiveIteratorI...
Delete a folder and all its content
[ "Delete", "a", "folder", "and", "all", "its", "content" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/AdminUtils.php#L78-L93
runcmf/runbb
src/RunBB/Core/AdminUtils.php
AdminUtils.getAdminIds
public static function getAdminIds() { if (!Container::get('cache')->isCached('admin_ids')) { Container::get('cache')->store('admin_ids', \RunBB\Model\Cache::getAdminIds()); } return Container::get('cache')->retrieve('admin_ids'); }
php
public static function getAdminIds() { if (!Container::get('cache')->isCached('admin_ids')) { Container::get('cache')->store('admin_ids', \RunBB\Model\Cache::getAdminIds()); } return Container::get('cache')->retrieve('admin_ids'); }
[ "public", "static", "function", "getAdminIds", "(", ")", "{", "if", "(", "!", "Container", "::", "get", "(", "'cache'", ")", "->", "isCached", "(", "'admin_ids'", ")", ")", "{", "Container", "::", "get", "(", "'cache'", ")", "->", "store", "(", "'admin...
Fetch admin IDs
[ "Fetch", "admin", "IDs" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/AdminUtils.php#L99-L106
runcmf/runbb
src/RunBB/Core/AdminUtils.php
AdminUtils.getContent
public static function getContent($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, "RunBB Marketplace"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_HTTPGET, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $content = curl_exec($ch); curl_close($ch); return $content; }
php
public static function getContent($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, "RunBB Marketplace"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_HTTPGET, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $content = curl_exec($ch); curl_close($ch); return $content; }
[ "public", "static", "function", "getContent", "(", "$", "url", ")", "{", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ...
Wrapper for cURL
[ "Wrapper", "for", "cURL" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Core/AdminUtils.php#L111-L128
box/shmock
src/Shmock/ClassBuilderInstanceClass.php
ClassBuilderInstanceClass.replay
public function replay() { $mockClassName = parent::replay(); $mockClassReflector = new \ReflectionClass($mockClassName); return $mockClassReflector->newInstanceArgs($this->constructor_arguments); }
php
public function replay() { $mockClassName = parent::replay(); $mockClassReflector = new \ReflectionClass($mockClassName); return $mockClassReflector->newInstanceArgs($this->constructor_arguments); }
[ "public", "function", "replay", "(", ")", "{", "$", "mockClassName", "=", "parent", "::", "replay", "(", ")", ";", "$", "mockClassReflector", "=", "new", "\\", "ReflectionClass", "(", "$", "mockClassName", ")", ";", "return", "$", "mockClassReflector", "->",...
When this is invoked, Shmock concludes this instance's build phase, runs any policies that may have been registered, and creates a mock object in the replay phase. @return mixed an instance of a subclass of the mocked class.
[ "When", "this", "is", "invoked", "Shmock", "concludes", "this", "instance", "s", "build", "phase", "runs", "any", "policies", "that", "may", "have", "been", "registered", "and", "creates", "a", "mock", "object", "in", "the", "replay", "phase", "." ]
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/ClassBuilderInstanceClass.php#L132-L138
box/shmock
src/Shmock/ClassBuilderInstanceClass.php
ClassBuilderInstanceClass.addMethodsToBuilder
protected function addMethodsToBuilder(ClassBuilder $builder, callable $resolveCall) { foreach (array_unique($this->expectedInstanceMethodCalls) as $methodCall) { $inspector = new MethodInspector($this->className, $methodCall); $builder->addMethod($methodCall, $resolveCall, $inspector->signatureArgs()); } return parent::addMethodsToBuilder($builder, $resolveCall); }
php
protected function addMethodsToBuilder(ClassBuilder $builder, callable $resolveCall) { foreach (array_unique($this->expectedInstanceMethodCalls) as $methodCall) { $inspector = new MethodInspector($this->className, $methodCall); $builder->addMethod($methodCall, $resolveCall, $inspector->signatureArgs()); } return parent::addMethodsToBuilder($builder, $resolveCall); }
[ "protected", "function", "addMethodsToBuilder", "(", "ClassBuilder", "$", "builder", ",", "callable", "$", "resolveCall", ")", "{", "foreach", "(", "array_unique", "(", "$", "this", "->", "expectedInstanceMethodCalls", ")", "as", "$", "methodCall", ")", "{", "$"...
Helper function to add all called methods to the class builder @param \Shmock\ClassBuilder\ClassBuilder $builder @param callable $resolveCall @return \Shmock\ClassBuilder\ClassBuilder
[ "Helper", "function", "to", "add", "all", "called", "methods", "to", "the", "class", "builder" ]
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/ClassBuilderInstanceClass.php#L147-L154
box/shmock
src/Shmock/ClassBuilderInstanceClass.php
ClassBuilderInstanceClass.shmock_class
public function shmock_class($closure) { $this->in_static_mode = true; $closure($this); $this->in_static_mode = false; }
php
public function shmock_class($closure) { $this->in_static_mode = true; $closure($this); $this->in_static_mode = false; }
[ "public", "function", "shmock_class", "(", "$", "closure", ")", "{", "$", "this", "->", "in_static_mode", "=", "true", ";", "$", "closure", "(", "$", "this", ")", ";", "$", "this", "->", "in_static_mode", "=", "false", ";", "}" ]
When mocking an object instance, it may be desirable to mock static methods as well. Because Shmock has strict rules that mock instances may only mock instance methods, to mock a static method requires dropping into the mock class context. This is made simple by the shmock_class() method on Instance. <pre> // User is an ActiveRecord-style class with finders and data members // (this is just an example, this is probably not a good way to organize this code) class User { private $id; private $userName; public function updateUserName($userName) { /// persist to db $this->userName = $userName; $handle = static::dbHandle(); $handle->update(['userName' => $this->userName]); $this->fireEvent('/users/username'); } public function fireEvent($eventType) { Notifications::fire($this->id, $eventType); } public static function dbHandle() { return new DbHandle('schema.users'); } } // In a test we want to ensure that save() will fire notifications // and correctly persist to the database. $mock = $this->shmock('User', function ($user) { // ensure that the user will fire the event $user->fireEvent('/users/username')->once(); // use shmock_class to mock the static method dbHandle() $user->shmock_class(function ($user_class) { $user_class->dbHandle()->return_value(new FakeDBHandle()); }); }); </pre> @param callable $closure @return void
[ "When", "mocking", "an", "object", "instance", "it", "may", "be", "desirable", "to", "mock", "static", "methods", "as", "well", ".", "Because", "Shmock", "has", "strict", "rules", "that", "mock", "instances", "may", "only", "mock", "instance", "methods", "to...
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/ClassBuilderInstanceClass.php#L203-L208
box/shmock
src/Shmock/ClassBuilderInstanceClass.php
ClassBuilderInstanceClass.initSpec
protected function initSpec($methodName, array $with) { if ($this->in_static_mode) { return new StaticSpec($this->testCase, $this->className, $methodName, $with, Shmock::$policies); } else { return new InstanceSpec($this->testCase, $this->className, $methodName, $with, Shmock::$policies); } }
php
protected function initSpec($methodName, array $with) { if ($this->in_static_mode) { return new StaticSpec($this->testCase, $this->className, $methodName, $with, Shmock::$policies); } else { return new InstanceSpec($this->testCase, $this->className, $methodName, $with, Shmock::$policies); } }
[ "protected", "function", "initSpec", "(", "$", "methodName", ",", "array", "$", "with", ")", "{", "if", "(", "$", "this", "->", "in_static_mode", ")", "{", "return", "new", "StaticSpec", "(", "$", "this", "->", "testCase", ",", "$", "this", "->", "clas...
Build a spec object given the method and args @param string $methodName @param array $with @return Spec
[ "Build", "a", "spec", "object", "given", "the", "method", "and", "args" ]
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/ClassBuilderInstanceClass.php#L216-L223
box/shmock
src/Shmock/ClassBuilderInstanceClass.php
ClassBuilderInstanceClass.recordMethodInvocation
protected function recordMethodInvocation($methodName) { if ($this->in_static_mode) { $this->expectedStaticMethodCalls[] = $methodName; } else { $this->expectedInstanceMethodCalls[] = $methodName; } }
php
protected function recordMethodInvocation($methodName) { if ($this->in_static_mode) { $this->expectedStaticMethodCalls[] = $methodName; } else { $this->expectedInstanceMethodCalls[] = $methodName; } }
[ "protected", "function", "recordMethodInvocation", "(", "$", "methodName", ")", "{", "if", "(", "$", "this", "->", "in_static_mode", ")", "{", "$", "this", "->", "expectedStaticMethodCalls", "[", "]", "=", "$", "methodName", ";", "}", "else", "{", "$", "th...
Housekeeping function to record a method invocation @param string $methodName @return void
[ "Housekeeping", "function", "to", "record", "a", "method", "invocation" ]
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/ClassBuilderInstanceClass.php#L231-L238
mosbth/Anax-MVC
src/Content/CFileContent.php
CFileContent.get
public function get($file) { $target = $this->path . $file; if (!is_readable($target)) { throw new \Exception("No such content " . $target); } return file_get_contents($target); }
php
public function get($file) { $target = $this->path . $file; if (!is_readable($target)) { throw new \Exception("No such content " . $target); } return file_get_contents($target); }
[ "public", "function", "get", "(", "$", "file", ")", "{", "$", "target", "=", "$", "this", "->", "path", ".", "$", "file", ";", "if", "(", "!", "is_readable", "(", "$", "target", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"No such cont...
Get file as content. @param string $file with content @return string as content of the file @throws \Exception when file does not exist
[ "Get", "file", "as", "content", "." ]
train
https://github.com/mosbth/Anax-MVC/blob/5574d105bcec9df8e57532a321585f6521b4581c/src/Content/CFileContent.php#L29-L38
box/shmock
src/Shmock/Shmock.php
Shmock.create
public static function create(\PHPUnit_Framework_TestCase $test_case, $class, callable $closure) { $shmock = new ClassBuilderInstanceClass($test_case, $class); self::$outstanding_shmocks[] = $shmock; if ($closure) { $closure($shmock); } return $shmock->replay(); }
php
public static function create(\PHPUnit_Framework_TestCase $test_case, $class, callable $closure) { $shmock = new ClassBuilderInstanceClass($test_case, $class); self::$outstanding_shmocks[] = $shmock; if ($closure) { $closure($shmock); } return $shmock->replay(); }
[ "public", "static", "function", "create", "(", "\\", "PHPUnit_Framework_TestCase", "$", "test_case", ",", "$", "class", ",", "callable", "$", "closure", ")", "{", "$", "shmock", "=", "new", "ClassBuilderInstanceClass", "(", "$", "test_case", ",", "$", "class",...
Create an instance of a mock object. Shmock uses a build / replay model for building mock objects. The third argument to the create method is a callable that acts as the mock's build phase. The resulting object from the create method is the object in the replay phase. Sample usage: <pre> // build a mock of MyCalculator, expecting a call to add // with arguments [1,2] and return the value 3, exactly once. $mock = \Shmock\Shmock::create($this, 'MyCalculator', function ($calc) { $calc->add(1,2)->return_value(3); }); </pre> In the example above, the invocation target of the method <code>add(1,2)</code> is an of \Shmock\Instance. This instance will allow you to mock any instance method on the class MyCalculator, so it might allow <code>add</code> or <code>subtract</code>, but not <code>openFileStream()</code> or <code>sbutract</code>. The result of the method is an instance of \Shmock\Spec, which contains many of the familiar expectation-setting methods for mock frameworks. You may easily design your own build / replay lifecycle to meet your needs by using the Instance and StaticClass classes directly. <pre> $shmock = new \Shmock\Instance($this, 'MyCalculator'); $shmock->add(1,2)->return_value(3); $mock = $shmock->replay(); </pre> @param \PHPUnit_Framework_TestCase $test_case @param string $class the class being mocked @param callable $closure the build phase of the mock @return mixed An instance of a subclass of $class. PHPUnit mocks require that all mocks be subclasses of the target class in order to replace target methods. For this reason, mocking will fail if the class is final. @see \Shmock\Instance \Shmock\Instance @see \Shmock\Class \Shmock\StaticClass @see \Shmock\Spec See \Shmock\Spec to get a sense of what methods are available for setting expectations. @see \Shmock\Shmockers See the Shmockers trait for a shorthand helper to use in test cases.
[ "Create", "an", "instance", "of", "a", "mock", "object", ".", "Shmock", "uses", "a", "build", "/", "replay", "model", "for", "building", "mock", "objects", ".", "The", "third", "argument", "to", "the", "create", "method", "is", "a", "callable", "that", "...
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/Shmock.php#L88-L97
box/shmock
src/Shmock/Shmock.php
Shmock.create_class
public static function create_class($test_case, $class, $closure) { $shmock_class = new ClassBuilderStaticClass($test_case, $class); self::$outstanding_shmocks[] = $shmock_class; if ($closure) { $closure($shmock_class); } return $shmock_class->replay(); }
php
public static function create_class($test_case, $class, $closure) { $shmock_class = new ClassBuilderStaticClass($test_case, $class); self::$outstanding_shmocks[] = $shmock_class; if ($closure) { $closure($shmock_class); } return $shmock_class->replay(); }
[ "public", "static", "function", "create_class", "(", "$", "test_case", ",", "$", "class", ",", "$", "closure", ")", "{", "$", "shmock_class", "=", "new", "ClassBuilderStaticClass", "(", "$", "test_case", ",", "$", "class", ")", ";", "self", "::", "$", "o...
Create a mock class. Mock classes go through the build / replay lifecycle like mock instances do. @param \PHPUnit_Framework_TestCase $test_case @param string $class the class to be mocked @param callable $closure the closure to apply to the class mock in its build phase. @return string a subclass of $class that has mock expectations set on it. @see \Shmock\Shmock::create()
[ "Create", "a", "mock", "class", ".", "Mock", "classes", "go", "through", "the", "build", "/", "replay", "lifecycle", "like", "mock", "instances", "do", "." ]
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/Shmock.php#L107-L116
box/shmock
src/Shmock/Shmock.php
Shmock.verify
public static function verify() { $mocks = self::$outstanding_shmocks; self::$outstanding_shmocks = []; foreach ($mocks as $mock) { $mock->verify(); } }
php
public static function verify() { $mocks = self::$outstanding_shmocks; self::$outstanding_shmocks = []; foreach ($mocks as $mock) { $mock->verify(); } }
[ "public", "static", "function", "verify", "(", ")", "{", "$", "mocks", "=", "self", "::", "$", "outstanding_shmocks", ";", "self", "::", "$", "outstanding_shmocks", "=", "[", "]", ";", "foreach", "(", "$", "mocks", "as", "$", "mock", ")", "{", "$", "...
This will verify that all mocks so far have been satisfied. It will clear the set of outstanding mocks, regardless if any have failed. @return void
[ "This", "will", "verify", "that", "all", "mocks", "so", "far", "have", "been", "satisfied", ".", "It", "will", "clear", "the", "set", "of", "outstanding", "mocks", "regardless", "if", "any", "have", "failed", "." ]
train
https://github.com/box/shmock/blob/d207d74b9aa2c6c48621091ddc9bbba219a8c45e/src/Shmock/Shmock.php#L145-L152
fintech-fab/bank-emulator
src/FintechFab/BankEmulator/Components/Helpers/Curl.php
Curl.post
public function post($url, $data) { $this->init($url); $this->setPost($data); $this->exec(); $this->fin(); }
php
public function post($url, $data) { $this->init($url); $this->setPost($data); $this->exec(); $this->fin(); }
[ "public", "function", "post", "(", "$", "url", ",", "$", "data", ")", "{", "$", "this", "->", "init", "(", "$", "url", ")", ";", "$", "this", "->", "setPost", "(", "$", "data", ")", ";", "$", "this", "->", "exec", "(", ")", ";", "$", "this", ...
содержимое страницы по url @param $url @param $data @return string
[ "содержимое", "страницы", "по", "url" ]
train
https://github.com/fintech-fab/bank-emulator/blob/6256be98509de0ff8e96b5683a0b0197acd67b9e/src/FintechFab/BankEmulator/Components/Helpers/Curl.php#L24-L30
ARCANEDEV/Settings
database/migrations/2015_12_12_000000_create_settings_table.php
CreateSettingsTable.up
public function up() { $this->createSchema(function(Blueprint $table) { $table->increments('id'); $table->string('key')->index(); $table->text('value'); }); }
php
public function up() { $this->createSchema(function(Blueprint $table) { $table->increments('id'); $table->string('key')->index(); $table->text('value'); }); }
[ "public", "function", "up", "(", ")", "{", "$", "this", "->", "createSchema", "(", "function", "(", "Blueprint", "$", "table", ")", "{", "$", "table", "->", "increments", "(", "'id'", ")", ";", "$", "table", "->", "string", "(", "'key'", ")", "->", ...
Run the migrations.
[ "Run", "the", "migrations", "." ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/database/migrations/2015_12_12_000000_create_settings_table.php#L30-L37
despark/ignicms
app/Http/Controllers/Admin/RolesController.php
RolesController.store
public function store(RoleRequest $request) { $input = $request->except('permissions'); $record = $this->model->create($input); $record->syncPermissions($request->permissions); $this->notify([ 'type' => 'success', 'title' => 'Successful create role!', 'description' => 'Role is created successfully!', ]); return redirect(route('role.edit', ['id' => $record->id])); }
php
public function store(RoleRequest $request) { $input = $request->except('permissions'); $record = $this->model->create($input); $record->syncPermissions($request->permissions); $this->notify([ 'type' => 'success', 'title' => 'Successful create role!', 'description' => 'Role is created successfully!', ]); return redirect(route('role.edit', ['id' => $record->id])); }
[ "public", "function", "store", "(", "RoleRequest", "$", "request", ")", "{", "$", "input", "=", "$", "request", "->", "except", "(", "'permissions'", ")", ";", "$", "record", "=", "$", "this", "->", "model", "->", "create", "(", "$", "input", ")", ";...
Store a newly created resource in storage. @param Request $request @return Response
[ "Store", "a", "newly", "created", "resource", "in", "storage", "." ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/app/Http/Controllers/Admin/RolesController.php#L53-L68
despark/ignicms
app/Http/Controllers/Admin/RolesController.php
RolesController.update
public function update(RoleRequest $request, $id) { $input = $request->except('permissions'); $record = $this->model->findOrFail($id); $record->syncPermissions($request->permissions); $record->update($input); $this->notify([ 'type' => 'success', 'title' => 'Successful update!', 'description' => 'This role is updated successfully.', ]); return redirect()->back(); }
php
public function update(RoleRequest $request, $id) { $input = $request->except('permissions'); $record = $this->model->findOrFail($id); $record->syncPermissions($request->permissions); $record->update($input); $this->notify([ 'type' => 'success', 'title' => 'Successful update!', 'description' => 'This role is updated successfully.', ]); return redirect()->back(); }
[ "public", "function", "update", "(", "RoleRequest", "$", "request", ",", "$", "id", ")", "{", "$", "input", "=", "$", "request", "->", "except", "(", "'permissions'", ")", ";", "$", "record", "=", "$", "this", "->", "model", "->", "findOrFail", "(", ...
Update the specified resource in storage. @param Request $request @param int $id @return Response
[ "Update", "the", "specified", "resource", "in", "storage", "." ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/app/Http/Controllers/Admin/RolesController.php#L97-L114
despark/ignicms
app/Http/Controllers/Admin/RolesController.php
RolesController.destroy
public function destroy($id) { $this->model->findOrFail($id)->delete(); $this->notify([ 'type' => 'danger', 'title' => 'Successful deleted Role!', 'description' => 'The role is deleted successfully.', ]); return redirect()->back(); }
php
public function destroy($id) { $this->model->findOrFail($id)->delete(); $this->notify([ 'type' => 'danger', 'title' => 'Successful deleted Role!', 'description' => 'The role is deleted successfully.', ]); return redirect()->back(); }
[ "public", "function", "destroy", "(", "$", "id", ")", "{", "$", "this", "->", "model", "->", "findOrFail", "(", "$", "id", ")", "->", "delete", "(", ")", ";", "$", "this", "->", "notify", "(", "[", "'type'", "=>", "'danger'", ",", "'title'", "=>", ...
Remove the specified resource from storage. @param int $id @return Response
[ "Remove", "the", "specified", "resource", "from", "storage", "." ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/app/Http/Controllers/Admin/RolesController.php#L123-L134
accompli/accompli
src/Console/Application.php
Application.getTerminalWidth
public function getTerminalWidth() { $terminalDimensions = $this->getTerminalDimensions(); $width = 120; if (isset($terminalDimensions[0]) && $terminalDimensions[0] > 0) { $width = $terminalDimensions[0]; } return $width; }
php
public function getTerminalWidth() { $terminalDimensions = $this->getTerminalDimensions(); $width = 120; if (isset($terminalDimensions[0]) && $terminalDimensions[0] > 0) { $width = $terminalDimensions[0]; } return $width; }
[ "public", "function", "getTerminalWidth", "(", ")", "{", "$", "terminalDimensions", "=", "$", "this", "->", "getTerminalDimensions", "(", ")", ";", "$", "width", "=", "120", ";", "if", "(", "isset", "(", "$", "terminalDimensions", "[", "0", "]", ")", "&&...
Returns the terminal width. @return int
[ "Returns", "the", "terminal", "width", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Console/Application.php#L41-L51
accompli/accompli
src/Console/Application.php
Application.getDefaultCommands
protected function getDefaultCommands() { $commands = parent::getDefaultCommands(); $commands[] = new InitCommand(); $commands[] = new InstallReleaseCommand(); $commands[] = new DeployReleaseCommand(); return $commands; }
php
protected function getDefaultCommands() { $commands = parent::getDefaultCommands(); $commands[] = new InitCommand(); $commands[] = new InstallReleaseCommand(); $commands[] = new DeployReleaseCommand(); return $commands; }
[ "protected", "function", "getDefaultCommands", "(", ")", "{", "$", "commands", "=", "parent", "::", "getDefaultCommands", "(", ")", ";", "$", "commands", "[", "]", "=", "new", "InitCommand", "(", ")", ";", "$", "commands", "[", "]", "=", "new", "InstallR...
Returns the array with default commands. @return array
[ "Returns", "the", "array", "with", "default", "commands", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Console/Application.php#L58-L66
nmdimas/yii2-user-agent-parser
UserAgentParser.php
UserAgentParser.getUserAgentObject
public function getUserAgentObject($userAgent = null) { if (!$userAgent) { $userAgent = $this->getUserAgentByRequest(); } $objectData = ArrayHelper::merge( ['class' => 'yii\useragentparser\UserAgentObject','userAgent'=>$userAgent], $this->parseUserAgent($userAgent) ); return Yii::createObject($objectData); }
php
public function getUserAgentObject($userAgent = null) { if (!$userAgent) { $userAgent = $this->getUserAgentByRequest(); } $objectData = ArrayHelper::merge( ['class' => 'yii\useragentparser\UserAgentObject','userAgent'=>$userAgent], $this->parseUserAgent($userAgent) ); return Yii::createObject($objectData); }
[ "public", "function", "getUserAgentObject", "(", "$", "userAgent", "=", "null", ")", "{", "if", "(", "!", "$", "userAgent", ")", "{", "$", "userAgent", "=", "$", "this", "->", "getUserAgentByRequest", "(", ")", ";", "}", "$", "objectData", "=", "ArrayHel...
This method return UserAgentObject. @param null|string $userAgent You can set user-agent. If $userAgent will be null, user-agent will be uses default $_SERVER['HTTP_USER_AGENT'] @return UserAgentObject @throws \yii\base\InvalidConfigException
[ "This", "method", "return", "UserAgentObject", "." ]
train
https://github.com/nmdimas/yii2-user-agent-parser/blob/16573a7c3555a6debfe93177c266aa461614bb4f/UserAgentParser.php#L48-L59
accompli/accompli
src/Deployment/Connection/LocalConnectionAdapter.php
LocalConnectionAdapter.executeCommand
public function executeCommand($command, array $arguments = array()) { if (empty($arguments) === false) { $command = ProcessUtility::escapeArguments($arguments, $command); } $process = new Process($command); $process->run(); return new ProcessExecutionResult($process->getExitCode(), $process->getOutput(), strval($process->getErrorOutput())); }
php
public function executeCommand($command, array $arguments = array()) { if (empty($arguments) === false) { $command = ProcessUtility::escapeArguments($arguments, $command); } $process = new Process($command); $process->run(); return new ProcessExecutionResult($process->getExitCode(), $process->getOutput(), strval($process->getErrorOutput())); }
[ "public", "function", "executeCommand", "(", "$", "command", ",", "array", "$", "arguments", "=", "array", "(", ")", ")", "{", "if", "(", "empty", "(", "$", "arguments", ")", "===", "false", ")", "{", "$", "command", "=", "ProcessUtility", "::", "escap...
{@inheritdoc}
[ "{" ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/LocalConnectionAdapter.php#L83-L93
accompli/accompli
src/Deployment/Connection/LocalConnectionAdapter.php
LocalConnectionAdapter.changePermissions
public function changePermissions($remoteTarget, $fileMode, $recursive = false) { if ($recursive === true && $this->isDirectory($remoteTarget)) { $result = true; $directoryItems = $this->getDirectoryContentsList($remoteTarget); foreach ($directoryItems as $directoryItem) { $directoryItem = $remoteTarget.'/'.$directoryItem; if ($this->isDirectory($directoryItem)) { $result = ($result && $this->changePermissions($directoryItem, $fileMode, $recursive)); } else { $result = ($result && $this->changePermissions($directoryItem, $fileMode, false)); } } return ($result && $this->changePermissions($remoteTarget, $fileMode, false)); } return chmod($remoteTarget, $fileMode); }
php
public function changePermissions($remoteTarget, $fileMode, $recursive = false) { if ($recursive === true && $this->isDirectory($remoteTarget)) { $result = true; $directoryItems = $this->getDirectoryContentsList($remoteTarget); foreach ($directoryItems as $directoryItem) { $directoryItem = $remoteTarget.'/'.$directoryItem; if ($this->isDirectory($directoryItem)) { $result = ($result && $this->changePermissions($directoryItem, $fileMode, $recursive)); } else { $result = ($result && $this->changePermissions($directoryItem, $fileMode, false)); } } return ($result && $this->changePermissions($remoteTarget, $fileMode, false)); } return chmod($remoteTarget, $fileMode); }
[ "public", "function", "changePermissions", "(", "$", "remoteTarget", ",", "$", "fileMode", ",", "$", "recursive", "=", "false", ")", "{", "if", "(", "$", "recursive", "===", "true", "&&", "$", "this", "->", "isDirectory", "(", "$", "remoteTarget", ")", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/LocalConnectionAdapter.php#L170-L188
accompli/accompli
src/Deployment/Connection/LocalConnectionAdapter.php
LocalConnectionAdapter.delete
public function delete($remoteTarget, $recursive = false) { if ($recursive === true && $this->isDirectory($remoteTarget)) { $result = true; $directoryItems = $this->getDirectoryContentsList($remoteTarget); foreach ($directoryItems as $directoryItem) { $directoryItem = $remoteTarget.'/'.$directoryItem; if ($this->isDirectory($directoryItem)) { $result = ($result && $this->delete($directoryItem, $recursive)); } else { $result = ($result && $this->delete($directoryItem, false)); } } return ($result && $this->delete($remoteTarget, false)); } if ($this->isDirectory($remoteTarget) && $this->isLink($remoteTarget) === false) { return rmdir($remoteTarget); } return unlink($remoteTarget); }
php
public function delete($remoteTarget, $recursive = false) { if ($recursive === true && $this->isDirectory($remoteTarget)) { $result = true; $directoryItems = $this->getDirectoryContentsList($remoteTarget); foreach ($directoryItems as $directoryItem) { $directoryItem = $remoteTarget.'/'.$directoryItem; if ($this->isDirectory($directoryItem)) { $result = ($result && $this->delete($directoryItem, $recursive)); } else { $result = ($result && $this->delete($directoryItem, false)); } } return ($result && $this->delete($remoteTarget, false)); } if ($this->isDirectory($remoteTarget) && $this->isLink($remoteTarget) === false) { return rmdir($remoteTarget); } return unlink($remoteTarget); }
[ "public", "function", "delete", "(", "$", "remoteTarget", ",", "$", "recursive", "=", "false", ")", "{", "if", "(", "$", "recursive", "===", "true", "&&", "$", "this", "->", "isDirectory", "(", "$", "remoteTarget", ")", ")", "{", "$", "result", "=", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Connection/LocalConnectionAdapter.php#L211-L233
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.loadVocabulary
public function loadVocabulary() { $entities = $this->entityManager ->getStorage('taxonomy_vocabulary') ->loadByProperties(['machine_name' => self::VOCABULARY_MACHINE_NAME]); return reset($entities); }
php
public function loadVocabulary() { $entities = $this->entityManager ->getStorage('taxonomy_vocabulary') ->loadByProperties(['machine_name' => self::VOCABULARY_MACHINE_NAME]); return reset($entities); }
[ "public", "function", "loadVocabulary", "(", ")", "{", "$", "entities", "=", "$", "this", "->", "entityManager", "->", "getStorage", "(", "'taxonomy_vocabulary'", ")", "->", "loadByProperties", "(", "[", "'machine_name'", "=>", "self", "::", "VOCABULARY_MACHINE_NA...
Load the labels vocabulary. @return stdClass
[ "Load", "the", "labels", "vocabulary", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L50-L57
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.isRootLabel
public function isRootLabel(\stdClass $label) { $q = $this->db ->select('taxonomy_term_hierarchy', 'h') ->condition('h.parent', 0) ->condition('h.tid', $label->tid) ->fields('h', array('tid')) ->range(0, 1) ->execute(); return !empty($q->fetch()); }
php
public function isRootLabel(\stdClass $label) { $q = $this->db ->select('taxonomy_term_hierarchy', 'h') ->condition('h.parent', 0) ->condition('h.tid', $label->tid) ->fields('h', array('tid')) ->range(0, 1) ->execute(); return !empty($q->fetch()); }
[ "public", "function", "isRootLabel", "(", "\\", "stdClass", "$", "label", ")", "{", "$", "q", "=", "$", "this", "->", "db", "->", "select", "(", "'taxonomy_term_hierarchy'", ",", "'h'", ")", "->", "condition", "(", "'h.parent'", ",", "0", ")", "->", "c...
Is the label a root term? @param stdClass $label @return boolean
[ "Is", "the", "label", "a", "root", "term?" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L155-L166
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.saveLabel
public function saveLabel(\stdClass $label) { if (!empty($label->tid)) { // Prevents to save a label with a parent if it has children. // The labels vocabulary must have only two levels. if (!isset($label->original)) { $label->original = $this->entityManager->getStorage('taxonomy_term')->loadUnchanged($label->tid); } if (!isset($label->original->parent)) { $label->original->parent = 0; } if ($this->hasChildren($label) && $label->parent != $label->original->parent) { throw new \LogicException("Can't define a parent to a label which has children."); } } return taxonomy_term_save($label); }
php
public function saveLabel(\stdClass $label) { if (!empty($label->tid)) { // Prevents to save a label with a parent if it has children. // The labels vocabulary must have only two levels. if (!isset($label->original)) { $label->original = $this->entityManager->getStorage('taxonomy_term')->loadUnchanged($label->tid); } if (!isset($label->original->parent)) { $label->original->parent = 0; } if ($this->hasChildren($label) && $label->parent != $label->original->parent) { throw new \LogicException("Can't define a parent to a label which has children."); } } return taxonomy_term_save($label); }
[ "public", "function", "saveLabel", "(", "\\", "stdClass", "$", "label", ")", "{", "if", "(", "!", "empty", "(", "$", "label", "->", "tid", ")", ")", "{", "// Prevents to save a label with a parent if it has children.", "// The labels vocabulary must have only two levels...
Save the label. @return integer Constant SAVED_NEW or SAVED_UPDATED. @throws \LogicException @see taxonomy_term_save().
[ "Save", "the", "label", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L176-L193
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.deleteLabel
public function deleteLabel(\stdClass $label) { // Prevents to delete a label which has children. if ($this->hasChildren($label)) { throw new \LogicException("Can't delete a label which has children."); } return taxonomy_term_delete($label->tid); }
php
public function deleteLabel(\stdClass $label) { // Prevents to delete a label which has children. if ($this->hasChildren($label)) { throw new \LogicException("Can't delete a label which has children."); } return taxonomy_term_delete($label->tid); }
[ "public", "function", "deleteLabel", "(", "\\", "stdClass", "$", "label", ")", "{", "// Prevents to delete a label which has children.", "if", "(", "$", "this", "->", "hasChildren", "(", "$", "label", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", ...
Delete the label. @return integer Constant SAVED_DELETED if no exception occurs. @throws \LogicException @see taxonomy_term_delete().
[ "Delete", "the", "label", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L203-L210
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.canEditLabel
public function canEditLabel(\stdClass $label, AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return ($label->is_locked == 0) ? user_access(LabelAccess::PERM_EDIT_NON_LOCKED, $account) : user_access(LabelAccess::PERM_EDIT_LOCKED, $account); }
php
public function canEditLabel(\stdClass $label, AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return ($label->is_locked == 0) ? user_access(LabelAccess::PERM_EDIT_NON_LOCKED, $account) : user_access(LabelAccess::PERM_EDIT_LOCKED, $account); }
[ "public", "function", "canEditLabel", "(", "\\", "stdClass", "$", "label", ",", "AccountInterface", "$", "account", "=", "null", ")", "{", "if", "(", "$", "account", "===", "null", ")", "{", "global", "$", "user", ";", "$", "account", "=", "$", "user",...
Is the user allowed to edit the given label? @param stdClass $label @param AccountInterface $account @return boolean
[ "Is", "the", "user", "allowed", "to", "edit", "the", "given", "label?" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L220-L230
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.canEditAllLabels
public function canEditAllLabels(AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return ( user_access(LabelAccess::PERM_EDIT_NON_LOCKED, $account) && user_access(LabelAccess::PERM_EDIT_LOCKED, $account) ); }
php
public function canEditAllLabels(AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return ( user_access(LabelAccess::PERM_EDIT_NON_LOCKED, $account) && user_access(LabelAccess::PERM_EDIT_LOCKED, $account) ); }
[ "public", "function", "canEditAllLabels", "(", "AccountInterface", "$", "account", "=", "null", ")", "{", "if", "(", "$", "account", "===", "null", ")", "{", "global", "$", "user", ";", "$", "account", "=", "$", "user", ";", "}", "return", "(", "user_a...
Is the user allowed to edit all labels (i.e. locked and non locked labels)? @param AccountInterface $account @return boolean
[ "Is", "the", "user", "allowed", "to", "edit", "all", "labels", "(", "i", ".", "e", ".", "locked", "and", "non", "locked", "labels", ")", "?" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L239-L250
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.canEditLockedLabels
public function canEditLockedLabels(AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return user_access(LabelAccess::PERM_EDIT_LOCKED, $account); }
php
public function canEditLockedLabels(AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return user_access(LabelAccess::PERM_EDIT_LOCKED, $account); }
[ "public", "function", "canEditLockedLabels", "(", "AccountInterface", "$", "account", "=", "null", ")", "{", "if", "(", "$", "account", "===", "null", ")", "{", "global", "$", "user", ";", "$", "account", "=", "$", "user", ";", "}", "return", "user_acces...
Is the user allowed to edit locked labels? @param AccountInterface $account @return boolean
[ "Is", "the", "user", "allowed", "to", "edit", "locked", "labels?" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L259-L267
makinacorpus/drupal-ucms
ucms_label/src/LabelManager.php
LabelManager.canEditNonLockedLabels
public function canEditNonLockedLabels(AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return user_access(LabelAccess::PERM_EDIT_NON_LOCKED, $account); }
php
public function canEditNonLockedLabels(AccountInterface $account = null) { if ($account === null) { global $user; $account = $user; } return user_access(LabelAccess::PERM_EDIT_NON_LOCKED, $account); }
[ "public", "function", "canEditNonLockedLabels", "(", "AccountInterface", "$", "account", "=", "null", ")", "{", "if", "(", "$", "account", "===", "null", ")", "{", "global", "$", "user", ";", "$", "account", "=", "$", "user", ";", "}", "return", "user_ac...
Is the user allowed to edit non locked labels? @param AccountInterface $account @return boolean
[ "Is", "the", "user", "allowed", "to", "edit", "non", "locked", "labels?" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/LabelManager.php#L276-L284
accompli/accompli
src/Deployment/Host.php
Host.isValidStage
public static function isValidStage($stage) { return in_array($stage, array(self::STAGE_TEST, self::STAGE_ACCEPTANCE, self::STAGE_PRODUCTION)); }
php
public static function isValidStage($stage) { return in_array($stage, array(self::STAGE_TEST, self::STAGE_ACCEPTANCE, self::STAGE_PRODUCTION)); }
[ "public", "static", "function", "isValidStage", "(", "$", "stage", ")", "{", "return", "in_array", "(", "$", "stage", ",", "array", "(", "self", "::", "STAGE_TEST", ",", "self", "::", "STAGE_ACCEPTANCE", ",", "self", "::", "STAGE_PRODUCTION", ")", ")", ";"...
Returns true if $stage is a valid stage type. @param string $stage @return bool
[ "Returns", "true", "if", "$stage", "is", "a", "valid", "stage", "type", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Deployment/Host.php#L189-L192
makinacorpus/drupal-ucms
ucms_search/src/Aggs/TermFacet.php
TermFacet.getFormattedChoices
public function getFormattedChoices() { $ret = []; $loaded = []; // Populate the raw formatted array with just values as values foreach (array_keys($this->choices) as $value) { $ret[$value] = $value; } // First start with arbitrarily set choices map if ($this->choicesMap) { $loaded = array_intersect_key($this->choicesMap, $ret); } // Execute the user given callback if ($this->choicesCallback) { $callbackLoaded = call_user_func( $this->choicesCallback, // Exclude already loaded items to leave the choices map // having precedence over the callback array_diff_key($ret, $loaded) ); // We are forced to proceed to a two step merge (using foreach) // else array_merge() as well as the + operator would terribly // fail merging integer keys if ($callbackLoaded) { foreach ($callbackLoaded as $value => $title) { $loaded[$value] = $title; } } } // Append the count for each value foreach ($this->choices as $value => $count) { $append = ' <span class="badge">' . $count . '</span>'; if (isset($loaded[$value])) { $ret[$value] = $loaded[$value] . $append; } elseif(!$this->exclusiveMode) { $ret[$value] .= $append; } else { unset($ret[$value]); } } return $ret; }
php
public function getFormattedChoices() { $ret = []; $loaded = []; // Populate the raw formatted array with just values as values foreach (array_keys($this->choices) as $value) { $ret[$value] = $value; } // First start with arbitrarily set choices map if ($this->choicesMap) { $loaded = array_intersect_key($this->choicesMap, $ret); } // Execute the user given callback if ($this->choicesCallback) { $callbackLoaded = call_user_func( $this->choicesCallback, // Exclude already loaded items to leave the choices map // having precedence over the callback array_diff_key($ret, $loaded) ); // We are forced to proceed to a two step merge (using foreach) // else array_merge() as well as the + operator would terribly // fail merging integer keys if ($callbackLoaded) { foreach ($callbackLoaded as $value => $title) { $loaded[$value] = $title; } } } // Append the count for each value foreach ($this->choices as $value => $count) { $append = ' <span class="badge">' . $count . '</span>'; if (isset($loaded[$value])) { $ret[$value] = $loaded[$value] . $append; } elseif(!$this->exclusiveMode) { $ret[$value] .= $append; } else { unset($ret[$value]); } } return $ret; }
[ "public", "function", "getFormattedChoices", "(", ")", "{", "$", "ret", "=", "[", "]", ";", "$", "loaded", "=", "[", "]", ";", "// Populate the raw formatted array with just values as values", "foreach", "(", "array_keys", "(", "$", "this", "->", "choices", ")",...
Get formatter list of choices after query @return string[]
[ "Get", "formatter", "list", "of", "choices", "after", "query" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Aggs/TermFacet.php#L151-L200
makinacorpus/drupal-ucms
ucms_search/src/Aggs/TermFacet.php
TermFacet.parseResponse
public function parseResponse(Search $search, Response $response, $raw) { $choices = []; $name = $this->getParameterName(); if (!isset($raw['aggregations'][$name])) { throw new \RuntimeException(sprintf("Aggregation '%s' is missing from response", $name)); } foreach ($raw['aggregations'][$name]['buckets'] as $bucket) { $choices[$bucket['key']] = $bucket['doc_count']; } $this->setChoices($choices); }
php
public function parseResponse(Search $search, Response $response, $raw) { $choices = []; $name = $this->getParameterName(); if (!isset($raw['aggregations'][$name])) { throw new \RuntimeException(sprintf("Aggregation '%s' is missing from response", $name)); } foreach ($raw['aggregations'][$name]['buckets'] as $bucket) { $choices[$bucket['key']] = $bucket['doc_count']; } $this->setChoices($choices); }
[ "public", "function", "parseResponse", "(", "Search", "$", "search", ",", "Response", "$", "response", ",", "$", "raw", ")", "{", "$", "choices", "=", "[", "]", ";", "$", "name", "=", "$", "this", "->", "getParameterName", "(", ")", ";", "if", "(", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Aggs/TermFacet.php#L216-L231
fogs/tagging-bundle
Controller/DefaultController.php
DefaultController.searchAction
public function searchAction($query) { $tags = $this->get('fpn_tag.tag_manager')->findTags($query); $tags = array_map(function ($value) { return $value['name']; }, $tags); return new JsonResponse($tags); }
php
public function searchAction($query) { $tags = $this->get('fpn_tag.tag_manager')->findTags($query); $tags = array_map(function ($value) { return $value['name']; }, $tags); return new JsonResponse($tags); }
[ "public", "function", "searchAction", "(", "$", "query", ")", "{", "$", "tags", "=", "$", "this", "->", "get", "(", "'fpn_tag.tag_manager'", ")", "->", "findTags", "(", "$", "query", ")", ";", "$", "tags", "=", "array_map", "(", "function", "(", "$", ...
Search for tags @Route("/{query}", name="tags_search", defaults={"query" = ""}) @Method("GET")
[ "Search", "for", "tags" ]
train
https://github.com/fogs/tagging-bundle/blob/1541b7f80462ed6fc0136f72dcbab67790ff17b6/Controller/DefaultController.php#L25-L32
despark/ignicms
src/Video/Provider.php
Provider.toHtml
public function toHtml(bool $preview = false) { $html = ''; if ($preview) { if ($this->getImageUrl()) { $html = "<img src='{$this->getImageUrl()}' style='max-width: 100%;' />"; } } if ($this->getVideoUrl()) { $html = "<iframe src='{$this->getVideoUrl()}' frameborder='0' allowfullscreen></iframe>"; } return $html; }
php
public function toHtml(bool $preview = false) { $html = ''; if ($preview) { if ($this->getImageUrl()) { $html = "<img src='{$this->getImageUrl()}' style='max-width: 100%;' />"; } } if ($this->getVideoUrl()) { $html = "<iframe src='{$this->getVideoUrl()}' frameborder='0' allowfullscreen></iframe>"; } return $html; }
[ "public", "function", "toHtml", "(", "bool", "$", "preview", "=", "false", ")", "{", "$", "html", "=", "''", ";", "if", "(", "$", "preview", ")", "{", "if", "(", "$", "this", "->", "getImageUrl", "(", ")", ")", "{", "$", "html", "=", "\"<img src=...
@param bool $preview @return mixed
[ "@param", "bool", "$preview" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Video/Provider.php#L38-L51
makinacorpus/drupal-ucms
ucms_user/src/Form/UserChangeEmail.php
UserChangeEmail.buildForm
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = null) { if ($user === null) { return []; } $form_state->setTemporaryValue('user', $user); $form['#form_horizontal'] = true; $form['mail'] = array( '#type' => 'textfield', '#title' => $this->t('Email'), '#default_value' => $user->getEmail(), '#maxlength' => EMAIL_MAX_LENGTH, '#required' => true, ); $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t('Save'), ); return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = null) { if ($user === null) { return []; } $form_state->setTemporaryValue('user', $user); $form['#form_horizontal'] = true; $form['mail'] = array( '#type' => 'textfield', '#title' => $this->t('Email'), '#default_value' => $user->getEmail(), '#maxlength' => EMAIL_MAX_LENGTH, '#required' => true, ); $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t('Save'), ); return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "UserInterface", "$", "user", "=", "null", ")", "{", "if", "(", "$", "user", "===", "null", ")", "{", "return", "[", "]", ";", "}", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserChangeEmail.php#L62-L87
makinacorpus/drupal-ucms
ucms_user/src/Form/UserChangeEmail.php
UserChangeEmail.validateForm
public function validateForm(array &$form, FormStateInterface $form_state) { // Trim whitespace from mail, to prevent confusing 'e-mail not valid' // warnings often caused by cutting and pasting. $mail = $form_state->getValue('mail'); $mail = trim($mail); $form_state->setValue('mail', $mail); // Validate the e-mail address, and check if it is taken by an existing user. if ($error = user_validate_mail($mail)) { $form_state->setErrorByName('mail', $error); } else { /* @var UserInterface $user */ $user = $form_state->getTemporaryValue('user'); $q = db_select('users') ->fields('users', array('uid')) ->condition('mail', db_like($mail), 'LIKE') ->condition('uid', $user->id(), '<>') ->range(0, 1); if ((bool) $q->execute()->fetchField()) { form_set_error('mail', $this->t('The e-mail address %email is already taken.', array('%email' => $mail))); } } }
php
public function validateForm(array &$form, FormStateInterface $form_state) { // Trim whitespace from mail, to prevent confusing 'e-mail not valid' // warnings often caused by cutting and pasting. $mail = $form_state->getValue('mail'); $mail = trim($mail); $form_state->setValue('mail', $mail); // Validate the e-mail address, and check if it is taken by an existing user. if ($error = user_validate_mail($mail)) { $form_state->setErrorByName('mail', $error); } else { /* @var UserInterface $user */ $user = $form_state->getTemporaryValue('user'); $q = db_select('users') ->fields('users', array('uid')) ->condition('mail', db_like($mail), 'LIKE') ->condition('uid', $user->id(), '<>') ->range(0, 1); if ((bool) $q->execute()->fetchField()) { form_set_error('mail', $this->t('The e-mail address %email is already taken.', array('%email' => $mail))); } } }
[ "public", "function", "validateForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "// Trim whitespace from mail, to prevent confusing 'e-mail not valid'", "// warnings often caused by cutting and pasting.", "$", "mail", "=", "$", "f...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserChangeEmail.php#L93-L119
makinacorpus/drupal-ucms
ucms_user/src/Form/UserChangeEmail.php
UserChangeEmail.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { /* @var $user UserInterface */ $user = $form_state->getTemporaryValue('user'); $user->setEmail($form_state->getValue('mail')); $saved = $this->entityManager->getStorage('user')->save($user); if ($saved) { drupal_set_message($this->t("@name's email address has been changed.", array('@name' => $user->name))); $this->dispatcher->dispatch('user:change_email', new UserEvent($user->uid, $this->currentUser()->id())); } else { drupal_set_message($this->t("An error occured. Please try again."), 'error'); } $form_state->setRedirect('admin/dashboard/user'); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { /* @var $user UserInterface */ $user = $form_state->getTemporaryValue('user'); $user->setEmail($form_state->getValue('mail')); $saved = $this->entityManager->getStorage('user')->save($user); if ($saved) { drupal_set_message($this->t("@name's email address has been changed.", array('@name' => $user->name))); $this->dispatcher->dispatch('user:change_email', new UserEvent($user->uid, $this->currentUser()->id())); } else { drupal_set_message($this->t("An error occured. Please try again."), 'error'); } $form_state->setRedirect('admin/dashboard/user'); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "/* @var $user UserInterface */", "$", "user", "=", "$", "form_state", "->", "getTemporaryValue", "(", "'user'", ")", ";", "$", "user", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserChangeEmail.php#L125-L141
aimeos/ai-admin-extadm
controller/jobs/src/Controller/Jobs/Admin/Job/Standard.php
Standard.run
public function run() { $context = $this->getContext(); $jobManager = \Aimeos\MAdmin\Job\Manager\Factory::createManager( $context ); $criteria = $jobManager->createSearch( true ); $start = 0; do { $items = $jobManager->searchItems( $criteria ); foreach( $items as $item ) { try { $job = $item->getMethod(); if( preg_match( '/^[a-zA-Z0-9\_]+\.[a-zA-Z0-9\_]+$/', $job ) !== 1 ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid characters in job name "%1$s"', $job ) ); } $parts = explode( '.', $job ); if( count( $parts ) !== 2 ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid job method "%1$s"', $job ) ); } $method = $parts[1]; $class = str_replace( '_', '\\', $parts[0] ); $name = '\\Aimeos\\Controller\\ExtJS\\' . $class . '\\Factory'; if( class_exists( $name ) === false ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Class "%1$s" not available', $name ) ); } $name .= '::createController'; if( ( $controller = call_user_func_array( $name, array( $context ) ) ) === false ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Unable to call factory method "%1$s"', $name ) ); } if( method_exists( $controller, $method ) === false ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Method "%1$s" not available', $method ) ); } $result = $controller->$method( (object) $item->getParameter() ); $item->setResult( $result ); $item->setStatus( -1 ); } catch( \Exception $e ) { $str = 'Error while processing job "%1$s": %2$s'; $context->getLogger()->log( sprintf( $str, $item->getMethod(), $e->getMessage() ) ); $item->setStatus( 0 ); } $jobManager->saveItem( $item, false ); } $count = count( $items ); $start += $count; $criteria->setSlice( $start ); } while( $count > 0 ); }
php
public function run() { $context = $this->getContext(); $jobManager = \Aimeos\MAdmin\Job\Manager\Factory::createManager( $context ); $criteria = $jobManager->createSearch( true ); $start = 0; do { $items = $jobManager->searchItems( $criteria ); foreach( $items as $item ) { try { $job = $item->getMethod(); if( preg_match( '/^[a-zA-Z0-9\_]+\.[a-zA-Z0-9\_]+$/', $job ) !== 1 ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid characters in job name "%1$s"', $job ) ); } $parts = explode( '.', $job ); if( count( $parts ) !== 2 ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid job method "%1$s"', $job ) ); } $method = $parts[1]; $class = str_replace( '_', '\\', $parts[0] ); $name = '\\Aimeos\\Controller\\ExtJS\\' . $class . '\\Factory'; if( class_exists( $name ) === false ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Class "%1$s" not available', $name ) ); } $name .= '::createController'; if( ( $controller = call_user_func_array( $name, array( $context ) ) ) === false ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Unable to call factory method "%1$s"', $name ) ); } if( method_exists( $controller, $method ) === false ) { throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Method "%1$s" not available', $method ) ); } $result = $controller->$method( (object) $item->getParameter() ); $item->setResult( $result ); $item->setStatus( -1 ); } catch( \Exception $e ) { $str = 'Error while processing job "%1$s": %2$s'; $context->getLogger()->log( sprintf( $str, $item->getMethod(), $e->getMessage() ) ); $item->setStatus( 0 ); } $jobManager->saveItem( $item, false ); } $count = count( $items ); $start += $count; $criteria->setSlice( $start ); } while( $count > 0 ); }
[ "public", "function", "run", "(", ")", "{", "$", "context", "=", "$", "this", "->", "getContext", "(", ")", ";", "$", "jobManager", "=", "\\", "Aimeos", "\\", "MAdmin", "\\", "Job", "\\", "Manager", "\\", "Factory", "::", "createManager", "(", "$", "...
Executes the job. @throws \Aimeos\Controller\Jobs\Exception If an error occurs
[ "Executes", "the", "job", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/jobs/src/Controller/Jobs/Admin/Job/Standard.php#L52-L119
PHPixie/HTTP
src/PHPixie/HTTP/Context/Cookies/Update.php
Update.asHeader
public function asHeader() { $header = urlencode($this->name).'='.urlencode((string) $this->value); if($this->domain !== null) { $header.= '; domain='.$this->domain; } if($this->path !== null) { $header.= '; path='.$this->path; } if($this->expires !== null) { $header.= '; expires=' . gmdate('D, d-M-Y H:i:s e', $this->expires); } if($this->secure) { $header.= '; secure'; } if($this->httpOnly) { $header.= '; HttpOnly'; } return $header; }
php
public function asHeader() { $header = urlencode($this->name).'='.urlencode((string) $this->value); if($this->domain !== null) { $header.= '; domain='.$this->domain; } if($this->path !== null) { $header.= '; path='.$this->path; } if($this->expires !== null) { $header.= '; expires=' . gmdate('D, d-M-Y H:i:s e', $this->expires); } if($this->secure) { $header.= '; secure'; } if($this->httpOnly) { $header.= '; HttpOnly'; } return $header; }
[ "public", "function", "asHeader", "(", ")", "{", "$", "header", "=", "urlencode", "(", "$", "this", "->", "name", ")", ".", "'='", ".", "urlencode", "(", "(", "string", ")", "$", "this", "->", "value", ")", ";", "if", "(", "$", "this", "->", "dom...
Get header representation @return string
[ "Get", "header", "representation" ]
train
https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP/Context/Cookies/Update.php#L141-L166
qloog/yaf-library
src/Captcha/Captcha.php
Captcha.generate
public function generate() { $this->img = imagecreatetruecolor($this->width, $this->height); $white = imagecolorallocate($this->img, 250, 250, 255); imagefill($this->img, 0, 0, $white); $xBase = intval($this->width / 8); $yBase = intval($this->height / 8); // 添加干扰线和文字 $offset = 0; for($i = 0; $i < $this->len; $i++) { $color = imagecolorallocate($this->img, mt_rand(0, 100), mt_rand(20, 120), mt_rand(50, 150)); $offset += mt_rand(12, $xBase * 2); // imagestring($this->img, 4, $offset, mt_rand(0, $yBase * 6), $this->code[$i], $color); imagettftext($this->img, mt_rand(14, 20), mt_rand(-20, 20), $offset, max(20, mt_rand($yBase * 3, $yBase * 7)), $color, $this->font, $this->code[$i]); // 添加同色干扰弧线 if ($i < 3) { // imageline($this->img, mt_rand(0, $xBase), mt_rand(0, $this->height), mt_rand($xBase * 6, $this->width), mt_rand($yBase, $this->height), $color); imagearc($this->img, mt_rand($xBase, $this->width), mt_rand(0, $yBase * 4), $this->width, $yBase * 4, mt_rand(0, 45), mt_rand(90, 200), $color); } } ob_clean(); header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Pragma: no-cache'); header('Cache-control: private'); header('Content-Type: image/png'); imagepng($this->img); imagedestroy($this->img); }
php
public function generate() { $this->img = imagecreatetruecolor($this->width, $this->height); $white = imagecolorallocate($this->img, 250, 250, 255); imagefill($this->img, 0, 0, $white); $xBase = intval($this->width / 8); $yBase = intval($this->height / 8); // 添加干扰线和文字 $offset = 0; for($i = 0; $i < $this->len; $i++) { $color = imagecolorallocate($this->img, mt_rand(0, 100), mt_rand(20, 120), mt_rand(50, 150)); $offset += mt_rand(12, $xBase * 2); // imagestring($this->img, 4, $offset, mt_rand(0, $yBase * 6), $this->code[$i], $color); imagettftext($this->img, mt_rand(14, 20), mt_rand(-20, 20), $offset, max(20, mt_rand($yBase * 3, $yBase * 7)), $color, $this->font, $this->code[$i]); // 添加同色干扰弧线 if ($i < 3) { // imageline($this->img, mt_rand(0, $xBase), mt_rand(0, $this->height), mt_rand($xBase * 6, $this->width), mt_rand($yBase, $this->height), $color); imagearc($this->img, mt_rand($xBase, $this->width), mt_rand(0, $yBase * 4), $this->width, $yBase * 4, mt_rand(0, 45), mt_rand(90, 200), $color); } } ob_clean(); header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Pragma: no-cache'); header('Cache-control: private'); header('Content-Type: image/png'); imagepng($this->img); imagedestroy($this->img); }
[ "public", "function", "generate", "(", ")", "{", "$", "this", "->", "img", "=", "imagecreatetruecolor", "(", "$", "this", "->", "width", ",", "$", "this", "->", "height", ")", ";", "$", "white", "=", "imagecolorallocate", "(", "$", "this", "->", "img",...
生成验证码字符串并输出
[ "生成验证码字符串并输出" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Captcha/Captcha.php#L87-L120
makinacorpus/drupal-ucms
ucms_notification/src/EventDispatcher/ContextPaneEventSubscriber.php
ContextPaneEventSubscriber.onContextPaneInit
public function onContextPaneInit(ContextPaneEvent $event) { $contextPane = $event->getContextPane(); $subscriber = $this->notificationService->getSubscriber($this->currentUser->id()); $limit = 10; $cursor = $subscriber ->fetch() ->addSort(Field::MSG_SENT, CursorInterface::SORT_DESC) ->addSort(Field::MSG_ID, CursorInterface::SORT_DESC) ->setRange($limit, 0) ; $unreadCount = $subscriber->fetch([Field::MSG_UNREAD => 1])->count(); $contextPane ->addTab('notification', $this->t("Notifications"), 'bell', 0, $unreadCount) ->add( notification_block_render_messages($cursor, true), // @todo hardcoded funtion call, twig template would have been better 'notification' ) ; // Set default tab on dashboard if (current_path() == 'admin/dashboard') { $contextPane->setDefaultTab('notification'); } }
php
public function onContextPaneInit(ContextPaneEvent $event) { $contextPane = $event->getContextPane(); $subscriber = $this->notificationService->getSubscriber($this->currentUser->id()); $limit = 10; $cursor = $subscriber ->fetch() ->addSort(Field::MSG_SENT, CursorInterface::SORT_DESC) ->addSort(Field::MSG_ID, CursorInterface::SORT_DESC) ->setRange($limit, 0) ; $unreadCount = $subscriber->fetch([Field::MSG_UNREAD => 1])->count(); $contextPane ->addTab('notification', $this->t("Notifications"), 'bell', 0, $unreadCount) ->add( notification_block_render_messages($cursor, true), // @todo hardcoded funtion call, twig template would have been better 'notification' ) ; // Set default tab on dashboard if (current_path() == 'admin/dashboard') { $contextPane->setDefaultTab('notification'); } }
[ "public", "function", "onContextPaneInit", "(", "ContextPaneEvent", "$", "event", ")", "{", "$", "contextPane", "=", "$", "event", "->", "getContextPane", "(", ")", ";", "$", "subscriber", "=", "$", "this", "->", "notificationService", "->", "getSubscriber", "...
Event: On ContextPane init. @param ContextPaneEvent $event
[ "Event", ":", "On", "ContextPane", "init", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_notification/src/EventDispatcher/ContextPaneEventSubscriber.php#L64-L92
NicolasMahe/Laravel-SlackOutput
src/Library/Stats.php
Stats.getClasses
protected function getClasses() { $classes = config('slack-output.stats.classes'); //force classes to have the right format $sanitized_classes = [ ]; foreach ($classes as $classes_name => $constraints) { //check constraints are supplied, if not, correct //the classes name with the right value if (is_int($classes_name)) { $classes_name = $constraints; $constraints = [ ]; } $sanitized_classes[$classes_name] = $constraints; } return $sanitized_classes; }
php
protected function getClasses() { $classes = config('slack-output.stats.classes'); //force classes to have the right format $sanitized_classes = [ ]; foreach ($classes as $classes_name => $constraints) { //check constraints are supplied, if not, correct //the classes name with the right value if (is_int($classes_name)) { $classes_name = $constraints; $constraints = [ ]; } $sanitized_classes[$classes_name] = $constraints; } return $sanitized_classes; }
[ "protected", "function", "getClasses", "(", ")", "{", "$", "classes", "=", "config", "(", "'slack-output.stats.classes'", ")", ";", "//force classes to have the right format", "$", "sanitized_classes", "=", "[", "]", ";", "foreach", "(", "$", "classes", "as", "$",...
Get the classes and sanitized them @return array
[ "Get", "the", "classes", "and", "sanitized", "them" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Library/Stats.php#L37-L55
NicolasMahe/Laravel-SlackOutput
src/Library/Stats.php
Stats.calculateStats
public function calculateStats() { $classes = $this->getClasses(); $dates = $this->getDates(); //explore all class to stated foreach ($classes as $objectClass => $constraints) { //prepare useful data $stats_fields = [ ]; $objectName = last(explode('\\', $objectClass)); //explore each date to count from foreach ($dates as $dateName => $date) { //create the sql request $sql = $objectClass::where('created_at', '>=', $date->toDateTimeString()); //taking into account the constraint foreach ($constraints as $constraintName => $constraintValue) { $sql = $sql->where($constraintName, $constraintValue); } //count ! $count = $sql->count(); //set count $stats_fields[] = [ "since" => $dateName, "value" => $count ]; } //add to stats array $this->stats[] = [ 'name' => $objectName, 'values' => $stats_fields ]; } }
php
public function calculateStats() { $classes = $this->getClasses(); $dates = $this->getDates(); //explore all class to stated foreach ($classes as $objectClass => $constraints) { //prepare useful data $stats_fields = [ ]; $objectName = last(explode('\\', $objectClass)); //explore each date to count from foreach ($dates as $dateName => $date) { //create the sql request $sql = $objectClass::where('created_at', '>=', $date->toDateTimeString()); //taking into account the constraint foreach ($constraints as $constraintName => $constraintValue) { $sql = $sql->where($constraintName, $constraintValue); } //count ! $count = $sql->count(); //set count $stats_fields[] = [ "since" => $dateName, "value" => $count ]; } //add to stats array $this->stats[] = [ 'name' => $objectName, 'values' => $stats_fields ]; } }
[ "public", "function", "calculateStats", "(", ")", "{", "$", "classes", "=", "$", "this", "->", "getClasses", "(", ")", ";", "$", "dates", "=", "$", "this", "->", "getDates", "(", ")", ";", "//explore all class to stated", "foreach", "(", "$", "classes", ...
Do the stats!
[ "Do", "the", "stats!" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Library/Stats.php#L72-L110
NicolasMahe/Laravel-SlackOutput
src/Library/Stats.php
Stats.prepareSlackAttachment
protected function prepareSlackAttachment() { $attachments = [ ]; foreach ($this->stats as $stats) { $name = $stats['name']; $fields = [ ]; foreach ($stats['values'] as $stat) { $count = $stat['value']; $since = $stat['since']; $fields[] = [ "title" => "Since " . $since, "value" => $count, "short" => true ]; } $attachments[] = [ 'color' => 'grey', "title" => "New " . $name . "s", "fields" => $fields ]; } return $attachments; }
php
protected function prepareSlackAttachment() { $attachments = [ ]; foreach ($this->stats as $stats) { $name = $stats['name']; $fields = [ ]; foreach ($stats['values'] as $stat) { $count = $stat['value']; $since = $stat['since']; $fields[] = [ "title" => "Since " . $since, "value" => $count, "short" => true ]; } $attachments[] = [ 'color' => 'grey', "title" => "New " . $name . "s", "fields" => $fields ]; } return $attachments; }
[ "protected", "function", "prepareSlackAttachment", "(", ")", "{", "$", "attachments", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "stats", "as", "$", "stats", ")", "{", "$", "name", "=", "$", "stats", "[", "'name'", "]", ";", "$", "fields"...
Transform the stats array to a slack attachment
[ "Transform", "the", "stats", "array", "to", "a", "slack", "attachment" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Library/Stats.php#L116-L144
NicolasMahe/Laravel-SlackOutput
src/Library/Stats.php
Stats.sendToSlack
public function sendToSlack($channel) { $attachments = $this->prepareSlackAttachment(); Artisan::call('slack:post', [ 'to' => $channel, 'attach' => $attachments, 'message' => "Stats of the " . Carbon::now()->toFormattedDateString() ]); }
php
public function sendToSlack($channel) { $attachments = $this->prepareSlackAttachment(); Artisan::call('slack:post', [ 'to' => $channel, 'attach' => $attachments, 'message' => "Stats of the " . Carbon::now()->toFormattedDateString() ]); }
[ "public", "function", "sendToSlack", "(", "$", "channel", ")", "{", "$", "attachments", "=", "$", "this", "->", "prepareSlackAttachment", "(", ")", ";", "Artisan", "::", "call", "(", "'slack:post'", ",", "[", "'to'", "=>", "$", "channel", ",", "'attach'", ...
Send the stats to output @param $channel
[ "Send", "the", "stats", "to", "output" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Library/Stats.php#L152-L161
alexandresalome/pagination
Adapter/GitlibLogAdapter.php
GitlibLogAdapter.get
public function get($offset, $limit) { $this->log->setOffset($offset); $this->log->setLimit($limit); return $this->log->getCommits(); }
php
public function get($offset, $limit) { $this->log->setOffset($offset); $this->log->setLimit($limit); return $this->log->getCommits(); }
[ "public", "function", "get", "(", "$", "offset", ",", "$", "limit", ")", "{", "$", "this", "->", "log", "->", "setOffset", "(", "$", "offset", ")", ";", "$", "this", "->", "log", "->", "setLimit", "(", "$", "limit", ")", ";", "return", "$", "this...
{@inheritdoc}
[ "{" ]
train
https://github.com/alexandresalome/pagination/blob/bef7e290a8514baf418a57f52c879528779d75d1/Adapter/GitlibLogAdapter.php#L32-L38
micschk/silverstripe-chunkeduploadfield
code/ChunkedUploadField.php
ChunkedUploadField.upload
public function upload(SS_HTTPRequest $request) { if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) { return $this->httpError(403); } // Protect against CSRF on destructive action $token = $this->getForm()->getSecurityToken(); if (!$token->checkRequest($request)) { return $this->httpError(400); } // Get form details (name of the relation) $name = $this->getName(); $postVars = $request->postVar($name); $uploadedFiles = $this->extractUploadedFileData($postVars); $return = array(); // // append all multiparts to one file here before proceeding // if ($request->getHeader('X-File-Name')) { // if chunked, get name from header //return Debug::dump($request->getHeader('X-File-Name')); $originalFileName = $request->getHeader('X-File-Name'); $totalSize = $request->getHeader('X-File-Size'); $uploadedChunkPath = $uploadedFiles[0]['tmp_name']; // We (mis)use the security ID as a way of 'unique-ifying' the temporary upload paths // so that we don't just depend on the original filename for this (or a scenario might // be possible to overwrite files based on an identical original name) // Added benefit it that the security ID will be different between form loads, which // makes the risk of appending to the same file over and over, a bit smaller $securityID = ($request->postVar('SecurityID')? $request->postVar('SecurityID'): 'none'); // hash to prevent directory traversal etc posibilities based on original file name $temphash = sha1($securityID.$originalFileName); // eg /tmp/123somelonghash456 instead of $originalFileName.'.part' $tmpFilePath = dirname($uploadedChunkPath).DIRECTORY_SEPARATOR.$temphash; $append = file_exists($tmpFilePath); // If it is the first chunk we have to create the file, othewise we append... // Note file_put_contents with FILE_APPEND produces overlapping chunks for some reason... $out_fp = fopen($tmpFilePath, $append ? "ab" : "wb"); //append or write mode $in_fp = fopen($uploadedChunkPath, "rb"); while ($buff = fread($in_fp, 4096)) { fwrite($out_fp, $buff); } fclose($out_fp); fclose($in_fp); // test if we're done with all chunks yet... // $done = (filesize($tmpFilePath)==$totalSize ? true : false); if (filesize($tmpFilePath) == $totalSize) { // move file to last uploaded chunks tmp_filename // & set size etc for regular upload handling as if uploaded normally rename($tmpFilePath, $uploadedChunkPath); $uploadedFiles[0]['name'] = $originalFileName; } else { // not done yet, return for now... $return = array('ok' => '('.$uploadedChunkPath.' - ' .$tmpFilePath.': '.filesize($tmpFilePath).'/'.$totalSize.')'); // Format response with json $response = new SS_HTTPResponse(Convert::raw2json(array($return))); $response->addHeader('Content-Type', 'text/plain'); return $response; } } // Multipart done (or small enough to have been done in one chunk)... // Save the temporary file into a File object $firstFile = reset($uploadedFiles); $file = $this->saveTemporaryFile($firstFile, $error); if (empty($file)) { array_push($return, array('error' => $error)); } else { array_push($return, $this->encodeFileAttributes($file)); } $this->upload->clearErrors(); // Format response with json $response = new SS_HTTPResponse(Convert::raw2json($return)); $response->addHeader('Content-Type', 'text/plain'); return $response; }
php
public function upload(SS_HTTPRequest $request) { if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) { return $this->httpError(403); } // Protect against CSRF on destructive action $token = $this->getForm()->getSecurityToken(); if (!$token->checkRequest($request)) { return $this->httpError(400); } // Get form details (name of the relation) $name = $this->getName(); $postVars = $request->postVar($name); $uploadedFiles = $this->extractUploadedFileData($postVars); $return = array(); // // append all multiparts to one file here before proceeding // if ($request->getHeader('X-File-Name')) { // if chunked, get name from header //return Debug::dump($request->getHeader('X-File-Name')); $originalFileName = $request->getHeader('X-File-Name'); $totalSize = $request->getHeader('X-File-Size'); $uploadedChunkPath = $uploadedFiles[0]['tmp_name']; // We (mis)use the security ID as a way of 'unique-ifying' the temporary upload paths // so that we don't just depend on the original filename for this (or a scenario might // be possible to overwrite files based on an identical original name) // Added benefit it that the security ID will be different between form loads, which // makes the risk of appending to the same file over and over, a bit smaller $securityID = ($request->postVar('SecurityID')? $request->postVar('SecurityID'): 'none'); // hash to prevent directory traversal etc posibilities based on original file name $temphash = sha1($securityID.$originalFileName); // eg /tmp/123somelonghash456 instead of $originalFileName.'.part' $tmpFilePath = dirname($uploadedChunkPath).DIRECTORY_SEPARATOR.$temphash; $append = file_exists($tmpFilePath); // If it is the first chunk we have to create the file, othewise we append... // Note file_put_contents with FILE_APPEND produces overlapping chunks for some reason... $out_fp = fopen($tmpFilePath, $append ? "ab" : "wb"); //append or write mode $in_fp = fopen($uploadedChunkPath, "rb"); while ($buff = fread($in_fp, 4096)) { fwrite($out_fp, $buff); } fclose($out_fp); fclose($in_fp); // test if we're done with all chunks yet... // $done = (filesize($tmpFilePath)==$totalSize ? true : false); if (filesize($tmpFilePath) == $totalSize) { // move file to last uploaded chunks tmp_filename // & set size etc for regular upload handling as if uploaded normally rename($tmpFilePath, $uploadedChunkPath); $uploadedFiles[0]['name'] = $originalFileName; } else { // not done yet, return for now... $return = array('ok' => '('.$uploadedChunkPath.' - ' .$tmpFilePath.': '.filesize($tmpFilePath).'/'.$totalSize.')'); // Format response with json $response = new SS_HTTPResponse(Convert::raw2json(array($return))); $response->addHeader('Content-Type', 'text/plain'); return $response; } } // Multipart done (or small enough to have been done in one chunk)... // Save the temporary file into a File object $firstFile = reset($uploadedFiles); $file = $this->saveTemporaryFile($firstFile, $error); if (empty($file)) { array_push($return, array('error' => $error)); } else { array_push($return, $this->encodeFileAttributes($file)); } $this->upload->clearErrors(); // Format response with json $response = new SS_HTTPResponse(Convert::raw2json($return)); $response->addHeader('Content-Type', 'text/plain'); return $response; }
[ "public", "function", "upload", "(", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "$", "this", "->", "isDisabled", "(", ")", "||", "$", "this", "->", "isReadonly", "(", ")", "||", "!", "$", "this", "->", "canUpload", "(", ")", ")", "{", "...
Action to handle upload of a single file @param SS_HTTPRequest $request @return SS_HTTPResponse @return SS_HTTPResponse
[ "Action", "to", "handle", "upload", "of", "a", "single", "file" ]
train
https://github.com/micschk/silverstripe-chunkeduploadfield/blob/6c8373357a1f57f17fd53ef3144f544fd315c12b/code/ChunkedUploadField.php#L85-L168
PHPixie/HTTP
src/PHPixie/HTTP.php
HTTP.request
public function request($serverRequest = null) { if ($serverRequest === null) { $serverRequest = $this->sapiServerRequest(); } return $this->builder->request($serverRequest); }
php
public function request($serverRequest = null) { if ($serverRequest === null) { $serverRequest = $this->sapiServerRequest(); } return $this->builder->request($serverRequest); }
[ "public", "function", "request", "(", "$", "serverRequest", "=", "null", ")", "{", "if", "(", "$", "serverRequest", "===", "null", ")", "{", "$", "serverRequest", "=", "$", "this", "->", "sapiServerRequest", "(", ")", ";", "}", "return", "$", "this", "...
Create PHPixie request from server request. If the server request is not specified it will be created from globals @param Request\ServerRequest $serverRequest @return HTTP\Request
[ "Create", "PHPixie", "request", "from", "server", "request", "." ]
train
https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP.php#L43-L49
PHPixie/HTTP
src/PHPixie/HTTP.php
HTTP.output
public function output($response, $context = null) { $this->builder->output()->response($response, $context); }
php
public function output($response, $context = null) { $this->builder->output()->response($response, $context); }
[ "public", "function", "output", "(", "$", "response", ",", "$", "context", "=", "null", ")", "{", "$", "this", "->", "builder", "->", "output", "(", ")", "->", "response", "(", "$", "response", ",", "$", "context", ")", ";", "}" ]
Output a HTTP response @param HTTP\Responses\Response $response @param HTTP\Context $context Optional HTTP context to use (e.g. for cookie data) @return void
[ "Output", "a", "HTTP", "response" ]
train
https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP.php#L57-L60
PHPixie/HTTP
src/PHPixie/HTTP.php
HTTP.context
public function context($request, $session = null) { $serverRequest = $request->serverRequest(); $cookieArray = $serverRequest->getCookieParams(); $cookies = $this->builder->cookies($cookieArray); if ($session === null) { $session = $this->builder->sapiSession(); } return $this->builder->context($request, $cookies, $session); }
php
public function context($request, $session = null) { $serverRequest = $request->serverRequest(); $cookieArray = $serverRequest->getCookieParams(); $cookies = $this->builder->cookies($cookieArray); if ($session === null) { $session = $this->builder->sapiSession(); } return $this->builder->context($request, $cookies, $session); }
[ "public", "function", "context", "(", "$", "request", ",", "$", "session", "=", "null", ")", "{", "$", "serverRequest", "=", "$", "request", "->", "serverRequest", "(", ")", ";", "$", "cookieArray", "=", "$", "serverRequest", "->", "getCookieParams", "(", ...
Create a context from a HTTP request @param HTTP\Request $request @param HTTP\Context\Session $session Optional session container, if not specified the default PHP session storage is used @return HTTP\Context
[ "Create", "a", "context", "from", "a", "HTTP", "request" ]
train
https://github.com/PHPixie/HTTP/blob/581c0df452fd07ca4ea0b3e24e8ddee8dddc2912/src/PHPixie/HTTP.php#L79-L89
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.deleteItems
public function deleteItems( \stdClass $params ) { $this->checkParams( $params, array( 'site', 'items' ) ); $this->setLocale( $params->site ); $this->getManager()->deleteItems( (array) $params->items ); $this->clearCache( (array) $params->items ); return array( 'items' => $params->items, 'success' => true, ); }
php
public function deleteItems( \stdClass $params ) { $this->checkParams( $params, array( 'site', 'items' ) ); $this->setLocale( $params->site ); $this->getManager()->deleteItems( (array) $params->items ); $this->clearCache( (array) $params->items ); return array( 'items' => $params->items, 'success' => true, ); }
[ "public", "function", "deleteItems", "(", "\\", "stdClass", "$", "params", ")", "{", "$", "this", "->", "checkParams", "(", "$", "params", ",", "array", "(", "'site'", ",", "'items'", ")", ")", ";", "$", "this", "->", "setLocale", "(", "$", "params", ...
Deletes an item or a list of items. @param \stdClass $params Associative list of parameters @return array Associative list with success value
[ "Deletes", "an", "item", "or", "a", "list", "of", "items", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L90-L102
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.searchItems
public function searchItems( \stdClass $params ) { $this->checkParams( $params, array( 'site' ) ); $this->setLocale( $params->site ); $total = 0; $manager = $this->getManager(); $search = $this->initCriteria( $manager->createSearch(), $params ); $items = $manager->searchItems( $search, [], $total ); return array( 'items' => $this->toArray( $items ), 'total' => $total, 'success' => true, ); }
php
public function searchItems( \stdClass $params ) { $this->checkParams( $params, array( 'site' ) ); $this->setLocale( $params->site ); $total = 0; $manager = $this->getManager(); $search = $this->initCriteria( $manager->createSearch(), $params ); $items = $manager->searchItems( $search, [], $total ); return array( 'items' => $this->toArray( $items ), 'total' => $total, 'success' => true, ); }
[ "public", "function", "searchItems", "(", "\\", "stdClass", "$", "params", ")", "{", "$", "this", "->", "checkParams", "(", "$", "params", ",", "array", "(", "'site'", ")", ")", ";", "$", "this", "->", "setLocale", "(", "$", "params", "->", "site", "...
Retrieves all items matching the given criteria. @param \stdClass $params Associative array containing the parameters @return array List of associative arrays with item properties, total number of items and success property
[ "Retrieves", "all", "items", "matching", "the", "given", "criteria", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L111-L126
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.getServiceDescription
public function getServiceDescription() { return array( $this->name . '.init' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.finish' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.deleteItems' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.saveItems' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.searchItems' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "condition", "optional" => true ), array( "type" => "integer", "name" => "start", "optional" => true ), array( "type" => "integer", "name" => "limit", "optional" => true ), array( "type" => "string", "name" => "sort", "optional" => true ), array( "type" => "string", "name" => "dir", "optional" => true ), array( "type" => "array", "name" => "options", "optional" => true ), ), "returns" => "array", ), ); }
php
public function getServiceDescription() { return array( $this->name . '.init' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.finish' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.deleteItems' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.saveItems' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "items", "optional" => false ), ), "returns" => "array", ), $this->name . '.searchItems' => array( "parameters" => array( array( "type" => "string", "name" => "site", "optional" => false ), array( "type" => "array", "name" => "condition", "optional" => true ), array( "type" => "integer", "name" => "start", "optional" => true ), array( "type" => "integer", "name" => "limit", "optional" => true ), array( "type" => "string", "name" => "sort", "optional" => true ), array( "type" => "string", "name" => "dir", "optional" => true ), array( "type" => "array", "name" => "options", "optional" => true ), ), "returns" => "array", ), ); }
[ "public", "function", "getServiceDescription", "(", ")", "{", "return", "array", "(", "$", "this", "->", "name", ".", "'.init'", "=>", "array", "(", "\"parameters\"", "=>", "array", "(", "array", "(", "\"type\"", "=>", "\"string\"", ",", "\"name\"", "=>", ...
Returns the service description of the class. It describes the class methods and its parameters including their types @return array Associative list of class/method names, their parameters and types
[ "Returns", "the", "service", "description", "of", "the", "class", ".", "It", "describes", "the", "class", "methods", "and", "its", "parameters", "including", "their", "types" ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L135-L179
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.getItemSchema
public function getItemSchema() { $attributes = $this->getManager()->getSearchAttributes( false ); return array( 'name' => $this->name, 'properties' => $this->getAttributeSchema( $attributes ), ); }
php
public function getItemSchema() { $attributes = $this->getManager()->getSearchAttributes( false ); return array( 'name' => $this->name, 'properties' => $this->getAttributeSchema( $attributes ), ); }
[ "public", "function", "getItemSchema", "(", ")", "{", "$", "attributes", "=", "$", "this", "->", "getManager", "(", ")", "->", "getSearchAttributes", "(", "false", ")", ";", "return", "array", "(", "'name'", "=>", "$", "this", "->", "name", ",", "'proper...
Returns the schema of the item. @return array Associative list of "name" and "properties" list (including "description", "type" and "optional")
[ "Returns", "the", "schema", "of", "the", "item", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L187-L194
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.checkFileUpload
protected function checkFileUpload( $filename, $errcode ) { switch( $errcode ) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new \Aimeos\Controller\ExtJS\Exception( 'The uploaded file exceeds the max. allowed filesize' ); case UPLOAD_ERR_PARTIAL: throw new \Aimeos\Controller\ExtJS\Exception( 'The uploaded file was only partially uploaded' ); case UPLOAD_ERR_NO_FILE: throw new \Aimeos\Controller\ExtJS\Exception( 'No file was uploaded' ); case UPLOAD_ERR_NO_TMP_DIR: throw new \Aimeos\Controller\ExtJS\Exception( 'Temporary folder is missing' ); case UPLOAD_ERR_CANT_WRITE: throw new \Aimeos\Controller\ExtJS\Exception( 'Failed to write file to disk' ); case UPLOAD_ERR_EXTENSION: throw new \Aimeos\Controller\ExtJS\Exception( 'File upload stopped by extension' ); default: throw new \Aimeos\Controller\ExtJS\Exception( 'Unknown upload error' ); } if( is_uploaded_file( $filename ) === false ) { throw new \Aimeos\Controller\ExtJS\Exception( 'File was not uploaded' ); } }
php
protected function checkFileUpload( $filename, $errcode ) { switch( $errcode ) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new \Aimeos\Controller\ExtJS\Exception( 'The uploaded file exceeds the max. allowed filesize' ); case UPLOAD_ERR_PARTIAL: throw new \Aimeos\Controller\ExtJS\Exception( 'The uploaded file was only partially uploaded' ); case UPLOAD_ERR_NO_FILE: throw new \Aimeos\Controller\ExtJS\Exception( 'No file was uploaded' ); case UPLOAD_ERR_NO_TMP_DIR: throw new \Aimeos\Controller\ExtJS\Exception( 'Temporary folder is missing' ); case UPLOAD_ERR_CANT_WRITE: throw new \Aimeos\Controller\ExtJS\Exception( 'Failed to write file to disk' ); case UPLOAD_ERR_EXTENSION: throw new \Aimeos\Controller\ExtJS\Exception( 'File upload stopped by extension' ); default: throw new \Aimeos\Controller\ExtJS\Exception( 'Unknown upload error' ); } if( is_uploaded_file( $filename ) === false ) { throw new \Aimeos\Controller\ExtJS\Exception( 'File was not uploaded' ); } }
[ "protected", "function", "checkFileUpload", "(", "$", "filename", ",", "$", "errcode", ")", "{", "switch", "(", "$", "errcode", ")", "{", "case", "UPLOAD_ERR_OK", ":", "break", ";", "case", "UPLOAD_ERR_INI_SIZE", ":", "case", "UPLOAD_ERR_FORM_SIZE", ":", "thro...
Checks if the uploaded file is valid. @param string $filename Name of the uploaded file in the file system of the server @param integer $errcode Status code of the uploaded file @throws \Aimeos\Controller\ExtJS\Exception If file upload is invalid
[ "Checks", "if", "the", "uploaded", "file", "is", "valid", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L265-L291
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.checkParams
protected function checkParams( \stdClass $params, array $names ) { foreach( $names as $name ) { if( !property_exists( $params, $name ) ) { throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Missing parameter "%1$s"', $name ), -1 ); } } }
php
protected function checkParams( \stdClass $params, array $names ) { foreach( $names as $name ) { if( !property_exists( $params, $name ) ) { throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Missing parameter "%1$s"', $name ), -1 ); } } }
[ "protected", "function", "checkParams", "(", "\\", "stdClass", "$", "params", ",", "array", "$", "names", ")", "{", "foreach", "(", "$", "names", "as", "$", "name", ")", "{", "if", "(", "!", "property_exists", "(", "$", "params", ",", "$", "name", ")...
Checks if the required parameter are available. @param \stdClass $params Item object containing the parameter @param string[] $names List of names of the required parameter @throws \Aimeos\Controller\ExtJS\Exception if a required parameter is missing
[ "Checks", "if", "the", "required", "parameter", "are", "available", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L301-L309
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.clearCache
protected function clearCache( array $ids, $domain = null ) { $domain = ( $domain !== null ? $domain : strtolower( $this->name ) ); $tags = array( $domain ); foreach( $ids as $id ) { $tags[] = $domain . '-' . $id; } $this->context->getCache()->deleteByTags( $tags ); }
php
protected function clearCache( array $ids, $domain = null ) { $domain = ( $domain !== null ? $domain : strtolower( $this->name ) ); $tags = array( $domain ); foreach( $ids as $id ) { $tags[] = $domain . '-' . $id; } $this->context->getCache()->deleteByTags( $tags ); }
[ "protected", "function", "clearCache", "(", "array", "$", "ids", ",", "$", "domain", "=", "null", ")", "{", "$", "domain", "=", "(", "$", "domain", "!==", "null", "?", "$", "domain", ":", "strtolower", "(", "$", "this", "->", "name", ")", ")", ";",...
Removes the cache entries tagged with the domain or domain items. @param array $ids List of domain IDs @param string|null $domain Domain of the IDs, null for current domain
[ "Removes", "the", "cache", "entries", "tagged", "with", "the", "domain", "or", "domain", "items", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L318-L328
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.getAttributeSchema
protected function getAttributeSchema( array $attributes, $all = true ) { $properties = []; $iface = '\\Aimeos\\MW\\Criteria\\Attribute\\Iface'; foreach( $attributes as $attribute ) { if( !( $attribute instanceof $iface ) ) { throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'List item doesn\'t implement "%1$s"', $iface ) ); } if( $attribute->isPublic() || (bool) $all ) { $properties[$attribute->getCode()] = array( 'description' => $attribute->getLabel(), 'optional' => !$attribute->isRequired(), 'type' => $attribute->getType(), ); } } return $properties; }
php
protected function getAttributeSchema( array $attributes, $all = true ) { $properties = []; $iface = '\\Aimeos\\MW\\Criteria\\Attribute\\Iface'; foreach( $attributes as $attribute ) { if( !( $attribute instanceof $iface ) ) { throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'List item doesn\'t implement "%1$s"', $iface ) ); } if( $attribute->isPublic() || (bool) $all ) { $properties[$attribute->getCode()] = array( 'description' => $attribute->getLabel(), 'optional' => !$attribute->isRequired(), 'type' => $attribute->getType(), ); } } return $properties; }
[ "protected", "function", "getAttributeSchema", "(", "array", "$", "attributes", ",", "$", "all", "=", "true", ")", "{", "$", "properties", "=", "[", "]", ";", "$", "iface", "=", "'\\\\Aimeos\\\\MW\\\\Criteria\\\\Attribute\\\\Iface'", ";", "foreach", "(", "$", ...
Returns the item properties suitable for creating a JSON schema. @param array $attributes List of attribute object implementing \Aimeos\MW\Criteria\Attribute\Iface @param boolean $all True if all search attributes should be returned or false for only public ones @throws \Aimeos\Controller\ExtJS\Exception if list item doesn't implement \Aimeos\MW\Criteria\Attribute\Iface
[ "Returns", "the", "item", "properties", "suitable", "for", "creating", "a", "JSON", "schema", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L338-L359
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.getItems
protected function getItems( array $ids, $prefix ) { $search = $this->getManager()->createSearch(); $search->setConditions( $search->compare( '==', $prefix . '.id', $ids ) ); $search->setSlice( 0, count( $ids ) ); $items = $this->toArray( $this->getManager()->searchItems( $search ) ); return array( 'items' => ( count( $ids ) === 1 ? reset( $items ) : $items ), 'success' => true, ); }
php
protected function getItems( array $ids, $prefix ) { $search = $this->getManager()->createSearch(); $search->setConditions( $search->compare( '==', $prefix . '.id', $ids ) ); $search->setSlice( 0, count( $ids ) ); $items = $this->toArray( $this->getManager()->searchItems( $search ) ); return array( 'items' => ( count( $ids ) === 1 ? reset( $items ) : $items ), 'success' => true, ); }
[ "protected", "function", "getItems", "(", "array", "$", "ids", ",", "$", "prefix", ")", "{", "$", "search", "=", "$", "this", "->", "getManager", "(", ")", "->", "createSearch", "(", ")", ";", "$", "search", "->", "setConditions", "(", "$", "search", ...
Returns the items for the given domain and IDs @param array $ids List of domain item IDs @param string $prefix Search key prefix @return array Associative array including items and status for ExtJS
[ "Returns", "the", "items", "for", "the", "given", "domain", "and", "IDs" ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L369-L380
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.initCriteria
protected function initCriteria( \Aimeos\MW\Criteria\Iface $criteria, \stdClass $params ) { $this->initCriteriaConditions( $criteria, $params ); $this->initCriteriaSortations( $criteria, $params ); $this->initCriteriaSlice( $criteria, $params ); return $criteria; }
php
protected function initCriteria( \Aimeos\MW\Criteria\Iface $criteria, \stdClass $params ) { $this->initCriteriaConditions( $criteria, $params ); $this->initCriteriaSortations( $criteria, $params ); $this->initCriteriaSlice( $criteria, $params ); return $criteria; }
[ "protected", "function", "initCriteria", "(", "\\", "Aimeos", "\\", "MW", "\\", "Criteria", "\\", "Iface", "$", "criteria", ",", "\\", "stdClass", "$", "params", ")", "{", "$", "this", "->", "initCriteriaConditions", "(", "$", "criteria", ",", "$", "params...
Initializes the criteria object based on the given parameter. @param \Aimeos\MW\Criteria\Iface $criteria Criteria object @param \stdClass $params Object that may contain the properties "condition", "sort", "dir", "start" and "limit" @return \Aimeos\MW\Criteria\Iface Initialized criteria object
[ "Initializes", "the", "criteria", "object", "based", "on", "the", "given", "parameter", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L390-L397
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.initCriteriaSlice
protected function initCriteriaSlice( \Aimeos\MW\Criteria\Iface $criteria, \stdClass $params ) { if( isset( $params->start ) && isset( $params->limit ) ) { $start = ( isset( $params->start ) ? $params->start : 0 ); $size = ( isset( $params->limit ) ? $params->limit : 25 ); $criteria->setSlice( $start, $size ); } }
php
protected function initCriteriaSlice( \Aimeos\MW\Criteria\Iface $criteria, \stdClass $params ) { if( isset( $params->start ) && isset( $params->limit ) ) { $start = ( isset( $params->start ) ? $params->start : 0 ); $size = ( isset( $params->limit ) ? $params->limit : 25 ); $criteria->setSlice( $start, $size ); } }
[ "protected", "function", "initCriteriaSlice", "(", "\\", "Aimeos", "\\", "MW", "\\", "Criteria", "\\", "Iface", "$", "criteria", ",", "\\", "stdClass", "$", "params", ")", "{", "if", "(", "isset", "(", "$", "params", "->", "start", ")", "&&", "isset", ...
Initializes the criteria object with the slice based on the given parameter. @param \Aimeos\MW\Criteria\Iface $criteria Criteria object @param \stdClass $params Object that may contain the properties "condition", "sort", "dir", "start" and "limit"
[ "Initializes", "the", "criteria", "object", "with", "the", "slice", "based", "on", "the", "given", "parameter", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L428-L437
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.initCriteriaSortations
protected function initCriteriaSortations( \Aimeos\MW\Criteria\Iface $criteria, \stdClass $params ) { if( isset( $params->sort ) && isset( $params->dir ) ) { $sortation = []; switch( $params->dir ) { case 'ASC': $sortation[] = $criteria->sort( '+', $params->sort ); break; case 'DESC': $sortation[] = $criteria->sort( '-', $params->sort ); break; default: throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Invalid sort direction "%1$s"', $params->sort ) ); } $criteria->setSortations( $sortation ); } if( $this->sort !== null ) { $sort = $criteria->getSortations(); $sort[] = $criteria->sort( '+', $this->sort ); $criteria->setSortations( $sort ); } }
php
protected function initCriteriaSortations( \Aimeos\MW\Criteria\Iface $criteria, \stdClass $params ) { if( isset( $params->sort ) && isset( $params->dir ) ) { $sortation = []; switch( $params->dir ) { case 'ASC': $sortation[] = $criteria->sort( '+', $params->sort ); break; case 'DESC': $sortation[] = $criteria->sort( '-', $params->sort ); break; default: throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Invalid sort direction "%1$s"', $params->sort ) ); } $criteria->setSortations( $sortation ); } if( $this->sort !== null ) { $sort = $criteria->getSortations(); $sort[] = $criteria->sort( '+', $this->sort ); $criteria->setSortations( $sort ); } }
[ "protected", "function", "initCriteriaSortations", "(", "\\", "Aimeos", "\\", "MW", "\\", "Criteria", "\\", "Iface", "$", "criteria", ",", "\\", "stdClass", "$", "params", ")", "{", "if", "(", "isset", "(", "$", "params", "->", "sort", ")", "&&", "isset"...
Initializes the criteria object with sortations based on the given parameter. @param \Aimeos\MW\Criteria\Iface $criteria Criteria object @param \stdClass $params Object that may contain the properties "condition", "sort", "dir", "start" and "limit"
[ "Initializes", "the", "criteria", "object", "with", "sortations", "based", "on", "the", "given", "parameter", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L446-L472
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.setLocale
protected function setLocale( $site, $langid = null, $currencyid = null ) { $siteManager = \Aimeos\MShop\Locale\Manager\Factory::createManager( $this->context )->getSubManager( 'site' ); $search = $siteManager->createSearch(); $search->setConditions( $search->compare( '==', 'locale.site.code', $site ) ); $sites = $siteManager->searchItems( $search ); if( ( $siteItem = reset( $sites ) ) === false ) { throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Site item for code "%1$s" not found', $site ) ); } $values = array( 'locale.siteid' => $siteItem->getId() ); $sitepath = array_keys( $siteManager->getPath( $siteItem->getId() ) ); $sitetree = $this->getSiteIdsFromTree( $siteManager->getTree( $siteItem->getId() ) ); $localeItem = new \Aimeos\MShop\Locale\Item\Standard( $values, $siteItem, $sitepath, $sitetree ); $localeItem->setLanguageId( $langid ); $localeItem->setCurrencyId( $currencyid ); $this->context->setLocale( $localeItem ); }
php
protected function setLocale( $site, $langid = null, $currencyid = null ) { $siteManager = \Aimeos\MShop\Locale\Manager\Factory::createManager( $this->context )->getSubManager( 'site' ); $search = $siteManager->createSearch(); $search->setConditions( $search->compare( '==', 'locale.site.code', $site ) ); $sites = $siteManager->searchItems( $search ); if( ( $siteItem = reset( $sites ) ) === false ) { throw new \Aimeos\Controller\ExtJS\Exception( sprintf( 'Site item for code "%1$s" not found', $site ) ); } $values = array( 'locale.siteid' => $siteItem->getId() ); $sitepath = array_keys( $siteManager->getPath( $siteItem->getId() ) ); $sitetree = $this->getSiteIdsFromTree( $siteManager->getTree( $siteItem->getId() ) ); $localeItem = new \Aimeos\MShop\Locale\Item\Standard( $values, $siteItem, $sitepath, $sitetree ); $localeItem->setLanguageId( $langid ); $localeItem->setCurrencyId( $currencyid ); $this->context->setLocale( $localeItem ); }
[ "protected", "function", "setLocale", "(", "$", "site", ",", "$", "langid", "=", "null", ",", "$", "currencyid", "=", "null", ")", "{", "$", "siteManager", "=", "\\", "Aimeos", "\\", "MShop", "\\", "Locale", "\\", "Manager", "\\", "Factory", "::", "cre...
Creates a new locale object and adds this object to the context. @param string $site Site code @param string|null $langid Two letter ISO code for language @param string|null $currencyid Three letter ISO code for currency
[ "Creates", "a", "new", "locale", "object", "and", "adds", "this", "object", "to", "the", "context", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L482-L503
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.toArray
protected function toArray( array $list ) { $result = []; foreach( $list as $item ) { $result[] = (object) $item->toArray( true ); } return $result; }
php
protected function toArray( array $list ) { $result = []; foreach( $list as $item ) { $result[] = (object) $item->toArray( true ); } return $result; }
[ "protected", "function", "toArray", "(", "array", "$", "list", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "$", "result", "[", "]", "=", "(", "object", ")", "$", "item", "->", "toArray", ...
Converts the given list of objects to a list of \stdClass objects @param array $list List of item objects @return array List of \stdClass objects containing the properties of the item objects
[ "Converts", "the", "given", "list", "of", "objects", "to", "a", "list", "of", "\\", "stdClass", "objects" ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L512-L521
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.getDomainItems
protected function getDomainItems( array $lists ) { $result = []; foreach( $lists as $domain => $ids ) { $manager = \Aimeos\MShop\Factory::createManager( $this->context, $domain ); $total = 0; $criteria = $manager->createSearch(); $criteria->setConditions( $criteria->compare( '==', str_replace( '/', '.', $domain ) . '.id', $ids ) ); $criteria->setSlice( 0, 0x7fffffff ); $items = $manager->searchItems( $criteria, [], $total ); $parts = explode( '/', $domain ); foreach( $parts as $key => $part ) { $parts[$key] = ucwords( $part ); } $result[implode( '_', $parts )] = array( 'items' => $this->toArray( $items ), 'total' => $total, ); } return $result; }
php
protected function getDomainItems( array $lists ) { $result = []; foreach( $lists as $domain => $ids ) { $manager = \Aimeos\MShop\Factory::createManager( $this->context, $domain ); $total = 0; $criteria = $manager->createSearch(); $criteria->setConditions( $criteria->compare( '==', str_replace( '/', '.', $domain ) . '.id', $ids ) ); $criteria->setSlice( 0, 0x7fffffff ); $items = $manager->searchItems( $criteria, [], $total ); $parts = explode( '/', $domain ); foreach( $parts as $key => $part ) { $parts[$key] = ucwords( $part ); } $result[implode( '_', $parts )] = array( 'items' => $this->toArray( $items ), 'total' => $total, ); } return $result; }
[ "protected", "function", "getDomainItems", "(", "array", "$", "lists", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "lists", "as", "$", "domain", "=>", "$", "ids", ")", "{", "$", "manager", "=", "\\", "Aimeos", "\\", "MShop", "...
Returns the items from the domains identified by their IDs. @param array $lists Associative list of domain names and list of IDs. The domain names must be in lower case (e.g. "product" for product items or "product/list" for product list items). Sub-domains are separated by a slash (/). @return array Associative list of controller names (e.g. "Product_List", generated from "product/list") and a list of pairs. Each list of pairs contains the key "items" with the list of object properties and the key "total" with the total number of items that are available in the storage
[ "Returns", "the", "items", "from", "the", "domains", "identified", "by", "their", "IDs", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L546-L573
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Base.php
Base.getSiteIdsFromTree
protected function getSiteIdsFromTree( \Aimeos\MShop\Locale\Item\Site\Iface $item ) { $list = array( $item->getId() ); foreach( $item->getChildren() as $child ) { $list = array_merge( $list, $this->getSiteIdsFromTree( $child ) ); } return $list; }
php
protected function getSiteIdsFromTree( \Aimeos\MShop\Locale\Item\Site\Iface $item ) { $list = array( $item->getId() ); foreach( $item->getChildren() as $child ) { $list = array_merge( $list, $this->getSiteIdsFromTree( $child ) ); } return $list; }
[ "protected", "function", "getSiteIdsFromTree", "(", "\\", "Aimeos", "\\", "MShop", "\\", "Locale", "\\", "Item", "\\", "Site", "\\", "Iface", "$", "item", ")", "{", "$", "list", "=", "array", "(", "$", "item", "->", "getId", "(", ")", ")", ";", "fore...
Returns the list of site IDs of the whole tree. @param \Aimeos\MShop\Locale\Item\Site\Iface $item Locale item, maybe with children @return array List of site IDs
[ "Returns", "the", "list", "of", "site", "IDs", "of", "the", "whole", "tree", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Base.php#L593-L602
garoevans/php-enum
src/Reflection/Enum.php
Enum.setDefault
protected function setDefault(array $constants) { if (!isset($constants[self::$defaultKey])) { throw new \UnexpectedValueException("No default enum set"); } $this->default = $constants[self::$defaultKey]; return $this; }
php
protected function setDefault(array $constants) { if (!isset($constants[self::$defaultKey])) { throw new \UnexpectedValueException("No default enum set"); } $this->default = $constants[self::$defaultKey]; return $this; }
[ "protected", "function", "setDefault", "(", "array", "$", "constants", ")", "{", "if", "(", "!", "isset", "(", "$", "constants", "[", "self", "::", "$", "defaultKey", "]", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "\"No default ...
@param array $constants @return Enum $this @throws \UnexpectedValueException
[ "@param", "array", "$constants" ]
train
https://github.com/garoevans/php-enum/blob/ef76bbc711bf52f63556fb91904cea0d762343c4/src/Reflection/Enum.php#L38-L47
garoevans/php-enum
src/Reflection/Enum.php
Enum.setEnums
protected function setEnums(array $constants) { $tempConstants = $constants; if (\array_key_exists(self::$defaultKey, $tempConstants)) { unset($tempConstants[self::$defaultKey]); } if (empty($tempConstants)) { throw new \UnexpectedValueException("No constants set"); } $this->enums = $tempConstants; $this->enumsReversed = \array_flip($this->enums); return $this; }
php
protected function setEnums(array $constants) { $tempConstants = $constants; if (\array_key_exists(self::$defaultKey, $tempConstants)) { unset($tempConstants[self::$defaultKey]); } if (empty($tempConstants)) { throw new \UnexpectedValueException("No constants set"); } $this->enums = $tempConstants; $this->enumsReversed = \array_flip($this->enums); return $this; }
[ "protected", "function", "setEnums", "(", "array", "$", "constants", ")", "{", "$", "tempConstants", "=", "$", "constants", ";", "if", "(", "\\", "array_key_exists", "(", "self", "::", "$", "defaultKey", ",", "$", "tempConstants", ")", ")", "{", "unset", ...
@param array $constants @return Enum $this @throws \UnexpectedValueException
[ "@param", "array", "$constants" ]
train
https://github.com/garoevans/php-enum/blob/ef76bbc711bf52f63556fb91904cea0d762343c4/src/Reflection/Enum.php#L55-L71