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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
yuncms/framework
src/models/BaseUser.php
BaseUser.resetPassword
public function resetPassword($password) { try { return (bool)$this->updateAttributes(['password_hash' => PasswordHelper::hash($password)]); } catch (Exception $e) { return false; } }
php
public function resetPassword($password) { try { return (bool)$this->updateAttributes(['password_hash' => PasswordHelper::hash($password)]); } catch (Exception $e) { return false; } }
[ "public", "function", "resetPassword", "(", "$", "password", ")", "{", "try", "{", "return", "(", "bool", ")", "$", "this", "->", "updateAttributes", "(", "[", "'password_hash'", "=>", "PasswordHelper", "::", "hash", "(", "$", "password", ")", "]", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
重置密码 @param string $password @return boolean
[ "重置密码" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/models/BaseUser.php#L341-L348
yuncms/framework
src/models/BaseUser.php
BaseUser.block
public function block() { try { return (bool)$this->updateAttributes(['blocked_at' => time(), 'auth_key' => Yii::$app->security->generateRandomString()]); } catch (Exception $e) { return false; } }
php
public function block() { try { return (bool)$this->updateAttributes(['blocked_at' => time(), 'auth_key' => Yii::$app->security->generateRandomString()]); } catch (Exception $e) { return false; } }
[ "public", "function", "block", "(", ")", "{", "try", "{", "return", "(", "bool", ")", "$", "this", "->", "updateAttributes", "(", "[", "'blocked_at'", "=>", "time", "(", ")", ",", "'auth_key'", "=>", "Yii", "::", "$", "app", "->", "security", "->", "generateRandomString", "(", ")", "]", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
锁定用户 @return boolean
[ "锁定用户" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/models/BaseUser.php#L354-L361
yuncms/framework
src/models/BaseUser.php
BaseUser.loadAllowance
public function loadAllowance($request, $action) { $allowance = Yii::$app->cache->get($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance'); $allowanceUpdatedAt = Yii::$app->cache->get($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance_update_at'); if ($allowance && $allowanceUpdatedAt) { return [$allowance, $allowanceUpdatedAt]; } else { return [Yii::$app->settings->get('requestRateLimit', 'user', 60), time()]; } }
php
public function loadAllowance($request, $action) { $allowance = Yii::$app->cache->get($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance'); $allowanceUpdatedAt = Yii::$app->cache->get($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance_update_at'); if ($allowance && $allowanceUpdatedAt) { return [$allowance, $allowanceUpdatedAt]; } else { return [Yii::$app->settings->get('requestRateLimit', 'user', 60), time()]; } }
[ "public", "function", "loadAllowance", "(", "$", "request", ",", "$", "action", ")", "{", "$", "allowance", "=", "Yii", "::", "$", "app", "->", "cache", "->", "get", "(", "$", "action", "->", "controller", "->", "id", ".", "':'", ".", "$", "action", "->", "id", ".", "':'", ".", "$", "this", "->", "id", ".", "'_allowance'", ")", ";", "$", "allowanceUpdatedAt", "=", "Yii", "::", "$", "app", "->", "cache", "->", "get", "(", "$", "action", "->", "controller", "->", "id", ".", "':'", ".", "$", "action", "->", "id", ".", "':'", ".", "$", "this", "->", "id", ".", "'_allowance_update_at'", ")", ";", "if", "(", "$", "allowance", "&&", "$", "allowanceUpdatedAt", ")", "{", "return", "[", "$", "allowance", ",", "$", "allowanceUpdatedAt", "]", ";", "}", "else", "{", "return", "[", "Yii", "::", "$", "app", "->", "settings", "->", "get", "(", "'requestRateLimit'", ",", "'user'", ",", "60", ")", ",", "time", "(", ")", "]", ";", "}", "}" ]
Loads the number of allowed requests and the corresponding timestamp from a persistent storage. @param \yii\web\Request $request the current request @param \yii\base\Action $action the action to be executed @return array an array of two elements. The first element is the number of allowed requests, and the second element is the corresponding UNIX timestamp.
[ "Loads", "the", "number", "of", "allowed", "requests", "and", "the", "corresponding", "timestamp", "from", "a", "persistent", "storage", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/models/BaseUser.php#L444-L453
yuncms/framework
src/models/BaseUser.php
BaseUser.saveAllowance
public function saveAllowance($request, $action, $allowance, $timestamp) { Yii::$app->cache->set($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance', $allowance, 60); Yii::$app->cache->set($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance_update_at', $timestamp, 60); }
php
public function saveAllowance($request, $action, $allowance, $timestamp) { Yii::$app->cache->set($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance', $allowance, 60); Yii::$app->cache->set($action->controller->id . ':' . $action->id . ':' . $this->id . '_allowance_update_at', $timestamp, 60); }
[ "public", "function", "saveAllowance", "(", "$", "request", ",", "$", "action", ",", "$", "allowance", ",", "$", "timestamp", ")", "{", "Yii", "::", "$", "app", "->", "cache", "->", "set", "(", "$", "action", "->", "controller", "->", "id", ".", "':'", ".", "$", "action", "->", "id", ".", "':'", ".", "$", "this", "->", "id", ".", "'_allowance'", ",", "$", "allowance", ",", "60", ")", ";", "Yii", "::", "$", "app", "->", "cache", "->", "set", "(", "$", "action", "->", "controller", "->", "id", ".", "':'", ".", "$", "action", "->", "id", ".", "':'", ".", "$", "this", "->", "id", ".", "'_allowance_update_at'", ",", "$", "timestamp", ",", "60", ")", ";", "}" ]
Saves the number of allowed requests and the corresponding timestamp to a persistent storage. @param \yii\web\Request $request the current request @param \yii\base\Action $action the action to be executed @param int $allowance the number of allowed requests remaining. @param int $timestamp the current timestamp.
[ "Saves", "the", "number", "of", "allowed", "requests", "and", "the", "corresponding", "timestamp", "to", "a", "persistent", "storage", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/models/BaseUser.php#L462-L466
yuncms/framework
src/models/BaseUser.php
BaseUser.routeNotificationFor
public function routeNotificationFor($channel) { if (method_exists($this, $method = 'routeNotificationFor' . Inflector::camelize($channel))) { return $this->{$method}(); } switch ($channel) { case 'database': return [ 'notifiable_id' => $this->id, 'notifiable_class' => User::class ]; case 'cloudPush': return [ 'target' => 'ACCOUNT', 'targetValue' => $this->id, ]; case 'mail': return $this->email; case 'sms': return $this->mobile; } return false; }
php
public function routeNotificationFor($channel) { if (method_exists($this, $method = 'routeNotificationFor' . Inflector::camelize($channel))) { return $this->{$method}(); } switch ($channel) { case 'database': return [ 'notifiable_id' => $this->id, 'notifiable_class' => User::class ]; case 'cloudPush': return [ 'target' => 'ACCOUNT', 'targetValue' => $this->id, ]; case 'mail': return $this->email; case 'sms': return $this->mobile; } return false; }
[ "public", "function", "routeNotificationFor", "(", "$", "channel", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", "=", "'routeNotificationFor'", ".", "Inflector", "::", "camelize", "(", "$", "channel", ")", ")", ")", "{", "return", "$", "this", "->", "{", "$", "method", "}", "(", ")", ";", "}", "switch", "(", "$", "channel", ")", "{", "case", "'database'", ":", "return", "[", "'notifiable_id'", "=>", "$", "this", "->", "id", ",", "'notifiable_class'", "=>", "User", "::", "class", "]", ";", "case", "'cloudPush'", ":", "return", "[", "'target'", "=>", "'ACCOUNT'", ",", "'targetValue'", "=>", "$", "this", "->", "id", ",", "]", ";", "case", "'mail'", ":", "return", "$", "this", "->", "email", ";", "case", "'sms'", ":", "return", "$", "this", "->", "mobile", ";", "}", "return", "false", ";", "}" ]
返回给定通道的通知路由信息。 ```php public function routeNotificationForMail() { return $this->email; } ``` @param $channel string @return mixed
[ "返回给定通道的通知路由信息。", "php", "public", "function", "routeNotificationForMail", "()", "{", "return", "$this", "-", ">", "email", ";", "}" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/models/BaseUser.php#L489-L511
necrox87/yii2-nudity-detector
Image.php
Image.type
static public function type($file) { $type = getimagesize($file); $type = $type[2]; switch($type) { case IMAGETYPE_GIF: return 'gif'; case IMAGETYPE_JPEG: return 'jpg'; case IMAGETYPE_PNG: return 'png'; } return FALSE; }
php
static public function type($file) { $type = getimagesize($file); $type = $type[2]; switch($type) { case IMAGETYPE_GIF: return 'gif'; case IMAGETYPE_JPEG: return 'jpg'; case IMAGETYPE_PNG: return 'png'; } return FALSE; }
[ "static", "public", "function", "type", "(", "$", "file", ")", "{", "$", "type", "=", "getimagesize", "(", "$", "file", ")", ";", "$", "type", "=", "$", "type", "[", "2", "]", ";", "switch", "(", "$", "type", ")", "{", "case", "IMAGETYPE_GIF", ":", "return", "'gif'", ";", "case", "IMAGETYPE_JPEG", ":", "return", "'jpg'", ";", "case", "IMAGETYPE_PNG", ":", "return", "'png'", ";", "}", "return", "FALSE", ";", "}" ]
Get image type if it is one of: .gif, .jpg or .png @param string $file Full path to file @return string|boolean
[ "Get", "image", "type", "if", "it", "is", "one", "of", ":", ".", "gif", ".", "jpg", "or", ".", "png" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L69-L78
necrox87/yii2-nudity-detector
Image.php
Image.rgbXY
public function rgbXY($x, $y) { $color = $this->colorXY($x, $y); return array(($color >> 16) & 0xFF, ($color >> 8) & 0xFF, $color & 0xFF); }
php
public function rgbXY($x, $y) { $color = $this->colorXY($x, $y); return array(($color >> 16) & 0xFF, ($color >> 8) & 0xFF, $color & 0xFF); }
[ "public", "function", "rgbXY", "(", "$", "x", ",", "$", "y", ")", "{", "$", "color", "=", "$", "this", "->", "colorXY", "(", "$", "x", ",", "$", "y", ")", ";", "return", "array", "(", "(", "$", "color", ">>", "16", ")", "&", "0xFF", ",", "(", "$", "color", ">>", "8", ")", "&", "0xFF", ",", "$", "color", "&", "0xFF", ")", ";", "}" ]
Returns RGB array of pixel's color @param int $x @param int $y
[ "Returns", "RGB", "array", "of", "pixel", "s", "color" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L110-L113
necrox87/yii2-nudity-detector
Image.php
Image.create
public function create() { switch($this->info[2]) { case IMAGETYPE_JPEG: $this->resource = imagecreatefromjpeg($this->file); break; case IMAGETYPE_GIF: $this->resource = imagecreatefromgif($this->file); break; case IMAGETYPE_PNG: $this->resource = imagecreatefrompng($this->file); break; default: throw new Exception('Image type is not supported'); break; } }
php
public function create() { switch($this->info[2]) { case IMAGETYPE_JPEG: $this->resource = imagecreatefromjpeg($this->file); break; case IMAGETYPE_GIF: $this->resource = imagecreatefromgif($this->file); break; case IMAGETYPE_PNG: $this->resource = imagecreatefrompng($this->file); break; default: throw new Exception('Image type is not supported'); break; } }
[ "public", "function", "create", "(", ")", "{", "switch", "(", "$", "this", "->", "info", "[", "2", "]", ")", "{", "case", "IMAGETYPE_JPEG", ":", "$", "this", "->", "resource", "=", "imagecreatefromjpeg", "(", "$", "this", "->", "file", ")", ";", "break", ";", "case", "IMAGETYPE_GIF", ":", "$", "this", "->", "resource", "=", "imagecreatefromgif", "(", "$", "this", "->", "file", ")", ";", "break", ";", "case", "IMAGETYPE_PNG", ":", "$", "this", "->", "resource", "=", "imagecreatefrompng", "(", "$", "this", "->", "file", ")", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "'Image type is not supported'", ")", ";", "break", ";", "}", "}" ]
Create an image resource
[ "Create", "an", "image", "resource" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L119-L134
necrox87/yii2-nudity-detector
Image.php
Image.save
public function save($file, $type = IMAGETYPE_JPEG, $quality = 75, $permissions = false) { // create directory if necessary $dir = dirname($file); if(!file_exists($dir)) { $mask = umask(); mkdir($dir, 0777, true); umask($mask); } switch($type) { case IMAGETYPE_JPEG: imagejpeg($this->resource, $file, $quality); break; case IMAGETYPE_GIF: imagegif($this->resource, $file); break; case IMAGETYPE_PNG: imagepng($this->resource, $file); break; default: throw new Exception('Image type is not supported'); break; } // change image rights if($permissions !== false) chmod($file, $permissions); // for method chaining return $this; }
php
public function save($file, $type = IMAGETYPE_JPEG, $quality = 75, $permissions = false) { // create directory if necessary $dir = dirname($file); if(!file_exists($dir)) { $mask = umask(); mkdir($dir, 0777, true); umask($mask); } switch($type) { case IMAGETYPE_JPEG: imagejpeg($this->resource, $file, $quality); break; case IMAGETYPE_GIF: imagegif($this->resource, $file); break; case IMAGETYPE_PNG: imagepng($this->resource, $file); break; default: throw new Exception('Image type is not supported'); break; } // change image rights if($permissions !== false) chmod($file, $permissions); // for method chaining return $this; }
[ "public", "function", "save", "(", "$", "file", ",", "$", "type", "=", "IMAGETYPE_JPEG", ",", "$", "quality", "=", "75", ",", "$", "permissions", "=", "false", ")", "{", "// create directory if necessary", "$", "dir", "=", "dirname", "(", "$", "file", ")", ";", "if", "(", "!", "file_exists", "(", "$", "dir", ")", ")", "{", "$", "mask", "=", "umask", "(", ")", ";", "mkdir", "(", "$", "dir", ",", "0777", ",", "true", ")", ";", "umask", "(", "$", "mask", ")", ";", "}", "switch", "(", "$", "type", ")", "{", "case", "IMAGETYPE_JPEG", ":", "imagejpeg", "(", "$", "this", "->", "resource", ",", "$", "file", ",", "$", "quality", ")", ";", "break", ";", "case", "IMAGETYPE_GIF", ":", "imagegif", "(", "$", "this", "->", "resource", ",", "$", "file", ")", ";", "break", ";", "case", "IMAGETYPE_PNG", ":", "imagepng", "(", "$", "this", "->", "resource", ",", "$", "file", ")", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "'Image type is not supported'", ")", ";", "break", ";", "}", "// change image rights", "if", "(", "$", "permissions", "!==", "false", ")", "chmod", "(", "$", "file", ",", "$", "permissions", ")", ";", "// for method chaining", "return", "$", "this", ";", "}" ]
Save image to file @param string $file File path @param int $type Image type constant @param int $quality JPEG compression quality from 0 to 100 @param int $permissions Unix file permissions
[ "Save", "image", "to", "file" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L162-L193
necrox87/yii2-nudity-detector
Image.php
Image.crop
public function crop($x, $y, $w, $h) { $new = @imagecreatetruecolor($w, $h); // This needed to deal with .png transparency imagealphablending($new, false); imagesavealpha($new, true); $transparent = imagecolorallocatealpha($new, 255, 255, 255, 127); imagefilledrectangle($new, 0, 0, $w, $h, $transparent); if($new === FALSE) { throw new Exception('Cannot Initialize new GD image stream'); return; } imagecopyresampled($new, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h); $this->resource = $new; // for method chaining return $this; }
php
public function crop($x, $y, $w, $h) { $new = @imagecreatetruecolor($w, $h); // This needed to deal with .png transparency imagealphablending($new, false); imagesavealpha($new, true); $transparent = imagecolorallocatealpha($new, 255, 255, 255, 127); imagefilledrectangle($new, 0, 0, $w, $h, $transparent); if($new === FALSE) { throw new Exception('Cannot Initialize new GD image stream'); return; } imagecopyresampled($new, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h); $this->resource = $new; // for method chaining return $this; }
[ "public", "function", "crop", "(", "$", "x", ",", "$", "y", ",", "$", "w", ",", "$", "h", ")", "{", "$", "new", "=", "@", "imagecreatetruecolor", "(", "$", "w", ",", "$", "h", ")", ";", "// This needed to deal with .png transparency", "imagealphablending", "(", "$", "new", ",", "false", ")", ";", "imagesavealpha", "(", "$", "new", ",", "true", ")", ";", "$", "transparent", "=", "imagecolorallocatealpha", "(", "$", "new", ",", "255", ",", "255", ",", "255", ",", "127", ")", ";", "imagefilledrectangle", "(", "$", "new", ",", "0", ",", "0", ",", "$", "w", ",", "$", "h", ",", "$", "transparent", ")", ";", "if", "(", "$", "new", "===", "FALSE", ")", "{", "throw", "new", "Exception", "(", "'Cannot Initialize new GD image stream'", ")", ";", "return", ";", "}", "imagecopyresampled", "(", "$", "new", ",", "$", "this", "->", "resource", ",", "0", ",", "0", ",", "$", "x", ",", "$", "y", ",", "$", "w", ",", "$", "h", ",", "$", "w", ",", "$", "h", ")", ";", "$", "this", "->", "resource", "=", "$", "new", ";", "// for method chaining", "return", "$", "this", ";", "}" ]
Crop image @param int $x @param int $y @param int $w @param int $h @return Image
[ "Crop", "image" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L204-L223
necrox87/yii2-nudity-detector
Image.php
Image.resize
public function resize($width, $height) { $new = @imagecreatetruecolor($width, $height); // This needed to deal with .png transparency imagealphablending($new, false); imagesavealpha($new, true); $transparent = imagecolorallocatealpha($new, 255, 255, 255, 127); imagefilledrectangle($new, 0, 0, $width, $height, $transparent); imagecopyresampled($new, $this->resource, 0, 0, 0, 0, $width, $height, $this->width(), $this->height()); $this->resource = $new; // for method chaining return $this; }
php
public function resize($width, $height) { $new = @imagecreatetruecolor($width, $height); // This needed to deal with .png transparency imagealphablending($new, false); imagesavealpha($new, true); $transparent = imagecolorallocatealpha($new, 255, 255, 255, 127); imagefilledrectangle($new, 0, 0, $width, $height, $transparent); imagecopyresampled($new, $this->resource, 0, 0, 0, 0, $width, $height, $this->width(), $this->height()); $this->resource = $new; // for method chaining return $this; }
[ "public", "function", "resize", "(", "$", "width", ",", "$", "height", ")", "{", "$", "new", "=", "@", "imagecreatetruecolor", "(", "$", "width", ",", "$", "height", ")", ";", "// This needed to deal with .png transparency", "imagealphablending", "(", "$", "new", ",", "false", ")", ";", "imagesavealpha", "(", "$", "new", ",", "true", ")", ";", "$", "transparent", "=", "imagecolorallocatealpha", "(", "$", "new", ",", "255", ",", "255", ",", "255", ",", "127", ")", ";", "imagefilledrectangle", "(", "$", "new", ",", "0", ",", "0", ",", "$", "width", ",", "$", "height", ",", "$", "transparent", ")", ";", "imagecopyresampled", "(", "$", "new", ",", "$", "this", "->", "resource", ",", "0", ",", "0", ",", "0", ",", "0", ",", "$", "width", ",", "$", "height", ",", "$", "this", "->", "width", "(", ")", ",", "$", "this", "->", "height", "(", ")", ")", ";", "$", "this", "->", "resource", "=", "$", "new", ";", "// for method chaining", "return", "$", "this", ";", "}" ]
Resize image @param int $width New width @param int $height New height
[ "Resize", "image" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L231-L247
necrox87/yii2-nudity-detector
Image.php
Image.fitResize
public function fitResize($max_width = 150, $max_height = 150, $min_width = 20, $min_height = 20) { $kw = $max_width / $this->width(); $kh = $max_height / $this->height(); if($kw > $kh) { $new_h = $max_height; $new_w = round($kh * $this->width()); } else { $new_w = $max_width; $new_h = round($kw * $this->height()); } $this->resize($new_w, $new_h); // Method chaining return $this; }
php
public function fitResize($max_width = 150, $max_height = 150, $min_width = 20, $min_height = 20) { $kw = $max_width / $this->width(); $kh = $max_height / $this->height(); if($kw > $kh) { $new_h = $max_height; $new_w = round($kh * $this->width()); } else { $new_w = $max_width; $new_h = round($kw * $this->height()); } $this->resize($new_w, $new_h); // Method chaining return $this; }
[ "public", "function", "fitResize", "(", "$", "max_width", "=", "150", ",", "$", "max_height", "=", "150", ",", "$", "min_width", "=", "20", ",", "$", "min_height", "=", "20", ")", "{", "$", "kw", "=", "$", "max_width", "/", "$", "this", "->", "width", "(", ")", ";", "$", "kh", "=", "$", "max_height", "/", "$", "this", "->", "height", "(", ")", ";", "if", "(", "$", "kw", ">", "$", "kh", ")", "{", "$", "new_h", "=", "$", "max_height", ";", "$", "new_w", "=", "round", "(", "$", "kh", "*", "$", "this", "->", "width", "(", ")", ")", ";", "}", "else", "{", "$", "new_w", "=", "$", "max_width", ";", "$", "new_h", "=", "round", "(", "$", "kw", "*", "$", "this", "->", "height", "(", ")", ")", ";", "}", "$", "this", "->", "resize", "(", "$", "new_w", ",", "$", "new_h", ")", ";", "// Method chaining", "return", "$", "this", ";", "}" ]
Fit the image with the same proportion into an area @param int $max_width @param int $max_height @param int $min_width @param int $min_height @return Image
[ "Fit", "the", "image", "with", "the", "same", "proportion", "into", "an", "area" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L258-L272
necrox87/yii2-nudity-detector
Image.php
Image.scaleResize
public function scaleResize($width, $height) { // calculate source coordinates $kw = $this->width() / $width; $kh = $this->height() / $height; if($kh < $kw) { $src_h = $this->height(); $src_y = 0; $src_w = round($kh * $width); $src_x = round(($this->width() - $src_w) / 2); } else { $src_h = round($kh * $height); $src_y = round(($this->height() - $src_h) / 2); $src_w = $this->width(); $src_x = 0; } // copy new image $new = imagecreatetruecolor($width, $height); imagecopyresampled($new, $this->resource, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h); $this->resource = $new; // for method chaining return $this; }
php
public function scaleResize($width, $height) { // calculate source coordinates $kw = $this->width() / $width; $kh = $this->height() / $height; if($kh < $kw) { $src_h = $this->height(); $src_y = 0; $src_w = round($kh * $width); $src_x = round(($this->width() - $src_w) / 2); } else { $src_h = round($kh * $height); $src_y = round(($this->height() - $src_h) / 2); $src_w = $this->width(); $src_x = 0; } // copy new image $new = imagecreatetruecolor($width, $height); imagecopyresampled($new, $this->resource, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h); $this->resource = $new; // for method chaining return $this; }
[ "public", "function", "scaleResize", "(", "$", "width", ",", "$", "height", ")", "{", "// calculate source coordinates", "$", "kw", "=", "$", "this", "->", "width", "(", ")", "/", "$", "width", ";", "$", "kh", "=", "$", "this", "->", "height", "(", ")", "/", "$", "height", ";", "if", "(", "$", "kh", "<", "$", "kw", ")", "{", "$", "src_h", "=", "$", "this", "->", "height", "(", ")", ";", "$", "src_y", "=", "0", ";", "$", "src_w", "=", "round", "(", "$", "kh", "*", "$", "width", ")", ";", "$", "src_x", "=", "round", "(", "(", "$", "this", "->", "width", "(", ")", "-", "$", "src_w", ")", "/", "2", ")", ";", "}", "else", "{", "$", "src_h", "=", "round", "(", "$", "kh", "*", "$", "height", ")", ";", "$", "src_y", "=", "round", "(", "(", "$", "this", "->", "height", "(", ")", "-", "$", "src_h", ")", "/", "2", ")", ";", "$", "src_w", "=", "$", "this", "->", "width", "(", ")", ";", "$", "src_x", "=", "0", ";", "}", "// copy new image", "$", "new", "=", "imagecreatetruecolor", "(", "$", "width", ",", "$", "height", ")", ";", "imagecopyresampled", "(", "$", "new", ",", "$", "this", "->", "resource", ",", "0", ",", "0", ",", "$", "src_x", ",", "$", "src_y", ",", "$", "width", ",", "$", "height", ",", "$", "src_w", ",", "$", "src_h", ")", ";", "$", "this", "->", "resource", "=", "$", "new", ";", "// for method chaining", "return", "$", "this", ";", "}" ]
Resize image correctly scaled and than crop the necessary area @param int $width New width @param int $height New height
[ "Resize", "image", "correctly", "scaled", "and", "than", "crop", "the", "necessary", "area" ]
train
https://github.com/necrox87/yii2-nudity-detector/blob/59474b1480f5ed53a17f06551318d30c3765d143/Image.php#L281-L306
okitcom/ok-lib-php
src/Service/BaseService.php
BaseService.getAttribute
public function getAttribute($attributes, $name) { foreach($attributes as $a) { if ($a->key == $name) { return $a->value; } } return null; }
php
public function getAttribute($attributes, $name) { foreach($attributes as $a) { if ($a->key == $name) { return $a->value; } } return null; }
[ "public", "function", "getAttribute", "(", "$", "attributes", ",", "$", "name", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "a", ")", "{", "if", "(", "$", "a", "->", "key", "==", "$", "name", ")", "{", "return", "$", "a", "->", "value", ";", "}", "}", "return", "null", ";", "}" ]
Returns the value of attribute with name @param $attributes array of attributes @param $name string Attribute's name @return mixed Attribute value
[ "Returns", "the", "value", "of", "attribute", "with", "name" ]
train
https://github.com/okitcom/ok-lib-php/blob/1f441f3d216af7c952788e864bfe66bc4f089467/src/Service/BaseService.php#L33-L40
shiftio/safestream-php-sdk
src/Http/SafeStreamHttpClient.php
SafeStreamHttpClient.getAuthToken
public function getAuthToken() { try { $response = $this->client->request('GET', "authenticate/accessToken", ['headers' => [ 'x-api-client-id' => $this->clientId, 'x-api-key' => $this->apiKey ]]); $this->authToken = json_decode($response->getBody())->token; return $this->authToken; } catch (GuzzleHttp\Exception\RequestException $e) { $this->handleExceptionResult($e); } }
php
public function getAuthToken() { try { $response = $this->client->request('GET', "authenticate/accessToken", ['headers' => [ 'x-api-client-id' => $this->clientId, 'x-api-key' => $this->apiKey ]]); $this->authToken = json_decode($response->getBody())->token; return $this->authToken; } catch (GuzzleHttp\Exception\RequestException $e) { $this->handleExceptionResult($e); } }
[ "public", "function", "getAuthToken", "(", ")", "{", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "request", "(", "'GET'", ",", "\"authenticate/accessToken\"", ",", "[", "'headers'", "=>", "[", "'x-api-client-id'", "=>", "$", "this", "->", "clientId", ",", "'x-api-key'", "=>", "$", "this", "->", "apiKey", "]", "]", ")", ";", "$", "this", "->", "authToken", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ")", "->", "token", ";", "return", "$", "this", "->", "authToken", ";", "}", "catch", "(", "GuzzleHttp", "\\", "Exception", "\\", "RequestException", "$", "e", ")", "{", "$", "this", "->", "handleExceptionResult", "(", "$", "e", ")", ";", "}", "}" ]
Gets an authorization token using the clients API key. Most requests to the SafeStream API require an authorization token. @return mixed: The JSON decoded response @throws SafeStreamHttpAuthException @throws SafeStreamHttpBadRequestException @throws SafeStreamHttpException @throws SafeStreamHttpThrottleException
[ "Gets", "an", "authorization", "token", "using", "the", "clients", "API", "key", ".", "Most", "requests", "to", "the", "SafeStream", "API", "require", "an", "authorization", "token", "." ]
train
https://github.com/shiftio/safestream-php-sdk/blob/1957cd5574725b24da1bbff9059aa30a9ca123c2/src/Http/SafeStreamHttpClient.php#L167-L180
apioo/psx-sandbox
src/Printer.php
Printer.pParam
protected function pParam(Node\Param $node) { return ($node->type ? $this->pType($node->type) . ' ' : '') . ($node->byRef ? '&' : '') . ($node->variadic ? '...' : '') . '$' . $node->name . ($node->default ? ' = ' . $this->p($node->default) : ''); }
php
protected function pParam(Node\Param $node) { return ($node->type ? $this->pType($node->type) . ' ' : '') . ($node->byRef ? '&' : '') . ($node->variadic ? '...' : '') . '$' . $node->name . ($node->default ? ' = ' . $this->p($node->default) : ''); }
[ "protected", "function", "pParam", "(", "Node", "\\", "Param", "$", "node", ")", "{", "return", "(", "$", "node", "->", "type", "?", "$", "this", "->", "pType", "(", "$", "node", "->", "type", ")", ".", "' '", ":", "''", ")", ".", "(", "$", "node", "->", "byRef", "?", "'&'", ":", "''", ")", ".", "(", "$", "node", "->", "variadic", "?", "'...'", ":", "''", ")", ".", "'$'", ".", "$", "node", "->", "name", ".", "(", "$", "node", "->", "default", "?", "' = '", ".", "$", "this", "->", "p", "(", "$", "node", "->", "default", ")", ":", "''", ")", ";", "}" ]
Special nodes
[ "Special", "nodes" ]
train
https://github.com/apioo/psx-sandbox/blob/5d136a398da375056e6526bbbc85d7f5d3df9441/src/Printer.php#L60-L67
apioo/psx-sandbox
src/Printer.php
Printer.pScalar_String
protected function pScalar_String(Scalar\String_ $node) { $kind = $node->getAttribute('kind', Scalar\String_::KIND_SINGLE_QUOTED); switch ($kind) { case Scalar\String_::KIND_NOWDOC: $label = $node->getAttribute('docLabel'); if ($label && !$this->containsEndLabel($node->value, $label)) { if ($node->value === '') { return $this->pNoIndent("<<<'$label'\n$label") . $this->docStringEndToken; } return $this->pNoIndent("<<<'$label'\n$node->value\n$label") . $this->docStringEndToken; } /* break missing intentionally */ case Scalar\String_::KIND_SINGLE_QUOTED: return '\'' . $this->pNoIndent(addcslashes($node->value, '\'\\')) . '\''; case Scalar\String_::KIND_HEREDOC: $label = $node->getAttribute('docLabel'); if ($label && !$this->containsEndLabel($node->value, $label)) { if ($node->value === '') { return $this->pNoIndent("<<<$label\n$label") . $this->docStringEndToken; } $escaped = $this->escapeString($node->value, null); return $this->pNoIndent("<<<$label\n" . $escaped . "\n$label") . $this->docStringEndToken; } /* break missing intentionally */ case Scalar\String_::KIND_DOUBLE_QUOTED: return '"' . $this->escapeString($node->value, '"') . '"'; } throw new \Exception('Invalid string kind'); }
php
protected function pScalar_String(Scalar\String_ $node) { $kind = $node->getAttribute('kind', Scalar\String_::KIND_SINGLE_QUOTED); switch ($kind) { case Scalar\String_::KIND_NOWDOC: $label = $node->getAttribute('docLabel'); if ($label && !$this->containsEndLabel($node->value, $label)) { if ($node->value === '') { return $this->pNoIndent("<<<'$label'\n$label") . $this->docStringEndToken; } return $this->pNoIndent("<<<'$label'\n$node->value\n$label") . $this->docStringEndToken; } /* break missing intentionally */ case Scalar\String_::KIND_SINGLE_QUOTED: return '\'' . $this->pNoIndent(addcslashes($node->value, '\'\\')) . '\''; case Scalar\String_::KIND_HEREDOC: $label = $node->getAttribute('docLabel'); if ($label && !$this->containsEndLabel($node->value, $label)) { if ($node->value === '') { return $this->pNoIndent("<<<$label\n$label") . $this->docStringEndToken; } $escaped = $this->escapeString($node->value, null); return $this->pNoIndent("<<<$label\n" . $escaped . "\n$label") . $this->docStringEndToken; } /* break missing intentionally */ case Scalar\String_::KIND_DOUBLE_QUOTED: return '"' . $this->escapeString($node->value, '"') . '"'; } throw new \Exception('Invalid string kind'); }
[ "protected", "function", "pScalar_String", "(", "Scalar", "\\", "String_", "$", "node", ")", "{", "$", "kind", "=", "$", "node", "->", "getAttribute", "(", "'kind'", ",", "Scalar", "\\", "String_", "::", "KIND_SINGLE_QUOTED", ")", ";", "switch", "(", "$", "kind", ")", "{", "case", "Scalar", "\\", "String_", "::", "KIND_NOWDOC", ":", "$", "label", "=", "$", "node", "->", "getAttribute", "(", "'docLabel'", ")", ";", "if", "(", "$", "label", "&&", "!", "$", "this", "->", "containsEndLabel", "(", "$", "node", "->", "value", ",", "$", "label", ")", ")", "{", "if", "(", "$", "node", "->", "value", "===", "''", ")", "{", "return", "$", "this", "->", "pNoIndent", "(", "\"<<<'$label'\\n$label\"", ")", ".", "$", "this", "->", "docStringEndToken", ";", "}", "return", "$", "this", "->", "pNoIndent", "(", "\"<<<'$label'\\n$node->value\\n$label\"", ")", ".", "$", "this", "->", "docStringEndToken", ";", "}", "/* break missing intentionally */", "case", "Scalar", "\\", "String_", "::", "KIND_SINGLE_QUOTED", ":", "return", "'\\''", ".", "$", "this", "->", "pNoIndent", "(", "addcslashes", "(", "$", "node", "->", "value", ",", "'\\'\\\\'", ")", ")", ".", "'\\''", ";", "case", "Scalar", "\\", "String_", "::", "KIND_HEREDOC", ":", "$", "label", "=", "$", "node", "->", "getAttribute", "(", "'docLabel'", ")", ";", "if", "(", "$", "label", "&&", "!", "$", "this", "->", "containsEndLabel", "(", "$", "node", "->", "value", ",", "$", "label", ")", ")", "{", "if", "(", "$", "node", "->", "value", "===", "''", ")", "{", "return", "$", "this", "->", "pNoIndent", "(", "\"<<<$label\\n$label\"", ")", ".", "$", "this", "->", "docStringEndToken", ";", "}", "$", "escaped", "=", "$", "this", "->", "escapeString", "(", "$", "node", "->", "value", ",", "null", ")", ";", "return", "$", "this", "->", "pNoIndent", "(", "\"<<<$label\\n\"", ".", "$", "escaped", ".", "\"\\n$label\"", ")", ".", "$", "this", "->", "docStringEndToken", ";", "}", "/* break missing intentionally */", "case", "Scalar", "\\", "String_", "::", "KIND_DOUBLE_QUOTED", ":", "return", "'\"'", ".", "$", "this", "->", "escapeString", "(", "$", "node", "->", "value", ",", "'\"'", ")", ".", "'\"'", ";", "}", "throw", "new", "\\", "Exception", "(", "'Invalid string kind'", ")", ";", "}" ]
Scalars
[ "Scalars" ]
train
https://github.com/apioo/psx-sandbox/blob/5d136a398da375056e6526bbbc85d7f5d3df9441/src/Printer.php#L145-L178
apioo/psx-sandbox
src/Printer.php
Printer.pExpr_BinaryOp_Plus
protected function pExpr_BinaryOp_Plus(BinaryOp\Plus $node) { return $this->pInfixOp('Expr_BinaryOp_Plus', $node->left, ' + ', $node->right); }
php
protected function pExpr_BinaryOp_Plus(BinaryOp\Plus $node) { return $this->pInfixOp('Expr_BinaryOp_Plus', $node->left, ' + ', $node->right); }
[ "protected", "function", "pExpr_BinaryOp_Plus", "(", "BinaryOp", "\\", "Plus", "$", "node", ")", "{", "return", "$", "this", "->", "pInfixOp", "(", "'Expr_BinaryOp_Plus'", ",", "$", "node", "->", "left", ",", "' + '", ",", "$", "node", "->", "right", ")", ";", "}" ]
Binary expressions
[ "Binary", "expressions" ]
train
https://github.com/apioo/psx-sandbox/blob/5d136a398da375056e6526bbbc85d7f5d3df9441/src/Printer.php#L327-L330
apioo/psx-sandbox
src/Printer.php
Printer.pExpr_FuncCall
protected function pExpr_FuncCall(Expr\FuncCall $node) { $functionName = $this->pCallLhs($node->name); $this->securityManager->checkFunctionCall($functionName, $node->args); return $functionName . '(' . $this->pMaybeMultiline($node->args) . ')'; }
php
protected function pExpr_FuncCall(Expr\FuncCall $node) { $functionName = $this->pCallLhs($node->name); $this->securityManager->checkFunctionCall($functionName, $node->args); return $functionName . '(' . $this->pMaybeMultiline($node->args) . ')'; }
[ "protected", "function", "pExpr_FuncCall", "(", "Expr", "\\", "FuncCall", "$", "node", ")", "{", "$", "functionName", "=", "$", "this", "->", "pCallLhs", "(", "$", "node", "->", "name", ")", ";", "$", "this", "->", "securityManager", "->", "checkFunctionCall", "(", "$", "functionName", ",", "$", "node", "->", "args", ")", ";", "return", "$", "functionName", ".", "'('", ".", "$", "this", "->", "pMaybeMultiline", "(", "$", "node", "->", "args", ")", ".", "')'", ";", "}" ]
Function calls and similar constructs
[ "Function", "calls", "and", "similar", "constructs" ]
train
https://github.com/apioo/psx-sandbox/blob/5d136a398da375056e6526bbbc85d7f5d3df9441/src/Printer.php#L563-L571
zodream/thirdparty
src/ALi/ZhiMa.php
ZhiMa.authQuery
public function authQuery($userId) { $data = $this->getAuthQuery()->parameters([ 'identity_param' => Json::encode([ 'userId' => $userId ]) ])->text(); return isset($data['authorized']) && $data['authorized']; }
php
public function authQuery($userId) { $data = $this->getAuthQuery()->parameters([ 'identity_param' => Json::encode([ 'userId' => $userId ]) ])->text(); return isset($data['authorized']) && $data['authorized']; }
[ "public", "function", "authQuery", "(", "$", "userId", ")", "{", "$", "data", "=", "$", "this", "->", "getAuthQuery", "(", ")", "->", "parameters", "(", "[", "'identity_param'", "=>", "Json", "::", "encode", "(", "[", "'userId'", "=>", "$", "userId", "]", ")", "]", ")", "->", "text", "(", ")", ";", "return", "isset", "(", "$", "data", "[", "'authorized'", "]", ")", "&&", "$", "data", "[", "'authorized'", "]", ";", "}" ]
判断用户是否授权 @param $userId @return bool @throws \Exception
[ "判断用户是否授权" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/ZhiMa.php#L70-L77
zodream/thirdparty
src/ALi/ZhiMa.php
ZhiMa.hasScore
public function hasScore($cert_no, $score, $cert_type = 'IDENTITY_CARD') { $data = $this->getHasScore()->parameters([ 'cert_type' => $cert_type, 'cert_no' => $cert_no, 'admittance_score' => $score, ])->text(); return isset($data['is_admittance']) && $data['is_admittance'] == 'Y'; }
php
public function hasScore($cert_no, $score, $cert_type = 'IDENTITY_CARD') { $data = $this->getHasScore()->parameters([ 'cert_type' => $cert_type, 'cert_no' => $cert_no, 'admittance_score' => $score, ])->text(); return isset($data['is_admittance']) && $data['is_admittance'] == 'Y'; }
[ "public", "function", "hasScore", "(", "$", "cert_no", ",", "$", "score", ",", "$", "cert_type", "=", "'IDENTITY_CARD'", ")", "{", "$", "data", "=", "$", "this", "->", "getHasScore", "(", ")", "->", "parameters", "(", "[", "'cert_type'", "=>", "$", "cert_type", ",", "'cert_no'", "=>", "$", "cert_no", ",", "'admittance_score'", "=>", "$", "score", ",", "]", ")", "->", "text", "(", ")", ";", "return", "isset", "(", "$", "data", "[", "'is_admittance'", "]", ")", "&&", "$", "data", "[", "'is_admittance'", "]", "==", "'Y'", ";", "}" ]
用于商户做准入判断 商户输入准入分 判断用户是否准入 @param $cert_no @param $score @param string $cert_type @return bool @throws \Exception
[ "用于商户做准入判断", "商户输入准入分", "判断用户是否准入" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/ZhiMa.php#L102-L109
webforge-labs/psc-cms
lib/Psc/Doctrine/Annotation.php
Annotation.getClosureHelpers
public static function getClosureHelpers() { // constructor $doctrineAnnotation = function ($shortName, Array $properties = array()) { return \Psc\Doctrine\Annotation::createDC($shortName)->setProperties($properties); }; // others $joinColumn = function ($name, $referencedColumnName = 'id', $onDelete = NULL) use ($doctrineAnnotation) { $properties = compact('name','referencedColumnName','onDelete'); return $doctrineAnnotation('joinColumn', $properties); }; $joinTable = function ($name, $joinColumns = array(), $inverseJoinColumns = array()) use ($doctrineAnnotation) { if (!is_array($joinColumns)) $joinColumns = array($joinColumns); if (!is_array($inverseJoinColumns)) $inverseJoinColumns = array($inverseJoinColumns); $properties = compact('name','joinColumns','inverseJoinColumns'); return $doctrineAnnotation('joinTable', $properties); }; // Relations $manyToMany = function ($targetEntity, Array $inversedOrMapped = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $inversedOrMapped); // inversedOrMapped fügt dann inversedBy oder mappedBy den Properties hinzu return $doctrineAnnotation('ManyToMany', $properties); }; $oneToMany = function ($targetEntity, Array $mapped = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $mapped); return $doctrineAnnotation('OneToMany', $properties); }; $manyToOne = function ($targetEntity, Array $inversed = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $inversed); return $doctrineAnnotation('ManyToOne', $properties); }; $oneToOne = function ($targetEntity, Array $inversedOrMapped = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $inversedOrMapped); return $doctrineAnnotation('OneToOne', $properties); }; // HelpersHelpers $inversedBy = function($propertyName) { return array('inversedBy'=>$propertyName); }; $mappedBy = function($propertyName) { return array('mappedBy'=>$propertyName); }; return compact('inversedBy','mappedBy','oneToOne', 'manyToMany','manyToOne','oneToMany','joinTable','joinColumn'); }
php
public static function getClosureHelpers() { // constructor $doctrineAnnotation = function ($shortName, Array $properties = array()) { return \Psc\Doctrine\Annotation::createDC($shortName)->setProperties($properties); }; // others $joinColumn = function ($name, $referencedColumnName = 'id', $onDelete = NULL) use ($doctrineAnnotation) { $properties = compact('name','referencedColumnName','onDelete'); return $doctrineAnnotation('joinColumn', $properties); }; $joinTable = function ($name, $joinColumns = array(), $inverseJoinColumns = array()) use ($doctrineAnnotation) { if (!is_array($joinColumns)) $joinColumns = array($joinColumns); if (!is_array($inverseJoinColumns)) $inverseJoinColumns = array($inverseJoinColumns); $properties = compact('name','joinColumns','inverseJoinColumns'); return $doctrineAnnotation('joinTable', $properties); }; // Relations $manyToMany = function ($targetEntity, Array $inversedOrMapped = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $inversedOrMapped); // inversedOrMapped fügt dann inversedBy oder mappedBy den Properties hinzu return $doctrineAnnotation('ManyToMany', $properties); }; $oneToMany = function ($targetEntity, Array $mapped = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $mapped); return $doctrineAnnotation('OneToMany', $properties); }; $manyToOne = function ($targetEntity, Array $inversed = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $inversed); return $doctrineAnnotation('ManyToOne', $properties); }; $oneToOne = function ($targetEntity, Array $inversedOrMapped = array(), Array $cascade = NULL, $fetch = 'LAZY') use ($doctrineAnnotation) { $properties = array_merge(compact('targetEntity','cascade','fetch'), $inversedOrMapped); return $doctrineAnnotation('OneToOne', $properties); }; // HelpersHelpers $inversedBy = function($propertyName) { return array('inversedBy'=>$propertyName); }; $mappedBy = function($propertyName) { return array('mappedBy'=>$propertyName); }; return compact('inversedBy','mappedBy','oneToOne', 'manyToMany','manyToOne','oneToMany','joinTable','joinColumn'); }
[ "public", "static", "function", "getClosureHelpers", "(", ")", "{", "// constructor", "$", "doctrineAnnotation", "=", "function", "(", "$", "shortName", ",", "Array", "$", "properties", "=", "array", "(", ")", ")", "{", "return", "\\", "Psc", "\\", "Doctrine", "\\", "Annotation", "::", "createDC", "(", "$", "shortName", ")", "->", "setProperties", "(", "$", "properties", ")", ";", "}", ";", "// others", "$", "joinColumn", "=", "function", "(", "$", "name", ",", "$", "referencedColumnName", "=", "'id'", ",", "$", "onDelete", "=", "NULL", ")", "use", "(", "$", "doctrineAnnotation", ")", "{", "$", "properties", "=", "compact", "(", "'name'", ",", "'referencedColumnName'", ",", "'onDelete'", ")", ";", "return", "$", "doctrineAnnotation", "(", "'joinColumn'", ",", "$", "properties", ")", ";", "}", ";", "$", "joinTable", "=", "function", "(", "$", "name", ",", "$", "joinColumns", "=", "array", "(", ")", ",", "$", "inverseJoinColumns", "=", "array", "(", ")", ")", "use", "(", "$", "doctrineAnnotation", ")", "{", "if", "(", "!", "is_array", "(", "$", "joinColumns", ")", ")", "$", "joinColumns", "=", "array", "(", "$", "joinColumns", ")", ";", "if", "(", "!", "is_array", "(", "$", "inverseJoinColumns", ")", ")", "$", "inverseJoinColumns", "=", "array", "(", "$", "inverseJoinColumns", ")", ";", "$", "properties", "=", "compact", "(", "'name'", ",", "'joinColumns'", ",", "'inverseJoinColumns'", ")", ";", "return", "$", "doctrineAnnotation", "(", "'joinTable'", ",", "$", "properties", ")", ";", "}", ";", "// Relations", "$", "manyToMany", "=", "function", "(", "$", "targetEntity", ",", "Array", "$", "inversedOrMapped", "=", "array", "(", ")", ",", "Array", "$", "cascade", "=", "NULL", ",", "$", "fetch", "=", "'LAZY'", ")", "use", "(", "$", "doctrineAnnotation", ")", "{", "$", "properties", "=", "array_merge", "(", "compact", "(", "'targetEntity'", ",", "'cascade'", ",", "'fetch'", ")", ",", "$", "inversedOrMapped", ")", ";", "// inversedOrMapped fügt dann inversedBy oder mappedBy den Properties hinzu", "return", "$", "doctrineAnnotation", "(", "'ManyToMany'", ",", "$", "properties", ")", ";", "}", ";", "$", "oneToMany", "=", "function", "(", "$", "targetEntity", ",", "Array", "$", "mapped", "=", "array", "(", ")", ",", "Array", "$", "cascade", "=", "NULL", ",", "$", "fetch", "=", "'LAZY'", ")", "use", "(", "$", "doctrineAnnotation", ")", "{", "$", "properties", "=", "array_merge", "(", "compact", "(", "'targetEntity'", ",", "'cascade'", ",", "'fetch'", ")", ",", "$", "mapped", ")", ";", "return", "$", "doctrineAnnotation", "(", "'OneToMany'", ",", "$", "properties", ")", ";", "}", ";", "$", "manyToOne", "=", "function", "(", "$", "targetEntity", ",", "Array", "$", "inversed", "=", "array", "(", ")", ",", "Array", "$", "cascade", "=", "NULL", ",", "$", "fetch", "=", "'LAZY'", ")", "use", "(", "$", "doctrineAnnotation", ")", "{", "$", "properties", "=", "array_merge", "(", "compact", "(", "'targetEntity'", ",", "'cascade'", ",", "'fetch'", ")", ",", "$", "inversed", ")", ";", "return", "$", "doctrineAnnotation", "(", "'ManyToOne'", ",", "$", "properties", ")", ";", "}", ";", "$", "oneToOne", "=", "function", "(", "$", "targetEntity", ",", "Array", "$", "inversedOrMapped", "=", "array", "(", ")", ",", "Array", "$", "cascade", "=", "NULL", ",", "$", "fetch", "=", "'LAZY'", ")", "use", "(", "$", "doctrineAnnotation", ")", "{", "$", "properties", "=", "array_merge", "(", "compact", "(", "'targetEntity'", ",", "'cascade'", ",", "'fetch'", ")", ",", "$", "inversedOrMapped", ")", ";", "return", "$", "doctrineAnnotation", "(", "'OneToOne'", ",", "$", "properties", ")", ";", "}", ";", "// HelpersHelpers", "$", "inversedBy", "=", "function", "(", "$", "propertyName", ")", "{", "return", "array", "(", "'inversedBy'", "=>", "$", "propertyName", ")", ";", "}", ";", "$", "mappedBy", "=", "function", "(", "$", "propertyName", ")", "{", "return", "array", "(", "'mappedBy'", "=>", "$", "propertyName", ")", ";", "}", ";", "return", "compact", "(", "'inversedBy'", ",", "'mappedBy'", ",", "'oneToOne'", ",", "'manyToMany'", ",", "'manyToOne'", ",", "'oneToMany'", ",", "'joinTable'", ",", "'joinColumn'", ")", ";", "}" ]
Gibt alle Helpers für DoctrineAnnotations (oder andere) zurück Jeder Closure-Helper stellt eine Annotation dar und gibt für diese ein explizites interface: - $joinTable($name, $joinColumn(s), $inverseJoinColumn(s)) für die columns kann ein array angegeben werden, muss aber nicht - $joinColumn($name, $referencedColumnName, $onDelete) - $manyToMany($targetEntity, $inversedBy($propertyName), Array $cascade, $fetch) - $manyToMany($targetEntity, $mappedBy($propertyName), Array $cascade, $fetch) - $oneToMany($targetEntity, $mappedBy($propertyName), Array $cascade, $fetch) - $ManyToOne($targetEntity, $inversedBy($propertyName), Array $cascade, $fetch) - $inversedBy($propertyName) - $mappedBy($propertyName) - $doctrineAnnotation($name) erzeugt eine Doctrine\ORM\Mapping\$name - Psc\Doctrine\Annotation @return Array
[ "Gibt", "alle", "Helpers", "für", "DoctrineAnnotations", "(", "oder", "andere", ")", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/Annotation.php#L146-L204
atkrad/data-tables
src/Column.php
Column.setCreatedCell
public function setCreatedCell($createdCell) { $hash = sha1($createdCell); $this->properties['createdCell'] = $hash; $this->callbacks[$hash] = $createdCell; return $this; }
php
public function setCreatedCell($createdCell) { $hash = sha1($createdCell); $this->properties['createdCell'] = $hash; $this->callbacks[$hash] = $createdCell; return $this; }
[ "public", "function", "setCreatedCell", "(", "$", "createdCell", ")", "{", "$", "hash", "=", "sha1", "(", "$", "createdCell", ")", ";", "$", "this", "->", "properties", "[", "'createdCell'", "]", "=", "$", "hash", ";", "$", "this", "->", "callbacks", "[", "$", "hash", "]", "=", "$", "createdCell", ";", "return", "$", "this", ";", "}" ]
This is a callback function that is executed whenever a cell is created (Ajax source, etc) or read from a DOM source. It can be used as a compliment to columns.renderDT allowing modification of the cell's DOM element (add background colour for example) when the element is created (cells my not be immediately created on table initialisation if deferRenderDT is enabled, or if rows are dynamically added using the API (rows.add()DT). @param callback $createdCell Cell created callback to allow DOM manipulation. @return Column @see http://datatables.net/reference/option/columns.createdCell
[ "This", "is", "a", "callback", "function", "that", "is", "executed", "whenever", "a", "cell", "is", "created", "(", "Ajax", "source", "etc", ")", "or", "read", "from", "a", "DOM", "source", ".", "It", "can", "be", "used", "as", "a", "compliment", "to", "columns", ".", "renderDT", "allowing", "modification", "of", "the", "cell", "s", "DOM", "element", "(", "add", "background", "colour", "for", "example", ")", "when", "the", "element", "is", "created", "(", "cells", "my", "not", "be", "immediately", "created", "on", "table", "initialisation", "if", "deferRenderDT", "is", "enabled", "or", "if", "rows", "are", "dynamically", "added", "using", "the", "API", "(", "rows", ".", "add", "()", "DT", ")", "." ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/Column.php#L113-L120
atkrad/data-tables
src/Column.php
Column.setData
public function setData($data) { if (is_string($data)) { $pattern = '/^(\s+)*(function)(\s+)*\(/i'; if (preg_match($pattern, $data, $matches) && strtolower($matches[2]) == 'function') { $hash = sha1($data); $this->properties['data'] = $hash; $this->callbacks[$hash] = $data; return $this; } $this->properties['data'] = $data; return $this; } else { $this->properties['data'] = $data; return $this; } }
php
public function setData($data) { if (is_string($data)) { $pattern = '/^(\s+)*(function)(\s+)*\(/i'; if (preg_match($pattern, $data, $matches) && strtolower($matches[2]) == 'function') { $hash = sha1($data); $this->properties['data'] = $hash; $this->callbacks[$hash] = $data; return $this; } $this->properties['data'] = $data; return $this; } else { $this->properties['data'] = $data; return $this; } }
[ "public", "function", "setData", "(", "$", "data", ")", "{", "if", "(", "is_string", "(", "$", "data", ")", ")", "{", "$", "pattern", "=", "'/^(\\s+)*(function)(\\s+)*\\(/i'", ";", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "data", ",", "$", "matches", ")", "&&", "strtolower", "(", "$", "matches", "[", "2", "]", ")", "==", "'function'", ")", "{", "$", "hash", "=", "sha1", "(", "$", "data", ")", ";", "$", "this", "->", "properties", "[", "'data'", "]", "=", "$", "hash", ";", "$", "this", "->", "callbacks", "[", "$", "hash", "]", "=", "$", "data", ";", "return", "$", "this", ";", "}", "$", "this", "->", "properties", "[", "'data'", "]", "=", "$", "data", ";", "return", "$", "this", ";", "}", "else", "{", "$", "this", "->", "properties", "[", "'data'", "]", "=", "$", "data", ";", "return", "$", "this", ";", "}", "}" ]
Set the data source for the column from the rows data object / array This property can be used to read data from any data source property, including deeply nested objects / properties. data can be given in a number of different ways which effect its behaviour as documented below. @param int|string|null|js object|callback $data Set the data source for the column from the rows data object / array @return Column @see http://datatables.net/reference/option/columns.data
[ "Set", "the", "data", "source", "for", "the", "column", "from", "the", "rows", "data", "object", "/", "array" ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/Column.php#L135-L155
atkrad/data-tables
src/Column.php
Column.setRender
public function setRender($render) { if (is_string($render)) { $pattern = '/^(\s+)*(function)(\s+)*\(/i'; if (preg_match($pattern, $render, $matches) && strtolower($matches[2]) == 'function') { $hash = sha1($render); $this->properties['render'] = $hash; $this->callbacks[$hash] = $render; return $this; } $this->properties['render'] = $render; return $this; } else { $this->properties['render'] = $render; return $this; } }
php
public function setRender($render) { if (is_string($render)) { $pattern = '/^(\s+)*(function)(\s+)*\(/i'; if (preg_match($pattern, $render, $matches) && strtolower($matches[2]) == 'function') { $hash = sha1($render); $this->properties['render'] = $hash; $this->callbacks[$hash] = $render; return $this; } $this->properties['render'] = $render; return $this; } else { $this->properties['render'] = $render; return $this; } }
[ "public", "function", "setRender", "(", "$", "render", ")", "{", "if", "(", "is_string", "(", "$", "render", ")", ")", "{", "$", "pattern", "=", "'/^(\\s+)*(function)(\\s+)*\\(/i'", ";", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "render", ",", "$", "matches", ")", "&&", "strtolower", "(", "$", "matches", "[", "2", "]", ")", "==", "'function'", ")", "{", "$", "hash", "=", "sha1", "(", "$", "render", ")", ";", "$", "this", "->", "properties", "[", "'render'", "]", "=", "$", "hash", ";", "$", "this", "->", "callbacks", "[", "$", "hash", "]", "=", "$", "render", ";", "return", "$", "this", ";", "}", "$", "this", "->", "properties", "[", "'render'", "]", "=", "$", "render", ";", "return", "$", "this", ";", "}", "else", "{", "$", "this", "->", "properties", "[", "'render'", "]", "=", "$", "render", ";", "return", "$", "this", ";", "}", "}" ]
This property is the rendering partner to columns.dataDT and it is suggested that when you want to manipulate data for display (including filtering, sorting etc) without altering the underlying data for the table, use this property. render can be considered to be the the read only companion to data which is read / write (then as such more complex). Like data this option can be given in a number of different ways to effect its behaviour as described below. @param int|string|object|callback $render Render (process) the data for use in the table. @return Column @see http://datatables.net/reference/option/columns.render
[ "This", "property", "is", "the", "rendering", "partner", "to", "columns", ".", "dataDT", "and", "it", "is", "suggested", "that", "when", "you", "want", "to", "manipulate", "data", "for", "display", "(", "including", "filtering", "sorting", "etc", ")", "without", "altering", "the", "underlying", "data", "for", "the", "table", "use", "this", "property", ".", "render", "can", "be", "considered", "to", "be", "the", "the", "read", "only", "companion", "to", "data", "which", "is", "read", "/", "write", "(", "then", "as", "such", "more", "complex", ")", ".", "Like", "data", "this", "option", "can", "be", "given", "in", "a", "number", "of", "different", "ways", "to", "effect", "its", "behaviour", "as", "described", "below", "." ]
train
https://github.com/atkrad/data-tables/blob/5afcc337ab624ca626e29d9674459c5105982b16/src/Column.php#L289-L306
jacobemerick/pqp
src/Display.php
Display.getReadableTime
protected function getReadableTime($time, $percision = 3) { $unit = 's'; if ($time < 1) { $time *= 1000; $percision = 0; $unit = 'ms'; } elseif ($time > 60) { $time /= 60; $unit = 'm'; } $time = number_format($time, $percision); return "{$time} {$unit}"; }
php
protected function getReadableTime($time, $percision = 3) { $unit = 's'; if ($time < 1) { $time *= 1000; $percision = 0; $unit = 'ms'; } elseif ($time > 60) { $time /= 60; $unit = 'm'; } $time = number_format($time, $percision); return "{$time} {$unit}"; }
[ "protected", "function", "getReadableTime", "(", "$", "time", ",", "$", "percision", "=", "3", ")", "{", "$", "unit", "=", "'s'", ";", "if", "(", "$", "time", "<", "1", ")", "{", "$", "time", "*=", "1000", ";", "$", "percision", "=", "0", ";", "$", "unit", "=", "'ms'", ";", "}", "elseif", "(", "$", "time", ">", "60", ")", "{", "$", "time", "/=", "60", ";", "$", "unit", "=", "'m'", ";", "}", "$", "time", "=", "number_format", "(", "$", "time", ",", "$", "percision", ")", ";", "return", "\"{$time} {$unit}\"", ";", "}" ]
Formatter for human-readable time Only handles time up to 60 minutes gracefully @param double $time @param integer $percision @return string
[ "Formatter", "for", "human", "-", "readable", "time", "Only", "handles", "time", "up", "to", "60", "minutes", "gracefully" ]
train
https://github.com/jacobemerick/pqp/blob/08276f050425d1ab71e7ca3b897eb8c409ccbe70/src/Display.php#L311-L324
jacobemerick/pqp
src/Display.php
Display.getReadableMemory
protected function getReadableMemory($size, $percision = 2) { $unitOptions = array('b', 'k', 'M', 'G'); $base = log($size, 1024); $memory = round(pow(1024, $base - floor($base)), $percision); $unit = $unitOptions[floor($base)]; return "{$memory} {$unit}"; }
php
protected function getReadableMemory($size, $percision = 2) { $unitOptions = array('b', 'k', 'M', 'G'); $base = log($size, 1024); $memory = round(pow(1024, $base - floor($base)), $percision); $unit = $unitOptions[floor($base)]; return "{$memory} {$unit}"; }
[ "protected", "function", "getReadableMemory", "(", "$", "size", ",", "$", "percision", "=", "2", ")", "{", "$", "unitOptions", "=", "array", "(", "'b'", ",", "'k'", ",", "'M'", ",", "'G'", ")", ";", "$", "base", "=", "log", "(", "$", "size", ",", "1024", ")", ";", "$", "memory", "=", "round", "(", "pow", "(", "1024", ",", "$", "base", "-", "floor", "(", "$", "base", ")", ")", ",", "$", "percision", ")", ";", "$", "unit", "=", "$", "unitOptions", "[", "floor", "(", "$", "base", ")", "]", ";", "return", "\"{$memory} {$unit}\"", ";", "}" ]
Formatter for human-readable memory Only handles time up to a few gigs gracefully @param double $size @param integer $percision
[ "Formatter", "for", "human", "-", "readable", "memory", "Only", "handles", "time", "up", "to", "a", "few", "gigs", "gracefully" ]
train
https://github.com/jacobemerick/pqp/blob/08276f050425d1ab71e7ca3b897eb8c409ccbe70/src/Display.php#L333-L342
webforge-labs/psc-cms
lib/Psc/CMS/Service/ControllerService.php
ControllerService.isResponsibleFor
public function isResponsibleFor(ServiceRequest $request) { /* hier könnte man mal den request hashen, dann den controller suchen und zu dem hash speichern dann könnte man den controller bei route() direkt aufrufen */ $this->log('überprüfe ob verantwortlich für: '.$request->debug()); try { return $this->doResponsibleFor($request); } catch (\Psc\CMS\Service\ControllerRouteException $e) { $this->log('fail: '.$e->getMessage()); } catch (\Psc\Net\HTTP\HTTPException $e) { $this->log('fail: '.$e->debug()); } catch (\Psc\Net\RequestMatchingException $e) { $this->log('fail: '.$e->getMessage()); } return FALSE; }
php
public function isResponsibleFor(ServiceRequest $request) { /* hier könnte man mal den request hashen, dann den controller suchen und zu dem hash speichern dann könnte man den controller bei route() direkt aufrufen */ $this->log('überprüfe ob verantwortlich für: '.$request->debug()); try { return $this->doResponsibleFor($request); } catch (\Psc\CMS\Service\ControllerRouteException $e) { $this->log('fail: '.$e->getMessage()); } catch (\Psc\Net\HTTP\HTTPException $e) { $this->log('fail: '.$e->debug()); } catch (\Psc\Net\RequestMatchingException $e) { $this->log('fail: '.$e->getMessage()); } return FALSE; }
[ "public", "function", "isResponsibleFor", "(", "ServiceRequest", "$", "request", ")", "{", "/*\n hier könnte man mal den request hashen, dann den controller suchen und zu dem hash speichern\n dann könnte man den controller bei route() direkt aufrufen\n */", "$", "this", "->", "log", "(", "'überprüfe ob verantwortlich für: '.$r", "e", "q", "uest->d", "eb", "ug())", ";", "", "", "", "try", "{", "return", "$", "this", "->", "doResponsibleFor", "(", "$", "request", ")", ";", "}", "catch", "(", "\\", "Psc", "\\", "CMS", "\\", "Service", "\\", "ControllerRouteException", "$", "e", ")", "{", "$", "this", "->", "log", "(", "'fail: '", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "\\", "Psc", "\\", "Net", "\\", "HTTP", "\\", "HTTPException", "$", "e", ")", "{", "$", "this", "->", "log", "(", "'fail: '", ".", "$", "e", "->", "debug", "(", ")", ")", ";", "}", "catch", "(", "\\", "Psc", "\\", "Net", "\\", "RequestMatchingException", "$", "e", ")", "{", "$", "this", "->", "log", "(", "'fail: '", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "return", "FALSE", ";", "}" ]
Gibt True zurück wenn der Service den ServiceRequest erfolgreich bearbeiten kann @todo "erfolgreich" definieren @return bool
[ "Gibt", "True", "zurück", "wenn", "der", "Service", "den", "ServiceRequest", "erfolgreich", "bearbeiten", "kann" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Service/ControllerService.php#L58-L77
webforge-labs/psc-cms
lib/Psc/CMS/Service/ControllerService.php
ControllerService.route
public function route(ServiceRequest $request) { list ($controller, $method, $params) = $this->routeController($request); $this->validateController($controller, $method, $params); $this->runController( $controller, $method, $params ); return $this->response; }
php
public function route(ServiceRequest $request) { list ($controller, $method, $params) = $this->routeController($request); $this->validateController($controller, $method, $params); $this->runController( $controller, $method, $params ); return $this->response; }
[ "public", "function", "route", "(", "ServiceRequest", "$", "request", ")", "{", "list", "(", "$", "controller", ",", "$", "method", ",", "$", "params", ")", "=", "$", "this", "->", "routeController", "(", "$", "request", ")", ";", "$", "this", "->", "validateController", "(", "$", "controller", ",", "$", "method", ",", "$", "params", ")", ";", "$", "this", "->", "runController", "(", "$", "controller", ",", "$", "method", ",", "$", "params", ")", ";", "return", "$", "this", "->", "response", ";", "}" ]
Führt den ServiceRequest aus ruft den passenden ServiceController auf @return ServiceResponse
[ "Führt", "den", "ServiceRequest", "aus" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Service/ControllerService.php#L94-L104
webforge-labs/psc-cms
lib/Psc/CMS/Service/ControllerService.php
ControllerService.runController
public function runController($controller, $method, Array $params) { $transactional = $controller instanceof \Psc\CMS\Controller\TransactionalController; try { try { $this->logf('running Controller: %s::%s(%s)', Code::getClass($controller), $method, implode(', ',array_map(function ($param) { return Code::varInfo($param); }, $params))); $cb = new Callback($controller, $method); $controllerResponse = $cb->call($params); $this->log('Converting Controller Response'); $this->setResponseFromControllerResponse($controllerResponse); $this->log('Response Format: '.($this->response->getFormat() ?: 'null')); $this->log('successful run'); $this->log('überprüfe ResponseMetadataController'); if ($controller instanceof \Psc\CMS\Controller\ResponseMetadataController && ($meta = $controller->getResponseMetadata()) != NULL) { $this->response->setMetadata($meta); $this->log('Metadaten übertragen'); } /* PDO Exceptions */ } catch (\PDOException $e) { throw \Psc\Doctrine\Exception::convertPDOException($e); } } catch (\Exception $e) { if ($transactional && $controller->hasActiveTransaction()) $controller->rollbackTransaction(); $this->handleException($e); } }
php
public function runController($controller, $method, Array $params) { $transactional = $controller instanceof \Psc\CMS\Controller\TransactionalController; try { try { $this->logf('running Controller: %s::%s(%s)', Code::getClass($controller), $method, implode(', ',array_map(function ($param) { return Code::varInfo($param); }, $params))); $cb = new Callback($controller, $method); $controllerResponse = $cb->call($params); $this->log('Converting Controller Response'); $this->setResponseFromControllerResponse($controllerResponse); $this->log('Response Format: '.($this->response->getFormat() ?: 'null')); $this->log('successful run'); $this->log('überprüfe ResponseMetadataController'); if ($controller instanceof \Psc\CMS\Controller\ResponseMetadataController && ($meta = $controller->getResponseMetadata()) != NULL) { $this->response->setMetadata($meta); $this->log('Metadaten übertragen'); } /* PDO Exceptions */ } catch (\PDOException $e) { throw \Psc\Doctrine\Exception::convertPDOException($e); } } catch (\Exception $e) { if ($transactional && $controller->hasActiveTransaction()) $controller->rollbackTransaction(); $this->handleException($e); } }
[ "public", "function", "runController", "(", "$", "controller", ",", "$", "method", ",", "Array", "$", "params", ")", "{", "$", "transactional", "=", "$", "controller", "instanceof", "\\", "Psc", "\\", "CMS", "\\", "Controller", "\\", "TransactionalController", ";", "try", "{", "try", "{", "$", "this", "->", "logf", "(", "'running Controller: %s::%s(%s)'", ",", "Code", "::", "getClass", "(", "$", "controller", ")", ",", "$", "method", ",", "implode", "(", "', '", ",", "array_map", "(", "function", "(", "$", "param", ")", "{", "return", "Code", "::", "varInfo", "(", "$", "param", ")", ";", "}", ",", "$", "params", ")", ")", ")", ";", "$", "cb", "=", "new", "Callback", "(", "$", "controller", ",", "$", "method", ")", ";", "$", "controllerResponse", "=", "$", "cb", "->", "call", "(", "$", "params", ")", ";", "$", "this", "->", "log", "(", "'Converting Controller Response'", ")", ";", "$", "this", "->", "setResponseFromControllerResponse", "(", "$", "controllerResponse", ")", ";", "$", "this", "->", "log", "(", "'Response Format: '", ".", "(", "$", "this", "->", "response", "->", "getFormat", "(", ")", "?", ":", "'null'", ")", ")", ";", "$", "this", "->", "log", "(", "'successful run'", ")", ";", "$", "this", "->", "log", "(", "'überprüfe ResponseMetadataController');", "", "", "if", "(", "$", "controller", "instanceof", "\\", "Psc", "\\", "CMS", "\\", "Controller", "\\", "ResponseMetadataController", "&&", "(", "$", "meta", "=", "$", "controller", "->", "getResponseMetadata", "(", ")", ")", "!=", "NULL", ")", "{", "$", "this", "->", "response", "->", "setMetadata", "(", "$", "meta", ")", ";", "$", "this", "->", "log", "(", "'Metadaten übertragen')", ";", "", "}", "/* PDO Exceptions */", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "throw", "\\", "Psc", "\\", "Doctrine", "\\", "Exception", "::", "convertPDOException", "(", "$", "e", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "transactional", "&&", "$", "controller", "->", "hasActiveTransaction", "(", ")", ")", "$", "controller", "->", "rollbackTransaction", "(", ")", ";", "$", "this", "->", "handleException", "(", "$", "e", ")", ";", "}", "}" ]
Führt den Controller aus catched dabei Exceptions und wandelt diese gegebenfalls in Error-Responses um
[ "Führt", "den", "Controller", "aus" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Service/ControllerService.php#L126-L157
webforge-labs/psc-cms
lib/Psc/CMS/Service/ControllerService.php
ControllerService.getControllersNamespace
public function getControllersNamespace() { if (!isset($this->controllersNamespace)) { $this->controllersNamespace = $this->project->getNamespace().'\\Controllers'; // siehe auch CreateControllerCommand, SimpleContainerEntityService } return $this->controllersNamespace; }
php
public function getControllersNamespace() { if (!isset($this->controllersNamespace)) { $this->controllersNamespace = $this->project->getNamespace().'\\Controllers'; // siehe auch CreateControllerCommand, SimpleContainerEntityService } return $this->controllersNamespace; }
[ "public", "function", "getControllersNamespace", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "controllersNamespace", ")", ")", "{", "$", "this", "->", "controllersNamespace", "=", "$", "this", "->", "project", "->", "getNamespace", "(", ")", ".", "'\\\\Controllers'", ";", "// siehe auch CreateControllerCommand, SimpleContainerEntityService", "}", "return", "$", "this", "->", "controllersNamespace", ";", "}" ]
Gibt den Namespace für die Controllers des Service zurück ohne \ davor und dahinter
[ "Gibt", "den", "Namespace", "für", "die", "Controllers", "des", "Service", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/Service/ControllerService.php#L249-L254
localhook/localhook
src/Command/AbstractCommand.php
AbstractCommand.loadConfiguration
protected function loadConfiguration() { try { $configuration = $this->configurationStorage->loadFromFile()->get(); } catch (NoConfigurationException $e) { $this->io->comment($e->getMessage()); if (!$this->secret) { $this->secret = $this->io->ask('Secret'); } $configuration = $this->parseConfigurationKey(); } $this->serverUrl = $configuration['socket_url']; $this->secret = $configuration['secret']; $this->configurationStorage->merge($configuration)->save(); }
php
protected function loadConfiguration() { try { $configuration = $this->configurationStorage->loadFromFile()->get(); } catch (NoConfigurationException $e) { $this->io->comment($e->getMessage()); if (!$this->secret) { $this->secret = $this->io->ask('Secret'); } $configuration = $this->parseConfigurationKey(); } $this->serverUrl = $configuration['socket_url']; $this->secret = $configuration['secret']; $this->configurationStorage->merge($configuration)->save(); }
[ "protected", "function", "loadConfiguration", "(", ")", "{", "try", "{", "$", "configuration", "=", "$", "this", "->", "configurationStorage", "->", "loadFromFile", "(", ")", "->", "get", "(", ")", ";", "}", "catch", "(", "NoConfigurationException", "$", "e", ")", "{", "$", "this", "->", "io", "->", "comment", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "if", "(", "!", "$", "this", "->", "secret", ")", "{", "$", "this", "->", "secret", "=", "$", "this", "->", "io", "->", "ask", "(", "'Secret'", ")", ";", "}", "$", "configuration", "=", "$", "this", "->", "parseConfigurationKey", "(", ")", ";", "}", "$", "this", "->", "serverUrl", "=", "$", "configuration", "[", "'socket_url'", "]", ";", "$", "this", "->", "secret", "=", "$", "configuration", "[", "'secret'", "]", ";", "$", "this", "->", "configurationStorage", "->", "merge", "(", "$", "configuration", ")", "->", "save", "(", ")", ";", "}" ]
Loads the local configuration from "~/.localhook/config.json" file.
[ "Loads", "the", "local", "configuration", "from", "~", "/", ".", "localhook", "/", "config", ".", "json", "file", "." ]
train
https://github.com/localhook/localhook/blob/f8010a7f06ddd514b224ad70dc62e425125d4feb/src/Command/AbstractCommand.php#L39-L55
VincentChalnot/SidusAdminBundle
Templating/TemplateResolver.php
TemplateResolver.getTemplate
public function getTemplate(Action $action, $format = 'html'): \Twig_Template { $admin = $action->getAdmin(); if ($action->getTemplate()) { // If the template was specified, do not try to fallback return $this->twig->loadTemplate($action->getTemplate()); } // Priority to new template_pattern system: if (\count($admin->getTemplatePattern()) > 0) { foreach ($admin->getTemplatePattern() as $templatePattern) { $template = strtr( $templatePattern, [ '{{admin}}' => lcfirst($admin->getCode()), '{{Admin}}' => ucfirst($admin->getCode()), '{{action}}' => lcfirst($action->getCode()), '{{Action}}' => ucfirst($action->getCode()), '{{format}}' => $format, ] ); try { return $this->twig->loadTemplate($template); } catch (\Twig_Error_Loader $mainError) { $this->logger->debug("Unable to load template '{$template}': {$mainError->getMessage()}"); continue; } } $flattened = implode(', ', $admin->getTemplatePattern()); throw new \RuntimeException( "Unable to resolve any valid template for the template_pattern configuration: {$flattened}" ); } $template = "{$action->getCode()}.{$format}.twig"; $customTemplate = $admin->getController().':'.$template; $fallbackTemplate = $admin->getFallbackTemplateDirectory() ? $admin->getFallbackTemplateDirectory().':'.$template : null; $globalFallbackTemplate = $this->globalFallbackTemplate ? $this->globalFallbackTemplate.':'.$template : null; try { return $this->twig->loadTemplate($customTemplate); } catch (\Twig_Error_Loader $mainError) { $nextTemplate = $fallbackTemplate ?: $globalFallbackTemplate; $this->logger->notice( "Missing template {$customTemplate}, falling back to template {$nextTemplate}", [ 'template' => $customTemplate, 'admin' => $admin->getCode(), 'action' => $action->getCode(), ] ); } if ($fallbackTemplate) { try { return $this->twig->loadTemplate($fallbackTemplate); } catch (\Twig_Error_Loader $fallbackError) { $this->logger->critical( "Missing template '{$customTemplate}' and fallback template '{$fallbackTemplate}'", [ 'template' => $customTemplate, 'fallbackTemplate' => $fallbackTemplate, 'admin' => $admin->getCode(), 'action' => $action->getCode(), 'error' => $fallbackError, ] ); } throw $mainError; } try { return $this->twig->loadTemplate($globalFallbackTemplate); } catch (\Twig_Error_Loader $fallbackError) { $this->logger->critical( "Missing template '{$customTemplate}' and global fallback template '{$globalFallbackTemplate}'", [ 'template' => $customTemplate, 'globalFallbackTemplate' => $globalFallbackTemplate, 'admin' => $admin->getCode(), 'action' => $action->getCode(), 'fallbackError' => $fallbackError, ] ); } throw $mainError; }
php
public function getTemplate(Action $action, $format = 'html'): \Twig_Template { $admin = $action->getAdmin(); if ($action->getTemplate()) { // If the template was specified, do not try to fallback return $this->twig->loadTemplate($action->getTemplate()); } // Priority to new template_pattern system: if (\count($admin->getTemplatePattern()) > 0) { foreach ($admin->getTemplatePattern() as $templatePattern) { $template = strtr( $templatePattern, [ '{{admin}}' => lcfirst($admin->getCode()), '{{Admin}}' => ucfirst($admin->getCode()), '{{action}}' => lcfirst($action->getCode()), '{{Action}}' => ucfirst($action->getCode()), '{{format}}' => $format, ] ); try { return $this->twig->loadTemplate($template); } catch (\Twig_Error_Loader $mainError) { $this->logger->debug("Unable to load template '{$template}': {$mainError->getMessage()}"); continue; } } $flattened = implode(', ', $admin->getTemplatePattern()); throw new \RuntimeException( "Unable to resolve any valid template for the template_pattern configuration: {$flattened}" ); } $template = "{$action->getCode()}.{$format}.twig"; $customTemplate = $admin->getController().':'.$template; $fallbackTemplate = $admin->getFallbackTemplateDirectory() ? $admin->getFallbackTemplateDirectory().':'.$template : null; $globalFallbackTemplate = $this->globalFallbackTemplate ? $this->globalFallbackTemplate.':'.$template : null; try { return $this->twig->loadTemplate($customTemplate); } catch (\Twig_Error_Loader $mainError) { $nextTemplate = $fallbackTemplate ?: $globalFallbackTemplate; $this->logger->notice( "Missing template {$customTemplate}, falling back to template {$nextTemplate}", [ 'template' => $customTemplate, 'admin' => $admin->getCode(), 'action' => $action->getCode(), ] ); } if ($fallbackTemplate) { try { return $this->twig->loadTemplate($fallbackTemplate); } catch (\Twig_Error_Loader $fallbackError) { $this->logger->critical( "Missing template '{$customTemplate}' and fallback template '{$fallbackTemplate}'", [ 'template' => $customTemplate, 'fallbackTemplate' => $fallbackTemplate, 'admin' => $admin->getCode(), 'action' => $action->getCode(), 'error' => $fallbackError, ] ); } throw $mainError; } try { return $this->twig->loadTemplate($globalFallbackTemplate); } catch (\Twig_Error_Loader $fallbackError) { $this->logger->critical( "Missing template '{$customTemplate}' and global fallback template '{$globalFallbackTemplate}'", [ 'template' => $customTemplate, 'globalFallbackTemplate' => $globalFallbackTemplate, 'admin' => $admin->getCode(), 'action' => $action->getCode(), 'fallbackError' => $fallbackError, ] ); } throw $mainError; }
[ "public", "function", "getTemplate", "(", "Action", "$", "action", ",", "$", "format", "=", "'html'", ")", ":", "\\", "Twig_Template", "{", "$", "admin", "=", "$", "action", "->", "getAdmin", "(", ")", ";", "if", "(", "$", "action", "->", "getTemplate", "(", ")", ")", "{", "// If the template was specified, do not try to fallback", "return", "$", "this", "->", "twig", "->", "loadTemplate", "(", "$", "action", "->", "getTemplate", "(", ")", ")", ";", "}", "// Priority to new template_pattern system:", "if", "(", "\\", "count", "(", "$", "admin", "->", "getTemplatePattern", "(", ")", ")", ">", "0", ")", "{", "foreach", "(", "$", "admin", "->", "getTemplatePattern", "(", ")", "as", "$", "templatePattern", ")", "{", "$", "template", "=", "strtr", "(", "$", "templatePattern", ",", "[", "'{{admin}}'", "=>", "lcfirst", "(", "$", "admin", "->", "getCode", "(", ")", ")", ",", "'{{Admin}}'", "=>", "ucfirst", "(", "$", "admin", "->", "getCode", "(", ")", ")", ",", "'{{action}}'", "=>", "lcfirst", "(", "$", "action", "->", "getCode", "(", ")", ")", ",", "'{{Action}}'", "=>", "ucfirst", "(", "$", "action", "->", "getCode", "(", ")", ")", ",", "'{{format}}'", "=>", "$", "format", ",", "]", ")", ";", "try", "{", "return", "$", "this", "->", "twig", "->", "loadTemplate", "(", "$", "template", ")", ";", "}", "catch", "(", "\\", "Twig_Error_Loader", "$", "mainError", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "\"Unable to load template '{$template}': {$mainError->getMessage()}\"", ")", ";", "continue", ";", "}", "}", "$", "flattened", "=", "implode", "(", "', '", ",", "$", "admin", "->", "getTemplatePattern", "(", ")", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "\"Unable to resolve any valid template for the template_pattern configuration: {$flattened}\"", ")", ";", "}", "$", "template", "=", "\"{$action->getCode()}.{$format}.twig\"", ";", "$", "customTemplate", "=", "$", "admin", "->", "getController", "(", ")", ".", "':'", ".", "$", "template", ";", "$", "fallbackTemplate", "=", "$", "admin", "->", "getFallbackTemplateDirectory", "(", ")", "?", "$", "admin", "->", "getFallbackTemplateDirectory", "(", ")", ".", "':'", ".", "$", "template", ":", "null", ";", "$", "globalFallbackTemplate", "=", "$", "this", "->", "globalFallbackTemplate", "?", "$", "this", "->", "globalFallbackTemplate", ".", "':'", ".", "$", "template", ":", "null", ";", "try", "{", "return", "$", "this", "->", "twig", "->", "loadTemplate", "(", "$", "customTemplate", ")", ";", "}", "catch", "(", "\\", "Twig_Error_Loader", "$", "mainError", ")", "{", "$", "nextTemplate", "=", "$", "fallbackTemplate", "?", ":", "$", "globalFallbackTemplate", ";", "$", "this", "->", "logger", "->", "notice", "(", "\"Missing template {$customTemplate}, falling back to template {$nextTemplate}\"", ",", "[", "'template'", "=>", "$", "customTemplate", ",", "'admin'", "=>", "$", "admin", "->", "getCode", "(", ")", ",", "'action'", "=>", "$", "action", "->", "getCode", "(", ")", ",", "]", ")", ";", "}", "if", "(", "$", "fallbackTemplate", ")", "{", "try", "{", "return", "$", "this", "->", "twig", "->", "loadTemplate", "(", "$", "fallbackTemplate", ")", ";", "}", "catch", "(", "\\", "Twig_Error_Loader", "$", "fallbackError", ")", "{", "$", "this", "->", "logger", "->", "critical", "(", "\"Missing template '{$customTemplate}' and fallback template '{$fallbackTemplate}'\"", ",", "[", "'template'", "=>", "$", "customTemplate", ",", "'fallbackTemplate'", "=>", "$", "fallbackTemplate", ",", "'admin'", "=>", "$", "admin", "->", "getCode", "(", ")", ",", "'action'", "=>", "$", "action", "->", "getCode", "(", ")", ",", "'error'", "=>", "$", "fallbackError", ",", "]", ")", ";", "}", "throw", "$", "mainError", ";", "}", "try", "{", "return", "$", "this", "->", "twig", "->", "loadTemplate", "(", "$", "globalFallbackTemplate", ")", ";", "}", "catch", "(", "\\", "Twig_Error_Loader", "$", "fallbackError", ")", "{", "$", "this", "->", "logger", "->", "critical", "(", "\"Missing template '{$customTemplate}' and global fallback template '{$globalFallbackTemplate}'\"", ",", "[", "'template'", "=>", "$", "customTemplate", ",", "'globalFallbackTemplate'", "=>", "$", "globalFallbackTemplate", ",", "'admin'", "=>", "$", "admin", "->", "getCode", "(", ")", ",", "'action'", "=>", "$", "action", "->", "getCode", "(", ")", ",", "'fallbackError'", "=>", "$", "fallbackError", ",", "]", ")", ";", "}", "throw", "$", "mainError", ";", "}" ]
@param Action $action @param string $format @return \Twig_Template
[ "@param", "Action", "$action", "@param", "string", "$format" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Templating/TemplateResolver.php#L53-L144
hendrikmaus/reynaldo
src/Elements/BaseElement.php
BaseElement.addContentElement
public function addContentElement(ApiElement $element) { $newContent = []; $rawElements = []; $content = $this->getContent(); if ($this->hasCopy()) { $newContent[] = array_shift($content); } foreach ($content as $resourceGroup) { if (!is_array($resourceGroup)) { $newContent[] = array_shift($content); } else { $rawElements[] = $resourceGroup; } } array_shift($rawElements); $newContent[] = $element; $this->content = array_merge($newContent, $rawElements); }
php
public function addContentElement(ApiElement $element) { $newContent = []; $rawElements = []; $content = $this->getContent(); if ($this->hasCopy()) { $newContent[] = array_shift($content); } foreach ($content as $resourceGroup) { if (!is_array($resourceGroup)) { $newContent[] = array_shift($content); } else { $rawElements[] = $resourceGroup; } } array_shift($rawElements); $newContent[] = $element; $this->content = array_merge($newContent, $rawElements); }
[ "public", "function", "addContentElement", "(", "ApiElement", "$", "element", ")", "{", "$", "newContent", "=", "[", "]", ";", "$", "rawElements", "=", "[", "]", ";", "$", "content", "=", "$", "this", "->", "getContent", "(", ")", ";", "if", "(", "$", "this", "->", "hasCopy", "(", ")", ")", "{", "$", "newContent", "[", "]", "=", "array_shift", "(", "$", "content", ")", ";", "}", "foreach", "(", "$", "content", "as", "$", "resourceGroup", ")", "{", "if", "(", "!", "is_array", "(", "$", "resourceGroup", ")", ")", "{", "$", "newContent", "[", "]", "=", "array_shift", "(", "$", "content", ")", ";", "}", "else", "{", "$", "rawElements", "[", "]", "=", "$", "resourceGroup", ";", "}", "}", "array_shift", "(", "$", "rawElements", ")", ";", "$", "newContent", "[", "]", "=", "$", "element", ";", "$", "this", "->", "content", "=", "array_merge", "(", "$", "newContent", ",", "$", "rawElements", ")", ";", "}" ]
Add content element to the current content This method has to be used sequentially while querying the recursive element tree. It will replace the raw content element one by one, top to bottom. Example: - copy element - raw array element (1) - raw array element (2) Calling `addContentElement` with a resource element: - copy element - resource element - raw array element (2) As you can see `raw array element (1)` was replaced with `resource element` So *you* need to make sure that *you* turned the raw array element into the resource element. @param ApiElement $element
[ "Add", "content", "element", "to", "the", "current", "content" ]
train
https://github.com/hendrikmaus/reynaldo/blob/be100f56e8f39d86d16ce9222838d20f462e8678/src/Elements/BaseElement.php#L52-L74
hendrikmaus/reynaldo
src/Elements/BaseElement.php
BaseElement.getCopyText
public function getCopyText() { $content = $this->getContent(); $copy = array_shift($content); if (!is_array($copy)) { return null; } if ($copy['element'] !== 'copy') { return null; } return $copy['content']; }
php
public function getCopyText() { $content = $this->getContent(); $copy = array_shift($content); if (!is_array($copy)) { return null; } if ($copy['element'] !== 'copy') { return null; } return $copy['content']; }
[ "public", "function", "getCopyText", "(", ")", "{", "$", "content", "=", "$", "this", "->", "getContent", "(", ")", ";", "$", "copy", "=", "array_shift", "(", "$", "content", ")", ";", "if", "(", "!", "is_array", "(", "$", "copy", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "copy", "[", "'element'", "]", "!==", "'copy'", ")", "{", "return", "null", ";", "}", "return", "$", "copy", "[", "'content'", "]", ";", "}" ]
Get the copy text of the current element; raw markdown likely @api @return string|null
[ "Get", "the", "copy", "text", "of", "the", "current", "element", ";", "raw", "markdown", "likely" ]
train
https://github.com/hendrikmaus/reynaldo/blob/be100f56e8f39d86d16ce9222838d20f462e8678/src/Elements/BaseElement.php#L109-L123
hendrikmaus/reynaldo
src/Elements/BaseElement.php
BaseElement.getElementsByType
public function getElementsByType($fqcn) { $elements = []; $content = $this->getContent(); foreach ($content as $element) { if ($element instanceof $fqcn) { $elements[] = $element; } } return $elements; }
php
public function getElementsByType($fqcn) { $elements = []; $content = $this->getContent(); foreach ($content as $element) { if ($element instanceof $fqcn) { $elements[] = $element; } } return $elements; }
[ "public", "function", "getElementsByType", "(", "$", "fqcn", ")", "{", "$", "elements", "=", "[", "]", ";", "$", "content", "=", "$", "this", "->", "getContent", "(", ")", ";", "foreach", "(", "$", "content", "as", "$", "element", ")", "{", "if", "(", "$", "element", "instanceof", "$", "fqcn", ")", "{", "$", "elements", "[", "]", "=", "$", "element", ";", "}", "}", "return", "$", "elements", ";", "}" ]
Query content of current element (single level) for elements of given type @param string $fqcn Fully Qualified Class Name, e.g. ResourceElement::class @return ApiElement[]
[ "Query", "content", "of", "current", "element", "(", "single", "level", ")", "for", "elements", "of", "given", "type" ]
train
https://github.com/hendrikmaus/reynaldo/blob/be100f56e8f39d86d16ce9222838d20f462e8678/src/Elements/BaseElement.php#L142-L154
hendrikmaus/reynaldo
src/Elements/BaseElement.php
BaseElement.getFirstElementByType
public function getFirstElementByType($fqcn) { $match = null; foreach ($this->getContent() as $element) { if (!($element instanceof $fqcn)) { continue; } $match = $element; break; } return $match; }
php
public function getFirstElementByType($fqcn) { $match = null; foreach ($this->getContent() as $element) { if (!($element instanceof $fqcn)) { continue; } $match = $element; break; } return $match; }
[ "public", "function", "getFirstElementByType", "(", "$", "fqcn", ")", "{", "$", "match", "=", "null", ";", "foreach", "(", "$", "this", "->", "getContent", "(", ")", "as", "$", "element", ")", "{", "if", "(", "!", "(", "$", "element", "instanceof", "$", "fqcn", ")", ")", "{", "continue", ";", "}", "$", "match", "=", "$", "element", ";", "break", ";", "}", "return", "$", "match", ";", "}" ]
Find the first occurrence of a given element inside the content (single level) @param string $fqcn Fully Qualified Class Name, e.g. ResourceElement::class @return ApiElement|null
[ "Find", "the", "first", "occurrence", "of", "a", "given", "element", "inside", "the", "content", "(", "single", "level", ")" ]
train
https://github.com/hendrikmaus/reynaldo/blob/be100f56e8f39d86d16ce9222838d20f462e8678/src/Elements/BaseElement.php#L162-L176
hendrikmaus/reynaldo
src/Elements/BaseElement.php
BaseElement.hasClass
public function hasClass($className) { foreach ($this->meta['classes'] as $classInMeta) { if ($classInMeta === $className) { return true; } } return false; }
php
public function hasClass($className) { foreach ($this->meta['classes'] as $classInMeta) { if ($classInMeta === $className) { return true; } } return false; }
[ "public", "function", "hasClass", "(", "$", "className", ")", "{", "foreach", "(", "$", "this", "->", "meta", "[", "'classes'", "]", "as", "$", "classInMeta", ")", "{", "if", "(", "$", "classInMeta", "===", "$", "className", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check whether or not this element has a given class @param string $className e.g. 'resourceGroup', 'messageBody' @return bool
[ "Check", "whether", "or", "not", "this", "element", "has", "a", "given", "class" ]
train
https://github.com/hendrikmaus/reynaldo/blob/be100f56e8f39d86d16ce9222838d20f462e8678/src/Elements/BaseElement.php#L199-L208
orzcc/autometa
src/AutoMeta/Providers/AutoMetaServiceProvider.php
AutoMetaServiceProvider.register
public function register() { $this->app->singleton('autometa', function ($app) { return new AutoMeta($app['config']->get('autometa', [])); }); $this->app->bind('Orzcc\AutoMeta\Contracts\MetaTags', 'Orzcc\AutoMeta\MetaTags'); }
php
public function register() { $this->app->singleton('autometa', function ($app) { return new AutoMeta($app['config']->get('autometa', [])); }); $this->app->bind('Orzcc\AutoMeta\Contracts\MetaTags', 'Orzcc\AutoMeta\MetaTags'); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'autometa'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "AutoMeta", "(", "$", "app", "[", "'config'", "]", "->", "get", "(", "'autometa'", ",", "[", "]", ")", ")", ";", "}", ")", ";", "$", "this", "->", "app", "->", "bind", "(", "'Orzcc\\AutoMeta\\Contracts\\MetaTags'", ",", "'Orzcc\\AutoMeta\\MetaTags'", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/orzcc/autometa/blob/1e3bd93f364e2619c9c20820399735c9fe805c9c/src/AutoMeta/Providers/AutoMetaServiceProvider.php#L35-L42
Lansoweb/LosBase
src/LosBase/DBAL/Types/BrDateTimeType.php
BrDateTimeType.convertToPHPValue
public function convertToPHPValue($value, AbstractPlatform $platform) { $val = parent::convertToPHPValue($value, $platform); return $val->setTimezone(new \DateTimeZone('America/Sao_Paulo')); }
php
public function convertToPHPValue($value, AbstractPlatform $platform) { $val = parent::convertToPHPValue($value, $platform); return $val->setTimezone(new \DateTimeZone('America/Sao_Paulo')); }
[ "public", "function", "convertToPHPValue", "(", "$", "value", ",", "AbstractPlatform", "$", "platform", ")", "{", "$", "val", "=", "parent", "::", "convertToPHPValue", "(", "$", "value", ",", "$", "platform", ")", ";", "return", "$", "val", "->", "setTimezone", "(", "new", "\\", "DateTimeZone", "(", "'America/Sao_Paulo'", ")", ")", ";", "}" ]
@param string $value @param DoctrineDBALPlatformsAbstractPlatform $platform @return DateTime|mixed|null @throws DoctrineDBALTypesConversionException
[ "@param", "string", "$value", "@param", "DoctrineDBALPlatformsAbstractPlatform", "$platform" ]
train
https://github.com/Lansoweb/LosBase/blob/90e18a53d29c1bd841c149dca43aa365eecc656d/src/LosBase/DBAL/Types/BrDateTimeType.php#L17-L22
webforge-labs/psc-cms
lib/Psc/CMS/AssociationsLister.php
AssociationsLister.getHTMLForList
public function getHTMLForList(AssociationList $assoc) { if (!isset($this->entity)) { throw new \RuntimeException('Entity muss gesetzt sein, wenn html() oder init() aufgerufen wird'); } $entities = $this->getAssocEntities($assoc); // die collection, ist klar if (($sorter = $assoc->getSortBy()) != NULL) { $entities = $sorter($entities); } $cnt = count($entities); if ($cnt > 0) { if ($assoc->hasLimit() && $cnt > $assoc->getLimit()) { return sprintf($assoc->getLimitMessage(), $cnt); } else { $html = h::listObjects( $entities, $assoc->getJoinedWith(), // zwischen allen items (außer dem vorletzten + letzten wenn andjoiner gesett) $assoc->getWithButton() ? $this->getHTMLButtonClosure() : $assoc->getWithLabel(), // html-closure für das foreign-entity $assoc->getAndJoiner() // zwischen dem vorletzten + letzten item // $formatter nicht angegeben ); } return \Psc\TPL\TPL::miniTemplate($assoc->getFormat(), array('list'=>$html)); } else { return $assoc->getEmptyText(); } }
php
public function getHTMLForList(AssociationList $assoc) { if (!isset($this->entity)) { throw new \RuntimeException('Entity muss gesetzt sein, wenn html() oder init() aufgerufen wird'); } $entities = $this->getAssocEntities($assoc); // die collection, ist klar if (($sorter = $assoc->getSortBy()) != NULL) { $entities = $sorter($entities); } $cnt = count($entities); if ($cnt > 0) { if ($assoc->hasLimit() && $cnt > $assoc->getLimit()) { return sprintf($assoc->getLimitMessage(), $cnt); } else { $html = h::listObjects( $entities, $assoc->getJoinedWith(), // zwischen allen items (außer dem vorletzten + letzten wenn andjoiner gesett) $assoc->getWithButton() ? $this->getHTMLButtonClosure() : $assoc->getWithLabel(), // html-closure für das foreign-entity $assoc->getAndJoiner() // zwischen dem vorletzten + letzten item // $formatter nicht angegeben ); } return \Psc\TPL\TPL::miniTemplate($assoc->getFormat(), array('list'=>$html)); } else { return $assoc->getEmptyText(); } }
[ "public", "function", "getHTMLForList", "(", "AssociationList", "$", "assoc", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "entity", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Entity muss gesetzt sein, wenn html() oder init() aufgerufen wird'", ")", ";", "}", "$", "entities", "=", "$", "this", "->", "getAssocEntities", "(", "$", "assoc", ")", ";", "// die collection, ist klar", "if", "(", "(", "$", "sorter", "=", "$", "assoc", "->", "getSortBy", "(", ")", ")", "!=", "NULL", ")", "{", "$", "entities", "=", "$", "sorter", "(", "$", "entities", ")", ";", "}", "$", "cnt", "=", "count", "(", "$", "entities", ")", ";", "if", "(", "$", "cnt", ">", "0", ")", "{", "if", "(", "$", "assoc", "->", "hasLimit", "(", ")", "&&", "$", "cnt", ">", "$", "assoc", "->", "getLimit", "(", ")", ")", "{", "return", "sprintf", "(", "$", "assoc", "->", "getLimitMessage", "(", ")", ",", "$", "cnt", ")", ";", "}", "else", "{", "$", "html", "=", "h", "::", "listObjects", "(", "$", "entities", ",", "$", "assoc", "->", "getJoinedWith", "(", ")", ",", "// zwischen allen items (außer dem vorletzten + letzten wenn andjoiner gesett)", "$", "assoc", "->", "getWithButton", "(", ")", "?", "$", "this", "->", "getHTMLButtonClosure", "(", ")", ":", "$", "assoc", "->", "getWithLabel", "(", ")", ",", "// html-closure für das foreign-entity", "$", "assoc", "->", "getAndJoiner", "(", ")", "// zwischen dem vorletzten + letzten item", "// $formatter nicht angegeben", ")", ";", "}", "return", "\\", "Psc", "\\", "TPL", "\\", "TPL", "::", "miniTemplate", "(", "$", "assoc", "->", "getFormat", "(", ")", ",", "array", "(", "'list'", "=>", "$", "html", ")", ")", ";", "}", "else", "{", "return", "$", "assoc", "->", "getEmptyText", "(", ")", ";", "}", "}" ]
Gibt das HTML für die AssociationList zurück ist $assoc->limit angegeben und ist die anzahl der entities größer als diess wird $assoc->limitMessage zurückgegeben sind keine Entities zu finden, wird $assoc->emptyText zurückgegeben ansonsten wird für jedes Entities $assoc.withLabel oder ein button erzeugt (withButton(TRUE))
[ "Gibt", "das", "HTML", "für", "die", "AssociationList", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/CMS/AssociationsLister.php#L42-L71
webforge-labs/psc-cms
lib/Psc/Config.php
Config.reqDefault
public static function reqDefault($keys, $defaultValue) { try { $value = self::req($keys); } catch (MissingConfigVariableException $e) { if (is_string($defaultValue) && !Preg::match($defaultValue,'/^(\'|")/') && !self::NEW_ARRAY) { $defaultValue = "'".$defaultValue."'"; } $e->setDefault($defaultValue); throw $e; } return $value; }
php
public static function reqDefault($keys, $defaultValue) { try { $value = self::req($keys); } catch (MissingConfigVariableException $e) { if (is_string($defaultValue) && !Preg::match($defaultValue,'/^(\'|")/') && !self::NEW_ARRAY) { $defaultValue = "'".$defaultValue."'"; } $e->setDefault($defaultValue); throw $e; } return $value; }
[ "public", "static", "function", "reqDefault", "(", "$", "keys", ",", "$", "defaultValue", ")", "{", "try", "{", "$", "value", "=", "self", "::", "req", "(", "$", "keys", ")", ";", "}", "catch", "(", "MissingConfigVariableException", "$", "e", ")", "{", "if", "(", "is_string", "(", "$", "defaultValue", ")", "&&", "!", "Preg", "::", "match", "(", "$", "defaultValue", ",", "'/^(\\'|\")/'", ")", "&&", "!", "self", "::", "NEW_ARRAY", ")", "{", "$", "defaultValue", "=", "\"'\"", ".", "$", "defaultValue", ".", "\"'\"", ";", "}", "$", "e", "->", "setDefault", "(", "$", "defaultValue", ")", ";", "throw", "$", "e", ";", "}", "return", "$", "value", ";", "}" ]
Required eine Variable, schlägt aber einen Default für die Config-Variable vor
[ "Required", "eine", "Variable", "schlägt", "aber", "einen", "Default", "für", "die", "Config", "-", "Variable", "vor" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Config.php#L60-L74
webforge-labs/psc-cms
lib/Psc/Config.php
Config.getDefault
public static function getDefault($keys, $defaultValue) { try { $value = self::req($keys); } catch (MissingConfigVariableException $e) { return $defaultValue; } return $value; }
php
public static function getDefault($keys, $defaultValue) { try { $value = self::req($keys); } catch (MissingConfigVariableException $e) { return $defaultValue; } return $value; }
[ "public", "static", "function", "getDefault", "(", "$", "keys", ",", "$", "defaultValue", ")", "{", "try", "{", "$", "value", "=", "self", "::", "req", "(", "$", "keys", ")", ";", "}", "catch", "(", "MissingConfigVariableException", "$", "e", ")", "{", "return", "$", "defaultValue", ";", "}", "return", "$", "value", ";", "}" ]
Required eine Variable, schlägt aber einen Default für die Config-Variable vor
[ "Required", "eine", "Variable", "schlägt", "aber", "einen", "Default", "für", "die", "Config", "-", "Variable", "vor" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Config.php#L81-L89
tbreuss/pvc
src/Middleware/RequestHandler.php
RequestHandler.handle
public function handle(ServerRequestInterface $request): ResponseInterface { $this->request = $request; $response = (new HttpFactory())->createResponse(); $response = $response->withHeader('Content-Type', 'text/html'); $pathInfo = RequestHelper::getPathInfo($request); try { $controller = $this->resolveController($pathInfo); $mixed = $this->executeAction($controller); } catch (\Throwable $t) { // handle errors with built-in error controller $controller = new ErrorController($this->view, $request, 'error/error'); $controller->setError($t); $mixed = $this->executeAction($controller); $response = $response->withStatus($t->getCode()); } if (is_array($mixed)) { $response = $response->withHeader('Content-Type', 'application/json'); $response->getBody()->write(json_encode($mixed)); } elseif (is_string($mixed)) { $response->getBody()->write($mixed); } else { throw new \Exception('Unsupported content type'); } return $response; }
php
public function handle(ServerRequestInterface $request): ResponseInterface { $this->request = $request; $response = (new HttpFactory())->createResponse(); $response = $response->withHeader('Content-Type', 'text/html'); $pathInfo = RequestHelper::getPathInfo($request); try { $controller = $this->resolveController($pathInfo); $mixed = $this->executeAction($controller); } catch (\Throwable $t) { // handle errors with built-in error controller $controller = new ErrorController($this->view, $request, 'error/error'); $controller->setError($t); $mixed = $this->executeAction($controller); $response = $response->withStatus($t->getCode()); } if (is_array($mixed)) { $response = $response->withHeader('Content-Type', 'application/json'); $response->getBody()->write(json_encode($mixed)); } elseif (is_string($mixed)) { $response->getBody()->write($mixed); } else { throw new \Exception('Unsupported content type'); } return $response; }
[ "public", "function", "handle", "(", "ServerRequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "$", "this", "->", "request", "=", "$", "request", ";", "$", "response", "=", "(", "new", "HttpFactory", "(", ")", ")", "->", "createResponse", "(", ")", ";", "$", "response", "=", "$", "response", "->", "withHeader", "(", "'Content-Type'", ",", "'text/html'", ")", ";", "$", "pathInfo", "=", "RequestHelper", "::", "getPathInfo", "(", "$", "request", ")", ";", "try", "{", "$", "controller", "=", "$", "this", "->", "resolveController", "(", "$", "pathInfo", ")", ";", "$", "mixed", "=", "$", "this", "->", "executeAction", "(", "$", "controller", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "t", ")", "{", "// handle errors with built-in error controller", "$", "controller", "=", "new", "ErrorController", "(", "$", "this", "->", "view", ",", "$", "request", ",", "'error/error'", ")", ";", "$", "controller", "->", "setError", "(", "$", "t", ")", ";", "$", "mixed", "=", "$", "this", "->", "executeAction", "(", "$", "controller", ")", ";", "$", "response", "=", "$", "response", "->", "withStatus", "(", "$", "t", "->", "getCode", "(", ")", ")", ";", "}", "if", "(", "is_array", "(", "$", "mixed", ")", ")", "{", "$", "response", "=", "$", "response", "->", "withHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "$", "response", "->", "getBody", "(", ")", "->", "write", "(", "json_encode", "(", "$", "mixed", ")", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "mixed", ")", ")", "{", "$", "response", "->", "getBody", "(", ")", "->", "write", "(", "$", "mixed", ")", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "'Unsupported content type'", ")", ";", "}", "return", "$", "response", ";", "}" ]
Handle the request and return a response. @param ServerRequestInterface $request @return ResponseInterface @throws HttpException @throws SystemException
[ "Handle", "the", "request", "and", "return", "a", "response", "." ]
train
https://github.com/tbreuss/pvc/blob/ae100351010a8c9f645ccb918f70a26e167de7a7/src/Middleware/RequestHandler.php#L54-L82
tbreuss/pvc
src/Middleware/RequestHandler.php
RequestHandler.getHttpGetVars
private function getHttpGetVars(BaseController $controller, string $methodName): array { $requestParams = []; $reflectionMethod = new \ReflectionMethod($controller, $methodName); $reflectionParameters = $reflectionMethod->getParameters(); foreach ($reflectionParameters as $reflectionParameter) { $name = $reflectionParameter->getName(); $queryParams = $this->request->getQueryParams(); if (isset($queryParams[$name])) { $requestParams[$name] = $queryParams[$name]; } } return $requestParams; }
php
private function getHttpGetVars(BaseController $controller, string $methodName): array { $requestParams = []; $reflectionMethod = new \ReflectionMethod($controller, $methodName); $reflectionParameters = $reflectionMethod->getParameters(); foreach ($reflectionParameters as $reflectionParameter) { $name = $reflectionParameter->getName(); $queryParams = $this->request->getQueryParams(); if (isset($queryParams[$name])) { $requestParams[$name] = $queryParams[$name]; } } return $requestParams; }
[ "private", "function", "getHttpGetVars", "(", "BaseController", "$", "controller", ",", "string", "$", "methodName", ")", ":", "array", "{", "$", "requestParams", "=", "[", "]", ";", "$", "reflectionMethod", "=", "new", "\\", "ReflectionMethod", "(", "$", "controller", ",", "$", "methodName", ")", ";", "$", "reflectionParameters", "=", "$", "reflectionMethod", "->", "getParameters", "(", ")", ";", "foreach", "(", "$", "reflectionParameters", "as", "$", "reflectionParameter", ")", "{", "$", "name", "=", "$", "reflectionParameter", "->", "getName", "(", ")", ";", "$", "queryParams", "=", "$", "this", "->", "request", "->", "getQueryParams", "(", ")", ";", "if", "(", "isset", "(", "$", "queryParams", "[", "$", "name", "]", ")", ")", "{", "$", "requestParams", "[", "$", "name", "]", "=", "$", "queryParams", "[", "$", "name", "]", ";", "}", "}", "return", "$", "requestParams", ";", "}" ]
Get the HTTP GET vars which are requested by the method using method parameters (a kind of injecting the get vars into the action method name). @param BaseController $controller @param string $methodName @return array @throws \ReflectionException
[ "Get", "the", "HTTP", "GET", "vars", "which", "are", "requested", "by", "the", "method", "using", "method", "parameters", "(", "a", "kind", "of", "injecting", "the", "get", "vars", "into", "the", "action", "method", "name", ")", "." ]
train
https://github.com/tbreuss/pvc/blob/ae100351010a8c9f645ccb918f70a26e167de7a7/src/Middleware/RequestHandler.php#L150-L164
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section.php
PHPWord_Section.addLink
public function addLink($linkSrc, $linkName = null, $styleFont = null, $styleParagraph = null) { $link = new PHPWord_Section_Link($linkSrc, $linkName, $styleFont, $styleParagraph); $rID = PHPWord_Media::addSectionLinkElement($linkSrc); $link->setRelationId($rID); $this->_elementCollection[] = $link; return $link; }
php
public function addLink($linkSrc, $linkName = null, $styleFont = null, $styleParagraph = null) { $link = new PHPWord_Section_Link($linkSrc, $linkName, $styleFont, $styleParagraph); $rID = PHPWord_Media::addSectionLinkElement($linkSrc); $link->setRelationId($rID); $this->_elementCollection[] = $link; return $link; }
[ "public", "function", "addLink", "(", "$", "linkSrc", ",", "$", "linkName", "=", "null", ",", "$", "styleFont", "=", "null", ",", "$", "styleParagraph", "=", "null", ")", "{", "$", "link", "=", "new", "PHPWord_Section_Link", "(", "$", "linkSrc", ",", "$", "linkName", ",", "$", "styleFont", ",", "$", "styleParagraph", ")", ";", "$", "rID", "=", "PHPWord_Media", "::", "addSectionLinkElement", "(", "$", "linkSrc", ")", ";", "$", "link", "->", "setRelationId", "(", "$", "rID", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "link", ";", "return", "$", "link", ";", "}" ]
Add a Link Element @param string $linkSrc @param string $linkName @param mixed $styleFont @param mixed $styleParagraph @return PHPWord_Section_Link
[ "Add", "a", "Link", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section.php#L126-L133
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section.php
PHPWord_Section.addTable
public function addTable($style = null) { $table = new PHPWord_Section_Table('section', $this->_sectionCount, $style); $this->_elementCollection[] = $table; return $table; }
php
public function addTable($style = null) { $table = new PHPWord_Section_Table('section', $this->_sectionCount, $style); $this->_elementCollection[] = $table; return $table; }
[ "public", "function", "addTable", "(", "$", "style", "=", "null", ")", "{", "$", "table", "=", "new", "PHPWord_Section_Table", "(", "'section'", ",", "$", "this", "->", "_sectionCount", ",", "$", "style", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "table", ";", "return", "$", "table", ";", "}" ]
Add a Table Element @param mixed $style @return PHPWord_Section_Table
[ "Add", "a", "Table", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section.php#L159-L163
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section.php
PHPWord_Section.addListItem
public function addListItem($text, $depth = 0, $styleFont = null, $styleList = null, $styleParagraph = null) { $listItem = new PHPWord_Section_ListItem($text, $depth, $styleFont, $styleList, $styleParagraph); $this->_elementCollection[] = $listItem; return $listItem; }
php
public function addListItem($text, $depth = 0, $styleFont = null, $styleList = null, $styleParagraph = null) { $listItem = new PHPWord_Section_ListItem($text, $depth, $styleFont, $styleList, $styleParagraph); $this->_elementCollection[] = $listItem; return $listItem; }
[ "public", "function", "addListItem", "(", "$", "text", ",", "$", "depth", "=", "0", ",", "$", "styleFont", "=", "null", ",", "$", "styleList", "=", "null", ",", "$", "styleParagraph", "=", "null", ")", "{", "$", "listItem", "=", "new", "PHPWord_Section_ListItem", "(", "$", "text", ",", "$", "depth", ",", "$", "styleFont", ",", "$", "styleList", ",", "$", "styleParagraph", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "listItem", ";", "return", "$", "listItem", ";", "}" ]
Add a ListItem Element @param string $text @param int $depth @param mixed $styleFont @param mixed $styleList @param mixed $styleParagraph @return PHPWord_Section_ListItem
[ "Add", "a", "ListItem", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section.php#L175-L179
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section.php
PHPWord_Section.addImage
public function addImage($src, $style = null) { $image = new PHPWord_Section_Image($src, $style); if(!is_null($image->getSource())) { $rID = PHPWord_Media::addSectionMediaElement($src, 'image'); $image->setRelationId($rID); $this->_elementCollection[] = $image; return $image; } else { trigger_error('Source does not exist or unsupported image type.'); } }
php
public function addImage($src, $style = null) { $image = new PHPWord_Section_Image($src, $style); if(!is_null($image->getSource())) { $rID = PHPWord_Media::addSectionMediaElement($src, 'image'); $image->setRelationId($rID); $this->_elementCollection[] = $image; return $image; } else { trigger_error('Source does not exist or unsupported image type.'); } }
[ "public", "function", "addImage", "(", "$", "src", ",", "$", "style", "=", "null", ")", "{", "$", "image", "=", "new", "PHPWord_Section_Image", "(", "$", "src", ",", "$", "style", ")", ";", "if", "(", "!", "is_null", "(", "$", "image", "->", "getSource", "(", ")", ")", ")", "{", "$", "rID", "=", "PHPWord_Media", "::", "addSectionMediaElement", "(", "$", "src", ",", "'image'", ")", ";", "$", "image", "->", "setRelationId", "(", "$", "rID", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "image", ";", "return", "$", "image", ";", "}", "else", "{", "trigger_error", "(", "'Source does not exist or unsupported image type.'", ")", ";", "}", "}" ]
Add a Image Element @param string $src @param mixed $style @return PHPWord_Section_Image
[ "Add", "a", "Image", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section.php#L228-L240
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section.php
PHPWord_Section.addTOC
public function addTOC($styleFont = null, $styleTOC = null) { $toc = new PHPWord_TOC($styleFont, $styleTOC); $this->_elementCollection[] = $toc; return $toc; }
php
public function addTOC($styleFont = null, $styleTOC = null) { $toc = new PHPWord_TOC($styleFont, $styleTOC); $this->_elementCollection[] = $toc; return $toc; }
[ "public", "function", "addTOC", "(", "$", "styleFont", "=", "null", ",", "$", "styleTOC", "=", "null", ")", "{", "$", "toc", "=", "new", "PHPWord_TOC", "(", "$", "styleFont", ",", "$", "styleTOC", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "toc", ";", "return", "$", "toc", ";", "}" ]
Add a Table-of-Contents Element @param mixed $styleFont @param mixed $styleTOC @return PHPWord_TOC
[ "Add", "a", "Table", "-", "of", "-", "Contents", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section.php#L269-L273
webforge-labs/psc-cms
lib/PHPWord/PHPWord/Section.php
PHPWord_Section.addTitle
public function addTitle($text, $depth = 1) { $styles = PHPWord_Style::getStyles(); if(array_key_exists('Heading_'.$depth, $styles)) { $style = 'Heading'.$depth; } else { $style = null; } $title = new PHPWord_Section_Title($text, $depth, $style); $data = PHPWord_TOC::addTitle($text, $depth); $anchor = $data[0]; $bookmarkId = $data[1]; $title->setAnchor($anchor); $title->setBookmarkId($bookmarkId); $this->_elementCollection[] = $title; return $title; }
php
public function addTitle($text, $depth = 1) { $styles = PHPWord_Style::getStyles(); if(array_key_exists('Heading_'.$depth, $styles)) { $style = 'Heading'.$depth; } else { $style = null; } $title = new PHPWord_Section_Title($text, $depth, $style); $data = PHPWord_TOC::addTitle($text, $depth); $anchor = $data[0]; $bookmarkId = $data[1]; $title->setAnchor($anchor); $title->setBookmarkId($bookmarkId); $this->_elementCollection[] = $title; return $title; }
[ "public", "function", "addTitle", "(", "$", "text", ",", "$", "depth", "=", "1", ")", "{", "$", "styles", "=", "PHPWord_Style", "::", "getStyles", "(", ")", ";", "if", "(", "array_key_exists", "(", "'Heading_'", ".", "$", "depth", ",", "$", "styles", ")", ")", "{", "$", "style", "=", "'Heading'", ".", "$", "depth", ";", "}", "else", "{", "$", "style", "=", "null", ";", "}", "$", "title", "=", "new", "PHPWord_Section_Title", "(", "$", "text", ",", "$", "depth", ",", "$", "style", ")", ";", "$", "data", "=", "PHPWord_TOC", "::", "addTitle", "(", "$", "text", ",", "$", "depth", ")", ";", "$", "anchor", "=", "$", "data", "[", "0", "]", ";", "$", "bookmarkId", "=", "$", "data", "[", "1", "]", ";", "$", "title", "->", "setAnchor", "(", "$", "anchor", ")", ";", "$", "title", "->", "setBookmarkId", "(", "$", "bookmarkId", ")", ";", "$", "this", "->", "_elementCollection", "[", "]", "=", "$", "title", ";", "return", "$", "title", ";", "}" ]
Add a Title Element @param string $text @param int $depth @return PHPWord_Section_Title
[ "Add", "a", "Title", "Element" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/PHPWord/PHPWord/Section.php#L282-L301
shrink0r/workflux
src/Transition/ExpressionConstraint.php
ExpressionConstraint.accepts
public function accepts(InputInterface $input, OutputInterface $output): bool { return (bool)$this->engine->evaluate( $this->expression, [ 'event' => $input->getEvent(), 'input' => $input, 'output' => $output ] ); }
php
public function accepts(InputInterface $input, OutputInterface $output): bool { return (bool)$this->engine->evaluate( $this->expression, [ 'event' => $input->getEvent(), 'input' => $input, 'output' => $output ] ); }
[ "public", "function", "accepts", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", ":", "bool", "{", "return", "(", "bool", ")", "$", "this", "->", "engine", "->", "evaluate", "(", "$", "this", "->", "expression", ",", "[", "'event'", "=>", "$", "input", "->", "getEvent", "(", ")", ",", "'input'", "=>", "$", "input", ",", "'output'", "=>", "$", "output", "]", ")", ";", "}" ]
@param InputInterface $input @param OutputInterface $output @return bool
[ "@param", "InputInterface", "$input", "@param", "OutputInterface", "$output" ]
train
https://github.com/shrink0r/workflux/blob/008f45c64f52b1f795ab7f6ddbfc1a55580254d9/src/Transition/ExpressionConstraint.php#L37-L43
phpmob/changmin
src/PhpMob/WidgetBundle/DependencyInjection/Compiler/RegisterWidgetPass.php
RegisterWidgetPass.process
public function process(ContainerBuilder $container) { $widgets = $container->getParameter('phpmob.widgets'); foreach ($container->findTaggedServiceIds('twig.extension') as $key => $twigs) { $definition = $container->getDefinition($key); $class = $definition->getClass(); if ($container->hasParameter($class)) { $class = $container->getParameterBag()->resolveValue($class); } if (!class_exists($class)) { continue; } $reflex = $container->getReflectionClass($class); if ($reflex->implementsInterface(WidgetInterface::class)) { if ($reflex->implementsInterface(ContainerAwareInterface::class)) { $definition->addMethodCall('setContainer', [new Reference('service_container')]); } $definition->addMethodCall('setRouter', [new Reference('router')]); $definition->addMethodCall('setWidgetAssets', [new Reference('phpmob.widget.assets')]); $definition->addMethodCall('resolverDefaultOptions', [ array_key_exists($class, $widgets) ? $widgets[$class]['options'] : [] ]); $container->getDefinition('phpmob.widget.registry') ->addMethodCall('addWidget', [$class]) ; } } }
php
public function process(ContainerBuilder $container) { $widgets = $container->getParameter('phpmob.widgets'); foreach ($container->findTaggedServiceIds('twig.extension') as $key => $twigs) { $definition = $container->getDefinition($key); $class = $definition->getClass(); if ($container->hasParameter($class)) { $class = $container->getParameterBag()->resolveValue($class); } if (!class_exists($class)) { continue; } $reflex = $container->getReflectionClass($class); if ($reflex->implementsInterface(WidgetInterface::class)) { if ($reflex->implementsInterface(ContainerAwareInterface::class)) { $definition->addMethodCall('setContainer', [new Reference('service_container')]); } $definition->addMethodCall('setRouter', [new Reference('router')]); $definition->addMethodCall('setWidgetAssets', [new Reference('phpmob.widget.assets')]); $definition->addMethodCall('resolverDefaultOptions', [ array_key_exists($class, $widgets) ? $widgets[$class]['options'] : [] ]); $container->getDefinition('phpmob.widget.registry') ->addMethodCall('addWidget', [$class]) ; } } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "widgets", "=", "$", "container", "->", "getParameter", "(", "'phpmob.widgets'", ")", ";", "foreach", "(", "$", "container", "->", "findTaggedServiceIds", "(", "'twig.extension'", ")", "as", "$", "key", "=>", "$", "twigs", ")", "{", "$", "definition", "=", "$", "container", "->", "getDefinition", "(", "$", "key", ")", ";", "$", "class", "=", "$", "definition", "->", "getClass", "(", ")", ";", "if", "(", "$", "container", "->", "hasParameter", "(", "$", "class", ")", ")", "{", "$", "class", "=", "$", "container", "->", "getParameterBag", "(", ")", "->", "resolveValue", "(", "$", "class", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "{", "continue", ";", "}", "$", "reflex", "=", "$", "container", "->", "getReflectionClass", "(", "$", "class", ")", ";", "if", "(", "$", "reflex", "->", "implementsInterface", "(", "WidgetInterface", "::", "class", ")", ")", "{", "if", "(", "$", "reflex", "->", "implementsInterface", "(", "ContainerAwareInterface", "::", "class", ")", ")", "{", "$", "definition", "->", "addMethodCall", "(", "'setContainer'", ",", "[", "new", "Reference", "(", "'service_container'", ")", "]", ")", ";", "}", "$", "definition", "->", "addMethodCall", "(", "'setRouter'", ",", "[", "new", "Reference", "(", "'router'", ")", "]", ")", ";", "$", "definition", "->", "addMethodCall", "(", "'setWidgetAssets'", ",", "[", "new", "Reference", "(", "'phpmob.widget.assets'", ")", "]", ")", ";", "$", "definition", "->", "addMethodCall", "(", "'resolverDefaultOptions'", ",", "[", "array_key_exists", "(", "$", "class", ",", "$", "widgets", ")", "?", "$", "widgets", "[", "$", "class", "]", "[", "'options'", "]", ":", "[", "]", "]", ")", ";", "$", "container", "->", "getDefinition", "(", "'phpmob.widget.registry'", ")", "->", "addMethodCall", "(", "'addWidget'", ",", "[", "$", "class", "]", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/WidgetBundle/DependencyInjection/Compiler/RegisterWidgetPass.php#L30-L64
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/Hostname.php
Zend_Validate_Hostname.isValid
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); // Check input against IP address schema if ($this->_ipValidator->setTranslator($this->getTranslator())->isValid($valueString)) { if (!($this->_allow & self::ALLOW_IP)) { $this->_error(self::IP_ADDRESS_NOT_ALLOWED); return false; } else{ return true; } } // Check input against DNS hostname schema $domainParts = explode('.', $valueString); if ((count($domainParts) > 1) && (strlen($valueString) >= 4) && (strlen($valueString) <= 254)) { $status = false; do { // First check TLD if (preg_match('/([^.]{2,10})$/i', end($domainParts), $matches) || (end($domainParts) == 'ایران') || (end($domainParts) == '中国') || (end($domainParts) == '公司') || (end($domainParts) == '网络')) { reset($domainParts); // Hostname characters are: *(label dot)(label dot label); max 254 chars // label: id-prefix [*ldh{61} id-prefix]; max 63 chars // id-prefix: alpha / digit // ldh: alpha / digit / dash // Match TLD against known list $this->_tld = strtolower($matches[1]); if ($this->_validateTld) { if (!in_array($this->_tld, $this->_validTlds)) { $this->_error(self::UNKNOWN_TLD); $status = false; break; } } /** * Match against IDN hostnames * Note: Keep label regex short to avoid issues with long patterns when matching IDN hostnames * @see Zend_Validate_Hostname_Interface */ $regexChars = array(0 => '/^[a-z0-9\x2d]{1,63}$/i'); if ($this->_validateIdn && isset($this->_validIdns[strtoupper($this->_tld)])) { if (is_string($this->_validIdns[strtoupper($this->_tld)])) { $regexChars += include($this->_validIdns[strtoupper($this->_tld)]); } else { $regexChars += $this->_validIdns[strtoupper($this->_tld)]; } } // Check each hostname part $valid = true; foreach ($domainParts as $domainPart) { // Decode Punycode domainnames to IDN if (strpos($domainPart, 'xn--') === 0) { $domainPart = $this->decodePunycode(substr($domainPart, 4)); if ($domainPart === false) { return false; } } // Check dash (-) does not start, end or appear in 3rd and 4th positions if ((strpos($domainPart, '-') === 0) || ((strlen($domainPart) > 2) && (strpos($domainPart, '-', 2) == 2) && (strpos($domainPart, '-', 3) == 3)) || (strpos($domainPart, '-') === (strlen($domainPart) - 1))) { $this->_error(self::INVALID_DASH); $status = false; break 2; } // Check each domain part $check = false; foreach($regexChars as $regexKey => $regexChar) { $status = @preg_match($regexChar, $domainPart); if ($status === false) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: DNS validation failed'); } elseif ($status !== 0) { $length = 63; if (array_key_exists(strtoupper($this->_tld), $this->_idnLength) && (array_key_exists($regexKey, $this->_idnLength[strtoupper($this->_tld)]))) { $length = $this->_idnLength[strtoupper($this->_tld)]; } if (iconv_strlen($domainPart) > $length) { $this->_error(self::INVALID_HOSTNAME); } else { $check = true; break 2; } } } if (!$check) { $valid = false; } } // If all labels didn't match, the hostname is invalid if (!$valid) { $this->_error(self::INVALID_HOSTNAME_SCHEMA); $status = false; } } else { // Hostname not long enough $this->_error(self::UNDECIPHERABLE_TLD); $status = false; } } while (false); // If the input passes as an Internet domain name, and domain names are allowed, then the hostname // passes validation if ($status && ($this->_allow & self::ALLOW_DNS)) { return true; } } else { $this->_error(self::INVALID_HOSTNAME); } // Check input against local network name schema; last chance to pass validation $regexLocal = '/^(([a-zA-Z0-9\x2d]{1,63}\x2e)*[a-zA-Z0-9\x2d]{1,63}){1,254}$/'; $status = @preg_match($regexLocal, $valueString); if (false === $status) { /** * Regex error * @see Zend_Validate_Exception */ require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: local network name validation failed'); } // If the input passes as a local network name, and local network names are allowed, then the // hostname passes validation $allowLocal = $this->_allow & self::ALLOW_LOCAL; if ($status && $allowLocal) { return true; } // If the input does not pass as a local network name, add a message if (!$status) { $this->_error(self::INVALID_LOCAL_NAME); } // If local network names are not allowed, add a message if ($status && !$allowLocal) { $this->_error(self::LOCAL_NAME_NOT_ALLOWED); } return false; }
php
public function isValid($value) { $valueString = (string) $value; $this->_setValue($valueString); // Check input against IP address schema if ($this->_ipValidator->setTranslator($this->getTranslator())->isValid($valueString)) { if (!($this->_allow & self::ALLOW_IP)) { $this->_error(self::IP_ADDRESS_NOT_ALLOWED); return false; } else{ return true; } } // Check input against DNS hostname schema $domainParts = explode('.', $valueString); if ((count($domainParts) > 1) && (strlen($valueString) >= 4) && (strlen($valueString) <= 254)) { $status = false; do { // First check TLD if (preg_match('/([^.]{2,10})$/i', end($domainParts), $matches) || (end($domainParts) == 'ایران') || (end($domainParts) == '中国') || (end($domainParts) == '公司') || (end($domainParts) == '网络')) { reset($domainParts); // Hostname characters are: *(label dot)(label dot label); max 254 chars // label: id-prefix [*ldh{61} id-prefix]; max 63 chars // id-prefix: alpha / digit // ldh: alpha / digit / dash // Match TLD against known list $this->_tld = strtolower($matches[1]); if ($this->_validateTld) { if (!in_array($this->_tld, $this->_validTlds)) { $this->_error(self::UNKNOWN_TLD); $status = false; break; } } /** * Match against IDN hostnames * Note: Keep label regex short to avoid issues with long patterns when matching IDN hostnames * @see Zend_Validate_Hostname_Interface */ $regexChars = array(0 => '/^[a-z0-9\x2d]{1,63}$/i'); if ($this->_validateIdn && isset($this->_validIdns[strtoupper($this->_tld)])) { if (is_string($this->_validIdns[strtoupper($this->_tld)])) { $regexChars += include($this->_validIdns[strtoupper($this->_tld)]); } else { $regexChars += $this->_validIdns[strtoupper($this->_tld)]; } } // Check each hostname part $valid = true; foreach ($domainParts as $domainPart) { // Decode Punycode domainnames to IDN if (strpos($domainPart, 'xn--') === 0) { $domainPart = $this->decodePunycode(substr($domainPart, 4)); if ($domainPart === false) { return false; } } // Check dash (-) does not start, end or appear in 3rd and 4th positions if ((strpos($domainPart, '-') === 0) || ((strlen($domainPart) > 2) && (strpos($domainPart, '-', 2) == 2) && (strpos($domainPart, '-', 3) == 3)) || (strpos($domainPart, '-') === (strlen($domainPart) - 1))) { $this->_error(self::INVALID_DASH); $status = false; break 2; } // Check each domain part $check = false; foreach($regexChars as $regexKey => $regexChar) { $status = @preg_match($regexChar, $domainPart); if ($status === false) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: DNS validation failed'); } elseif ($status !== 0) { $length = 63; if (array_key_exists(strtoupper($this->_tld), $this->_idnLength) && (array_key_exists($regexKey, $this->_idnLength[strtoupper($this->_tld)]))) { $length = $this->_idnLength[strtoupper($this->_tld)]; } if (iconv_strlen($domainPart) > $length) { $this->_error(self::INVALID_HOSTNAME); } else { $check = true; break 2; } } } if (!$check) { $valid = false; } } // If all labels didn't match, the hostname is invalid if (!$valid) { $this->_error(self::INVALID_HOSTNAME_SCHEMA); $status = false; } } else { // Hostname not long enough $this->_error(self::UNDECIPHERABLE_TLD); $status = false; } } while (false); // If the input passes as an Internet domain name, and domain names are allowed, then the hostname // passes validation if ($status && ($this->_allow & self::ALLOW_DNS)) { return true; } } else { $this->_error(self::INVALID_HOSTNAME); } // Check input against local network name schema; last chance to pass validation $regexLocal = '/^(([a-zA-Z0-9\x2d]{1,63}\x2e)*[a-zA-Z0-9\x2d]{1,63}){1,254}$/'; $status = @preg_match($regexLocal, $valueString); if (false === $status) { /** * Regex error * @see Zend_Validate_Exception */ require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Internal error: local network name validation failed'); } // If the input passes as a local network name, and local network names are allowed, then the // hostname passes validation $allowLocal = $this->_allow & self::ALLOW_LOCAL; if ($status && $allowLocal) { return true; } // If the input does not pass as a local network name, add a message if (!$status) { $this->_error(self::INVALID_LOCAL_NAME); } // If local network names are not allowed, add a message if ($status && !$allowLocal) { $this->_error(self::LOCAL_NAME_NOT_ALLOWED); } return false; }
[ "public", "function", "isValid", "(", "$", "value", ")", "{", "$", "valueString", "=", "(", "string", ")", "$", "value", ";", "$", "this", "->", "_setValue", "(", "$", "valueString", ")", ";", "// Check input against IP address schema", "if", "(", "$", "this", "->", "_ipValidator", "->", "setTranslator", "(", "$", "this", "->", "getTranslator", "(", ")", ")", "->", "isValid", "(", "$", "valueString", ")", ")", "{", "if", "(", "!", "(", "$", "this", "->", "_allow", "&", "self", "::", "ALLOW_IP", ")", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "IP_ADDRESS_NOT_ALLOWED", ")", ";", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}", "// Check input against DNS hostname schema", "$", "domainParts", "=", "explode", "(", "'.'", ",", "$", "valueString", ")", ";", "if", "(", "(", "count", "(", "$", "domainParts", ")", ">", "1", ")", "&&", "(", "strlen", "(", "$", "valueString", ")", ">=", "4", ")", "&&", "(", "strlen", "(", "$", "valueString", ")", "<=", "254", ")", ")", "{", "$", "status", "=", "false", ";", "do", "{", "// First check TLD", "if", "(", "preg_match", "(", "'/([^.]{2,10})$/i'", ",", "end", "(", "$", "domainParts", ")", ",", "$", "matches", ")", "||", "(", "end", "(", "$", "domainParts", ")", "==", "'ایران') || ", "(", "nd", "$", "dom", "a", "i", "nParts) == ", "'", "国'", " ||", "", "", "(", "end", "(", "$", "domainParts", ")", "==", "'公司') ||", " ", "en", "(", "$do", "m", "a", "inParts) ==", " ", "网络", ")) {", "", "", "", "reset", "(", "$", "domainParts", ")", ";", "// Hostname characters are: *(label dot)(label dot label); max 254 chars", "// label: id-prefix [*ldh{61} id-prefix]; max 63 chars", "// id-prefix: alpha / digit", "// ldh: alpha / digit / dash", "// Match TLD against known list", "$", "this", "->", "_tld", "=", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ";", "if", "(", "$", "this", "->", "_validateTld", ")", "{", "if", "(", "!", "in_array", "(", "$", "this", "->", "_tld", ",", "$", "this", "->", "_validTlds", ")", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "UNKNOWN_TLD", ")", ";", "$", "status", "=", "false", ";", "break", ";", "}", "}", "/**\n * Match against IDN hostnames\n * Note: Keep label regex short to avoid issues with long patterns when matching IDN hostnames\n * @see Zend_Validate_Hostname_Interface\n */", "$", "regexChars", "=", "array", "(", "0", "=>", "'/^[a-z0-9\\x2d]{1,63}$/i'", ")", ";", "if", "(", "$", "this", "->", "_validateIdn", "&&", "isset", "(", "$", "this", "->", "_validIdns", "[", "strtoupper", "(", "$", "this", "->", "_tld", ")", "]", ")", ")", "{", "if", "(", "is_string", "(", "$", "this", "->", "_validIdns", "[", "strtoupper", "(", "$", "this", "->", "_tld", ")", "]", ")", ")", "{", "$", "regexChars", "+=", "include", "(", "$", "this", "->", "_validIdns", "[", "strtoupper", "(", "$", "this", "->", "_tld", ")", "]", ")", ";", "}", "else", "{", "$", "regexChars", "+=", "$", "this", "->", "_validIdns", "[", "strtoupper", "(", "$", "this", "->", "_tld", ")", "]", ";", "}", "}", "// Check each hostname part", "$", "valid", "=", "true", ";", "foreach", "(", "$", "domainParts", "as", "$", "domainPart", ")", "{", "// Decode Punycode domainnames to IDN", "if", "(", "strpos", "(", "$", "domainPart", ",", "'xn--'", ")", "===", "0", ")", "{", "$", "domainPart", "=", "$", "this", "->", "decodePunycode", "(", "substr", "(", "$", "domainPart", ",", "4", ")", ")", ";", "if", "(", "$", "domainPart", "===", "false", ")", "{", "return", "false", ";", "}", "}", "// Check dash (-) does not start, end or appear in 3rd and 4th positions", "if", "(", "(", "strpos", "(", "$", "domainPart", ",", "'-'", ")", "===", "0", ")", "||", "(", "(", "strlen", "(", "$", "domainPart", ")", ">", "2", ")", "&&", "(", "strpos", "(", "$", "domainPart", ",", "'-'", ",", "2", ")", "==", "2", ")", "&&", "(", "strpos", "(", "$", "domainPart", ",", "'-'", ",", "3", ")", "==", "3", ")", ")", "||", "(", "strpos", "(", "$", "domainPart", ",", "'-'", ")", "===", "(", "strlen", "(", "$", "domainPart", ")", "-", "1", ")", ")", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_DASH", ")", ";", "$", "status", "=", "false", ";", "break", "2", ";", "}", "// Check each domain part", "$", "check", "=", "false", ";", "foreach", "(", "$", "regexChars", "as", "$", "regexKey", "=>", "$", "regexChar", ")", "{", "$", "status", "=", "@", "preg_match", "(", "$", "regexChar", ",", "$", "domainPart", ")", ";", "if", "(", "$", "status", "===", "false", ")", "{", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "'Internal error: DNS validation failed'", ")", ";", "}", "elseif", "(", "$", "status", "!==", "0", ")", "{", "$", "length", "=", "63", ";", "if", "(", "array_key_exists", "(", "strtoupper", "(", "$", "this", "->", "_tld", ")", ",", "$", "this", "->", "_idnLength", ")", "&&", "(", "array_key_exists", "(", "$", "regexKey", ",", "$", "this", "->", "_idnLength", "[", "strtoupper", "(", "$", "this", "->", "_tld", ")", "]", ")", ")", ")", "{", "$", "length", "=", "$", "this", "->", "_idnLength", "[", "strtoupper", "(", "$", "this", "->", "_tld", ")", "]", ";", "}", "if", "(", "iconv_strlen", "(", "$", "domainPart", ")", ">", "$", "length", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_HOSTNAME", ")", ";", "}", "else", "{", "$", "check", "=", "true", ";", "break", "2", ";", "}", "}", "}", "if", "(", "!", "$", "check", ")", "{", "$", "valid", "=", "false", ";", "}", "}", "// If all labels didn't match, the hostname is invalid", "if", "(", "!", "$", "valid", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_HOSTNAME_SCHEMA", ")", ";", "$", "status", "=", "false", ";", "}", "}", "else", "{", "// Hostname not long enough", "$", "this", "->", "_error", "(", "self", "::", "UNDECIPHERABLE_TLD", ")", ";", "$", "status", "=", "false", ";", "}", "}", "while", "(", "false", ")", ";", "// If the input passes as an Internet domain name, and domain names are allowed, then the hostname", "// passes validation", "if", "(", "$", "status", "&&", "(", "$", "this", "->", "_allow", "&", "self", "::", "ALLOW_DNS", ")", ")", "{", "return", "true", ";", "}", "}", "else", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_HOSTNAME", ")", ";", "}", "// Check input against local network name schema; last chance to pass validation", "$", "regexLocal", "=", "'/^(([a-zA-Z0-9\\x2d]{1,63}\\x2e)*[a-zA-Z0-9\\x2d]{1,63}){1,254}$/'", ";", "$", "status", "=", "@", "preg_match", "(", "$", "regexLocal", ",", "$", "valueString", ")", ";", "if", "(", "false", "===", "$", "status", ")", "{", "/**\n * Regex error\n * @see Zend_Validate_Exception\n */", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "'Internal error: local network name validation failed'", ")", ";", "}", "// If the input passes as a local network name, and local network names are allowed, then the", "// hostname passes validation", "$", "allowLocal", "=", "$", "this", "->", "_allow", "&", "self", "::", "ALLOW_LOCAL", ";", "if", "(", "$", "status", "&&", "$", "allowLocal", ")", "{", "return", "true", ";", "}", "// If the input does not pass as a local network name, add a message", "if", "(", "!", "$", "status", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "INVALID_LOCAL_NAME", ")", ";", "}", "// If local network names are not allowed, add a message", "if", "(", "$", "status", "&&", "!", "$", "allowLocal", ")", "{", "$", "this", "->", "_error", "(", "self", "::", "LOCAL_NAME_NOT_ALLOWED", ")", ";", "}", "return", "false", ";", "}" ]
Defined by Zend_Validate_Interface Returns true if and only if the $value is a valid hostname with respect to the current allow option @param string $value @throws Zend_Validate_Exception if a fatal error occurs for validation process @return boolean
[ "Defined", "by", "Zend_Validate_Interface" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/Hostname.php#L415-L574
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/Hostname.php
Zend_Validate_Hostname.decodePunycode
protected function decodePunycode($encoded) { $matches = array(); $found = preg_match('/([^a-z0-9\x2d]{1,10})$/i', $encoded); if (empty($encoded) || (count($matches) > 0)) { // no punycode encoded string, return as is $this->_error(self::CANNOT_DECODE_PUNYCODE); return false; } $separator = strrpos($encoded, '-'); if ($separator > 0) { for ($x = 0; $x < $separator; ++$x) { // prepare decoding matrix $decoded[] = ord($encoded[$x]); } } else { $this->_error(self::CANNOT_DECODE_PUNYCODE); return false; } $lengthd = count($decoded); $lengthe = strlen($encoded); // decoding $init = true; $base = 72; $index = 0; $char = 0x80; for ($indexe = ($separator) ? ($separator + 1) : 0; $indexe < $lengthe; ++$lengthd) { for ($old_index = $index, $pos = 1, $key = 36; 1 ; $key += 36) { $hex = ord($encoded[$indexe++]); $digit = ($hex - 48 < 10) ? $hex - 22 : (($hex - 65 < 26) ? $hex - 65 : (($hex - 97 < 26) ? $hex - 97 : 36)); $index += $digit * $pos; $tag = ($key <= $base) ? 1 : (($key >= $base + 26) ? 26 : ($key - $base)); if ($digit < $tag) { break; } $pos = (int) ($pos * (36 - $tag)); } $delta = intval($init ? (($index - $old_index) / 700) : (($index - $old_index) / 2)); $delta += intval($delta / ($lengthd + 1)); for ($key = 0; $delta > 910 / 2; $key += 36) { $delta = intval($delta / 35); } $base = intval($key + 36 * $delta / ($delta + 38)); $init = false; $char += (int) ($index / ($lengthd + 1)); $index %= ($lengthd + 1); if ($lengthd > 0) { for ($i = $lengthd; $i > $index; $i--) { $decoded[$i] = $decoded[($i - 1)]; } } $decoded[$index++] = $char; } // convert decoded ucs4 to utf8 string foreach ($decoded as $key => $value) { if ($value < 128) { $decoded[$key] = chr($value); } elseif ($value < (1 << 11)) { $decoded[$key] = chr(192 + ($value >> 6)); $decoded[$key] .= chr(128 + ($value & 63)); } elseif ($value < (1 << 16)) { $decoded[$key] = chr(224 + ($value >> 12)); $decoded[$key] .= chr(128 + (($value >> 6) & 63)); $decoded[$key] .= chr(128 + ($value & 63)); } elseif ($value < (1 << 21)) { $decoded[$key] = chr(240 + ($value >> 18)); $decoded[$key] .= chr(128 + (($value >> 12) & 63)); $decoded[$key] .= chr(128 + (($value >> 6) & 63)); $decoded[$key] .= chr(128 + ($value & 63)); } else { $this->_error(self::CANNOT_DECODE_PUNYCODE); return false; } } return implode($decoded); }
php
protected function decodePunycode($encoded) { $matches = array(); $found = preg_match('/([^a-z0-9\x2d]{1,10})$/i', $encoded); if (empty($encoded) || (count($matches) > 0)) { // no punycode encoded string, return as is $this->_error(self::CANNOT_DECODE_PUNYCODE); return false; } $separator = strrpos($encoded, '-'); if ($separator > 0) { for ($x = 0; $x < $separator; ++$x) { // prepare decoding matrix $decoded[] = ord($encoded[$x]); } } else { $this->_error(self::CANNOT_DECODE_PUNYCODE); return false; } $lengthd = count($decoded); $lengthe = strlen($encoded); // decoding $init = true; $base = 72; $index = 0; $char = 0x80; for ($indexe = ($separator) ? ($separator + 1) : 0; $indexe < $lengthe; ++$lengthd) { for ($old_index = $index, $pos = 1, $key = 36; 1 ; $key += 36) { $hex = ord($encoded[$indexe++]); $digit = ($hex - 48 < 10) ? $hex - 22 : (($hex - 65 < 26) ? $hex - 65 : (($hex - 97 < 26) ? $hex - 97 : 36)); $index += $digit * $pos; $tag = ($key <= $base) ? 1 : (($key >= $base + 26) ? 26 : ($key - $base)); if ($digit < $tag) { break; } $pos = (int) ($pos * (36 - $tag)); } $delta = intval($init ? (($index - $old_index) / 700) : (($index - $old_index) / 2)); $delta += intval($delta / ($lengthd + 1)); for ($key = 0; $delta > 910 / 2; $key += 36) { $delta = intval($delta / 35); } $base = intval($key + 36 * $delta / ($delta + 38)); $init = false; $char += (int) ($index / ($lengthd + 1)); $index %= ($lengthd + 1); if ($lengthd > 0) { for ($i = $lengthd; $i > $index; $i--) { $decoded[$i] = $decoded[($i - 1)]; } } $decoded[$index++] = $char; } // convert decoded ucs4 to utf8 string foreach ($decoded as $key => $value) { if ($value < 128) { $decoded[$key] = chr($value); } elseif ($value < (1 << 11)) { $decoded[$key] = chr(192 + ($value >> 6)); $decoded[$key] .= chr(128 + ($value & 63)); } elseif ($value < (1 << 16)) { $decoded[$key] = chr(224 + ($value >> 12)); $decoded[$key] .= chr(128 + (($value >> 6) & 63)); $decoded[$key] .= chr(128 + ($value & 63)); } elseif ($value < (1 << 21)) { $decoded[$key] = chr(240 + ($value >> 18)); $decoded[$key] .= chr(128 + (($value >> 12) & 63)); $decoded[$key] .= chr(128 + (($value >> 6) & 63)); $decoded[$key] .= chr(128 + ($value & 63)); } else { $this->_error(self::CANNOT_DECODE_PUNYCODE); return false; } } return implode($decoded); }
[ "protected", "function", "decodePunycode", "(", "$", "encoded", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "$", "found", "=", "preg_match", "(", "'/([^a-z0-9\\x2d]{1,10})$/i'", ",", "$", "encoded", ")", ";", "if", "(", "empty", "(", "$", "encoded", ")", "||", "(", "count", "(", "$", "matches", ")", ">", "0", ")", ")", "{", "// no punycode encoded string, return as is", "$", "this", "->", "_error", "(", "self", "::", "CANNOT_DECODE_PUNYCODE", ")", ";", "return", "false", ";", "}", "$", "separator", "=", "strrpos", "(", "$", "encoded", ",", "'-'", ")", ";", "if", "(", "$", "separator", ">", "0", ")", "{", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<", "$", "separator", ";", "++", "$", "x", ")", "{", "// prepare decoding matrix", "$", "decoded", "[", "]", "=", "ord", "(", "$", "encoded", "[", "$", "x", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "_error", "(", "self", "::", "CANNOT_DECODE_PUNYCODE", ")", ";", "return", "false", ";", "}", "$", "lengthd", "=", "count", "(", "$", "decoded", ")", ";", "$", "lengthe", "=", "strlen", "(", "$", "encoded", ")", ";", "// decoding", "$", "init", "=", "true", ";", "$", "base", "=", "72", ";", "$", "index", "=", "0", ";", "$", "char", "=", "0x80", ";", "for", "(", "$", "indexe", "=", "(", "$", "separator", ")", "?", "(", "$", "separator", "+", "1", ")", ":", "0", ";", "$", "indexe", "<", "$", "lengthe", ";", "++", "$", "lengthd", ")", "{", "for", "(", "$", "old_index", "=", "$", "index", ",", "$", "pos", "=", "1", ",", "$", "key", "=", "36", ";", "1", ";", "$", "key", "+=", "36", ")", "{", "$", "hex", "=", "ord", "(", "$", "encoded", "[", "$", "indexe", "++", "]", ")", ";", "$", "digit", "=", "(", "$", "hex", "-", "48", "<", "10", ")", "?", "$", "hex", "-", "22", ":", "(", "(", "$", "hex", "-", "65", "<", "26", ")", "?", "$", "hex", "-", "65", ":", "(", "(", "$", "hex", "-", "97", "<", "26", ")", "?", "$", "hex", "-", "97", ":", "36", ")", ")", ";", "$", "index", "+=", "$", "digit", "*", "$", "pos", ";", "$", "tag", "=", "(", "$", "key", "<=", "$", "base", ")", "?", "1", ":", "(", "(", "$", "key", ">=", "$", "base", "+", "26", ")", "?", "26", ":", "(", "$", "key", "-", "$", "base", ")", ")", ";", "if", "(", "$", "digit", "<", "$", "tag", ")", "{", "break", ";", "}", "$", "pos", "=", "(", "int", ")", "(", "$", "pos", "*", "(", "36", "-", "$", "tag", ")", ")", ";", "}", "$", "delta", "=", "intval", "(", "$", "init", "?", "(", "(", "$", "index", "-", "$", "old_index", ")", "/", "700", ")", ":", "(", "(", "$", "index", "-", "$", "old_index", ")", "/", "2", ")", ")", ";", "$", "delta", "+=", "intval", "(", "$", "delta", "/", "(", "$", "lengthd", "+", "1", ")", ")", ";", "for", "(", "$", "key", "=", "0", ";", "$", "delta", ">", "910", "/", "2", ";", "$", "key", "+=", "36", ")", "{", "$", "delta", "=", "intval", "(", "$", "delta", "/", "35", ")", ";", "}", "$", "base", "=", "intval", "(", "$", "key", "+", "36", "*", "$", "delta", "/", "(", "$", "delta", "+", "38", ")", ")", ";", "$", "init", "=", "false", ";", "$", "char", "+=", "(", "int", ")", "(", "$", "index", "/", "(", "$", "lengthd", "+", "1", ")", ")", ";", "$", "index", "%=", "(", "$", "lengthd", "+", "1", ")", ";", "if", "(", "$", "lengthd", ">", "0", ")", "{", "for", "(", "$", "i", "=", "$", "lengthd", ";", "$", "i", ">", "$", "index", ";", "$", "i", "--", ")", "{", "$", "decoded", "[", "$", "i", "]", "=", "$", "decoded", "[", "(", "$", "i", "-", "1", ")", "]", ";", "}", "}", "$", "decoded", "[", "$", "index", "++", "]", "=", "$", "char", ";", "}", "// convert decoded ucs4 to utf8 string", "foreach", "(", "$", "decoded", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "<", "128", ")", "{", "$", "decoded", "[", "$", "key", "]", "=", "chr", "(", "$", "value", ")", ";", "}", "elseif", "(", "$", "value", "<", "(", "1", "<<", "11", ")", ")", "{", "$", "decoded", "[", "$", "key", "]", "=", "chr", "(", "192", "+", "(", "$", "value", ">>", "6", ")", ")", ";", "$", "decoded", "[", "$", "key", "]", ".=", "chr", "(", "128", "+", "(", "$", "value", "&", "63", ")", ")", ";", "}", "elseif", "(", "$", "value", "<", "(", "1", "<<", "16", ")", ")", "{", "$", "decoded", "[", "$", "key", "]", "=", "chr", "(", "224", "+", "(", "$", "value", ">>", "12", ")", ")", ";", "$", "decoded", "[", "$", "key", "]", ".=", "chr", "(", "128", "+", "(", "(", "$", "value", ">>", "6", ")", "&", "63", ")", ")", ";", "$", "decoded", "[", "$", "key", "]", ".=", "chr", "(", "128", "+", "(", "$", "value", "&", "63", ")", ")", ";", "}", "elseif", "(", "$", "value", "<", "(", "1", "<<", "21", ")", ")", "{", "$", "decoded", "[", "$", "key", "]", "=", "chr", "(", "240", "+", "(", "$", "value", ">>", "18", ")", ")", ";", "$", "decoded", "[", "$", "key", "]", ".=", "chr", "(", "128", "+", "(", "(", "$", "value", ">>", "12", ")", "&", "63", ")", ")", ";", "$", "decoded", "[", "$", "key", "]", ".=", "chr", "(", "128", "+", "(", "(", "$", "value", ">>", "6", ")", "&", "63", ")", ")", ";", "$", "decoded", "[", "$", "key", "]", ".=", "chr", "(", "128", "+", "(", "$", "value", "&", "63", ")", ")", ";", "}", "else", "{", "$", "this", "->", "_error", "(", "self", "::", "CANNOT_DECODE_PUNYCODE", ")", ";", "return", "false", ";", "}", "}", "return", "implode", "(", "$", "decoded", ")", ";", "}" ]
Decodes a punycode encoded string to it's original utf8 string In case of a decoding failure the original string is returned @param string $encoded Punycode encoded string to decode @return string
[ "Decodes", "a", "punycode", "encoded", "string", "to", "it", "s", "original", "utf8", "string", "In", "case", "of", "a", "decoding", "failure", "the", "original", "string", "is", "returned" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/Hostname.php#L583-L672
webforge-labs/psc-cms
lib/Psc/UI/Tabs2.php
Tabs2.addItem
public function addItem(TabsContentItem $item) { if ($item instanceof \Psc\Doctrine\Entity && \Psc\PSC::getProject()->isDevelopment()) { throw new \Psc\DeprecatedException('Entities übergeben ist deprecated. Psc\CMS\Item\Adapter benutzen.'); } return $this->add($item->getTabsLabel(TabsContentItem::LABEL_TAB), NULL, $item->getTabsURL(), HTML::string2id(implode('-',$item->getTabsId()))); }
php
public function addItem(TabsContentItem $item) { if ($item instanceof \Psc\Doctrine\Entity && \Psc\PSC::getProject()->isDevelopment()) { throw new \Psc\DeprecatedException('Entities übergeben ist deprecated. Psc\CMS\Item\Adapter benutzen.'); } return $this->add($item->getTabsLabel(TabsContentItem::LABEL_TAB), NULL, $item->getTabsURL(), HTML::string2id(implode('-',$item->getTabsId()))); }
[ "public", "function", "addItem", "(", "TabsContentItem", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "\\", "Psc", "\\", "Doctrine", "\\", "Entity", "&&", "\\", "Psc", "\\", "PSC", "::", "getProject", "(", ")", "->", "isDevelopment", "(", ")", ")", "{", "throw", "new", "\\", "Psc", "\\", "DeprecatedException", "(", "'Entities übergeben ist deprecated. Psc\\CMS\\Item\\Adapter benutzen.')", ";", "", "}", "return", "$", "this", "->", "add", "(", "$", "item", "->", "getTabsLabel", "(", "TabsContentItem", "::", "LABEL_TAB", ")", ",", "NULL", ",", "$", "item", "->", "getTabsURL", "(", ")", ",", "HTML", "::", "string2id", "(", "implode", "(", "'-'", ",", "$", "item", "->", "getTabsId", "(", ")", ")", ")", ")", ";", "}" ]
Fügt ein TabsContentItem (nur V2) den Tabs hinzu der Content wird per Ajax geladen mit der URL die das TabsContentItem angibt
[ "Fügt", "ein", "TabsContentItem", "(", "nur", "V2", ")", "den", "Tabs", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Tabs2.php#L65-L70
webforge-labs/psc-cms
lib/Psc/UI/Tabs2.php
Tabs2.addTabOpenable
public function addTabOpenable(TabOpenable $item) { $rm = $item->getTabRequestMeta(); return $this->add($item->getTabLabel(), NULL, $rm->getUrl(), $this->exporter->convertToId($item)); }
php
public function addTabOpenable(TabOpenable $item) { $rm = $item->getTabRequestMeta(); return $this->add($item->getTabLabel(), NULL, $rm->getUrl(), $this->exporter->convertToId($item)); }
[ "public", "function", "addTabOpenable", "(", "TabOpenable", "$", "item", ")", "{", "$", "rm", "=", "$", "item", "->", "getTabRequestMeta", "(", ")", ";", "return", "$", "this", "->", "add", "(", "$", "item", "->", "getTabLabel", "(", ")", ",", "NULL", ",", "$", "rm", "->", "getUrl", "(", ")", ",", "$", "this", "->", "exporter", "->", "convertToId", "(", "$", "item", ")", ")", ";", "}" ]
Fügt ein TabOpenable den Tabs hinzu
[ "Fügt", "ein", "TabOpenable", "den", "Tabs", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Tabs2.php#L76-L79
webforge-labs/psc-cms
lib/Psc/UI/Tabs2.php
Tabs2.add
public function add($headline, $content = NULL, $contentLink = NULL, $tabName = NULL, $closeable = NULL) { $this->init(); $this->tabsIndex++; if (!isset($closeable)) { $closeable = $this->closeable; } if (!isset($tabName)) { $tabName = $this->prefix.$this->tabsIndex; } if (!isset($contentLink)) { $contentLink = '#'.$tabName; } $this->html->content->ul->content[] = HTML::Tag('li', array( HTML::Tag('a', HTML::esc($headline), array('title'=>$tabName,'href'=>$contentLink) ), // das muss in sync mit Psc.UI.Tabs.js sein ($closeable ? '<span class="ui-icon ui-icon-gear options"></span>' : NULL), // schon auch closeable weil in den options "close" ist ($closeable ? '<span class="ui-icon ui-icon-close">'.HTML::esc($closeable).'</span>' : NULL) ) )->setGlueContent('%s'); if (isset($content)) $this->html->content->$tabName = HTML::Tag('div', $content, array('id'=>$tabName)); return $this; }
php
public function add($headline, $content = NULL, $contentLink = NULL, $tabName = NULL, $closeable = NULL) { $this->init(); $this->tabsIndex++; if (!isset($closeable)) { $closeable = $this->closeable; } if (!isset($tabName)) { $tabName = $this->prefix.$this->tabsIndex; } if (!isset($contentLink)) { $contentLink = '#'.$tabName; } $this->html->content->ul->content[] = HTML::Tag('li', array( HTML::Tag('a', HTML::esc($headline), array('title'=>$tabName,'href'=>$contentLink) ), // das muss in sync mit Psc.UI.Tabs.js sein ($closeable ? '<span class="ui-icon ui-icon-gear options"></span>' : NULL), // schon auch closeable weil in den options "close" ist ($closeable ? '<span class="ui-icon ui-icon-close">'.HTML::esc($closeable).'</span>' : NULL) ) )->setGlueContent('%s'); if (isset($content)) $this->html->content->$tabName = HTML::Tag('div', $content, array('id'=>$tabName)); return $this; }
[ "public", "function", "add", "(", "$", "headline", ",", "$", "content", "=", "NULL", ",", "$", "contentLink", "=", "NULL", ",", "$", "tabName", "=", "NULL", ",", "$", "closeable", "=", "NULL", ")", "{", "$", "this", "->", "init", "(", ")", ";", "$", "this", "->", "tabsIndex", "++", ";", "if", "(", "!", "isset", "(", "$", "closeable", ")", ")", "{", "$", "closeable", "=", "$", "this", "->", "closeable", ";", "}", "if", "(", "!", "isset", "(", "$", "tabName", ")", ")", "{", "$", "tabName", "=", "$", "this", "->", "prefix", ".", "$", "this", "->", "tabsIndex", ";", "}", "if", "(", "!", "isset", "(", "$", "contentLink", ")", ")", "{", "$", "contentLink", "=", "'#'", ".", "$", "tabName", ";", "}", "$", "this", "->", "html", "->", "content", "->", "ul", "->", "content", "[", "]", "=", "HTML", "::", "Tag", "(", "'li'", ",", "array", "(", "HTML", "::", "Tag", "(", "'a'", ",", "HTML", "::", "esc", "(", "$", "headline", ")", ",", "array", "(", "'title'", "=>", "$", "tabName", ",", "'href'", "=>", "$", "contentLink", ")", ")", ",", "// das muss in sync mit Psc.UI.Tabs.js sein", "(", "$", "closeable", "?", "'<span class=\"ui-icon ui-icon-gear options\"></span>'", ":", "NULL", ")", ",", "// schon auch closeable weil in den options \"close\" ist", "(", "$", "closeable", "?", "'<span class=\"ui-icon ui-icon-close\">'", ".", "HTML", "::", "esc", "(", "$", "closeable", ")", ".", "'</span>'", ":", "NULL", ")", ")", ")", "->", "setGlueContent", "(", "'%s'", ")", ";", "if", "(", "isset", "(", "$", "content", ")", ")", "$", "this", "->", "html", "->", "content", "->", "$", "tabName", "=", "HTML", "::", "Tag", "(", "'div'", ",", "$", "content", ",", "array", "(", "'id'", "=>", "$", "tabName", ")", ")", ";", "return", "$", "this", ";", "}" ]
Fügt einen Tab hinzu Es kann alles angegebenwerden (Low-Level)
[ "Fügt", "einen", "Tab", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Tabs2.php#L86-L118
webforge-labs/psc-cms
lib/Psc/UI/Tabs2.php
Tabs2.select
public function select($index) { $this->init(); $this->select = $index; $this->html->getTemplateContent()->select = jsHelper::embed( jsHelper::bootLoad( array('app/main'), array('main'), sprintf("var tabs = main.getTabs(), tab = tabs.tab({index: %d});\n tabs.select(tab);", $this->select) ) ) ; return $this; }
php
public function select($index) { $this->init(); $this->select = $index; $this->html->getTemplateContent()->select = jsHelper::embed( jsHelper::bootLoad( array('app/main'), array('main'), sprintf("var tabs = main.getTabs(), tab = tabs.tab({index: %d});\n tabs.select(tab);", $this->select) ) ) ; return $this; }
[ "public", "function", "select", "(", "$", "index", ")", "{", "$", "this", "->", "init", "(", ")", ";", "$", "this", "->", "select", "=", "$", "index", ";", "$", "this", "->", "html", "->", "getTemplateContent", "(", ")", "->", "select", "=", "jsHelper", "::", "embed", "(", "jsHelper", "::", "bootLoad", "(", "array", "(", "'app/main'", ")", ",", "array", "(", "'main'", ")", ",", "sprintf", "(", "\"var tabs = main.getTabs(), tab = tabs.tab({index: %d});\\n tabs.select(tab);\"", ",", "$", "this", "->", "select", ")", ")", ")", ";", "return", "$", "this", ";", "}" ]
Wählt den Index aus, der direkt nach dem Laden der Seite geladen werden soll dies initialisiert das widget auch auf Javascript-Basis
[ "Wählt", "den", "Index", "aus", "der", "direkt", "nach", "dem", "Laden", "der", "Seite", "geladen", "werden", "soll" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/UI/Tabs2.php#L132-L146
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.deleteContainers
public function deleteContainers($containers, $force = false) { if (!empty($containers)) { if (!isset($containers[0])) { // single folder, make into array $containers = [$containers]; } foreach ($containers as $key => $folder) { try { // path is full path, name is relative to root, take either $name = array_get($folder, 'name', trim(array_get($folder, 'path'), '/')); if (!empty($name)) { $this->deleteContainer($name, $force); } else { throw new DfException('No name found for container in delete request.'); } } catch (\Exception $ex) { // error whole batch here? $containers[$key]['error'] = ['message' => $ex->getMessage(), 'code' => $ex->getCode()]; } } } return $containers; }
php
public function deleteContainers($containers, $force = false) { if (!empty($containers)) { if (!isset($containers[0])) { // single folder, make into array $containers = [$containers]; } foreach ($containers as $key => $folder) { try { // path is full path, name is relative to root, take either $name = array_get($folder, 'name', trim(array_get($folder, 'path'), '/')); if (!empty($name)) { $this->deleteContainer($name, $force); } else { throw new DfException('No name found for container in delete request.'); } } catch (\Exception $ex) { // error whole batch here? $containers[$key]['error'] = ['message' => $ex->getMessage(), 'code' => $ex->getCode()]; } } } return $containers; }
[ "public", "function", "deleteContainers", "(", "$", "containers", ",", "$", "force", "=", "false", ")", "{", "if", "(", "!", "empty", "(", "$", "containers", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "containers", "[", "0", "]", ")", ")", "{", "// single folder, make into array", "$", "containers", "=", "[", "$", "containers", "]", ";", "}", "foreach", "(", "$", "containers", "as", "$", "key", "=>", "$", "folder", ")", "{", "try", "{", "// path is full path, name is relative to root, take either", "$", "name", "=", "array_get", "(", "$", "folder", ",", "'name'", ",", "trim", "(", "array_get", "(", "$", "folder", ",", "'path'", ")", ",", "'/'", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "name", ")", ")", "{", "$", "this", "->", "deleteContainer", "(", "$", "name", ",", "$", "force", ")", ";", "}", "else", "{", "throw", "new", "DfException", "(", "'No name found for container in delete request.'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "// error whole batch here?", "$", "containers", "[", "$", "key", "]", "[", "'error'", "]", "=", "[", "'message'", "=>", "$", "ex", "->", "getMessage", "(", ")", ",", "'code'", "=>", "$", "ex", "->", "getCode", "(", ")", "]", ";", "}", "}", "}", "return", "$", "containers", ";", "}" ]
Delete multiple containers and all of their content @param array $containers @param bool $force Force a delete if it is not empty @throws DfException @return array
[ "Delete", "multiple", "containers", "and", "all", "of", "their", "content" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L79-L103
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.folderExists
public function folderExists($container, $path) { $path = FileUtilities::fixFolderPath($path); if ($this->containerExists($container)) { if ($this->blobExists($container, $path)) { return true; } } return false; }
php
public function folderExists($container, $path) { $path = FileUtilities::fixFolderPath($path); if ($this->containerExists($container)) { if ($this->blobExists($container, $path)) { return true; } } return false; }
[ "public", "function", "folderExists", "(", "$", "container", ",", "$", "path", ")", "{", "$", "path", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "path", ")", ";", "if", "(", "$", "this", "->", "containerExists", "(", "$", "container", ")", ")", "{", "if", "(", "$", "this", "->", "blobExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
@param string $container @param $path @return bool @throws \Exception
[ "@param", "string", "$container", "@param", "$path" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L112-L122
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.getFolder
public function getFolder($container, $path, $include_files = true, $include_folders = true, $full_tree = false) { $delimiter = ($full_tree) ? '' : '/'; $resources = []; if ($this->containerExists($container)) { if (!empty($path)) { if (!$this->blobExists($container, $path)) { // blob may not exist for "fake" folders, i.e. S3 prefixes throw new NotFoundException("Folder '$path' does not exist in storage."); } } $results = $this->listBlobs($container, $path, $delimiter); foreach ($results as $data) { $fullPathName = array_get($data, 'name'); $data['path'] = $fullPathName; $data['name'] = rtrim(substr($fullPathName, strlen($path)), '/'); if ('/' == substr($fullPathName, -1)) { // folders if ($include_folders) { $data['type'] = 'folder'; $resources[] = $data; } } else { // files if ($include_files) { $data['type'] = 'file'; $resources[] = $data; } } } } else { if (!empty($path)) { throw new NotFoundException("Folder '$path' does not exist in storage."); } // container root doesn't really exist until first write creates it } return $resources; }
php
public function getFolder($container, $path, $include_files = true, $include_folders = true, $full_tree = false) { $delimiter = ($full_tree) ? '' : '/'; $resources = []; if ($this->containerExists($container)) { if (!empty($path)) { if (!$this->blobExists($container, $path)) { // blob may not exist for "fake" folders, i.e. S3 prefixes throw new NotFoundException("Folder '$path' does not exist in storage."); } } $results = $this->listBlobs($container, $path, $delimiter); foreach ($results as $data) { $fullPathName = array_get($data, 'name'); $data['path'] = $fullPathName; $data['name'] = rtrim(substr($fullPathName, strlen($path)), '/'); if ('/' == substr($fullPathName, -1)) { // folders if ($include_folders) { $data['type'] = 'folder'; $resources[] = $data; } } else { // files if ($include_files) { $data['type'] = 'file'; $resources[] = $data; } } } } else { if (!empty($path)) { throw new NotFoundException("Folder '$path' does not exist in storage."); } // container root doesn't really exist until first write creates it } return $resources; }
[ "public", "function", "getFolder", "(", "$", "container", ",", "$", "path", ",", "$", "include_files", "=", "true", ",", "$", "include_folders", "=", "true", ",", "$", "full_tree", "=", "false", ")", "{", "$", "delimiter", "=", "(", "$", "full_tree", ")", "?", "''", ":", "'/'", ";", "$", "resources", "=", "[", "]", ";", "if", "(", "$", "this", "->", "containerExists", "(", "$", "container", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "path", ")", ")", "{", "if", "(", "!", "$", "this", "->", "blobExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "// blob may not exist for \"fake\" folders, i.e. S3 prefixes", "throw", "new", "NotFoundException", "(", "\"Folder '$path' does not exist in storage.\"", ")", ";", "}", "}", "$", "results", "=", "$", "this", "->", "listBlobs", "(", "$", "container", ",", "$", "path", ",", "$", "delimiter", ")", ";", "foreach", "(", "$", "results", "as", "$", "data", ")", "{", "$", "fullPathName", "=", "array_get", "(", "$", "data", ",", "'name'", ")", ";", "$", "data", "[", "'path'", "]", "=", "$", "fullPathName", ";", "$", "data", "[", "'name'", "]", "=", "rtrim", "(", "substr", "(", "$", "fullPathName", ",", "strlen", "(", "$", "path", ")", ")", ",", "'/'", ")", ";", "if", "(", "'/'", "==", "substr", "(", "$", "fullPathName", ",", "-", "1", ")", ")", "{", "// folders", "if", "(", "$", "include_folders", ")", "{", "$", "data", "[", "'type'", "]", "=", "'folder'", ";", "$", "resources", "[", "]", "=", "$", "data", ";", "}", "}", "else", "{", "// files", "if", "(", "$", "include_files", ")", "{", "$", "data", "[", "'type'", "]", "=", "'file'", ";", "$", "resources", "[", "]", "=", "$", "data", ";", "}", "}", "}", "}", "else", "{", "if", "(", "!", "empty", "(", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$path' does not exist in storage.\"", ")", ";", "}", "// container root doesn't really exist until first write creates it", "}", "return", "$", "resources", ";", "}" ]
@param string $container @param string $path @param bool $include_files @param bool $include_folders @param bool $full_tree @throws NotFoundException @return array
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "bool", "$include_files", "@param", "bool", "$include_folders", "@param", "bool", "$full_tree" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L134-L172
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.getFolderProperties
public function getFolderProperties($container, $path) { $path = FileUtilities::fixFolderPath($path); $shortName = FileUtilities::getNameFromPath($path); $out = ['name' => $shortName, 'path' => $path]; if ($this->containerExists($container) && $this->blobExists($container, $path)) { $properties = $this->getBlobProperties($container, $path); $out = array_merge($properties, $out); } return $out; }
php
public function getFolderProperties($container, $path) { $path = FileUtilities::fixFolderPath($path); $shortName = FileUtilities::getNameFromPath($path); $out = ['name' => $shortName, 'path' => $path]; if ($this->containerExists($container) && $this->blobExists($container, $path)) { $properties = $this->getBlobProperties($container, $path); $out = array_merge($properties, $out); } return $out; }
[ "public", "function", "getFolderProperties", "(", "$", "container", ",", "$", "path", ")", "{", "$", "path", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "path", ")", ";", "$", "shortName", "=", "FileUtilities", "::", "getNameFromPath", "(", "$", "path", ")", ";", "$", "out", "=", "[", "'name'", "=>", "$", "shortName", ",", "'path'", "=>", "$", "path", "]", ";", "if", "(", "$", "this", "->", "containerExists", "(", "$", "container", ")", "&&", "$", "this", "->", "blobExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "$", "properties", "=", "$", "this", "->", "getBlobProperties", "(", "$", "container", ",", "$", "path", ")", ";", "$", "out", "=", "array_merge", "(", "$", "properties", ",", "$", "out", ")", ";", "}", "return", "$", "out", ";", "}" ]
@param string $container @param string $path @throws NotFoundException @return array
[ "@param", "string", "$container", "@param", "string", "$path" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L181-L192
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.createFolder
public function createFolder($container, $path, $is_public = true, $properties = [], $check_exist = true) { if (empty($path)) { throw new BadRequestException("Invalid empty path."); } // does this folder already exist? $path = FileUtilities::fixFolderPath($path); if ($this->folderExists($container, $path)) { if ($check_exist) { throw new BadRequestException("Folder '$path' already exists."); } return; } // does this folder's parent exist? $parent = FileUtilities::getParentFolder($path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { if ($check_exist) { throw new NotFoundException("Folder '$parent' does not exist."); } $this->createFolder($container, $parent, $is_public, $properties, false); } // create the folder $this->checkContainerForWrite($container); // need to be able to write to storage $properties = (empty($properties)) ? '' : json_encode($properties); $this->putBlobData($container, $path, $properties); }
php
public function createFolder($container, $path, $is_public = true, $properties = [], $check_exist = true) { if (empty($path)) { throw new BadRequestException("Invalid empty path."); } // does this folder already exist? $path = FileUtilities::fixFolderPath($path); if ($this->folderExists($container, $path)) { if ($check_exist) { throw new BadRequestException("Folder '$path' already exists."); } return; } // does this folder's parent exist? $parent = FileUtilities::getParentFolder($path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { if ($check_exist) { throw new NotFoundException("Folder '$parent' does not exist."); } $this->createFolder($container, $parent, $is_public, $properties, false); } // create the folder $this->checkContainerForWrite($container); // need to be able to write to storage $properties = (empty($properties)) ? '' : json_encode($properties); $this->putBlobData($container, $path, $properties); }
[ "public", "function", "createFolder", "(", "$", "container", ",", "$", "path", ",", "$", "is_public", "=", "true", ",", "$", "properties", "=", "[", "]", ",", "$", "check_exist", "=", "true", ")", "{", "if", "(", "empty", "(", "$", "path", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"Invalid empty path.\"", ")", ";", "}", "// does this folder already exist?", "$", "path", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "path", ")", ";", "if", "(", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "if", "(", "$", "check_exist", ")", "{", "throw", "new", "BadRequestException", "(", "\"Folder '$path' already exists.\"", ")", ";", "}", "return", ";", "}", "// does this folder's parent exist?", "$", "parent", "=", "FileUtilities", "::", "getParentFolder", "(", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", "&&", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "parent", ")", ")", ")", "{", "if", "(", "$", "check_exist", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$parent' does not exist.\"", ")", ";", "}", "$", "this", "->", "createFolder", "(", "$", "container", ",", "$", "parent", ",", "$", "is_public", ",", "$", "properties", ",", "false", ")", ";", "}", "// create the folder", "$", "this", "->", "checkContainerForWrite", "(", "$", "container", ")", ";", "// need to be able to write to storage", "$", "properties", "=", "(", "empty", "(", "$", "properties", ")", ")", "?", "''", ":", "json_encode", "(", "$", "properties", ")", ";", "$", "this", "->", "putBlobData", "(", "$", "container", ",", "$", "path", ",", "$", "properties", ")", ";", "}" ]
@param string $container @param string $path @param bool $is_public @param array $properties @param bool $check_exist @throws \Exception @throws NotFoundException @throws BadRequestException @return void
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "bool", "$is_public", "@param", "array", "$properties", "@param", "bool", "$check_exist" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L206-L234
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.copyFolder
public function copyFolder($container, $dest_path, $src_container, $src_path, $check_exist = false) { // does this file already exist? if (!$this->folderExists($container, $src_path)) { throw new NotFoundException("Folder '$src_path' does not exist."); } if ($this->folderExists($container, $dest_path)) { if (($check_exist)) { throw new BadRequestException("Folder '$dest_path' already exists."); } } // does this file's parent folder exist? $parent = FileUtilities::getParentFolder($dest_path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the folder $this->checkContainerForWrite($container); // need to be able to write to storage $this->copyBlob($container, $dest_path, $src_container, $src_path); // now copy content of folder... $blobs = $this->listBlobs($src_container, $src_path); if (!empty($blobs)) { foreach ($blobs as $blob) { $srcName = array_get($blob, 'name'); if ((0 !== strcasecmp($src_path, $srcName))) { // not self properties blob $name = FileUtilities::getNameFromPath($srcName); $fullPathName = $dest_path . $name; $this->copyBlob($container, $fullPathName, $src_container, $srcName); } } } }
php
public function copyFolder($container, $dest_path, $src_container, $src_path, $check_exist = false) { // does this file already exist? if (!$this->folderExists($container, $src_path)) { throw new NotFoundException("Folder '$src_path' does not exist."); } if ($this->folderExists($container, $dest_path)) { if (($check_exist)) { throw new BadRequestException("Folder '$dest_path' already exists."); } } // does this file's parent folder exist? $parent = FileUtilities::getParentFolder($dest_path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the folder $this->checkContainerForWrite($container); // need to be able to write to storage $this->copyBlob($container, $dest_path, $src_container, $src_path); // now copy content of folder... $blobs = $this->listBlobs($src_container, $src_path); if (!empty($blobs)) { foreach ($blobs as $blob) { $srcName = array_get($blob, 'name'); if ((0 !== strcasecmp($src_path, $srcName))) { // not self properties blob $name = FileUtilities::getNameFromPath($srcName); $fullPathName = $dest_path . $name; $this->copyBlob($container, $fullPathName, $src_container, $srcName); } } } }
[ "public", "function", "copyFolder", "(", "$", "container", ",", "$", "dest_path", ",", "$", "src_container", ",", "$", "src_path", ",", "$", "check_exist", "=", "false", ")", "{", "// does this file already exist?", "if", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "src_path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$src_path' does not exist.\"", ")", ";", "}", "if", "(", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "dest_path", ")", ")", "{", "if", "(", "(", "$", "check_exist", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"Folder '$dest_path' already exists.\"", ")", ";", "}", "}", "// does this file's parent folder exist?", "$", "parent", "=", "FileUtilities", "::", "getParentFolder", "(", "$", "dest_path", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", "&&", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "parent", ")", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$parent' does not exist.\"", ")", ";", "}", "// create the folder", "$", "this", "->", "checkContainerForWrite", "(", "$", "container", ")", ";", "// need to be able to write to storage", "$", "this", "->", "copyBlob", "(", "$", "container", ",", "$", "dest_path", ",", "$", "src_container", ",", "$", "src_path", ")", ";", "// now copy content of folder...", "$", "blobs", "=", "$", "this", "->", "listBlobs", "(", "$", "src_container", ",", "$", "src_path", ")", ";", "if", "(", "!", "empty", "(", "$", "blobs", ")", ")", "{", "foreach", "(", "$", "blobs", "as", "$", "blob", ")", "{", "$", "srcName", "=", "array_get", "(", "$", "blob", ",", "'name'", ")", ";", "if", "(", "(", "0", "!==", "strcasecmp", "(", "$", "src_path", ",", "$", "srcName", ")", ")", ")", "{", "// not self properties blob", "$", "name", "=", "FileUtilities", "::", "getNameFromPath", "(", "$", "srcName", ")", ";", "$", "fullPathName", "=", "$", "dest_path", ".", "$", "name", ";", "$", "this", "->", "copyBlob", "(", "$", "container", ",", "$", "fullPathName", ",", "$", "src_container", ",", "$", "srcName", ")", ";", "}", "}", "}", "}" ]
@param string $container @param string $dest_path @param string $src_container @param string $src_path @param bool $check_exist @throws \Exception @throws NotFoundException @throws BadRequestException @return void
[ "@param", "string", "$container", "@param", "string", "$dest_path", "@param", "string", "$src_container", "@param", "string", "$src_path", "@param", "bool", "$check_exist" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L248-L280
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.updateFolderProperties
public function updateFolderProperties($container, $path, $properties = []) { $path = FileUtilities::fixFolderPath($path); // does this folder exist? if (!$this->folderExists($container, $path)) { throw new NotFoundException("Folder '$path' does not exist."); } // update the file that holds folder properties $properties = json_encode($properties); $this->putBlobData($container, $path, $properties); }
php
public function updateFolderProperties($container, $path, $properties = []) { $path = FileUtilities::fixFolderPath($path); // does this folder exist? if (!$this->folderExists($container, $path)) { throw new NotFoundException("Folder '$path' does not exist."); } // update the file that holds folder properties $properties = json_encode($properties); $this->putBlobData($container, $path, $properties); }
[ "public", "function", "updateFolderProperties", "(", "$", "container", ",", "$", "path", ",", "$", "properties", "=", "[", "]", ")", "{", "$", "path", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "path", ")", ";", "// does this folder exist?", "if", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$path' does not exist.\"", ")", ";", "}", "// update the file that holds folder properties", "$", "properties", "=", "json_encode", "(", "$", "properties", ")", ";", "$", "this", "->", "putBlobData", "(", "$", "container", ",", "$", "path", ",", "$", "properties", ")", ";", "}" ]
@param string $container @param string $path @param array $properties @throws NotFoundException @throws \Exception @return void
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "array", "$properties" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L291-L301
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.deleteFolder
public function deleteFolder($container, $path, $force = false, $content_only = false) { $path = rtrim($path, '/') . '/'; $blobs = $this->listBlobs($container, $path); if (!empty($blobs)) { if ((1 === count($blobs)) && (0 === strcasecmp($path, $blobs[0]['name']))) { // only self properties blob } else { if (!$force) { throw new BadRequestException("Folder '$path' contains other files or folders."); } foreach ($blobs as $blob) { $name = array_get($blob, 'name'); $this->deleteBlob($container, $name); } } } if (!$content_only) { $this->deleteBlob($container, $path); } }
php
public function deleteFolder($container, $path, $force = false, $content_only = false) { $path = rtrim($path, '/') . '/'; $blobs = $this->listBlobs($container, $path); if (!empty($blobs)) { if ((1 === count($blobs)) && (0 === strcasecmp($path, $blobs[0]['name']))) { // only self properties blob } else { if (!$force) { throw new BadRequestException("Folder '$path' contains other files or folders."); } foreach ($blobs as $blob) { $name = array_get($blob, 'name'); $this->deleteBlob($container, $name); } } } if (!$content_only) { $this->deleteBlob($container, $path); } }
[ "public", "function", "deleteFolder", "(", "$", "container", ",", "$", "path", ",", "$", "force", "=", "false", ",", "$", "content_only", "=", "false", ")", "{", "$", "path", "=", "rtrim", "(", "$", "path", ",", "'/'", ")", ".", "'/'", ";", "$", "blobs", "=", "$", "this", "->", "listBlobs", "(", "$", "container", ",", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "blobs", ")", ")", "{", "if", "(", "(", "1", "===", "count", "(", "$", "blobs", ")", ")", "&&", "(", "0", "===", "strcasecmp", "(", "$", "path", ",", "$", "blobs", "[", "0", "]", "[", "'name'", "]", ")", ")", ")", "{", "// only self properties blob", "}", "else", "{", "if", "(", "!", "$", "force", ")", "{", "throw", "new", "BadRequestException", "(", "\"Folder '$path' contains other files or folders.\"", ")", ";", "}", "foreach", "(", "$", "blobs", "as", "$", "blob", ")", "{", "$", "name", "=", "array_get", "(", "$", "blob", ",", "'name'", ")", ";", "$", "this", "->", "deleteBlob", "(", "$", "container", ",", "$", "name", ")", ";", "}", "}", "}", "if", "(", "!", "$", "content_only", ")", "{", "$", "this", "->", "deleteBlob", "(", "$", "container", ",", "$", "path", ")", ";", "}", "}" ]
@param string $container @param string $path @param bool $force If true, delete folder content as well, otherwise return error when content present. @param bool $content_only If true, delete folder itself, false then just the content, @return void @throws \Exception
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "bool", "$force", "If", "true", "delete", "folder", "content", "as", "well", "otherwise", "return", "error", "when", "content", "present", ".", "@param", "bool", "$content_only", "If", "true", "delete", "folder", "itself", "false", "then", "just", "the", "content" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L313-L333
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.deleteFolders
public function deleteFolders($container, $folders, $root = '', $force = false) { $root = FileUtilities::fixFolderPath($root); foreach ($folders as $key => $folder) { try { // path is full path, name is relative to root, take either $path = array_get($folder, 'path'); $name = array_get($folder, 'name'); if (!empty($path)) { $path = static::removeContainerFromPath($container, $path); } elseif (!empty($name)) { $path = $root . $folder['name']; } else { throw new BadRequestException('No path or name found for folder in delete request.'); } if (!empty($path)) { $this->deleteFolder($container, $path, $force); } else { throw new BadRequestException('No path or name found for folder in delete request.'); } } catch (\Exception $ex) { // error whole batch here? $folders[$key]['error'] = ['message' => $ex->getMessage(), 'code' => $ex->getCode()]; } } return $folders; }
php
public function deleteFolders($container, $folders, $root = '', $force = false) { $root = FileUtilities::fixFolderPath($root); foreach ($folders as $key => $folder) { try { // path is full path, name is relative to root, take either $path = array_get($folder, 'path'); $name = array_get($folder, 'name'); if (!empty($path)) { $path = static::removeContainerFromPath($container, $path); } elseif (!empty($name)) { $path = $root . $folder['name']; } else { throw new BadRequestException('No path or name found for folder in delete request.'); } if (!empty($path)) { $this->deleteFolder($container, $path, $force); } else { throw new BadRequestException('No path or name found for folder in delete request.'); } } catch (\Exception $ex) { // error whole batch here? $folders[$key]['error'] = ['message' => $ex->getMessage(), 'code' => $ex->getCode()]; } } return $folders; }
[ "public", "function", "deleteFolders", "(", "$", "container", ",", "$", "folders", ",", "$", "root", "=", "''", ",", "$", "force", "=", "false", ")", "{", "$", "root", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "root", ")", ";", "foreach", "(", "$", "folders", "as", "$", "key", "=>", "$", "folder", ")", "{", "try", "{", "// path is full path, name is relative to root, take either", "$", "path", "=", "array_get", "(", "$", "folder", ",", "'path'", ")", ";", "$", "name", "=", "array_get", "(", "$", "folder", ",", "'name'", ")", ";", "if", "(", "!", "empty", "(", "$", "path", ")", ")", "{", "$", "path", "=", "static", "::", "removeContainerFromPath", "(", "$", "container", ",", "$", "path", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "name", ")", ")", "{", "$", "path", "=", "$", "root", ".", "$", "folder", "[", "'name'", "]", ";", "}", "else", "{", "throw", "new", "BadRequestException", "(", "'No path or name found for folder in delete request.'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "path", ")", ")", "{", "$", "this", "->", "deleteFolder", "(", "$", "container", ",", "$", "path", ",", "$", "force", ")", ";", "}", "else", "{", "throw", "new", "BadRequestException", "(", "'No path or name found for folder in delete request.'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "// error whole batch here?", "$", "folders", "[", "$", "key", "]", "[", "'error'", "]", "=", "[", "'message'", "=>", "$", "ex", "->", "getMessage", "(", ")", ",", "'code'", "=>", "$", "ex", "->", "getCode", "(", ")", "]", ";", "}", "}", "return", "$", "folders", ";", "}" ]
@param string $container @param array $folders @param string $root @param bool $force If true, delete folder content as well, otherwise return error when content present. @return array
[ "@param", "string", "$container", "@param", "array", "$folders", "@param", "string", "$root", "@param", "bool", "$force", "If", "true", "delete", "folder", "content", "as", "well", "otherwise", "return", "error", "when", "content", "present", "." ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L344-L371
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.fileExists
public function fileExists($container, $path) { if ($this->containerExists($container)) { if ($this->blobExists($container, $path)) { return true; } } return false; }
php
public function fileExists($container, $path) { if ($this->containerExists($container)) { if ($this->blobExists($container, $path)) { return true; } } return false; }
[ "public", "function", "fileExists", "(", "$", "container", ",", "$", "path", ")", "{", "if", "(", "$", "this", "->", "containerExists", "(", "$", "container", ")", ")", "{", "if", "(", "$", "this", "->", "blobExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
@param string $container @param $path @throws \Exception @return bool
[ "@param", "string", "$container", "@param", "$path" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L380-L389
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.getFileContent
public function getFileContent($container, $path, $local_file = '', $content_as_base = true) { if (!$this->containerExists($container) || !$this->blobExists($container, $path)) { throw new NotFoundException("File '$path' does not exist in storage."); } if (!empty($local_file)) { // write to local or temp file $this->getBlobAsFile($container, $path, $local_file); return ''; } else { // get content as raw or encoded as base64 for transport $data = $this->getBlobData($container, $path); if ($content_as_base) { $data = base64_encode($data); } return $data; } }
php
public function getFileContent($container, $path, $local_file = '', $content_as_base = true) { if (!$this->containerExists($container) || !$this->blobExists($container, $path)) { throw new NotFoundException("File '$path' does not exist in storage."); } if (!empty($local_file)) { // write to local or temp file $this->getBlobAsFile($container, $path, $local_file); return ''; } else { // get content as raw or encoded as base64 for transport $data = $this->getBlobData($container, $path); if ($content_as_base) { $data = base64_encode($data); } return $data; } }
[ "public", "function", "getFileContent", "(", "$", "container", ",", "$", "path", ",", "$", "local_file", "=", "''", ",", "$", "content_as_base", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "containerExists", "(", "$", "container", ")", "||", "!", "$", "this", "->", "blobExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"File '$path' does not exist in storage.\"", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "local_file", ")", ")", "{", "// write to local or temp file", "$", "this", "->", "getBlobAsFile", "(", "$", "container", ",", "$", "path", ",", "$", "local_file", ")", ";", "return", "''", ";", "}", "else", "{", "// get content as raw or encoded as base64 for transport", "$", "data", "=", "$", "this", "->", "getBlobData", "(", "$", "container", ",", "$", "path", ")", ";", "if", "(", "$", "content_as_base", ")", "{", "$", "data", "=", "base64_encode", "(", "$", "data", ")", ";", "}", "return", "$", "data", ";", "}", "}" ]
@param string $container @param string $path @param string $local_file @param bool $content_as_base @throws NotFoundException @throws \Exception @return string
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "string", "$local_file", "@param", "bool", "$content_as_base" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L401-L420
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.getFileProperties
public function getFileProperties($container, $path, $include_content = false, $content_as_base = true) { if (!$this->containerExists($container) || !$this->blobExists($container, $path)) { throw new NotFoundException("File '$path' does not exist in storage."); } $blob = $this->getBlobProperties($container, $path); $shortName = FileUtilities::getNameFromPath($path); $blob['path'] = $path; $blob['name'] = $shortName; if ($include_content) { $data = $this->getBlobData($container, $path); if ($content_as_base) { $data = base64_encode($data); } $blob['content'] = $data; } return $blob; }
php
public function getFileProperties($container, $path, $include_content = false, $content_as_base = true) { if (!$this->containerExists($container) || !$this->blobExists($container, $path)) { throw new NotFoundException("File '$path' does not exist in storage."); } $blob = $this->getBlobProperties($container, $path); $shortName = FileUtilities::getNameFromPath($path); $blob['path'] = $path; $blob['name'] = $shortName; if ($include_content) { $data = $this->getBlobData($container, $path); if ($content_as_base) { $data = base64_encode($data); } $blob['content'] = $data; } return $blob; }
[ "public", "function", "getFileProperties", "(", "$", "container", ",", "$", "path", ",", "$", "include_content", "=", "false", ",", "$", "content_as_base", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "containerExists", "(", "$", "container", ")", "||", "!", "$", "this", "->", "blobExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"File '$path' does not exist in storage.\"", ")", ";", "}", "$", "blob", "=", "$", "this", "->", "getBlobProperties", "(", "$", "container", ",", "$", "path", ")", ";", "$", "shortName", "=", "FileUtilities", "::", "getNameFromPath", "(", "$", "path", ")", ";", "$", "blob", "[", "'path'", "]", "=", "$", "path", ";", "$", "blob", "[", "'name'", "]", "=", "$", "shortName", ";", "if", "(", "$", "include_content", ")", "{", "$", "data", "=", "$", "this", "->", "getBlobData", "(", "$", "container", ",", "$", "path", ")", ";", "if", "(", "$", "content_as_base", ")", "{", "$", "data", "=", "base64_encode", "(", "$", "data", ")", ";", "}", "$", "blob", "[", "'content'", "]", "=", "$", "data", ";", "}", "return", "$", "blob", ";", "}" ]
@param string $container @param string $path @param bool $include_content @param bool $content_as_base @throws NotFoundException @throws \Exception @return array
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "bool", "$include_content", "@param", "bool", "$content_as_base" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L432-L450
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.streamFile
public function streamFile($container, $path, $download = false) { $params = ($download) ? ['disposition' => 'attachment'] : []; $this->streamBlob($container, $path, $params); }
php
public function streamFile($container, $path, $download = false) { $params = ($download) ? ['disposition' => 'attachment'] : []; $this->streamBlob($container, $path, $params); }
[ "public", "function", "streamFile", "(", "$", "container", ",", "$", "path", ",", "$", "download", "=", "false", ")", "{", "$", "params", "=", "(", "$", "download", ")", "?", "[", "'disposition'", "=>", "'attachment'", "]", ":", "[", "]", ";", "$", "this", "->", "streamBlob", "(", "$", "container", ",", "$", "path", ",", "$", "params", ")", ";", "}" ]
@param string $container @param string $path @param bool $download @throws \Exception @return void
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "bool", "$download" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L460-L464
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.updateFileProperties
public function updateFileProperties($container, $path, $properties = []) { $path = FileUtilities::fixFolderPath($path); // does this file exist? if (!$this->fileExists($container, $path)) { throw new NotFoundException("Folder '$path' does not exist."); } // update the file properties $properties = json_encode($properties); $this->putBlobData($container, $path, $properties); }
php
public function updateFileProperties($container, $path, $properties = []) { $path = FileUtilities::fixFolderPath($path); // does this file exist? if (!$this->fileExists($container, $path)) { throw new NotFoundException("Folder '$path' does not exist."); } // update the file properties $properties = json_encode($properties); $this->putBlobData($container, $path, $properties); }
[ "public", "function", "updateFileProperties", "(", "$", "container", ",", "$", "path", ",", "$", "properties", "=", "[", "]", ")", "{", "$", "path", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "path", ")", ";", "// does this file exist?", "if", "(", "!", "$", "this", "->", "fileExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$path' does not exist.\"", ")", ";", "}", "// update the file properties", "$", "properties", "=", "json_encode", "(", "$", "properties", ")", ";", "$", "this", "->", "putBlobData", "(", "$", "container", ",", "$", "path", ",", "$", "properties", ")", ";", "}" ]
@param string $container @param string $path @param array $properties @throws NotFoundException @throws \Exception @return void
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "array", "$properties" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L475-L485
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.writeFile
public function writeFile($container, $path, $content, $content_is_base = false, $check_exist = false) { // does this file already exist? if ($this->fileExists($container, $path)) { if (($check_exist)) { throw new BadRequestException("File '$path' already exists."); } } // does this folder's parent exist? $parent = FileUtilities::getParentFolder($path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the file $this->checkContainerForWrite($container); // need to be able to write to storage if ($content_is_base) { $content = base64_decode($content); } $ext = FileUtilities::getFileExtension($path); $mime = FileUtilities::determineContentType($ext, $content); $this->putBlobData($container, $path, $content, $mime); }
php
public function writeFile($container, $path, $content, $content_is_base = false, $check_exist = false) { // does this file already exist? if ($this->fileExists($container, $path)) { if (($check_exist)) { throw new BadRequestException("File '$path' already exists."); } } // does this folder's parent exist? $parent = FileUtilities::getParentFolder($path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the file $this->checkContainerForWrite($container); // need to be able to write to storage if ($content_is_base) { $content = base64_decode($content); } $ext = FileUtilities::getFileExtension($path); $mime = FileUtilities::determineContentType($ext, $content); $this->putBlobData($container, $path, $content, $mime); }
[ "public", "function", "writeFile", "(", "$", "container", ",", "$", "path", ",", "$", "content", ",", "$", "content_is_base", "=", "false", ",", "$", "check_exist", "=", "false", ")", "{", "// does this file already exist?", "if", "(", "$", "this", "->", "fileExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "if", "(", "(", "$", "check_exist", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"File '$path' already exists.\"", ")", ";", "}", "}", "// does this folder's parent exist?", "$", "parent", "=", "FileUtilities", "::", "getParentFolder", "(", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", "&&", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "parent", ")", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$parent' does not exist.\"", ")", ";", "}", "// create the file", "$", "this", "->", "checkContainerForWrite", "(", "$", "container", ")", ";", "// need to be able to write to storage", "if", "(", "$", "content_is_base", ")", "{", "$", "content", "=", "base64_decode", "(", "$", "content", ")", ";", "}", "$", "ext", "=", "FileUtilities", "::", "getFileExtension", "(", "$", "path", ")", ";", "$", "mime", "=", "FileUtilities", "::", "determineContentType", "(", "$", "ext", ",", "$", "content", ")", ";", "$", "this", "->", "putBlobData", "(", "$", "container", ",", "$", "path", ",", "$", "content", ",", "$", "mime", ")", ";", "}" ]
@param string $container @param string $path @param string $content @param boolean $content_is_base @param bool $check_exist @throws NotFoundException @throws \Exception @return void
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "string", "$content", "@param", "boolean", "$content_is_base", "@param", "bool", "$check_exist" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L498-L520
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.moveFile
public function moveFile($container, $path, $local_path, $check_exist = true) { // does local file exist? if (!file_exists($local_path)) { throw new NotFoundException("File '$local_path' does not exist."); } // does this file already exist? if ($this->fileExists($container, $path)) { if (($check_exist)) { throw new BadRequestException("File '$path' already exists."); } } // does this file's parent folder exist? $parent = FileUtilities::getParentFolder($path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the file $this->checkContainerForWrite($container); // need to be able to write to storage $ext = FileUtilities::getFileExtension($path); $mime = FileUtilities::determineContentType($ext, '', $local_path); $this->putBlobFromFile($container, $path, $local_path, $mime); }
php
public function moveFile($container, $path, $local_path, $check_exist = true) { // does local file exist? if (!file_exists($local_path)) { throw new NotFoundException("File '$local_path' does not exist."); } // does this file already exist? if ($this->fileExists($container, $path)) { if (($check_exist)) { throw new BadRequestException("File '$path' already exists."); } } // does this file's parent folder exist? $parent = FileUtilities::getParentFolder($path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the file $this->checkContainerForWrite($container); // need to be able to write to storage $ext = FileUtilities::getFileExtension($path); $mime = FileUtilities::determineContentType($ext, '', $local_path); $this->putBlobFromFile($container, $path, $local_path, $mime); }
[ "public", "function", "moveFile", "(", "$", "container", ",", "$", "path", ",", "$", "local_path", ",", "$", "check_exist", "=", "true", ")", "{", "// does local file exist?", "if", "(", "!", "file_exists", "(", "$", "local_path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"File '$local_path' does not exist.\"", ")", ";", "}", "// does this file already exist?", "if", "(", "$", "this", "->", "fileExists", "(", "$", "container", ",", "$", "path", ")", ")", "{", "if", "(", "(", "$", "check_exist", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"File '$path' already exists.\"", ")", ";", "}", "}", "// does this file's parent folder exist?", "$", "parent", "=", "FileUtilities", "::", "getParentFolder", "(", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", "&&", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "parent", ")", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$parent' does not exist.\"", ")", ";", "}", "// create the file", "$", "this", "->", "checkContainerForWrite", "(", "$", "container", ")", ";", "// need to be able to write to storage", "$", "ext", "=", "FileUtilities", "::", "getFileExtension", "(", "$", "path", ")", ";", "$", "mime", "=", "FileUtilities", "::", "determineContentType", "(", "$", "ext", ",", "''", ",", "$", "local_path", ")", ";", "$", "this", "->", "putBlobFromFile", "(", "$", "container", ",", "$", "path", ",", "$", "local_path", ",", "$", "mime", ")", ";", "}" ]
@param string $container @param string $path @param string $local_path @param bool $check_exist @throws \Exception @throws NotFoundException @throws BadRequestException @return void
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "string", "$local_path", "@param", "bool", "$check_exist" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L533-L556
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.copyFile
public function copyFile($container, $dest_path, $src_container, $src_path, $check_exist = false) { // does this file already exist? if (!$this->fileExists($src_container, $src_path)) { throw new NotFoundException("File '$src_path' does not exist."); } if ($this->fileExists($container, $dest_path)) { if (($check_exist)) { throw new BadRequestException("File '$dest_path' already exists."); } } // does this file's parent folder exist? $parent = FileUtilities::getParentFolder($dest_path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the file $this->checkContainerForWrite($container); // need to be able to write to storage $this->copyBlob($container, $dest_path, $src_container, $src_path); }
php
public function copyFile($container, $dest_path, $src_container, $src_path, $check_exist = false) { // does this file already exist? if (!$this->fileExists($src_container, $src_path)) { throw new NotFoundException("File '$src_path' does not exist."); } if ($this->fileExists($container, $dest_path)) { if (($check_exist)) { throw new BadRequestException("File '$dest_path' already exists."); } } // does this file's parent folder exist? $parent = FileUtilities::getParentFolder($dest_path); if (!empty($parent) && (!$this->folderExists($container, $parent))) { throw new NotFoundException("Folder '$parent' does not exist."); } // create the file $this->checkContainerForWrite($container); // need to be able to write to storage $this->copyBlob($container, $dest_path, $src_container, $src_path); }
[ "public", "function", "copyFile", "(", "$", "container", ",", "$", "dest_path", ",", "$", "src_container", ",", "$", "src_path", ",", "$", "check_exist", "=", "false", ")", "{", "// does this file already exist?", "if", "(", "!", "$", "this", "->", "fileExists", "(", "$", "src_container", ",", "$", "src_path", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"File '$src_path' does not exist.\"", ")", ";", "}", "if", "(", "$", "this", "->", "fileExists", "(", "$", "container", ",", "$", "dest_path", ")", ")", "{", "if", "(", "(", "$", "check_exist", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"File '$dest_path' already exists.\"", ")", ";", "}", "}", "// does this file's parent folder exist?", "$", "parent", "=", "FileUtilities", "::", "getParentFolder", "(", "$", "dest_path", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", "&&", "(", "!", "$", "this", "->", "folderExists", "(", "$", "container", ",", "$", "parent", ")", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"Folder '$parent' does not exist.\"", ")", ";", "}", "// create the file", "$", "this", "->", "checkContainerForWrite", "(", "$", "container", ")", ";", "// need to be able to write to storage", "$", "this", "->", "copyBlob", "(", "$", "container", ",", "$", "dest_path", ",", "$", "src_container", ",", "$", "src_path", ")", ";", "}" ]
@param string $container @param string $dest_path @param string $src_container @param string $src_path @param bool $check_exist @throws \Exception @throws NotFoundException @throws BadRequestException @return void
[ "@param", "string", "$container", "@param", "string", "$dest_path", "@param", "string", "$src_container", "@param", "string", "$src_path", "@param", "bool", "$check_exist" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L570-L590
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.deleteFile
public function deleteFile($container, $path, $noCheck = false) { $this->deleteBlob($container, $path, $noCheck); }
php
public function deleteFile($container, $path, $noCheck = false) { $this->deleteBlob($container, $path, $noCheck); }
[ "public", "function", "deleteFile", "(", "$", "container", ",", "$", "path", ",", "$", "noCheck", "=", "false", ")", "{", "$", "this", "->", "deleteBlob", "(", "$", "container", ",", "$", "path", ",", "$", "noCheck", ")", ";", "}" ]
@param string $container @param stiring $path @param bool $noCheck @return void @throws \Exception
[ "@param", "string", "$container", "@param", "stiring", "$path", "@param", "bool", "$noCheck" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L600-L603
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.deleteFiles
public function deleteFiles($container, $files, $root = '') { $root = FileUtilities::fixFolderPath($root); foreach ($files as $key => $file) { try { // path is full path, name is relative to root, take either $path = array_get($file, 'path'); $name = array_get($file, 'name'); if (!empty($path)) { $path = static::removeContainerFromPath($container, $path); } elseif (!empty($name)) { $path = $root . $name; } else { throw new BadRequestException('No path or name found for file in delete request.'); } if (!empty($path)) { $this->deleteFile($container, $path); } else { throw new BadRequestException('No path or name found for file in delete request.'); } } catch (\Exception $ex) { // error whole batch here? $files[$key]['error'] = ['message' => $ex->getMessage(), 'code' => $ex->getCode()]; } } return $files; }
php
public function deleteFiles($container, $files, $root = '') { $root = FileUtilities::fixFolderPath($root); foreach ($files as $key => $file) { try { // path is full path, name is relative to root, take either $path = array_get($file, 'path'); $name = array_get($file, 'name'); if (!empty($path)) { $path = static::removeContainerFromPath($container, $path); } elseif (!empty($name)) { $path = $root . $name; } else { throw new BadRequestException('No path or name found for file in delete request.'); } if (!empty($path)) { $this->deleteFile($container, $path); } else { throw new BadRequestException('No path or name found for file in delete request.'); } } catch (\Exception $ex) { // error whole batch here? $files[$key]['error'] = ['message' => $ex->getMessage(), 'code' => $ex->getCode()]; } } return $files; }
[ "public", "function", "deleteFiles", "(", "$", "container", ",", "$", "files", ",", "$", "root", "=", "''", ")", "{", "$", "root", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "root", ")", ";", "foreach", "(", "$", "files", "as", "$", "key", "=>", "$", "file", ")", "{", "try", "{", "// path is full path, name is relative to root, take either", "$", "path", "=", "array_get", "(", "$", "file", ",", "'path'", ")", ";", "$", "name", "=", "array_get", "(", "$", "file", ",", "'name'", ")", ";", "if", "(", "!", "empty", "(", "$", "path", ")", ")", "{", "$", "path", "=", "static", "::", "removeContainerFromPath", "(", "$", "container", ",", "$", "path", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "name", ")", ")", "{", "$", "path", "=", "$", "root", ".", "$", "name", ";", "}", "else", "{", "throw", "new", "BadRequestException", "(", "'No path or name found for file in delete request.'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "path", ")", ")", "{", "$", "this", "->", "deleteFile", "(", "$", "container", ",", "$", "path", ")", ";", "}", "else", "{", "throw", "new", "BadRequestException", "(", "'No path or name found for file in delete request.'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "// error whole batch here?", "$", "files", "[", "$", "key", "]", "[", "'error'", "]", "=", "[", "'message'", "=>", "$", "ex", "->", "getMessage", "(", ")", ",", "'code'", "=>", "$", "ex", "->", "getCode", "(", ")", "]", ";", "}", "}", "return", "$", "files", ";", "}" ]
@param string $container @param array $files @param string $root @throws BadRequestException @return array
[ "@param", "string", "$container", "@param", "array", "$files", "@param", "string", "$root" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L613-L640
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.getFolderAsZip
public function getFolderAsZip($container, $path, $zip = null, $zipFileName = '', $overwrite = false) { $path = FileUtilities::fixFolderPath($path); $delimiter = ''; if (!$this->containerExists($container)) { throw new BadRequestException("Can not find directory '$container'."); } $needClose = false; if (!isset($zip)) { $needClose = true; $zip = new \ZipArchive(); if (empty($zipFileName)) { $temp = basename($path); if (empty($temp)) { $temp = $container; } $tempDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $zipFileName = $tempDir . $temp . '.zip'; } if (true !== $zip->open($zipFileName, ($overwrite ? \ZipArchive::OVERWRITE : \ZipArchive::CREATE))) { throw new InternalServerErrorException("Can not create zip file for directory '$path'."); } } $results = $this->listBlobs($container, $path, $delimiter); if (empty($results)) { $zip->addEmptyDir($path); } else { foreach ($results as $blob) { $fullPathName = array_get($blob, 'name'); $shortName = substr_replace($fullPathName, '', 0, strlen($path)); if (empty($shortName)) { continue; } if ('/' == substr($fullPathName, strlen($fullPathName) - 1)) { // folders if (!$zip->addEmptyDir($shortName)) { throw new InternalServerErrorException("Can not include folder '$shortName' in zip file."); } } else { // files $content = $this->getBlobData($container, $fullPathName); if (!$zip->addFromString($shortName, $content)) { throw new InternalServerErrorException("Can not include file '$shortName' in zip file."); } } } } if ($needClose) { $zip->close(); } return $zipFileName; }
php
public function getFolderAsZip($container, $path, $zip = null, $zipFileName = '', $overwrite = false) { $path = FileUtilities::fixFolderPath($path); $delimiter = ''; if (!$this->containerExists($container)) { throw new BadRequestException("Can not find directory '$container'."); } $needClose = false; if (!isset($zip)) { $needClose = true; $zip = new \ZipArchive(); if (empty($zipFileName)) { $temp = basename($path); if (empty($temp)) { $temp = $container; } $tempDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $zipFileName = $tempDir . $temp . '.zip'; } if (true !== $zip->open($zipFileName, ($overwrite ? \ZipArchive::OVERWRITE : \ZipArchive::CREATE))) { throw new InternalServerErrorException("Can not create zip file for directory '$path'."); } } $results = $this->listBlobs($container, $path, $delimiter); if (empty($results)) { $zip->addEmptyDir($path); } else { foreach ($results as $blob) { $fullPathName = array_get($blob, 'name'); $shortName = substr_replace($fullPathName, '', 0, strlen($path)); if (empty($shortName)) { continue; } if ('/' == substr($fullPathName, strlen($fullPathName) - 1)) { // folders if (!$zip->addEmptyDir($shortName)) { throw new InternalServerErrorException("Can not include folder '$shortName' in zip file."); } } else { // files $content = $this->getBlobData($container, $fullPathName); if (!$zip->addFromString($shortName, $content)) { throw new InternalServerErrorException("Can not include file '$shortName' in zip file."); } } } } if ($needClose) { $zip->close(); } return $zipFileName; }
[ "public", "function", "getFolderAsZip", "(", "$", "container", ",", "$", "path", ",", "$", "zip", "=", "null", ",", "$", "zipFileName", "=", "''", ",", "$", "overwrite", "=", "false", ")", "{", "$", "path", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "path", ")", ";", "$", "delimiter", "=", "''", ";", "if", "(", "!", "$", "this", "->", "containerExists", "(", "$", "container", ")", ")", "{", "throw", "new", "BadRequestException", "(", "\"Can not find directory '$container'.\"", ")", ";", "}", "$", "needClose", "=", "false", ";", "if", "(", "!", "isset", "(", "$", "zip", ")", ")", "{", "$", "needClose", "=", "true", ";", "$", "zip", "=", "new", "\\", "ZipArchive", "(", ")", ";", "if", "(", "empty", "(", "$", "zipFileName", ")", ")", "{", "$", "temp", "=", "basename", "(", "$", "path", ")", ";", "if", "(", "empty", "(", "$", "temp", ")", ")", "{", "$", "temp", "=", "$", "container", ";", "}", "$", "tempDir", "=", "rtrim", "(", "sys_get_temp_dir", "(", ")", ",", "DIRECTORY_SEPARATOR", ")", ".", "DIRECTORY_SEPARATOR", ";", "$", "zipFileName", "=", "$", "tempDir", ".", "$", "temp", ".", "'.zip'", ";", "}", "if", "(", "true", "!==", "$", "zip", "->", "open", "(", "$", "zipFileName", ",", "(", "$", "overwrite", "?", "\\", "ZipArchive", "::", "OVERWRITE", ":", "\\", "ZipArchive", "::", "CREATE", ")", ")", ")", "{", "throw", "new", "InternalServerErrorException", "(", "\"Can not create zip file for directory '$path'.\"", ")", ";", "}", "}", "$", "results", "=", "$", "this", "->", "listBlobs", "(", "$", "container", ",", "$", "path", ",", "$", "delimiter", ")", ";", "if", "(", "empty", "(", "$", "results", ")", ")", "{", "$", "zip", "->", "addEmptyDir", "(", "$", "path", ")", ";", "}", "else", "{", "foreach", "(", "$", "results", "as", "$", "blob", ")", "{", "$", "fullPathName", "=", "array_get", "(", "$", "blob", ",", "'name'", ")", ";", "$", "shortName", "=", "substr_replace", "(", "$", "fullPathName", ",", "''", ",", "0", ",", "strlen", "(", "$", "path", ")", ")", ";", "if", "(", "empty", "(", "$", "shortName", ")", ")", "{", "continue", ";", "}", "if", "(", "'/'", "==", "substr", "(", "$", "fullPathName", ",", "strlen", "(", "$", "fullPathName", ")", "-", "1", ")", ")", "{", "// folders", "if", "(", "!", "$", "zip", "->", "addEmptyDir", "(", "$", "shortName", ")", ")", "{", "throw", "new", "InternalServerErrorException", "(", "\"Can not include folder '$shortName' in zip file.\"", ")", ";", "}", "}", "else", "{", "// files", "$", "content", "=", "$", "this", "->", "getBlobData", "(", "$", "container", ",", "$", "fullPathName", ")", ";", "if", "(", "!", "$", "zip", "->", "addFromString", "(", "$", "shortName", ",", "$", "content", ")", ")", "{", "throw", "new", "InternalServerErrorException", "(", "\"Can not include file '$shortName' in zip file.\"", ")", ";", "}", "}", "}", "}", "if", "(", "$", "needClose", ")", "{", "$", "zip", "->", "close", "(", ")", ";", "}", "return", "$", "zipFileName", ";", "}" ]
@param string $container @param string $path @param null|\ZipArchive $zip @param string $zipFileName @param bool $overwrite @throws \Exception @throws BadRequestException @throws InternalServerErrorException @return string Zip File Name created/updated
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "null|", "\\", "ZipArchive", "$zip", "@param", "string", "$zipFileName", "@param", "bool", "$overwrite" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L654-L707
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.extractZipFile
public function extractZipFile($container, $path, $zip, $clean = false, $drop_path = '') { if ($clean) { try { // clear out anything in this directory $blobs = $this->listBlobs($container, $path); if (!empty($blobs)) { foreach ($blobs as $blob) { if ((0 !== strcasecmp($path, $blob['name']))) { // not folder itself $this->deleteBlob($container, $blob['name']); } } } } catch (\Exception $ex) { throw new InternalServerErrorException("Could not clean out existing directory $path.\n{$ex->getMessage()}"); } } for ($i = 0; $i < $zip->numFiles; $i++) { try { $name = $zip->getNameIndex($i); if (empty($name)) { continue; } if (!empty($drop_path)) { $name = str_ireplace($drop_path, '', $name); } $fullPathName = $path . $name; if ('/' === substr($fullPathName, -1)) { $this->createFolder($container, $fullPathName, true, [], false); } else { $parent = FileUtilities::getParentFolder($fullPathName); if (!empty($parent)) { $this->createFolder($container, $parent, true, [], false); } $content = $zip->getFromIndex($i); $this->writeFile($container, $fullPathName, $content); } } catch (\Exception $ex) { throw $ex; } } return ['name' => rtrim($path, DIRECTORY_SEPARATOR), 'path' => $path]; }
php
public function extractZipFile($container, $path, $zip, $clean = false, $drop_path = '') { if ($clean) { try { // clear out anything in this directory $blobs = $this->listBlobs($container, $path); if (!empty($blobs)) { foreach ($blobs as $blob) { if ((0 !== strcasecmp($path, $blob['name']))) { // not folder itself $this->deleteBlob($container, $blob['name']); } } } } catch (\Exception $ex) { throw new InternalServerErrorException("Could not clean out existing directory $path.\n{$ex->getMessage()}"); } } for ($i = 0; $i < $zip->numFiles; $i++) { try { $name = $zip->getNameIndex($i); if (empty($name)) { continue; } if (!empty($drop_path)) { $name = str_ireplace($drop_path, '', $name); } $fullPathName = $path . $name; if ('/' === substr($fullPathName, -1)) { $this->createFolder($container, $fullPathName, true, [], false); } else { $parent = FileUtilities::getParentFolder($fullPathName); if (!empty($parent)) { $this->createFolder($container, $parent, true, [], false); } $content = $zip->getFromIndex($i); $this->writeFile($container, $fullPathName, $content); } } catch (\Exception $ex) { throw $ex; } } return ['name' => rtrim($path, DIRECTORY_SEPARATOR), 'path' => $path]; }
[ "public", "function", "extractZipFile", "(", "$", "container", ",", "$", "path", ",", "$", "zip", ",", "$", "clean", "=", "false", ",", "$", "drop_path", "=", "''", ")", "{", "if", "(", "$", "clean", ")", "{", "try", "{", "// clear out anything in this directory", "$", "blobs", "=", "$", "this", "->", "listBlobs", "(", "$", "container", ",", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "blobs", ")", ")", "{", "foreach", "(", "$", "blobs", "as", "$", "blob", ")", "{", "if", "(", "(", "0", "!==", "strcasecmp", "(", "$", "path", ",", "$", "blob", "[", "'name'", "]", ")", ")", ")", "{", "// not folder itself", "$", "this", "->", "deleteBlob", "(", "$", "container", ",", "$", "blob", "[", "'name'", "]", ")", ";", "}", "}", "}", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "throw", "new", "InternalServerErrorException", "(", "\"Could not clean out existing directory $path.\\n{$ex->getMessage()}\"", ")", ";", "}", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "zip", "->", "numFiles", ";", "$", "i", "++", ")", "{", "try", "{", "$", "name", "=", "$", "zip", "->", "getNameIndex", "(", "$", "i", ")", ";", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "empty", "(", "$", "drop_path", ")", ")", "{", "$", "name", "=", "str_ireplace", "(", "$", "drop_path", ",", "''", ",", "$", "name", ")", ";", "}", "$", "fullPathName", "=", "$", "path", ".", "$", "name", ";", "if", "(", "'/'", "===", "substr", "(", "$", "fullPathName", ",", "-", "1", ")", ")", "{", "$", "this", "->", "createFolder", "(", "$", "container", ",", "$", "fullPathName", ",", "true", ",", "[", "]", ",", "false", ")", ";", "}", "else", "{", "$", "parent", "=", "FileUtilities", "::", "getParentFolder", "(", "$", "fullPathName", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", ")", "{", "$", "this", "->", "createFolder", "(", "$", "container", ",", "$", "parent", ",", "true", ",", "[", "]", ",", "false", ")", ";", "}", "$", "content", "=", "$", "zip", "->", "getFromIndex", "(", "$", "i", ")", ";", "$", "this", "->", "writeFile", "(", "$", "container", ",", "$", "fullPathName", ",", "$", "content", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "throw", "$", "ex", ";", "}", "}", "return", "[", "'name'", "=>", "rtrim", "(", "$", "path", ",", "DIRECTORY_SEPARATOR", ")", ",", "'path'", "=>", "$", "path", "]", ";", "}" ]
@param string $container @param string $path @param \ZipArchive $zip @param bool $clean @param string $drop_path @return array @throws \Exception
[ "@param", "string", "$container", "@param", "string", "$path", "@param", "\\", "ZipArchive", "$zip", "@param", "bool", "$clean", "@param", "string", "$drop_path" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L719-L762
dreamfactorysoftware/df-file
src/Components/RemoteFileSystem.php
RemoteFileSystem.removeContainerFromPath
private static function removeContainerFromPath($container, $path) { if (empty($container)) { return $path; } $container = FileUtilities::fixFolderPath($container); return substr($path, strlen($container)); }
php
private static function removeContainerFromPath($container, $path) { if (empty($container)) { return $path; } $container = FileUtilities::fixFolderPath($container); return substr($path, strlen($container)); }
[ "private", "static", "function", "removeContainerFromPath", "(", "$", "container", ",", "$", "path", ")", "{", "if", "(", "empty", "(", "$", "container", ")", ")", "{", "return", "$", "path", ";", "}", "$", "container", "=", "FileUtilities", "::", "fixFolderPath", "(", "$", "container", ")", ";", "return", "substr", "(", "$", "path", ",", "strlen", "(", "$", "container", ")", ")", ";", "}" ]
@param $container @param $path @return string
[ "@param", "$container", "@param", "$path" ]
train
https://github.com/dreamfactorysoftware/df-file/blob/e78aaec3e1d6585b5e7fe9b7646af4b1180ecd66/src/Components/RemoteFileSystem.php#L792-L800
phpmob/changmin
src/PhpMob/CoreBundle/EventListener/UserMailerListener.php
UserMailerListener.sendUserRegistrationEmail
public function sendUserRegistrationEmail(GenericEvent $event) { if ($this->systemSettingContext->get('security.user_verification')) { return; } $user = $event->getSubject(); Assert::isInstanceOf($user, WebUserInterface::class); $this->emailSender->send(Emails::USER_REGISTRATION, [$user->getEmail()], ['user' => $user]); }
php
public function sendUserRegistrationEmail(GenericEvent $event) { if ($this->systemSettingContext->get('security.user_verification')) { return; } $user = $event->getSubject(); Assert::isInstanceOf($user, WebUserInterface::class); $this->emailSender->send(Emails::USER_REGISTRATION, [$user->getEmail()], ['user' => $user]); }
[ "public", "function", "sendUserRegistrationEmail", "(", "GenericEvent", "$", "event", ")", "{", "if", "(", "$", "this", "->", "systemSettingContext", "->", "get", "(", "'security.user_verification'", ")", ")", "{", "return", ";", "}", "$", "user", "=", "$", "event", "->", "getSubject", "(", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "user", ",", "WebUserInterface", "::", "class", ")", ";", "$", "this", "->", "emailSender", "->", "send", "(", "Emails", "::", "USER_REGISTRATION", ",", "[", "$", "user", "->", "getEmail", "(", ")", "]", ",", "[", "'user'", "=>", "$", "user", "]", ")", ";", "}" ]
@param GenericEvent $event @throws UnexpectedTypeException
[ "@param", "GenericEvent", "$event" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/CoreBundle/EventListener/UserMailerListener.php#L51-L62
geekwright/Po
src/PoInitAbstract.php
PoInitAbstract.msginitFile
public function msginitFile(string $filename): PoFile { if (!is_readable($filename)) { $source = false; } else { $source = file_get_contents($filename); } if (false===$source) { throw new FileNotReadableException($filename); } return $this->msginitString($source, $filename); }
php
public function msginitFile(string $filename): PoFile { if (!is_readable($filename)) { $source = false; } else { $source = file_get_contents($filename); } if (false===$source) { throw new FileNotReadableException($filename); } return $this->msginitString($source, $filename); }
[ "public", "function", "msginitFile", "(", "string", "$", "filename", ")", ":", "PoFile", "{", "if", "(", "!", "is_readable", "(", "$", "filename", ")", ")", "{", "$", "source", "=", "false", ";", "}", "else", "{", "$", "source", "=", "file_get_contents", "(", "$", "filename", ")", ";", "}", "if", "(", "false", "===", "$", "source", ")", "{", "throw", "new", "FileNotReadableException", "(", "$", "filename", ")", ";", "}", "return", "$", "this", "->", "msginitString", "(", "$", "source", ",", "$", "filename", ")", ";", "}" ]
Inspect the supplied source file, capture gettext references as a PoFile object @param string $filename name of source file @return PoFile @throws FileNotReadableException
[ "Inspect", "the", "supplied", "source", "file", "capture", "gettext", "references", "as", "a", "PoFile", "object" ]
train
https://github.com/geekwright/Po/blob/9474d059a83b64e6242cc41e5c5b7a08bc57e4e2/src/PoInitAbstract.php#L173-L184
geekwright/Po
src/PoInitAbstract.php
PoInitAbstract.escapeForPo
public function escapeForPo(string $string): string { if ($string[0]=='"' || $string[0]=="'") { $string = substr($string, 1, -1); } $string = str_replace("\r\n", "\n", $string); $string = stripcslashes($string); return addcslashes($string, "\0..\37\""); }
php
public function escapeForPo(string $string): string { if ($string[0]=='"' || $string[0]=="'") { $string = substr($string, 1, -1); } $string = str_replace("\r\n", "\n", $string); $string = stripcslashes($string); return addcslashes($string, "\0..\37\""); }
[ "public", "function", "escapeForPo", "(", "string", "$", "string", ")", ":", "string", "{", "if", "(", "$", "string", "[", "0", "]", "==", "'\"'", "||", "$", "string", "[", "0", "]", "==", "\"'\"", ")", "{", "$", "string", "=", "substr", "(", "$", "string", ",", "1", ",", "-", "1", ")", ";", "}", "$", "string", "=", "str_replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "$", "string", ")", ";", "$", "string", "=", "stripcslashes", "(", "$", "string", ")", ";", "return", "addcslashes", "(", "$", "string", ",", "\"\\0..\\37\\\"\"", ")", ";", "}" ]
Prepare a string from tokenized output for use in a po file. Remove any surrounding quotes, escape control characters and double quotes. @param string $string raw string (T_STRING) identified by php token_get_all @return string
[ "Prepare", "a", "string", "from", "tokenized", "output", "for", "use", "in", "a", "po", "file", ".", "Remove", "any", "surrounding", "quotes", "escape", "control", "characters", "and", "double", "quotes", "." ]
train
https://github.com/geekwright/Po/blob/9474d059a83b64e6242cc41e5c5b7a08bc57e4e2/src/PoInitAbstract.php#L204-L212
geekwright/Po
src/PoInitAbstract.php
PoInitAbstract.checkPhpFormatFlag
public function checkPhpFormatFlag(PoEntry $entry): void { if (preg_match( '#(?<!%)%(?:\d+\$)?[+-]?(?:[ 0]|\'.{1})?-?\d*(?:\.\d+)?[bcdeEufFgGosxX]#', $entry->get(PoTokens::MESSAGE) . $entry->get(PoTokens::PLURAL) )) { $entry->addFlag('php-format'); } }
php
public function checkPhpFormatFlag(PoEntry $entry): void { if (preg_match( '#(?<!%)%(?:\d+\$)?[+-]?(?:[ 0]|\'.{1})?-?\d*(?:\.\d+)?[bcdeEufFgGosxX]#', $entry->get(PoTokens::MESSAGE) . $entry->get(PoTokens::PLURAL) )) { $entry->addFlag('php-format'); } }
[ "public", "function", "checkPhpFormatFlag", "(", "PoEntry", "$", "entry", ")", ":", "void", "{", "if", "(", "preg_match", "(", "'#(?<!%)%(?:\\d+\\$)?[+-]?(?:[ 0]|\\'.{1})?-?\\d*(?:\\.\\d+)?[bcdeEufFgGosxX]#'", ",", "$", "entry", "->", "get", "(", "PoTokens", "::", "MESSAGE", ")", ".", "$", "entry", "->", "get", "(", "PoTokens", "::", "PLURAL", ")", ")", ")", "{", "$", "entry", "->", "addFlag", "(", "'php-format'", ")", ";", "}", "}" ]
Check the supplied entry for sprintf directives and set php-format flag if found @param PoEntry $entry entry to check @return void
[ "Check", "the", "supplied", "entry", "for", "sprintf", "directives", "and", "set", "php", "-", "format", "flag", "if", "found" ]
train
https://github.com/geekwright/Po/blob/9474d059a83b64e6242cc41e5c5b7a08bc57e4e2/src/PoInitAbstract.php#L221-L229
spiral-modules/scaffolder
source/Scaffolder/Commands/CommandCommand.php
CommandCommand.perform
public function perform() { /** @var CommandDeclaration $declaration */ $declaration = $this->createDeclaration(compact('alias')); $declaration->setAlias($this->argument('alias') ?? $this->argument('name')); $declaration->setDescription((string)$this->option('description')); $this->writeDeclaration($declaration); }
php
public function perform() { /** @var CommandDeclaration $declaration */ $declaration = $this->createDeclaration(compact('alias')); $declaration->setAlias($this->argument('alias') ?? $this->argument('name')); $declaration->setDescription((string)$this->option('description')); $this->writeDeclaration($declaration); }
[ "public", "function", "perform", "(", ")", "{", "/** @var CommandDeclaration $declaration */", "$", "declaration", "=", "$", "this", "->", "createDeclaration", "(", "compact", "(", "'alias'", ")", ")", ";", "$", "declaration", "->", "setAlias", "(", "$", "this", "->", "argument", "(", "'alias'", ")", "??", "$", "this", "->", "argument", "(", "'name'", ")", ")", ";", "$", "declaration", "->", "setDescription", "(", "(", "string", ")", "$", "this", "->", "option", "(", "'description'", ")", ")", ";", "$", "this", "->", "writeDeclaration", "(", "$", "declaration", ")", ";", "}" ]
Create command declaration.
[ "Create", "command", "declaration", "." ]
train
https://github.com/spiral-modules/scaffolder/blob/9be9dd0da6e4b02232db24e797fe5c288afbbddf/source/Scaffolder/Commands/CommandCommand.php#L36-L45
slashworks/control-bundle
src/Slashworks/BackendBundle/Controller/BackendController.php
BackendController.getDatatablesLanguagefileAction
public function getDatatablesLanguagefileAction($sLang) { $sPath = $this->get('kernel')->locateResource('@SlashworksBackendBundle/Resources/public/js/plugins/dataTables/languages/' . $sLang . '.json'); $response = new Response(file_get_contents($sPath)); $response->headers->set('Content-Type', 'application/json'); return $response; }
php
public function getDatatablesLanguagefileAction($sLang) { $sPath = $this->get('kernel')->locateResource('@SlashworksBackendBundle/Resources/public/js/plugins/dataTables/languages/' . $sLang . '.json'); $response = new Response(file_get_contents($sPath)); $response->headers->set('Content-Type', 'application/json'); return $response; }
[ "public", "function", "getDatatablesLanguagefileAction", "(", "$", "sLang", ")", "{", "$", "sPath", "=", "$", "this", "->", "get", "(", "'kernel'", ")", "->", "locateResource", "(", "'@SlashworksBackendBundle/Resources/public/js/plugins/dataTables/languages/'", ".", "$", "sLang", ".", "'.json'", ")", ";", "$", "response", "=", "new", "Response", "(", "file_get_contents", "(", "$", "sPath", ")", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "return", "$", "response", ";", "}" ]
@param $sLang @return \Symfony\Component\HttpFoundation\Response
[ "@param", "$sLang" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Controller/BackendController.php#L40-L49
Chill-project/Main
Entity/User.php
User.isGroupCenterPresentOnce
public function isGroupCenterPresentOnce(ExecutionContextInterface $context) { $groupCentersIds = array(); foreach ($this->getGroupCenters() as $groupCenter) { if (in_array($groupCenter->getId(), $groupCentersIds)) { $context->buildViolation("The user has already those permissions") ->addViolation(); } else { $groupCentersIds[] = $groupCenter->getId(); } } }
php
public function isGroupCenterPresentOnce(ExecutionContextInterface $context) { $groupCentersIds = array(); foreach ($this->getGroupCenters() as $groupCenter) { if (in_array($groupCenter->getId(), $groupCentersIds)) { $context->buildViolation("The user has already those permissions") ->addViolation(); } else { $groupCentersIds[] = $groupCenter->getId(); } } }
[ "public", "function", "isGroupCenterPresentOnce", "(", "ExecutionContextInterface", "$", "context", ")", "{", "$", "groupCentersIds", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getGroupCenters", "(", ")", "as", "$", "groupCenter", ")", "{", "if", "(", "in_array", "(", "$", "groupCenter", "->", "getId", "(", ")", ",", "$", "groupCentersIds", ")", ")", "{", "$", "context", "->", "buildViolation", "(", "\"The user has already those permissions\"", ")", "->", "addViolation", "(", ")", ";", "}", "else", "{", "$", "groupCentersIds", "[", "]", "=", "$", "groupCenter", "->", "getId", "(", ")", ";", "}", "}", "}" ]
This function check that groupCenter are present only once. The validator use this function to avoid a user to be associated to the same groupCenter more than once.
[ "This", "function", "check", "that", "groupCenter", "are", "present", "only", "once", ".", "The", "validator", "use", "this", "function", "to", "avoid", "a", "user", "to", "be", "associated", "to", "the", "same", "groupCenter", "more", "than", "once", "." ]
train
https://github.com/Chill-project/Main/blob/384cb6c793072a4f1047dc5cafc2157ee2419f60/Entity/User.php#L216-L228
yuncms/framework
src/admin/models/UserBizRuleSearch.php
UserBizRuleSearch.search
public function search($params) { $models = []; $included = !($this->load($params) && $this->validate() && trim($this->name) !== ''); foreach (UserRBACHelper::getAuthManager()->getRules() as $name => $item) { if ($name != RouteRule::RULE_NAME && ($included || stripos($item->name, $this->name) !== false)) { $models[$name] = new AdminBizRule($item); } } return new ArrayDataProvider([ 'allModels' => $models, ]); }
php
public function search($params) { $models = []; $included = !($this->load($params) && $this->validate() && trim($this->name) !== ''); foreach (UserRBACHelper::getAuthManager()->getRules() as $name => $item) { if ($name != RouteRule::RULE_NAME && ($included || stripos($item->name, $this->name) !== false)) { $models[$name] = new AdminBizRule($item); } } return new ArrayDataProvider([ 'allModels' => $models, ]); }
[ "public", "function", "search", "(", "$", "params", ")", "{", "$", "models", "=", "[", "]", ";", "$", "included", "=", "!", "(", "$", "this", "->", "load", "(", "$", "params", ")", "&&", "$", "this", "->", "validate", "(", ")", "&&", "trim", "(", "$", "this", "->", "name", ")", "!==", "''", ")", ";", "foreach", "(", "UserRBACHelper", "::", "getAuthManager", "(", ")", "->", "getRules", "(", ")", "as", "$", "name", "=>", "$", "item", ")", "{", "if", "(", "$", "name", "!=", "RouteRule", "::", "RULE_NAME", "&&", "(", "$", "included", "||", "stripos", "(", "$", "item", "->", "name", ",", "$", "this", "->", "name", ")", "!==", "false", ")", ")", "{", "$", "models", "[", "$", "name", "]", "=", "new", "AdminBizRule", "(", "$", "item", ")", ";", "}", "}", "return", "new", "ArrayDataProvider", "(", "[", "'allModels'", "=>", "$", "models", ",", "]", ")", ";", "}" ]
Search BizRule @param array $params @return \yii\data\ActiveDataProvider|\yii\data\ArrayDataProvider @throws \yii\base\InvalidConfigException
[ "Search", "BizRule" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/admin/models/UserBizRuleSearch.php#L49-L62
alanpich/slender
src/Core/Util/Util.php
Util.stringStartsWith
public static function stringStartsWith($str, $prefix) { if(is_array($prefix)){ foreach($prefix as $p){ if($p === "" || strpos($str, $p) === 0){ return true; }; } return false; } return $prefix === "" || strpos($str, $prefix) === 0; }
php
public static function stringStartsWith($str, $prefix) { if(is_array($prefix)){ foreach($prefix as $p){ if($p === "" || strpos($str, $p) === 0){ return true; }; } return false; } return $prefix === "" || strpos($str, $prefix) === 0; }
[ "public", "static", "function", "stringStartsWith", "(", "$", "str", ",", "$", "prefix", ")", "{", "if", "(", "is_array", "(", "$", "prefix", ")", ")", "{", "foreach", "(", "$", "prefix", "as", "$", "p", ")", "{", "if", "(", "$", "p", "===", "\"\"", "||", "strpos", "(", "$", "str", ",", "$", "p", ")", "===", "0", ")", "{", "return", "true", ";", "}", ";", "}", "return", "false", ";", "}", "return", "$", "prefix", "===", "\"\"", "||", "strpos", "(", "$", "str", ",", "$", "prefix", ")", "===", "0", ";", "}" ]
Does a string start with another string? @param string $str The string to check @param string|array $prefix The prefix to check for @return bool
[ "Does", "a", "string", "start", "with", "another", "string?" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/Util/Util.php#L77-L88
alanpich/slender
src/Core/Util/Util.php
Util.stringEndsWith
public static function stringEndsWith($str, $postfix) { if(is_array($postfix)){ foreach($postfix as $p){ if($p === "" || substr($str, -strlen($p)) === $p){ return true; } } return false; } return $postfix === "" || substr($str, -strlen($postfix)) === $postfix; }
php
public static function stringEndsWith($str, $postfix) { if(is_array($postfix)){ foreach($postfix as $p){ if($p === "" || substr($str, -strlen($p)) === $p){ return true; } } return false; } return $postfix === "" || substr($str, -strlen($postfix)) === $postfix; }
[ "public", "static", "function", "stringEndsWith", "(", "$", "str", ",", "$", "postfix", ")", "{", "if", "(", "is_array", "(", "$", "postfix", ")", ")", "{", "foreach", "(", "$", "postfix", "as", "$", "p", ")", "{", "if", "(", "$", "p", "===", "\"\"", "||", "substr", "(", "$", "str", ",", "-", "strlen", "(", "$", "p", ")", ")", "===", "$", "p", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "return", "$", "postfix", "===", "\"\"", "||", "substr", "(", "$", "str", ",", "-", "strlen", "(", "$", "postfix", ")", ")", "===", "$", "postfix", ";", "}" ]
Does a string end with another string? @param string $str The string to check @param string|array $postfix The postfix to check for @return bool
[ "Does", "a", "string", "end", "with", "another", "string?" ]
train
https://github.com/alanpich/slender/blob/247f5c08af20cda95b116eb5d9f6f623d61e8a8a/src/Core/Util/Util.php#L98-L109
microinginer/yii2-human-formatter
src/HumanFormatter.php
HumanFormatter.asDatetime
public function asDatetime ($value, $format = null) { switch ($this->locale) { case 'ru': { return $this->datetimeAsHumanRu($value, $format); } case 'en': { return $this->datetimeAsHumanEn($value, $format); } default: { return parent::asDatetime($value, $format); } } }
php
public function asDatetime ($value, $format = null) { switch ($this->locale) { case 'ru': { return $this->datetimeAsHumanRu($value, $format); } case 'en': { return $this->datetimeAsHumanEn($value, $format); } default: { return parent::asDatetime($value, $format); } } }
[ "public", "function", "asDatetime", "(", "$", "value", ",", "$", "format", "=", "null", ")", "{", "switch", "(", "$", "this", "->", "locale", ")", "{", "case", "'ru'", ":", "{", "return", "$", "this", "->", "datetimeAsHumanRu", "(", "$", "value", ",", "$", "format", ")", ";", "}", "case", "'en'", ":", "{", "return", "$", "this", "->", "datetimeAsHumanEn", "(", "$", "value", ",", "$", "format", ")", ";", "}", "default", ":", "{", "return", "parent", "::", "asDatetime", "(", "$", "value", ",", "$", "format", ")", ";", "}", "}", "}" ]
Formats the value as a datetime. @param integer|string|DateTime $value the value to be formatted. The following types of value are supported: - an integer representing a UNIX timestamp - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php). The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given. - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object @param string $format the format used to convert the value into a date string. If null, [[dateFormat]] will be used. This can be 'short', 'medium', 'long', or 'full', which represents a preset format of different lengths. It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime). Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the PHP [date()](http://php.net/manual/de/function.date.php)-function. @return string the formatted result. @throws InvalidParamException if the input value can not be evaluated as a date value. @throws InvalidConfigException if the date format is invalid. @see datetimeFormat
[ "Formats", "the", "value", "as", "a", "datetime", ".", "@param", "integer|string|DateTime", "$value", "the", "value", "to", "be", "formatted", ".", "The", "following", "types", "of", "value", "are", "supported", ":" ]
train
https://github.com/microinginer/yii2-human-formatter/blob/d9a3536e99a22f5cfbbc2dd10b287cb89d85b56b/src/HumanFormatter.php#L73-L86
rayrutjes/domain-foundation
src/Command/GenericCommand.php
GenericCommand.enrichMetadata
public function enrichMetadata(array $data) { $metadata = $this->message->metadata()->mergeWith($data); return new self($this->identifier(), $this->payload(), $metadata); }
php
public function enrichMetadata(array $data) { $metadata = $this->message->metadata()->mergeWith($data); return new self($this->identifier(), $this->payload(), $metadata); }
[ "public", "function", "enrichMetadata", "(", "array", "$", "data", ")", "{", "$", "metadata", "=", "$", "this", "->", "message", "->", "metadata", "(", ")", "->", "mergeWith", "(", "$", "data", ")", ";", "return", "new", "self", "(", "$", "this", "->", "identifier", "(", ")", ",", "$", "this", "->", "payload", "(", ")", ",", "$", "metadata", ")", ";", "}" ]
@param array $data @return Message
[ "@param", "array", "$data" ]
train
https://github.com/rayrutjes/domain-foundation/blob/2bce7cd6a6612f718e70e3176589c1abf39d1a3e/src/Command/GenericCommand.php#L89-L94
4devs/ElfinderPhpConnector
FileInfo.php
FileInfo.toArray
public function toArray() { $data = array( 'name' => $this->name, 'hash' => $this->hash, 'phash' => $this->phash, 'mime' => $this->mime, 'ts' => $this->ts, 'size' => $this->size, 'dirs' => $this->dirs, 'read' => $this->read, 'write' => $this->write, 'locked' => $this->locked, 'tmb' => $this->tmb, 'alias' => $this->alias, 'thash' => $this->thash, 'dim' => $this->dim, 'volumeid' => $this->volumeid, 'path' => $this->path, 'url' => $this->url, ); return array_filter( $data, function ($var) { return !is_null($var); } ); }
php
public function toArray() { $data = array( 'name' => $this->name, 'hash' => $this->hash, 'phash' => $this->phash, 'mime' => $this->mime, 'ts' => $this->ts, 'size' => $this->size, 'dirs' => $this->dirs, 'read' => $this->read, 'write' => $this->write, 'locked' => $this->locked, 'tmb' => $this->tmb, 'alias' => $this->alias, 'thash' => $this->thash, 'dim' => $this->dim, 'volumeid' => $this->volumeid, 'path' => $this->path, 'url' => $this->url, ); return array_filter( $data, function ($var) { return !is_null($var); } ); }
[ "public", "function", "toArray", "(", ")", "{", "$", "data", "=", "array", "(", "'name'", "=>", "$", "this", "->", "name", ",", "'hash'", "=>", "$", "this", "->", "hash", ",", "'phash'", "=>", "$", "this", "->", "phash", ",", "'mime'", "=>", "$", "this", "->", "mime", ",", "'ts'", "=>", "$", "this", "->", "ts", ",", "'size'", "=>", "$", "this", "->", "size", ",", "'dirs'", "=>", "$", "this", "->", "dirs", ",", "'read'", "=>", "$", "this", "->", "read", ",", "'write'", "=>", "$", "this", "->", "write", ",", "'locked'", "=>", "$", "this", "->", "locked", ",", "'tmb'", "=>", "$", "this", "->", "tmb", ",", "'alias'", "=>", "$", "this", "->", "alias", ",", "'thash'", "=>", "$", "this", "->", "thash", ",", "'dim'", "=>", "$", "this", "->", "dim", ",", "'volumeid'", "=>", "$", "this", "->", "volumeid", ",", "'path'", "=>", "$", "this", "->", "path", ",", "'url'", "=>", "$", "this", "->", "url", ",", ")", ";", "return", "array_filter", "(", "$", "data", ",", "function", "(", "$", "var", ")", "{", "return", "!", "is_null", "(", "$", "var", ")", ";", "}", ")", ";", "}" ]
FileInfo return as array. @return array
[ "FileInfo", "return", "as", "array", "." ]
train
https://github.com/4devs/ElfinderPhpConnector/blob/510e295dcafeaa0f796986ad87b3ed5f6b0d9338/FileInfo.php#L574-L602
nyeholt/silverstripe-external-content
thirdparty/Zend/Http/Client/Adapter/Socket.php
Zend_Http_Client_Adapter_Socket.read
public function read() { // First, read headers only $response = ''; $gotStatus = false; while (($line = @fgets($this->socket)) !== false) { $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false); if ($gotStatus) { $response .= $line; if (rtrim($line) === '') break; } } $statusCode = Zend_Http_Response::extractCode($response); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) return $this->read(); /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == Zend_Http_Client::HEAD) return $response; // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); // If we got a 'transfer-encoding: chunked' header if (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $line = @fgets($this->socket); $chunk = $line; // Figure out the next chunk size $chunksize = trim($line); if (! ctype_xdigit($chunksize)) { $this->close(); require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' . $chunksize . '" unable to read chunked body'); } // Convert the hexadecimal value to plain integer $chunksize = hexdec($chunksize); // Read chunk $left_to_read = $chunksize; while ($left_to_read > 0) { $line = @fread($this->socket, $left_to_read); if ($line === false || strlen($line) === 0) { break; } else { $chunk .= $line; $left_to_read -= strlen($line); } // Break if the connection ended prematurely if (feof($this->socket)) break; } $chunk .= @fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding'); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = @fread($this->socket, $left_to_read); if ($chunk === false || strlen($chunk) === 0) { break; } else { $left_to_read -= strlen($chunk); $response .= $chunk; } // Break if the connection ended prematurely if (feof($this->socket)) break; } // Fallback: just read the response until EOF } else { do { $buff = @fread($this->socket, 8192); if ($buff === false || strlen($buff) === 0) { break; } else { $response .= $buff; } } while (feof($this->socket) === false); $this->close(); } // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; }
php
public function read() { // First, read headers only $response = ''; $gotStatus = false; while (($line = @fgets($this->socket)) !== false) { $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false); if ($gotStatus) { $response .= $line; if (rtrim($line) === '') break; } } $statusCode = Zend_Http_Response::extractCode($response); // Handle 100 and 101 responses internally by restarting the read again if ($statusCode == 100 || $statusCode == 101) return $this->read(); /** * Responses to HEAD requests and 204 or 304 responses are not expected * to have a body - stop reading here */ if ($statusCode == 304 || $statusCode == 204 || $this->method == Zend_Http_Client::HEAD) return $response; // Check headers to see what kind of connection / transfer encoding we have $headers = Zend_Http_Response::extractHeaders($response); // If we got a 'transfer-encoding: chunked' header if (isset($headers['transfer-encoding'])) { if ($headers['transfer-encoding'] == 'chunked') { do { $line = @fgets($this->socket); $chunk = $line; // Figure out the next chunk size $chunksize = trim($line); if (! ctype_xdigit($chunksize)) { $this->close(); require_once 'Zend/Http/Client/Adapter/Exception.php'; throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' . $chunksize . '" unable to read chunked body'); } // Convert the hexadecimal value to plain integer $chunksize = hexdec($chunksize); // Read chunk $left_to_read = $chunksize; while ($left_to_read > 0) { $line = @fread($this->socket, $left_to_read); if ($line === false || strlen($line) === 0) { break; } else { $chunk .= $line; $left_to_read -= strlen($line); } // Break if the connection ended prematurely if (feof($this->socket)) break; } $chunk .= @fgets($this->socket); $response .= $chunk; } while ($chunksize > 0); } else { throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' . $headers['transfer-encoding'] . '" transfer encoding'); } // Else, if we got the content-length header, read this number of bytes } elseif (isset($headers['content-length'])) { $left_to_read = $headers['content-length']; $chunk = ''; while ($left_to_read > 0) { $chunk = @fread($this->socket, $left_to_read); if ($chunk === false || strlen($chunk) === 0) { break; } else { $left_to_read -= strlen($chunk); $response .= $chunk; } // Break if the connection ended prematurely if (feof($this->socket)) break; } // Fallback: just read the response until EOF } else { do { $buff = @fread($this->socket, 8192); if ($buff === false || strlen($buff) === 0) { break; } else { $response .= $buff; } } while (feof($this->socket) === false); $this->close(); } // Close the connection if requested to do so by the server if (isset($headers['connection']) && $headers['connection'] == 'close') { $this->close(); } return $response; }
[ "public", "function", "read", "(", ")", "{", "// First, read headers only", "$", "response", "=", "''", ";", "$", "gotStatus", "=", "false", ";", "while", "(", "(", "$", "line", "=", "@", "fgets", "(", "$", "this", "->", "socket", ")", ")", "!==", "false", ")", "{", "$", "gotStatus", "=", "$", "gotStatus", "||", "(", "strpos", "(", "$", "line", ",", "'HTTP'", ")", "!==", "false", ")", ";", "if", "(", "$", "gotStatus", ")", "{", "$", "response", ".=", "$", "line", ";", "if", "(", "rtrim", "(", "$", "line", ")", "===", "''", ")", "break", ";", "}", "}", "$", "statusCode", "=", "Zend_Http_Response", "::", "extractCode", "(", "$", "response", ")", ";", "// Handle 100 and 101 responses internally by restarting the read again", "if", "(", "$", "statusCode", "==", "100", "||", "$", "statusCode", "==", "101", ")", "return", "$", "this", "->", "read", "(", ")", ";", "/**\n * Responses to HEAD requests and 204 or 304 responses are not expected\n * to have a body - stop reading here\n */", "if", "(", "$", "statusCode", "==", "304", "||", "$", "statusCode", "==", "204", "||", "$", "this", "->", "method", "==", "Zend_Http_Client", "::", "HEAD", ")", "return", "$", "response", ";", "// Check headers to see what kind of connection / transfer encoding we have", "$", "headers", "=", "Zend_Http_Response", "::", "extractHeaders", "(", "$", "response", ")", ";", "// If we got a 'transfer-encoding: chunked' header", "if", "(", "isset", "(", "$", "headers", "[", "'transfer-encoding'", "]", ")", ")", "{", "if", "(", "$", "headers", "[", "'transfer-encoding'", "]", "==", "'chunked'", ")", "{", "do", "{", "$", "line", "=", "@", "fgets", "(", "$", "this", "->", "socket", ")", ";", "$", "chunk", "=", "$", "line", ";", "// Figure out the next chunk size", "$", "chunksize", "=", "trim", "(", "$", "line", ")", ";", "if", "(", "!", "ctype_xdigit", "(", "$", "chunksize", ")", ")", "{", "$", "this", "->", "close", "(", ")", ";", "require_once", "'Zend/Http/Client/Adapter/Exception.php'", ";", "throw", "new", "Zend_Http_Client_Adapter_Exception", "(", "'Invalid chunk size \"'", ".", "$", "chunksize", ".", "'\" unable to read chunked body'", ")", ";", "}", "// Convert the hexadecimal value to plain integer", "$", "chunksize", "=", "hexdec", "(", "$", "chunksize", ")", ";", "// Read chunk", "$", "left_to_read", "=", "$", "chunksize", ";", "while", "(", "$", "left_to_read", ">", "0", ")", "{", "$", "line", "=", "@", "fread", "(", "$", "this", "->", "socket", ",", "$", "left_to_read", ")", ";", "if", "(", "$", "line", "===", "false", "||", "strlen", "(", "$", "line", ")", "===", "0", ")", "{", "break", ";", "}", "else", "{", "$", "chunk", ".=", "$", "line", ";", "$", "left_to_read", "-=", "strlen", "(", "$", "line", ")", ";", "}", "// Break if the connection ended prematurely", "if", "(", "feof", "(", "$", "this", "->", "socket", ")", ")", "break", ";", "}", "$", "chunk", ".=", "@", "fgets", "(", "$", "this", "->", "socket", ")", ";", "$", "response", ".=", "$", "chunk", ";", "}", "while", "(", "$", "chunksize", ">", "0", ")", ";", "}", "else", "{", "throw", "new", "Zend_Http_Client_Adapter_Exception", "(", "'Cannot handle \"'", ".", "$", "headers", "[", "'transfer-encoding'", "]", ".", "'\" transfer encoding'", ")", ";", "}", "// Else, if we got the content-length header, read this number of bytes", "}", "elseif", "(", "isset", "(", "$", "headers", "[", "'content-length'", "]", ")", ")", "{", "$", "left_to_read", "=", "$", "headers", "[", "'content-length'", "]", ";", "$", "chunk", "=", "''", ";", "while", "(", "$", "left_to_read", ">", "0", ")", "{", "$", "chunk", "=", "@", "fread", "(", "$", "this", "->", "socket", ",", "$", "left_to_read", ")", ";", "if", "(", "$", "chunk", "===", "false", "||", "strlen", "(", "$", "chunk", ")", "===", "0", ")", "{", "break", ";", "}", "else", "{", "$", "left_to_read", "-=", "strlen", "(", "$", "chunk", ")", ";", "$", "response", ".=", "$", "chunk", ";", "}", "// Break if the connection ended prematurely", "if", "(", "feof", "(", "$", "this", "->", "socket", ")", ")", "break", ";", "}", "// Fallback: just read the response until EOF", "}", "else", "{", "do", "{", "$", "buff", "=", "@", "fread", "(", "$", "this", "->", "socket", ",", "8192", ")", ";", "if", "(", "$", "buff", "===", "false", "||", "strlen", "(", "$", "buff", ")", "===", "0", ")", "{", "break", ";", "}", "else", "{", "$", "response", ".=", "$", "buff", ";", "}", "}", "while", "(", "feof", "(", "$", "this", "->", "socket", ")", "===", "false", ")", ";", "$", "this", "->", "close", "(", ")", ";", "}", "// Close the connection if requested to do so by the server", "if", "(", "isset", "(", "$", "headers", "[", "'connection'", "]", ")", "&&", "$", "headers", "[", "'connection'", "]", "==", "'close'", ")", "{", "$", "this", "->", "close", "(", ")", ";", "}", "return", "$", "response", ";", "}" ]
Read response from server @return string
[ "Read", "response", "from", "server" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Http/Client/Adapter/Socket.php#L217-L328
okitcom/ok-lib-php
src/Model/Cash/LineItem.php
LineItem.create
public static function create($quantity, $productCode, $description, $amount, $vat, $currency = "EUR") { $item = new LineItem; $item->quantity = $quantity; $item->productCode = $productCode; $item->description = $description; $item->amount = $amount; $item->vat = $vat; $item->currency = $currency; return $item; }
php
public static function create($quantity, $productCode, $description, $amount, $vat, $currency = "EUR") { $item = new LineItem; $item->quantity = $quantity; $item->productCode = $productCode; $item->description = $description; $item->amount = $amount; $item->vat = $vat; $item->currency = $currency; return $item; }
[ "public", "static", "function", "create", "(", "$", "quantity", ",", "$", "productCode", ",", "$", "description", ",", "$", "amount", ",", "$", "vat", ",", "$", "currency", "=", "\"EUR\"", ")", "{", "$", "item", "=", "new", "LineItem", ";", "$", "item", "->", "quantity", "=", "$", "quantity", ";", "$", "item", "->", "productCode", "=", "$", "productCode", ";", "$", "item", "->", "description", "=", "$", "description", ";", "$", "item", "->", "amount", "=", "$", "amount", ";", "$", "item", "->", "vat", "=", "$", "vat", ";", "$", "item", "->", "currency", "=", "$", "currency", ";", "return", "$", "item", ";", "}" ]
LineItem creator. @param int $quantity @param string $productCode @param string $description @param Amount $amount @param int $vat @param string $currency @return LineItem
[ "LineItem", "creator", "." ]
train
https://github.com/okitcom/ok-lib-php/blob/1f441f3d216af7c952788e864bfe66bc4f089467/src/Model/Cash/LineItem.php#L66-L75
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php
BaseCountryQuery.create
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof CountryQuery) { return $criteria; } $query = new CountryQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
php
public static function create($modelAlias = null, $criteria = null) { if ($criteria instanceof CountryQuery) { return $criteria; } $query = new CountryQuery(null, null, $modelAlias); if ($criteria instanceof Criteria) { $query->mergeWith($criteria); } return $query; }
[ "public", "static", "function", "create", "(", "$", "modelAlias", "=", "null", ",", "$", "criteria", "=", "null", ")", "{", "if", "(", "$", "criteria", "instanceof", "CountryQuery", ")", "{", "return", "$", "criteria", ";", "}", "$", "query", "=", "new", "CountryQuery", "(", "null", ",", "null", ",", "$", "modelAlias", ")", ";", "if", "(", "$", "criteria", "instanceof", "Criteria", ")", "{", "$", "query", "->", "mergeWith", "(", "$", "criteria", ")", ";", "}", "return", "$", "query", ";", "}" ]
Returns a new CountryQuery object. @param string $modelAlias The alias of a model in the query @param CountryQuery|Criteria $criteria Optional Criteria to build the query from @return CountryQuery
[ "Returns", "a", "new", "CountryQuery", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php#L79-L91
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php
BaseCountryQuery.filterByEn
public function filterByEn($en = null, $comparison = null) { if (null === $comparison) { if (is_array($en)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $en)) { $en = str_replace('*', '%', $en); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(CountryPeer::EN, $en, $comparison); }
php
public function filterByEn($en = null, $comparison = null) { if (null === $comparison) { if (is_array($en)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $en)) { $en = str_replace('*', '%', $en); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(CountryPeer::EN, $en, $comparison); }
[ "public", "function", "filterByEn", "(", "$", "en", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "en", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "en", ")", ")", "{", "$", "en", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "en", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "CountryPeer", "::", "EN", ",", "$", "en", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the en column Example usage: <code> $query->filterByEn('fooValue'); // WHERE en = 'fooValue' $query->filterByEn('%fooValue%'); // WHERE en LIKE '%fooValue%' </code> @param string $en The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return CountryQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "en", "column" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php#L330-L342
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php
BaseCountryQuery.filterByDe
public function filterByDe($de = null, $comparison = null) { if (null === $comparison) { if (is_array($de)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $de)) { $de = str_replace('*', '%', $de); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(CountryPeer::DE, $de, $comparison); }
php
public function filterByDe($de = null, $comparison = null) { if (null === $comparison) { if (is_array($de)) { $comparison = Criteria::IN; } elseif (preg_match('/[\%\*]/', $de)) { $de = str_replace('*', '%', $de); $comparison = Criteria::LIKE; } } return $this->addUsingAlias(CountryPeer::DE, $de, $comparison); }
[ "public", "function", "filterByDe", "(", "$", "de", "=", "null", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "null", "===", "$", "comparison", ")", "{", "if", "(", "is_array", "(", "$", "de", ")", ")", "{", "$", "comparison", "=", "Criteria", "::", "IN", ";", "}", "elseif", "(", "preg_match", "(", "'/[\\%\\*]/'", ",", "$", "de", ")", ")", "{", "$", "de", "=", "str_replace", "(", "'*'", ",", "'%'", ",", "$", "de", ")", ";", "$", "comparison", "=", "Criteria", "::", "LIKE", ";", "}", "}", "return", "$", "this", "->", "addUsingAlias", "(", "CountryPeer", "::", "DE", ",", "$", "de", ",", "$", "comparison", ")", ";", "}" ]
Filter the query on the de column Example usage: <code> $query->filterByDe('fooValue'); // WHERE de = 'fooValue' $query->filterByDe('%fooValue%'); // WHERE de LIKE '%fooValue%' </code> @param string $de The value to use as filter. Accepts wildcards (* and % trigger a LIKE) @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return CountryQuery The current query, for fluid interface
[ "Filter", "the", "query", "on", "the", "de", "column" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php#L359-L371
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php
BaseCountryQuery.filterByCustomer
public function filterByCustomer($customer, $comparison = null) { if ($customer instanceof Customer) { return $this ->addUsingAlias(CountryPeer::ID, $customer->getCountryId(), $comparison); } elseif ($customer instanceof PropelObjectCollection) { return $this ->useCustomerQuery() ->filterByPrimaryKeys($customer->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByCustomer() only accepts arguments of type Customer or PropelCollection'); } }
php
public function filterByCustomer($customer, $comparison = null) { if ($customer instanceof Customer) { return $this ->addUsingAlias(CountryPeer::ID, $customer->getCountryId(), $comparison); } elseif ($customer instanceof PropelObjectCollection) { return $this ->useCustomerQuery() ->filterByPrimaryKeys($customer->getPrimaryKeys()) ->endUse(); } else { throw new PropelException('filterByCustomer() only accepts arguments of type Customer or PropelCollection'); } }
[ "public", "function", "filterByCustomer", "(", "$", "customer", ",", "$", "comparison", "=", "null", ")", "{", "if", "(", "$", "customer", "instanceof", "Customer", ")", "{", "return", "$", "this", "->", "addUsingAlias", "(", "CountryPeer", "::", "ID", ",", "$", "customer", "->", "getCountryId", "(", ")", ",", "$", "comparison", ")", ";", "}", "elseif", "(", "$", "customer", "instanceof", "PropelObjectCollection", ")", "{", "return", "$", "this", "->", "useCustomerQuery", "(", ")", "->", "filterByPrimaryKeys", "(", "$", "customer", "->", "getPrimaryKeys", "(", ")", ")", "->", "endUse", "(", ")", ";", "}", "else", "{", "throw", "new", "PropelException", "(", "'filterByCustomer() only accepts arguments of type Customer or PropelCollection'", ")", ";", "}", "}" ]
Filter the query by a related Customer object @param Customer|PropelObjectCollection $customer the related object to use as filter @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL @return CountryQuery The current query, for fluid interface @throws PropelException - if the provided filter is invalid.
[ "Filter", "the", "query", "by", "a", "related", "Customer", "object" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseCountryQuery.php#L382-L395