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
josegonzalez/cakephp-sanction
Model/Behavior/PermitBehavior.php
PermitBehavior.user
public function user(Model $Model, $result, $key = null) { if (method_exists($Model, 'user')) { return $Model->user($key, $result); } if (class_exists('AuthComponent')) { return AuthComponent::user($key); } if (class_exists('Authsome')) { return Authsome::get($key); } if (method_exists($Model, 'get')) { $className = get_class($Model); $ref = new ReflectionMethod($className, 'get'); if ($ref->isStatic()) { return $className::get($key); } } return false; }
php
public function user(Model $Model, $result, $key = null) { if (method_exists($Model, 'user')) { return $Model->user($key, $result); } if (class_exists('AuthComponent')) { return AuthComponent::user($key); } if (class_exists('Authsome')) { return Authsome::get($key); } if (method_exists($Model, 'get')) { $className = get_class($Model); $ref = new ReflectionMethod($className, 'get'); if ($ref->isStatic()) { return $className::get($key); } } return false; }
[ "public", "function", "user", "(", "Model", "$", "Model", ",", "$", "result", ",", "$", "key", "=", "null", ")", "{", "if", "(", "method_exists", "(", "$", "Model", ",", "'user'", ")", ")", "{", "return", "$", "Model", "->", "user", "(", "$", "key", ",", "$", "result", ")", ";", "}", "if", "(", "class_exists", "(", "'AuthComponent'", ")", ")", "{", "return", "AuthComponent", "::", "user", "(", "$", "key", ")", ";", "}", "if", "(", "class_exists", "(", "'Authsome'", ")", ")", "{", "return", "Authsome", "::", "get", "(", "$", "key", ")", ";", "}", "if", "(", "method_exists", "(", "$", "Model", ",", "'get'", ")", ")", "{", "$", "className", "=", "get_class", "(", "$", "Model", ")", ";", "$", "ref", "=", "new", "ReflectionMethod", "(", "$", "className", ",", "'get'", ")", ";", "if", "(", "$", "ref", "->", "isStatic", "(", ")", ")", "{", "return", "$", "className", "::", "get", "(", "$", "key", ")", ";", "}", "}", "return", "false", ";", "}" ]
Wrapper around retrieving user data Can be overriden in the Model to provide advanced control @param Model $Model Model to use to retrieve user @param array $result single Model record being authenticated against @param string $key field to retrieve. Leave null to get entire User record @return mixed User record. or null if no user is logged in.
[ "Wrapper", "around", "retrieving", "user", "data" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Model/Behavior/PermitBehavior.php#L145-L167
josegonzalez/cakephp-sanction
Model/Behavior/PermitBehavior.php
PermitBehavior.permit
public function permit(Model $Model, $settings = array()) { // store existing model defaults $this->modelDefaultsPersist[$Model->alias] = $this->modelDefaults[$Model->alias]; // assign new settings $this->modelDefaults[$Model->alias] = array_merge($this->modelDefaults[$Model->alias], $settings); }
php
public function permit(Model $Model, $settings = array()) { // store existing model defaults $this->modelDefaultsPersist[$Model->alias] = $this->modelDefaults[$Model->alias]; // assign new settings $this->modelDefaults[$Model->alias] = array_merge($this->modelDefaults[$Model->alias], $settings); }
[ "public", "function", "permit", "(", "Model", "$", "Model", ",", "$", "settings", "=", "array", "(", ")", ")", "{", "// store existing model defaults", "$", "this", "->", "modelDefaultsPersist", "[", "$", "Model", "->", "alias", "]", "=", "$", "this", "->", "modelDefaults", "[", "$", "Model", "->", "alias", "]", ";", "// assign new settings", "$", "this", "->", "modelDefaults", "[", "$", "Model", "->", "alias", "]", "=", "array_merge", "(", "$", "this", "->", "modelDefaults", "[", "$", "Model", "->", "alias", "]", ",", "$", "settings", ")", ";", "}" ]
Used to dynamically assign permit settings @param Model $Model Model to dynamically assign permissions on @param array $settings same as the settings used to set-up the model, with the addition of 'persist' (boolean), which will keep the passed settings for all future model calls @return void
[ "Used", "to", "dynamically", "assign", "permit", "settings" ]
train
https://github.com/josegonzalez/cakephp-sanction/blob/df2a8f0c0602c0ace802773db2c2ca6c89555c47/Model/Behavior/PermitBehavior.php#L176-L181
zhouyl/mellivora
Mellivora/Pagination/PaginationServiceProvider.php
PaginationServiceProvider.loadViewsFrom
protected function loadViewsFrom($path, $namespace) { if (is_dir($appPath = resource_path('views/vendor/' . $namespace))) { $this->container['view']->addNamespace($namespace, $appPath); } $this->container['view']->addNamespace($namespace, $path); }
php
protected function loadViewsFrom($path, $namespace) { if (is_dir($appPath = resource_path('views/vendor/' . $namespace))) { $this->container['view']->addNamespace($namespace, $appPath); } $this->container['view']->addNamespace($namespace, $path); }
[ "protected", "function", "loadViewsFrom", "(", "$", "path", ",", "$", "namespace", ")", "{", "if", "(", "is_dir", "(", "$", "appPath", "=", "resource_path", "(", "'views/vendor/'", ".", "$", "namespace", ")", ")", ")", "{", "$", "this", "->", "container", "[", "'view'", "]", "->", "addNamespace", "(", "$", "namespace", ",", "$", "appPath", ")", ";", "}", "$", "this", "->", "container", "[", "'view'", "]", "->", "addNamespace", "(", "$", "namespace", ",", "$", "path", ")", ";", "}" ]
Register a view file namespace. @param string $path @param string $namespace @return void
[ "Register", "a", "view", "file", "namespace", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Pagination/PaginationServiceProvider.php#L17-L24
zhouyl/mellivora
Mellivora/Pagination/PaginationServiceProvider.php
PaginationServiceProvider.register
public function register() { $this->loadViewsFrom(__DIR__ . '/resources/views', 'pagination'); Paginator::viewFactoryResolver(function () { return $this->container['view']; }); Paginator::currentPathResolver(function () { return $this->container['request']->fullurl(); }); Paginator::currentPageResolver(function ($pageName = 'page') { $page = $this->container['request']->input($pageName); if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) { return $page; } return 1; }); }
php
public function register() { $this->loadViewsFrom(__DIR__ . '/resources/views', 'pagination'); Paginator::viewFactoryResolver(function () { return $this->container['view']; }); Paginator::currentPathResolver(function () { return $this->container['request']->fullurl(); }); Paginator::currentPageResolver(function ($pageName = 'page') { $page = $this->container['request']->input($pageName); if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) { return $page; } return 1; }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "loadViewsFrom", "(", "__DIR__", ".", "'/resources/views'", ",", "'pagination'", ")", ";", "Paginator", "::", "viewFactoryResolver", "(", "function", "(", ")", "{", "return", "$", "this", "->", "container", "[", "'view'", "]", ";", "}", ")", ";", "Paginator", "::", "currentPathResolver", "(", "function", "(", ")", "{", "return", "$", "this", "->", "container", "[", "'request'", "]", "->", "fullurl", "(", ")", ";", "}", ")", ";", "Paginator", "::", "currentPageResolver", "(", "function", "(", "$", "pageName", "=", "'page'", ")", "{", "$", "page", "=", "$", "this", "->", "container", "[", "'request'", "]", "->", "input", "(", "$", "pageName", ")", ";", "if", "(", "filter_var", "(", "$", "page", ",", "FILTER_VALIDATE_INT", ")", "!==", "false", "&&", "(", "int", ")", "$", "page", ">=", "1", ")", "{", "return", "$", "page", ";", "}", "return", "1", ";", "}", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Pagination/PaginationServiceProvider.php#L31-L52
novaway/open-graph
src/Builder/DefaultDriverFactory.php
DefaultDriverFactory.createDriver
public function createDriver(array $metadataDirectories, Reader $annotationReader) { if (!empty($metadataDirectories)) { $fileLocator = new FileLocator($metadataDirectories); return new DriverChain([ new YamlDriver($fileLocator), new AnnotationDriver($annotationReader), ]); } return new AnnotationDriver($annotationReader); }
php
public function createDriver(array $metadataDirectories, Reader $annotationReader) { if (!empty($metadataDirectories)) { $fileLocator = new FileLocator($metadataDirectories); return new DriverChain([ new YamlDriver($fileLocator), new AnnotationDriver($annotationReader), ]); } return new AnnotationDriver($annotationReader); }
[ "public", "function", "createDriver", "(", "array", "$", "metadataDirectories", ",", "Reader", "$", "annotationReader", ")", "{", "if", "(", "!", "empty", "(", "$", "metadataDirectories", ")", ")", "{", "$", "fileLocator", "=", "new", "FileLocator", "(", "$", "metadataDirectories", ")", ";", "return", "new", "DriverChain", "(", "[", "new", "YamlDriver", "(", "$", "fileLocator", ")", ",", "new", "AnnotationDriver", "(", "$", "annotationReader", ")", ",", "]", ")", ";", "}", "return", "new", "AnnotationDriver", "(", "$", "annotationReader", ")", ";", "}" ]
Create driver @param array $metadataDirs @param Reader $annotationReader @return DefaultDriverFactory
[ "Create", "driver" ]
train
https://github.com/novaway/open-graph/blob/19817bee4b91cf26ca3fe44883ad58b32328e464/src/Builder/DefaultDriverFactory.php#L20-L32
antaresproject/notifications
src/Widgets/NotificationSender/Form/NotificationWidgetForm.php
NotificationWidgetForm.get
public function get() { $this->scripts(); return app('antares.form')->of("antares.widgets: notification-widget")->extend(function (FormGrid $form) { $form->name('Notification Tester'); $form->simple(handles('antares::notifications/widgets/send'), ['id' => 'notification-widget-form']); $form->layout('antares/notifications::widgets.forms.send_notification_form'); $form->fieldset(trans('Default Fieldset'), function (Fieldset $fieldset) { $fieldset->control('input:hidden', 'url') ->attributes(['class' => 'notification-widget-url']) ->value(handles('antares::notifications/notifications')) ->block(['class' => 'hidden']); $fieldset->control('select', 'type') ->attributes(['class' => 'notification-widget-change-type-select', 'url' => handles('antares::notifications/notifications')]) ->options($this->repository->getDecoratedNotificationTypes()) ->wrapper(['class' => 'w200']); $fieldset->control('select', 'notifications') ->attributes(['class' => 'notification-widget-notifications-select']) ->options($this->repository->getNotificationContents('email')->pluck('title', 'id')) ->wrapper(['class' => 'w300']); if (!is_null(from_route('user'))) { $fieldset->control('button', 'send') ->attributes([ 'type' => 'submit', 'class' => 'notification-widget-send-button', 'data-title' => trans('Are you sure to send notification?'), 'url' => handles('antares::notifications/widgets/send'), ])->value(trans('Send')); } $fieldset->control('button', 'test') ->attributes([ 'type' => 'submit', 'class' => 'notification-widget-test-button btn--red', 'data-title' => trans('Are you sure to test notification?'), 'url' => handles('antares::notifications/widgets/test'), ])->value(trans('Test')); }); $form->rules($this->rules); $form->ajaxable([ 'afterValidate' => $this->afterValidateInline() ]); }); }
php
public function get() { $this->scripts(); return app('antares.form')->of("antares.widgets: notification-widget")->extend(function (FormGrid $form) { $form->name('Notification Tester'); $form->simple(handles('antares::notifications/widgets/send'), ['id' => 'notification-widget-form']); $form->layout('antares/notifications::widgets.forms.send_notification_form'); $form->fieldset(trans('Default Fieldset'), function (Fieldset $fieldset) { $fieldset->control('input:hidden', 'url') ->attributes(['class' => 'notification-widget-url']) ->value(handles('antares::notifications/notifications')) ->block(['class' => 'hidden']); $fieldset->control('select', 'type') ->attributes(['class' => 'notification-widget-change-type-select', 'url' => handles('antares::notifications/notifications')]) ->options($this->repository->getDecoratedNotificationTypes()) ->wrapper(['class' => 'w200']); $fieldset->control('select', 'notifications') ->attributes(['class' => 'notification-widget-notifications-select']) ->options($this->repository->getNotificationContents('email')->pluck('title', 'id')) ->wrapper(['class' => 'w300']); if (!is_null(from_route('user'))) { $fieldset->control('button', 'send') ->attributes([ 'type' => 'submit', 'class' => 'notification-widget-send-button', 'data-title' => trans('Are you sure to send notification?'), 'url' => handles('antares::notifications/widgets/send'), ])->value(trans('Send')); } $fieldset->control('button', 'test') ->attributes([ 'type' => 'submit', 'class' => 'notification-widget-test-button btn--red', 'data-title' => trans('Are you sure to test notification?'), 'url' => handles('antares::notifications/widgets/test'), ])->value(trans('Test')); }); $form->rules($this->rules); $form->ajaxable([ 'afterValidate' => $this->afterValidateInline() ]); }); }
[ "public", "function", "get", "(", ")", "{", "$", "this", "->", "scripts", "(", ")", ";", "return", "app", "(", "'antares.form'", ")", "->", "of", "(", "\"antares.widgets: notification-widget\"", ")", "->", "extend", "(", "function", "(", "FormGrid", "$", "form", ")", "{", "$", "form", "->", "name", "(", "'Notification Tester'", ")", ";", "$", "form", "->", "simple", "(", "handles", "(", "'antares::notifications/widgets/send'", ")", ",", "[", "'id'", "=>", "'notification-widget-form'", "]", ")", ";", "$", "form", "->", "layout", "(", "'antares/notifications::widgets.forms.send_notification_form'", ")", ";", "$", "form", "->", "fieldset", "(", "trans", "(", "'Default Fieldset'", ")", ",", "function", "(", "Fieldset", "$", "fieldset", ")", "{", "$", "fieldset", "->", "control", "(", "'input:hidden'", ",", "'url'", ")", "->", "attributes", "(", "[", "'class'", "=>", "'notification-widget-url'", "]", ")", "->", "value", "(", "handles", "(", "'antares::notifications/notifications'", ")", ")", "->", "block", "(", "[", "'class'", "=>", "'hidden'", "]", ")", ";", "$", "fieldset", "->", "control", "(", "'select'", ",", "'type'", ")", "->", "attributes", "(", "[", "'class'", "=>", "'notification-widget-change-type-select'", ",", "'url'", "=>", "handles", "(", "'antares::notifications/notifications'", ")", "]", ")", "->", "options", "(", "$", "this", "->", "repository", "->", "getDecoratedNotificationTypes", "(", ")", ")", "->", "wrapper", "(", "[", "'class'", "=>", "'w200'", "]", ")", ";", "$", "fieldset", "->", "control", "(", "'select'", ",", "'notifications'", ")", "->", "attributes", "(", "[", "'class'", "=>", "'notification-widget-notifications-select'", "]", ")", "->", "options", "(", "$", "this", "->", "repository", "->", "getNotificationContents", "(", "'email'", ")", "->", "pluck", "(", "'title'", ",", "'id'", ")", ")", "->", "wrapper", "(", "[", "'class'", "=>", "'w300'", "]", ")", ";", "if", "(", "!", "is_null", "(", "from_route", "(", "'user'", ")", ")", ")", "{", "$", "fieldset", "->", "control", "(", "'button'", ",", "'send'", ")", "->", "attributes", "(", "[", "'type'", "=>", "'submit'", ",", "'class'", "=>", "'notification-widget-send-button'", ",", "'data-title'", "=>", "trans", "(", "'Are you sure to send notification?'", ")", ",", "'url'", "=>", "handles", "(", "'antares::notifications/widgets/send'", ")", ",", "]", ")", "->", "value", "(", "trans", "(", "'Send'", ")", ")", ";", "}", "$", "fieldset", "->", "control", "(", "'button'", ",", "'test'", ")", "->", "attributes", "(", "[", "'type'", "=>", "'submit'", ",", "'class'", "=>", "'notification-widget-test-button btn--red'", ",", "'data-title'", "=>", "trans", "(", "'Are you sure to test notification?'", ")", ",", "'url'", "=>", "handles", "(", "'antares::notifications/widgets/test'", ")", ",", "]", ")", "->", "value", "(", "trans", "(", "'Test'", ")", ")", ";", "}", ")", ";", "$", "form", "->", "rules", "(", "$", "this", "->", "rules", ")", ";", "$", "form", "->", "ajaxable", "(", "[", "'afterValidate'", "=>", "$", "this", "->", "afterValidateInline", "(", ")", "]", ")", ";", "}", ")", ";", "}" ]
Gets form instance @return \Antares\Html\Form\FormBuilder
[ "Gets", "form", "instance" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Widgets/NotificationSender/Form/NotificationWidgetForm.php#L71-L120
Laralum/Permissions
src/Traits/HasPermissions.php
HasPermissions.hasPermission
public function hasPermission($permission) { $permission = !is_string($permission) ?: Permission::where(['slug' => $permission])->first(); if ($permission) { foreach ($this->permissions as $p) { if ($p->id == $permission->id) { return true; } } } return false; }
php
public function hasPermission($permission) { $permission = !is_string($permission) ?: Permission::where(['slug' => $permission])->first(); if ($permission) { foreach ($this->permissions as $p) { if ($p->id == $permission->id) { return true; } } } return false; }
[ "public", "function", "hasPermission", "(", "$", "permission", ")", "{", "$", "permission", "=", "!", "is_string", "(", "$", "permission", ")", "?", ":", "Permission", "::", "where", "(", "[", "'slug'", "=>", "$", "permission", "]", ")", "->", "first", "(", ")", ";", "if", "(", "$", "permission", ")", "{", "foreach", "(", "$", "this", "->", "permissions", "as", "$", "p", ")", "{", "if", "(", "$", "p", "->", "id", "==", "$", "permission", "->", "id", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Returns if the user has a permission. @param mixed $permision @return bool
[ "Returns", "if", "the", "user", "has", "a", "permission", "." ]
train
https://github.com/Laralum/Permissions/blob/79970ee7d1bff816ad4b9adee29067faead3f756/src/Traits/HasPermissions.php#L24-L37
gedex/php-janrain-api
lib/Janrain/Api/Partner/App.php
App.create
public function create(array $params) { if (!isset($params['email'])) { throw new MissingArgumentException('email'); } if (!isset($params['name'])) { throw new MissingArgumentException('name'); } if (!isset($params['domain'])) { throw new MissingArgumentException('domain'); } return $this->post('app/create', $params); }
php
public function create(array $params) { if (!isset($params['email'])) { throw new MissingArgumentException('email'); } if (!isset($params['name'])) { throw new MissingArgumentException('name'); } if (!isset($params['domain'])) { throw new MissingArgumentException('domain'); } return $this->post('app/create', $params); }
[ "public", "function", "create", "(", "array", "$", "params", ")", "{", "if", "(", "!", "isset", "(", "$", "params", "[", "'email'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'email'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "params", "[", "'name'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'name'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "params", "[", "'domain'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'domain'", ")", ";", "}", "return", "$", "this", "->", "post", "(", "'app/create'", ",", "$", "params", ")", ";", "}" ]
Creates a new Engage application. @param array $params @link http://developers.janrain.com/documentation/api-methods/partner/app/create/
[ "Creates", "a", "new", "Engage", "application", "." ]
train
https://github.com/gedex/php-janrain-api/blob/6283f68454e0ad5211ac620f1d337df38cd49597/lib/Janrain/Api/Partner/App.php#L47-L62
gedex/php-janrain-api
lib/Janrain/Api/Partner/App.php
App.verifyDomain
public function verifyDomain(array $params) { if (!isset($params['provider'])) { throw new MissingArgumentException('provider'); } if (!isset($params['code'])) { throw new MissingArgumentException('code'); } if (!isset($params['filename'])) { throw new MissingArgumentException('filename'); } return $this->post('app/verify_domain', $params); }
php
public function verifyDomain(array $params) { if (!isset($params['provider'])) { throw new MissingArgumentException('provider'); } if (!isset($params['code'])) { throw new MissingArgumentException('code'); } if (!isset($params['filename'])) { throw new MissingArgumentException('filename'); } return $this->post('app/verify_domain', $params); }
[ "public", "function", "verifyDomain", "(", "array", "$", "params", ")", "{", "if", "(", "!", "isset", "(", "$", "params", "[", "'provider'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'provider'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "params", "[", "'code'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'code'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "params", "[", "'filename'", "]", ")", ")", "{", "throw", "new", "MissingArgumentException", "(", "'filename'", ")", ";", "}", "return", "$", "this", "->", "post", "(", "'app/verify_domain'", ",", "$", "params", ")", ";", "}" ]
Automates the server-side component of the provider-specific domain verification mechanism. @param array $params
[ "Automates", "the", "server", "-", "side", "component", "of", "the", "provider", "-", "specific", "domain", "verification", "mechanism", "." ]
train
https://github.com/gedex/php-janrain-api/blob/6283f68454e0ad5211ac620f1d337df38cd49597/lib/Janrain/Api/Partner/App.php#L184-L199
gordalina/mangopay-php
src/Gordalina/Mangopay/Request/RequestModelCollection.php
RequestModelCollection.handle
public function handle(ResponseInterface $response) { $collection = array(); $class = get_class($this->model); $objects = json_decode($response->getBody()); foreach ($objects as $object) { $model = new $class(); $model->update($object); $collection[] = $model; } $response->setCollection($collection); }
php
public function handle(ResponseInterface $response) { $collection = array(); $class = get_class($this->model); $objects = json_decode($response->getBody()); foreach ($objects as $object) { $model = new $class(); $model->update($object); $collection[] = $model; } $response->setCollection($collection); }
[ "public", "function", "handle", "(", "ResponseInterface", "$", "response", ")", "{", "$", "collection", "=", "array", "(", ")", ";", "$", "class", "=", "get_class", "(", "$", "this", "->", "model", ")", ";", "$", "objects", "=", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ")", ";", "foreach", "(", "$", "objects", "as", "$", "object", ")", "{", "$", "model", "=", "new", "$", "class", "(", ")", ";", "$", "model", "->", "update", "(", "$", "object", ")", ";", "$", "collection", "[", "]", "=", "$", "model", ";", "}", "$", "response", "->", "setCollection", "(", "$", "collection", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/gordalina/mangopay-php/blob/6807992416d964e25670d961b66dbccd7a46ef62/src/Gordalina/Mangopay/Request/RequestModelCollection.php#L29-L42
ezsystems/ezcomments-ls-extension
classes/ezcomcookiemanager.php
ezcomCookieManager.storeCookie
public function storeCookie( $comment = null ) { $userData = array(); $sessionID = session_id(); $currentUser = eZUser::currentUser(); if( is_null( $comment ) ) { if( $currentUser->isAnonymous() ) { return ''; } else { $userData[$sessionID] = array( 'email' => $currentUser->attribute( 'email' ), 'name' => $currentUser->contentObject()->name() ); } } else { $userData[$sessionID] = array( 'email' => $comment->attribute( 'email' ), 'website' => $comment->attribute( 'url' ), 'name' => $comment->attribute( 'name' ) ); if ( !$currentUser->isAnonymous() ) { $userData[$sessionID]['email'] = $currentUser->attribute( 'email' ); } } setcookie( 'eZCommentsUserData', base64_encode( json_encode( $userData ) ), $this->expiryTime, '/' ); return $userData; }
php
public function storeCookie( $comment = null ) { $userData = array(); $sessionID = session_id(); $currentUser = eZUser::currentUser(); if( is_null( $comment ) ) { if( $currentUser->isAnonymous() ) { return ''; } else { $userData[$sessionID] = array( 'email' => $currentUser->attribute( 'email' ), 'name' => $currentUser->contentObject()->name() ); } } else { $userData[$sessionID] = array( 'email' => $comment->attribute( 'email' ), 'website' => $comment->attribute( 'url' ), 'name' => $comment->attribute( 'name' ) ); if ( !$currentUser->isAnonymous() ) { $userData[$sessionID]['email'] = $currentUser->attribute( 'email' ); } } setcookie( 'eZCommentsUserData', base64_encode( json_encode( $userData ) ), $this->expiryTime, '/' ); return $userData; }
[ "public", "function", "storeCookie", "(", "$", "comment", "=", "null", ")", "{", "$", "userData", "=", "array", "(", ")", ";", "$", "sessionID", "=", "session_id", "(", ")", ";", "$", "currentUser", "=", "eZUser", "::", "currentUser", "(", ")", ";", "if", "(", "is_null", "(", "$", "comment", ")", ")", "{", "if", "(", "$", "currentUser", "->", "isAnonymous", "(", ")", ")", "{", "return", "''", ";", "}", "else", "{", "$", "userData", "[", "$", "sessionID", "]", "=", "array", "(", "'email'", "=>", "$", "currentUser", "->", "attribute", "(", "'email'", ")", ",", "'name'", "=>", "$", "currentUser", "->", "contentObject", "(", ")", "->", "name", "(", ")", ")", ";", "}", "}", "else", "{", "$", "userData", "[", "$", "sessionID", "]", "=", "array", "(", "'email'", "=>", "$", "comment", "->", "attribute", "(", "'email'", ")", ",", "'website'", "=>", "$", "comment", "->", "attribute", "(", "'url'", ")", ",", "'name'", "=>", "$", "comment", "->", "attribute", "(", "'name'", ")", ")", ";", "if", "(", "!", "$", "currentUser", "->", "isAnonymous", "(", ")", ")", "{", "$", "userData", "[", "$", "sessionID", "]", "[", "'email'", "]", "=", "$", "currentUser", "->", "attribute", "(", "'email'", ")", ";", "}", "}", "setcookie", "(", "'eZCommentsUserData'", ",", "base64_encode", "(", "json_encode", "(", "$", "userData", ")", ")", ",", "$", "this", "->", "expiryTime", ",", "'/'", ")", ";", "return", "$", "userData", ";", "}" ]
store data into cookie if field is null, set cookie based on user data, other wise set cookie based on fields @param $comment comment object @return arrary stored data
[ "store", "data", "into", "cookie", "if", "field", "is", "null", "set", "cookie", "based", "on", "user", "data", "other", "wise", "set", "cookie", "based", "on", "fields" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomcookiemanager.php#L33-L62
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.getCustomers
public function getCustomers(Get\RequestData $requestData = null) { $request = new Get\Request($requestData); $apiResponse = $this->sendRequest($request, Get\ApiResponse::class); /** @var Get\Response $response */ $response = $apiResponse->getResponse(); foreach ($response->getCustomers() as $customer) { if ($customer->getBirthday() instanceof \DateTime) { $customer->getBirthday()->setTime(0, 0, 0); } } return $apiResponse; }
php
public function getCustomers(Get\RequestData $requestData = null) { $request = new Get\Request($requestData); $apiResponse = $this->sendRequest($request, Get\ApiResponse::class); /** @var Get\Response $response */ $response = $apiResponse->getResponse(); foreach ($response->getCustomers() as $customer) { if ($customer->getBirthday() instanceof \DateTime) { $customer->getBirthday()->setTime(0, 0, 0); } } return $apiResponse; }
[ "public", "function", "getCustomers", "(", "Get", "\\", "RequestData", "$", "requestData", "=", "null", ")", "{", "$", "request", "=", "new", "Get", "\\", "Request", "(", "$", "requestData", ")", ";", "$", "apiResponse", "=", "$", "this", "->", "sendRequest", "(", "$", "request", ",", "Get", "\\", "ApiResponse", "::", "class", ")", ";", "/** @var Get\\Response $response */", "$", "response", "=", "$", "apiResponse", "->", "getResponse", "(", ")", ";", "foreach", "(", "$", "response", "->", "getCustomers", "(", ")", "as", "$", "customer", ")", "{", "if", "(", "$", "customer", "->", "getBirthday", "(", ")", "instanceof", "\\", "DateTime", ")", "{", "$", "customer", "->", "getBirthday", "(", ")", "->", "setTime", "(", "0", ",", "0", ",", "0", ")", ";", "}", "}", "return", "$", "apiResponse", ";", "}" ]
Get the customers. @param Get\RequestData|null $requestData The request data. @return Get\ApiResponse
[ "Get", "the", "customers", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L19-L34
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.getCustomer
public function getCustomer($customerId) { $requestData = new Get\RequestData(); $requestData->setCustomerId($customerId); $customers = $this->getCustomers($requestData)->getResponse()->getCustomers(); return isset($customers[0]) ? $customers[0] : null; }
php
public function getCustomer($customerId) { $requestData = new Get\RequestData(); $requestData->setCustomerId($customerId); $customers = $this->getCustomers($requestData)->getResponse()->getCustomers(); return isset($customers[0]) ? $customers[0] : null; }
[ "public", "function", "getCustomer", "(", "$", "customerId", ")", "{", "$", "requestData", "=", "new", "Get", "\\", "RequestData", "(", ")", ";", "$", "requestData", "->", "setCustomerId", "(", "$", "customerId", ")", ";", "$", "customers", "=", "$", "this", "->", "getCustomers", "(", "$", "requestData", ")", "->", "getResponse", "(", ")", "->", "getCustomers", "(", ")", ";", "return", "isset", "(", "$", "customers", "[", "0", "]", ")", "?", "$", "customers", "[", "0", "]", ":", "null", ";", "}" ]
Get one customer by ID. @param integer $customerId The customer ID. @return Customer|null
[ "Get", "one", "customer", "by", "ID", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L42-L50
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.getCustomerByExternalUid
public function getCustomerByExternalUid($customerExternalUid) { $requestData = new Get\RequestData(); $requestData->setCustomerExternalUid($customerExternalUid); $customers = $this->getCustomers($requestData)->getResponse()->getCustomers(); return isset($customers[0]) ? $customers[0] : null; }
php
public function getCustomerByExternalUid($customerExternalUid) { $requestData = new Get\RequestData(); $requestData->setCustomerExternalUid($customerExternalUid); $customers = $this->getCustomers($requestData)->getResponse()->getCustomers(); return isset($customers[0]) ? $customers[0] : null; }
[ "public", "function", "getCustomerByExternalUid", "(", "$", "customerExternalUid", ")", "{", "$", "requestData", "=", "new", "Get", "\\", "RequestData", "(", ")", ";", "$", "requestData", "->", "setCustomerExternalUid", "(", "$", "customerExternalUid", ")", ";", "$", "customers", "=", "$", "this", "->", "getCustomers", "(", "$", "requestData", ")", "->", "getResponse", "(", ")", "->", "getCustomers", "(", ")", ";", "return", "isset", "(", "$", "customers", "[", "0", "]", ")", "?", "$", "customers", "[", "0", "]", ":", "null", ";", "}" ]
Get once customer by the external ID. @param string $customerExternalUid The external customer ID. @return Customer|null
[ "Get", "once", "customer", "by", "the", "external", "ID", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L58-L66
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.updateCustomer
public function updateCustomer(Update\RequestData $requestData) { $request = new Update\Request($requestData); return $this->sendRequest($request, Update\ApiResponse::class); }
php
public function updateCustomer(Update\RequestData $requestData) { $request = new Update\Request($requestData); return $this->sendRequest($request, Update\ApiResponse::class); }
[ "public", "function", "updateCustomer", "(", "Update", "\\", "RequestData", "$", "requestData", ")", "{", "$", "request", "=", "new", "Update", "\\", "Request", "(", "$", "requestData", ")", ";", "return", "$", "this", "->", "sendRequest", "(", "$", "request", ",", "Update", "\\", "ApiResponse", "::", "class", ")", ";", "}" ]
Update a customer. @param Update\RequestData $requestData The data to send. @return Update\ApiResponse
[ "Update", "a", "customer", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L74-L79
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.createCustomer
public function createCustomer(Customer $customer) { $request = new Create\Request($customer); return $this->sendRequest($request, Create\ApiResponse::class); }
php
public function createCustomer(Customer $customer) { $request = new Create\Request($customer); return $this->sendRequest($request, Create\ApiResponse::class); }
[ "public", "function", "createCustomer", "(", "Customer", "$", "customer", ")", "{", "$", "request", "=", "new", "Create", "\\", "Request", "(", "$", "customer", ")", ";", "return", "$", "this", "->", "sendRequest", "(", "$", "request", ",", "Create", "\\", "ApiResponse", "::", "class", ")", ";", "}" ]
Create a customer. @param Customer $customer The customer data to send. @return Create\ApiResponse
[ "Create", "a", "customer", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L87-L92
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.deleteCustomer
public function deleteCustomer($customerId) { $requestData = new Delete\RequestData($customerId); $request = new Delete\Request($requestData); return $this->sendRequest($request, Delete\ApiResponse::class); }
php
public function deleteCustomer($customerId) { $requestData = new Delete\RequestData($customerId); $request = new Delete\Request($requestData); return $this->sendRequest($request, Delete\ApiResponse::class); }
[ "public", "function", "deleteCustomer", "(", "$", "customerId", ")", "{", "$", "requestData", "=", "new", "Delete", "\\", "RequestData", "(", "$", "customerId", ")", ";", "$", "request", "=", "new", "Delete", "\\", "Request", "(", "$", "requestData", ")", ";", "return", "$", "this", "->", "sendRequest", "(", "$", "request", ",", "Delete", "\\", "ApiResponse", "::", "class", ")", ";", "}" ]
Delete a customer. @param integer $customerId The customer ID to delete. @return Delete\ApiResponse
[ "Delete", "a", "customer", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L100-L106
Speicher210/monsum-api
src/Service/Customer/CustomerService.php
CustomerService.addCredits
public function addCredits($customerId, $amount) { $requestData = new AddCredits\RequestData($customerId, $amount); $request = new AddCredits\Request($requestData); return $this->sendRequest($request, AddCredits\ApiResponse::class); }
php
public function addCredits($customerId, $amount) { $requestData = new AddCredits\RequestData($customerId, $amount); $request = new AddCredits\Request($requestData); return $this->sendRequest($request, AddCredits\ApiResponse::class); }
[ "public", "function", "addCredits", "(", "$", "customerId", ",", "$", "amount", ")", "{", "$", "requestData", "=", "new", "AddCredits", "\\", "RequestData", "(", "$", "customerId", ",", "$", "amount", ")", ";", "$", "request", "=", "new", "AddCredits", "\\", "Request", "(", "$", "requestData", ")", ";", "return", "$", "this", "->", "sendRequest", "(", "$", "request", ",", "AddCredits", "\\", "ApiResponse", "::", "class", ")", ";", "}" ]
Add credits to a customer. @param integer $customerId The customer ID. @param float $amount The amount of credit to add. @return AddCredits\ApiResponse
[ "Add", "credits", "to", "a", "customer", "." ]
train
https://github.com/Speicher210/monsum-api/blob/4611a048097de5d2b0efe9d4426779c783c0af4d/src/Service/Customer/CustomerService.php#L115-L121
xiewulong/yii2-fileupload
oss/libs/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcher.php
EventDispatcher.dispatch
public function dispatch($eventName, Event $event = null) { if (null === $event) { $event = new Event(); } $event->setDispatcher($this); $event->setName($eventName); if (!isset($this->listeners[$eventName])) { return $event; } $this->doDispatch($this->getListeners($eventName), $eventName, $event); return $event; }
php
public function dispatch($eventName, Event $event = null) { if (null === $event) { $event = new Event(); } $event->setDispatcher($this); $event->setName($eventName); if (!isset($this->listeners[$eventName])) { return $event; } $this->doDispatch($this->getListeners($eventName), $eventName, $event); return $event; }
[ "public", "function", "dispatch", "(", "$", "eventName", ",", "Event", "$", "event", "=", "null", ")", "{", "if", "(", "null", "===", "$", "event", ")", "{", "$", "event", "=", "new", "Event", "(", ")", ";", "}", "$", "event", "->", "setDispatcher", "(", "$", "this", ")", ";", "$", "event", "->", "setName", "(", "$", "eventName", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "listeners", "[", "$", "eventName", "]", ")", ")", "{", "return", "$", "event", ";", "}", "$", "this", "->", "doDispatch", "(", "$", "this", "->", "getListeners", "(", "$", "eventName", ")", ",", "$", "eventName", ",", "$", "event", ")", ";", "return", "$", "event", ";", "}" ]
@see EventDispatcherInterface::dispatch @api
[ "@see", "EventDispatcherInterface", "::", "dispatch" ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcher.php#L40-L56
xiewulong/yii2-fileupload
oss/libs/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcher.php
EventDispatcher.sortListeners
private function sortListeners($eventName) { $this->sorted[$eventName] = array(); if (isset($this->listeners[$eventName])) { krsort($this->listeners[$eventName]); $this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]); } }
php
private function sortListeners($eventName) { $this->sorted[$eventName] = array(); if (isset($this->listeners[$eventName])) { krsort($this->listeners[$eventName]); $this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]); } }
[ "private", "function", "sortListeners", "(", "$", "eventName", ")", "{", "$", "this", "->", "sorted", "[", "$", "eventName", "]", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "listeners", "[", "$", "eventName", "]", ")", ")", "{", "krsort", "(", "$", "this", "->", "listeners", "[", "$", "eventName", "]", ")", ";", "$", "this", "->", "sorted", "[", "$", "eventName", "]", "=", "call_user_func_array", "(", "'array_merge'", ",", "$", "this", "->", "listeners", "[", "$", "eventName", "]", ")", ";", "}", "}" ]
Sorts the internal list of listeners for the given event by priority. @param string $eventName The name of the event.
[ "Sorts", "the", "internal", "list", "of", "listeners", "for", "the", "given", "event", "by", "priority", "." ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/symfony/event-dispatcher/Symfony/Component/EventDispatcher/EventDispatcher.php#L176-L184
mothership-ec/composer
src/Composer/Package/Archiver/BaseExcludeFilter.php
BaseExcludeFilter.parseLines
protected function parseLines(array $lines, $lineParser) { return array_filter( array_map( function ($line) use ($lineParser) { $line = trim($line); if (!$line || 0 === strpos($line, '#')) { return; } return call_user_func($lineParser, $line); }, $lines ), function ($pattern) { return $pattern !== null; } ); }
php
protected function parseLines(array $lines, $lineParser) { return array_filter( array_map( function ($line) use ($lineParser) { $line = trim($line); if (!$line || 0 === strpos($line, '#')) { return; } return call_user_func($lineParser, $line); }, $lines ), function ($pattern) { return $pattern !== null; } ); }
[ "protected", "function", "parseLines", "(", "array", "$", "lines", ",", "$", "lineParser", ")", "{", "return", "array_filter", "(", "array_map", "(", "function", "(", "$", "line", ")", "use", "(", "$", "lineParser", ")", "{", "$", "line", "=", "trim", "(", "$", "line", ")", ";", "if", "(", "!", "$", "line", "||", "0", "===", "strpos", "(", "$", "line", ",", "'#'", ")", ")", "{", "return", ";", "}", "return", "call_user_func", "(", "$", "lineParser", ",", "$", "line", ")", ";", "}", ",", "$", "lines", ")", ",", "function", "(", "$", "pattern", ")", "{", "return", "$", "pattern", "!==", "null", ";", "}", ")", ";", "}" ]
Processes a file containing exclude rules of different formats per line @param array $lines A set of lines to be parsed @param callback $lineParser The parser to be used on each line @return array Exclude patterns to be used in filter()
[ "Processes", "a", "file", "containing", "exclude", "rules", "of", "different", "formats", "per", "line" ]
train
https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Package/Archiver/BaseExcludeFilter.php#L78-L97
zhouyl/mellivora
Mellivora/Console/Command.php
Command.alert
public function alert($string) { $this->comment(str_repeat('*', strlen($string) + 12)); $this->comment('* ' . $string . ' *'); $this->comment(str_repeat('*', strlen($string) + 12)); $this->output->writeln(''); }
php
public function alert($string) { $this->comment(str_repeat('*', strlen($string) + 12)); $this->comment('* ' . $string . ' *'); $this->comment(str_repeat('*', strlen($string) + 12)); $this->output->writeln(''); }
[ "public", "function", "alert", "(", "$", "string", ")", "{", "$", "this", "->", "comment", "(", "str_repeat", "(", "'*'", ",", "strlen", "(", "$", "string", ")", "+", "12", ")", ")", ";", "$", "this", "->", "comment", "(", "'* '", ".", "$", "string", ".", "' *'", ")", ";", "$", "this", "->", "comment", "(", "str_repeat", "(", "'*'", ",", "strlen", "(", "$", "string", ")", "+", "12", ")", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "''", ")", ";", "}" ]
Write a string in an alert box. @param string $string @return void
[ "Write", "a", "string", "in", "an", "alert", "box", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Console/Command.php#L522-L529
mikelgoig/nova-spotify-auth-tool
src/Http/Controllers/SpotifyAuthToolController.php
SpotifyAuthToolController.auth
public function auth() { $spotify = app() ->make('SpotifyWrapper', [ 'callback' => '/nova-vendor/nova-spotify-auth-tool/auth', 'scope' => [], 'show_dialog' => true, ]) ->requestAccessToken(); $spotify->api->setAccessToken($spotify->session->getAccessToken()); Spotify::updateOrCreate( ['key' => 'user_id'], ['value' => $spotify->api->me()->id] ); Spotify::updateOrCreate( ['key' => 'refresh_token'], ['value' => $spotify->session->getRefreshToken()] ); return redirect('nova/nova-spotify-auth-tool'); }
php
public function auth() { $spotify = app() ->make('SpotifyWrapper', [ 'callback' => '/nova-vendor/nova-spotify-auth-tool/auth', 'scope' => [], 'show_dialog' => true, ]) ->requestAccessToken(); $spotify->api->setAccessToken($spotify->session->getAccessToken()); Spotify::updateOrCreate( ['key' => 'user_id'], ['value' => $spotify->api->me()->id] ); Spotify::updateOrCreate( ['key' => 'refresh_token'], ['value' => $spotify->session->getRefreshToken()] ); return redirect('nova/nova-spotify-auth-tool'); }
[ "public", "function", "auth", "(", ")", "{", "$", "spotify", "=", "app", "(", ")", "->", "make", "(", "'SpotifyWrapper'", ",", "[", "'callback'", "=>", "'/nova-vendor/nova-spotify-auth-tool/auth'", ",", "'scope'", "=>", "[", "]", ",", "'show_dialog'", "=>", "true", ",", "]", ")", "->", "requestAccessToken", "(", ")", ";", "$", "spotify", "->", "api", "->", "setAccessToken", "(", "$", "spotify", "->", "session", "->", "getAccessToken", "(", ")", ")", ";", "Spotify", "::", "updateOrCreate", "(", "[", "'key'", "=>", "'user_id'", "]", ",", "[", "'value'", "=>", "$", "spotify", "->", "api", "->", "me", "(", ")", "->", "id", "]", ")", ";", "Spotify", "::", "updateOrCreate", "(", "[", "'key'", "=>", "'refresh_token'", "]", ",", "[", "'value'", "=>", "$", "spotify", "->", "session", "->", "getRefreshToken", "(", ")", "]", ")", ";", "return", "redirect", "(", "'nova/nova-spotify-auth-tool'", ")", ";", "}" ]
Spotify authentication. @return mixed
[ "Spotify", "authentication", "." ]
train
https://github.com/mikelgoig/nova-spotify-auth-tool/blob/a5351c386206c45f77fe6ae833cdac51f2a030f4/src/Http/Controllers/SpotifyAuthToolController.php#L21-L44
InactiveProjects/limoncello-illuminate
app/Database/Migrations/MigratePasswordResets.php
MigratePasswordResets.apply
public function apply() { Schema::create('password_resets', function (Blueprint $table) { /** @noinspection PhpUndefinedMethodInspection */ $table->string('email')->index(); /** @noinspection PhpUndefinedMethodInspection */ $table->string('token')->index(); $table->timestamp('created_at'); }); }
php
public function apply() { Schema::create('password_resets', function (Blueprint $table) { /** @noinspection PhpUndefinedMethodInspection */ $table->string('email')->index(); /** @noinspection PhpUndefinedMethodInspection */ $table->string('token')->index(); $table->timestamp('created_at'); }); }
[ "public", "function", "apply", "(", ")", "{", "Schema", "::", "create", "(", "'password_resets'", ",", "function", "(", "Blueprint", "$", "table", ")", "{", "/** @noinspection PhpUndefinedMethodInspection */", "$", "table", "->", "string", "(", "'email'", ")", "->", "index", "(", ")", ";", "/** @noinspection PhpUndefinedMethodInspection */", "$", "table", "->", "string", "(", "'token'", ")", "->", "index", "(", ")", ";", "$", "table", "->", "timestamp", "(", "'created_at'", ")", ";", "}", ")", ";", "}" ]
@inheritdoc @SuppressWarnings(PHPMD.StaticAccess)
[ "@inheritdoc" ]
train
https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Database/Migrations/MigratePasswordResets.php#L15-L24
flint/Antenna
src/Security/UsernamePasswordAuthenticator.php
UsernamePasswordAuthenticator.createToken
public function createToken(Request $request, $providerKey) { if (!$request->isMethod('POST')) { throw new MethodNotAllowedHttpException(['POST']); } if ($request->getContentType() != 'json') { throw new UnsupportedMediaTypeHttpException('Content-Type must be "application/json".'); } $body = json_decode($request->getContent(), true); list($username, $password) = array_values($body + ['username' => null, 'password' => null]); return new UsernamePasswordToken($username, $password, $providerKey); }
php
public function createToken(Request $request, $providerKey) { if (!$request->isMethod('POST')) { throw new MethodNotAllowedHttpException(['POST']); } if ($request->getContentType() != 'json') { throw new UnsupportedMediaTypeHttpException('Content-Type must be "application/json".'); } $body = json_decode($request->getContent(), true); list($username, $password) = array_values($body + ['username' => null, 'password' => null]); return new UsernamePasswordToken($username, $password, $providerKey); }
[ "public", "function", "createToken", "(", "Request", "$", "request", ",", "$", "providerKey", ")", "{", "if", "(", "!", "$", "request", "->", "isMethod", "(", "'POST'", ")", ")", "{", "throw", "new", "MethodNotAllowedHttpException", "(", "[", "'POST'", "]", ")", ";", "}", "if", "(", "$", "request", "->", "getContentType", "(", ")", "!=", "'json'", ")", "{", "throw", "new", "UnsupportedMediaTypeHttpException", "(", "'Content-Type must be \"application/json\".'", ")", ";", "}", "$", "body", "=", "json_decode", "(", "$", "request", "->", "getContent", "(", ")", ",", "true", ")", ";", "list", "(", "$", "username", ",", "$", "password", ")", "=", "array_values", "(", "$", "body", "+", "[", "'username'", "=>", "null", ",", "'password'", "=>", "null", "]", ")", ";", "return", "new", "UsernamePasswordToken", "(", "$", "username", ",", "$", "password", ",", "$", "providerKey", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/flint/Antenna/blob/282bafa99bf75bade965b00ef43fc421674048a5/src/Security/UsernamePasswordAuthenticator.php#L73-L88
flint/Antenna
src/Security/UsernamePasswordAuthenticator.php
UsernamePasswordAuthenticator.supportsToken
public function supportsToken(TokenInterface $token, $providerKey) { if (!$token instanceof UsernamePasswordToken) { return false; } return $providerKey == $token->getProviderKey(); }
php
public function supportsToken(TokenInterface $token, $providerKey) { if (!$token instanceof UsernamePasswordToken) { return false; } return $providerKey == $token->getProviderKey(); }
[ "public", "function", "supportsToken", "(", "TokenInterface", "$", "token", ",", "$", "providerKey", ")", "{", "if", "(", "!", "$", "token", "instanceof", "UsernamePasswordToken", ")", "{", "return", "false", ";", "}", "return", "$", "providerKey", "==", "$", "token", "->", "getProviderKey", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/flint/Antenna/blob/282bafa99bf75bade965b00ef43fc421674048a5/src/Security/UsernamePasswordAuthenticator.php#L108-L115
webdevvie/pheanstalk-task-queue-bundle
Command/Tender/ChildProcessContainer.php
ChildProcessContainer.checkHealth
public function checkHealth() { if (!$this->process->isRunning()) { if ($this->status == self::STATUS_CLEANINGUP || $this->status == self::STATUS_CLEANEDUP) { //okay so we're ready to stop! $this->status = self::STATUS_DEAD; return true; } elseif ($this->status == ChildProcessContainer::STATUS_SLEEPY) { //okay so we're ready to stop! $this->status = self::STATUS_DEAD; return true; } $this->status = self::STATUS_DEAD; return false; } else { return true; } }
php
public function checkHealth() { if (!$this->process->isRunning()) { if ($this->status == self::STATUS_CLEANINGUP || $this->status == self::STATUS_CLEANEDUP) { //okay so we're ready to stop! $this->status = self::STATUS_DEAD; return true; } elseif ($this->status == ChildProcessContainer::STATUS_SLEEPY) { //okay so we're ready to stop! $this->status = self::STATUS_DEAD; return true; } $this->status = self::STATUS_DEAD; return false; } else { return true; } }
[ "public", "function", "checkHealth", "(", ")", "{", "if", "(", "!", "$", "this", "->", "process", "->", "isRunning", "(", ")", ")", "{", "if", "(", "$", "this", "->", "status", "==", "self", "::", "STATUS_CLEANINGUP", "||", "$", "this", "->", "status", "==", "self", "::", "STATUS_CLEANEDUP", ")", "{", "//okay so we're ready to stop!", "$", "this", "->", "status", "=", "self", "::", "STATUS_DEAD", ";", "return", "true", ";", "}", "elseif", "(", "$", "this", "->", "status", "==", "ChildProcessContainer", "::", "STATUS_SLEEPY", ")", "{", "//okay so we're ready to stop!", "$", "this", "->", "status", "=", "self", "::", "STATUS_DEAD", ";", "return", "true", ";", "}", "$", "this", "->", "status", "=", "self", "::", "STATUS_DEAD", ";", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Checks the health of this child and returns true if healthy otherwise marks it for cleanup @return boolean
[ "Checks", "the", "health", "of", "this", "child", "and", "returns", "true", "if", "healthy", "otherwise", "marks", "it", "for", "cleanup" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Tender/ChildProcessContainer.php#L138-L156
webdevvie/pheanstalk-task-queue-bundle
Command/Tender/ChildProcessContainer.php
ChildProcessContainer.cleanUp
public function cleanUp() { $this->status = self::STATUS_CLEANINGUP; if ($this->process->isRunning()) { $this->sendTERMSignal(); } else { $this->status = self::STATUS_CLEANEDUP; } }
php
public function cleanUp() { $this->status = self::STATUS_CLEANINGUP; if ($this->process->isRunning()) { $this->sendTERMSignal(); } else { $this->status = self::STATUS_CLEANEDUP; } }
[ "public", "function", "cleanUp", "(", ")", "{", "$", "this", "->", "status", "=", "self", "::", "STATUS_CLEANINGUP", ";", "if", "(", "$", "this", "->", "process", "->", "isRunning", "(", ")", ")", "{", "$", "this", "->", "sendTERMSignal", "(", ")", ";", "}", "else", "{", "$", "this", "->", "status", "=", "self", "::", "STATUS_CLEANEDUP", ";", "}", "}" ]
Cleans up a process @return void
[ "Cleans", "up", "a", "process" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Tender/ChildProcessContainer.php#L173-L182
webdevvie/pheanstalk-task-queue-bundle
Command/Tender/ChildProcessContainer.php
ChildProcessContainer.processOutput
public function processOutput($childName) { $output = $this->outputBuffer . $this->process->getIncrementalOutput(); $errorOutput = $this->errorOutputBuffer . $this->process->getIncrementalErrorOutput(); $outputLines = explode("\n", $output); $errorOutputLines = explode("\n", $errorOutput); if (count($outputLines) > 0) { $lastItem = array_pop($outputLines); $this->outputBuffer = $lastItem; $this->bufferLength += implode("\n", $outputLines); foreach ($outputLines as $line) { if (strstr($line, "[[CHILD::BUSY]]")) { $this->parent->verboseOutput('<info>' . $childName . ' BUSY</info>'); $this->status = ChildProcessContainer::STATUS_BUSY; } elseif (strstr($line, "[[CHILD::READY]]")) { $this->parent->verboseOutput('<info>' . $childName . ' READY</info>'); if ($this->status != ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY) { $this->status = ChildProcessContainer::STATUS_READY; } else { $this->status = ChildProcessContainer::STATUS_SLEEPY; } } elseif (strlen($line) > 0) { $this->parent->verboseOutput('<info>OUTPUT ' . $childName . ':</info>' . $line); } } } if (count($errorOutputLines) > 0) { $lastItemError = array_pop($errorOutputLines); $this->errorOutputBuffer = $lastItemError; $knownErrorOutput = implode("\n", $errorOutputLines); $this->bufferLength += strlen($knownErrorOutput); } }
php
public function processOutput($childName) { $output = $this->outputBuffer . $this->process->getIncrementalOutput(); $errorOutput = $this->errorOutputBuffer . $this->process->getIncrementalErrorOutput(); $outputLines = explode("\n", $output); $errorOutputLines = explode("\n", $errorOutput); if (count($outputLines) > 0) { $lastItem = array_pop($outputLines); $this->outputBuffer = $lastItem; $this->bufferLength += implode("\n", $outputLines); foreach ($outputLines as $line) { if (strstr($line, "[[CHILD::BUSY]]")) { $this->parent->verboseOutput('<info>' . $childName . ' BUSY</info>'); $this->status = ChildProcessContainer::STATUS_BUSY; } elseif (strstr($line, "[[CHILD::READY]]")) { $this->parent->verboseOutput('<info>' . $childName . ' READY</info>'); if ($this->status != ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY) { $this->status = ChildProcessContainer::STATUS_READY; } else { $this->status = ChildProcessContainer::STATUS_SLEEPY; } } elseif (strlen($line) > 0) { $this->parent->verboseOutput('<info>OUTPUT ' . $childName . ':</info>' . $line); } } } if (count($errorOutputLines) > 0) { $lastItemError = array_pop($errorOutputLines); $this->errorOutputBuffer = $lastItemError; $knownErrorOutput = implode("\n", $errorOutputLines); $this->bufferLength += strlen($knownErrorOutput); } }
[ "public", "function", "processOutput", "(", "$", "childName", ")", "{", "$", "output", "=", "$", "this", "->", "outputBuffer", ".", "$", "this", "->", "process", "->", "getIncrementalOutput", "(", ")", ";", "$", "errorOutput", "=", "$", "this", "->", "errorOutputBuffer", ".", "$", "this", "->", "process", "->", "getIncrementalErrorOutput", "(", ")", ";", "$", "outputLines", "=", "explode", "(", "\"\\n\"", ",", "$", "output", ")", ";", "$", "errorOutputLines", "=", "explode", "(", "\"\\n\"", ",", "$", "errorOutput", ")", ";", "if", "(", "count", "(", "$", "outputLines", ")", ">", "0", ")", "{", "$", "lastItem", "=", "array_pop", "(", "$", "outputLines", ")", ";", "$", "this", "->", "outputBuffer", "=", "$", "lastItem", ";", "$", "this", "->", "bufferLength", "+=", "implode", "(", "\"\\n\"", ",", "$", "outputLines", ")", ";", "foreach", "(", "$", "outputLines", "as", "$", "line", ")", "{", "if", "(", "strstr", "(", "$", "line", ",", "\"[[CHILD::BUSY]]\"", ")", ")", "{", "$", "this", "->", "parent", "->", "verboseOutput", "(", "'<info>'", ".", "$", "childName", ".", "' BUSY</info>'", ")", ";", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_BUSY", ";", "}", "elseif", "(", "strstr", "(", "$", "line", ",", "\"[[CHILD::READY]]\"", ")", ")", "{", "$", "this", "->", "parent", "->", "verboseOutput", "(", "'<info>'", ".", "$", "childName", ".", "' READY</info>'", ")", ";", "if", "(", "$", "this", "->", "status", "!=", "ChildProcessContainer", "::", "STATUS_BUSY_BUT_SLEEPY", ")", "{", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_READY", ";", "}", "else", "{", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_SLEEPY", ";", "}", "}", "elseif", "(", "strlen", "(", "$", "line", ")", ">", "0", ")", "{", "$", "this", "->", "parent", "->", "verboseOutput", "(", "'<info>OUTPUT '", ".", "$", "childName", ".", "':</info>'", ".", "$", "line", ")", ";", "}", "}", "}", "if", "(", "count", "(", "$", "errorOutputLines", ")", ">", "0", ")", "{", "$", "lastItemError", "=", "array_pop", "(", "$", "errorOutputLines", ")", ";", "$", "this", "->", "errorOutputBuffer", "=", "$", "lastItemError", ";", "$", "knownErrorOutput", "=", "implode", "(", "\"\\n\"", ",", "$", "errorOutputLines", ")", ";", "$", "this", "->", "bufferLength", "+=", "strlen", "(", "$", "knownErrorOutput", ")", ";", "}", "}" ]
Looks into and processes the child's output @param string $childName @return void
[ "Looks", "into", "and", "processes", "the", "child", "s", "output" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Tender/ChildProcessContainer.php#L211-L243
webdevvie/pheanstalk-task-queue-bundle
Command/Tender/ChildProcessContainer.php
ChildProcessContainer.start
public function start() { $cmd = 'app/console ' . $this->workerCommand; if ($this->tube != '') { $cmd .= ' --use-tube=' . escapeshellarg($this->tube); } if ($this->parent->isVerbose()) { $cmd .= ' -vvvv'; } $this->startTime = time(); $this->parent->verboseOutput('<info>Starting:</info>' . $cmd); $this->process = new Process('exec ' . $cmd, $this->consolePath, null, null, null); $this->process->start(); if ($this->process->isRunning()) { $this->status = ChildProcessContainer::STATUS_ALIVE; } else { $this->status = ChildProcessContainer::STATUS_DEAD; } }
php
public function start() { $cmd = 'app/console ' . $this->workerCommand; if ($this->tube != '') { $cmd .= ' --use-tube=' . escapeshellarg($this->tube); } if ($this->parent->isVerbose()) { $cmd .= ' -vvvv'; } $this->startTime = time(); $this->parent->verboseOutput('<info>Starting:</info>' . $cmd); $this->process = new Process('exec ' . $cmd, $this->consolePath, null, null, null); $this->process->start(); if ($this->process->isRunning()) { $this->status = ChildProcessContainer::STATUS_ALIVE; } else { $this->status = ChildProcessContainer::STATUS_DEAD; } }
[ "public", "function", "start", "(", ")", "{", "$", "cmd", "=", "'app/console '", ".", "$", "this", "->", "workerCommand", ";", "if", "(", "$", "this", "->", "tube", "!=", "''", ")", "{", "$", "cmd", ".=", "' --use-tube='", ".", "escapeshellarg", "(", "$", "this", "->", "tube", ")", ";", "}", "if", "(", "$", "this", "->", "parent", "->", "isVerbose", "(", ")", ")", "{", "$", "cmd", ".=", "' -vvvv'", ";", "}", "$", "this", "->", "startTime", "=", "time", "(", ")", ";", "$", "this", "->", "parent", "->", "verboseOutput", "(", "'<info>Starting:</info>'", ".", "$", "cmd", ")", ";", "$", "this", "->", "process", "=", "new", "Process", "(", "'exec '", ".", "$", "cmd", ",", "$", "this", "->", "consolePath", ",", "null", ",", "null", ",", "null", ")", ";", "$", "this", "->", "process", "->", "start", "(", ")", ";", "if", "(", "$", "this", "->", "process", "->", "isRunning", "(", ")", ")", "{", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_ALIVE", ";", "}", "else", "{", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_DEAD", ";", "}", "}" ]
Starts the child process @return void
[ "Starts", "the", "child", "process" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Tender/ChildProcessContainer.php#L250-L268
webdevvie/pheanstalk-task-queue-bundle
Command/Tender/ChildProcessContainer.php
ChildProcessContainer.sendTERMSignal
private function sendTERMSignal() { if (!$this->hasReceivedHUP) { $this->hasReceivedHUP = true; try { $this->process->signal(SIGTERM); } catch (\Symfony\Component\Process\Exception\LogicException $e) { //In case the process ends between checking and actually sending the signal } } }
php
private function sendTERMSignal() { if (!$this->hasReceivedHUP) { $this->hasReceivedHUP = true; try { $this->process->signal(SIGTERM); } catch (\Symfony\Component\Process\Exception\LogicException $e) { //In case the process ends between checking and actually sending the signal } } }
[ "private", "function", "sendTERMSignal", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasReceivedHUP", ")", "{", "$", "this", "->", "hasReceivedHUP", "=", "true", ";", "try", "{", "$", "this", "->", "process", "->", "signal", "(", "SIGTERM", ")", ";", "}", "catch", "(", "\\", "Symfony", "\\", "Component", "\\", "Process", "\\", "Exception", "\\", "LogicException", "$", "e", ")", "{", "//In case the process ends between checking and actually sending the signal", "}", "}", "}" ]
Sends a signal to the process, this method prevents the signal from being sent twice @return void
[ "Sends", "a", "signal", "to", "the", "process", "this", "method", "prevents", "the", "signal", "from", "being", "sent", "twice" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Tender/ChildProcessContainer.php#L286-L296
webdevvie/pheanstalk-task-queue-bundle
Command/Tender/ChildProcessContainer.php
ChildProcessContainer.getReadyForBed
public function getReadyForBed() { $busyStatusses = array(ChildProcessContainer::STATUS_SLEEPY, ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY ); if (in_array($this->status, $busyStatusses)) { //ready for bed return; } if($this->status == ChildProcessContainer::STATUS_DEAD) { // do nothing } else if ($this->status == ChildProcessContainer::STATUS_BUSY) { $this->status = ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY; } else { $this->status = ChildProcessContainer::STATUS_SLEEPY; } if ($this->process->isRunning()) { $this->sendTERMSignal(); } }
php
public function getReadyForBed() { $busyStatusses = array(ChildProcessContainer::STATUS_SLEEPY, ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY ); if (in_array($this->status, $busyStatusses)) { //ready for bed return; } if($this->status == ChildProcessContainer::STATUS_DEAD) { // do nothing } else if ($this->status == ChildProcessContainer::STATUS_BUSY) { $this->status = ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY; } else { $this->status = ChildProcessContainer::STATUS_SLEEPY; } if ($this->process->isRunning()) { $this->sendTERMSignal(); } }
[ "public", "function", "getReadyForBed", "(", ")", "{", "$", "busyStatusses", "=", "array", "(", "ChildProcessContainer", "::", "STATUS_SLEEPY", ",", "ChildProcessContainer", "::", "STATUS_BUSY_BUT_SLEEPY", ")", ";", "if", "(", "in_array", "(", "$", "this", "->", "status", ",", "$", "busyStatusses", ")", ")", "{", "//ready for bed", "return", ";", "}", "if", "(", "$", "this", "->", "status", "==", "ChildProcessContainer", "::", "STATUS_DEAD", ")", "{", "// do nothing", "}", "else", "if", "(", "$", "this", "->", "status", "==", "ChildProcessContainer", "::", "STATUS_BUSY", ")", "{", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_BUSY_BUT_SLEEPY", ";", "}", "else", "{", "$", "this", "->", "status", "=", "ChildProcessContainer", "::", "STATUS_SLEEPY", ";", "}", "if", "(", "$", "this", "->", "process", "->", "isRunning", "(", ")", ")", "{", "$", "this", "->", "sendTERMSignal", "(", ")", ";", "}", "}" ]
Tells the child to not pick up any more work and go to bed @return void
[ "Tells", "the", "child", "to", "not", "pick", "up", "any", "more", "work", "and", "go", "to", "bed" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Tender/ChildProcessContainer.php#L303-L324
mridang/magazine
lib/magento/Target.php
Mage_Connect_Package_Target._getTargetMap
protected function _getTargetMap() { if (is_null($this->_targetMap)) { $this->_targetMap = array(); $this->_targetMap[] = array('name'=>"magelocal" ,'label'=>"Magento Local module file" , 'uri'=>"./app/code/local"); $this->_targetMap[] = array('name'=>"magecommunity" ,'label'=>"Magento Community module file" , 'uri'=>"./app/code/community"); $this->_targetMap[] = array('name'=>"magecore" ,'label'=>"Magento Core team module file" , 'uri'=>"./app/code/core"); $this->_targetMap[] = array('name'=>"magedesign" ,'label'=>"Magento User Interface (layouts, templates)" , 'uri'=>"./app/design"); $this->_targetMap[] = array('name'=>"mageetc" ,'label'=>"Magento Global Configuration" , 'uri'=>"./app/etc"); $this->_targetMap[] = array('name'=>"magelib" ,'label'=>"Magento PHP Library file" , 'uri'=>"./lib"); $this->_targetMap[] = array('name'=>"magelocale" ,'label'=>"Magento Locale language file" , 'uri'=>"./app/locale"); $this->_targetMap[] = array('name'=>"magemedia" ,'label'=>"Magento Media library" , 'uri'=>"./media"); $this->_targetMap[] = array('name'=>"mageskin" ,'label'=>"Magento Theme Skin (Images, CSS, JS)" , 'uri'=>"./skin"); $this->_targetMap[] = array('name'=>"mageweb" ,'label'=>"Magento Other web accessible file" , 'uri'=>"."); $this->_targetMap[] = array('name'=>"magetest" ,'label'=>"Magento PHPUnit test" , 'uri'=>"./tests"); $this->_targetMap[] = array('name'=>"mage" ,'label'=>"Magento other" , 'uri'=>"."); } return $this->_targetMap; }
php
protected function _getTargetMap() { if (is_null($this->_targetMap)) { $this->_targetMap = array(); $this->_targetMap[] = array('name'=>"magelocal" ,'label'=>"Magento Local module file" , 'uri'=>"./app/code/local"); $this->_targetMap[] = array('name'=>"magecommunity" ,'label'=>"Magento Community module file" , 'uri'=>"./app/code/community"); $this->_targetMap[] = array('name'=>"magecore" ,'label'=>"Magento Core team module file" , 'uri'=>"./app/code/core"); $this->_targetMap[] = array('name'=>"magedesign" ,'label'=>"Magento User Interface (layouts, templates)" , 'uri'=>"./app/design"); $this->_targetMap[] = array('name'=>"mageetc" ,'label'=>"Magento Global Configuration" , 'uri'=>"./app/etc"); $this->_targetMap[] = array('name'=>"magelib" ,'label'=>"Magento PHP Library file" , 'uri'=>"./lib"); $this->_targetMap[] = array('name'=>"magelocale" ,'label'=>"Magento Locale language file" , 'uri'=>"./app/locale"); $this->_targetMap[] = array('name'=>"magemedia" ,'label'=>"Magento Media library" , 'uri'=>"./media"); $this->_targetMap[] = array('name'=>"mageskin" ,'label'=>"Magento Theme Skin (Images, CSS, JS)" , 'uri'=>"./skin"); $this->_targetMap[] = array('name'=>"mageweb" ,'label'=>"Magento Other web accessible file" , 'uri'=>"."); $this->_targetMap[] = array('name'=>"magetest" ,'label'=>"Magento PHPUnit test" , 'uri'=>"./tests"); $this->_targetMap[] = array('name'=>"mage" ,'label'=>"Magento other" , 'uri'=>"."); } return $this->_targetMap; }
[ "protected", "function", "_getTargetMap", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "_targetMap", ")", ")", "{", "$", "this", "->", "_targetMap", "=", "array", "(", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magelocal\"", ",", "'label'", "=>", "\"Magento Local module file\"", ",", "'uri'", "=>", "\"./app/code/local\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magecommunity\"", ",", "'label'", "=>", "\"Magento Community module file\"", ",", "'uri'", "=>", "\"./app/code/community\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magecore\"", ",", "'label'", "=>", "\"Magento Core team module file\"", ",", "'uri'", "=>", "\"./app/code/core\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magedesign\"", ",", "'label'", "=>", "\"Magento User Interface (layouts, templates)\"", ",", "'uri'", "=>", "\"./app/design\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"mageetc\"", ",", "'label'", "=>", "\"Magento Global Configuration\"", ",", "'uri'", "=>", "\"./app/etc\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magelib\"", ",", "'label'", "=>", "\"Magento PHP Library file\"", ",", "'uri'", "=>", "\"./lib\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magelocale\"", ",", "'label'", "=>", "\"Magento Locale language file\"", ",", "'uri'", "=>", "\"./app/locale\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magemedia\"", ",", "'label'", "=>", "\"Magento Media library\"", ",", "'uri'", "=>", "\"./media\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"mageskin\"", ",", "'label'", "=>", "\"Magento Theme Skin (Images, CSS, JS)\"", ",", "'uri'", "=>", "\"./skin\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"mageweb\"", ",", "'label'", "=>", "\"Magento Other web accessible file\"", ",", "'uri'", "=>", "\".\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"magetest\"", ",", "'label'", "=>", "\"Magento PHPUnit test\"", ",", "'uri'", "=>", "\"./tests\"", ")", ";", "$", "this", "->", "_targetMap", "[", "]", "=", "array", "(", "'name'", "=>", "\"mage\"", ",", "'label'", "=>", "\"Magento other\"", ",", "'uri'", "=>", "\".\"", ")", ";", "}", "return", "$", "this", "->", "_targetMap", ";", "}" ]
Retrieve content from target.xml. @return SimpleXMLElement
[ "Retrieve", "content", "from", "target", ".", "xml", "." ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Target.php#L57-L75
mridang/magazine
lib/magento/Target.php
Mage_Connect_Package_Target.getTargets
public function getTargets() { if (!is_array($this->_targets)) { $this->_targets = array(); if($this->_getTargetMap()) { foreach ($this->_getTargetMap() as $_target) { $this->_targets[$_target['name']] = (string)$_target['uri']; } } } return $this->_targets; }
php
public function getTargets() { if (!is_array($this->_targets)) { $this->_targets = array(); if($this->_getTargetMap()) { foreach ($this->_getTargetMap() as $_target) { $this->_targets[$_target['name']] = (string)$_target['uri']; } } } return $this->_targets; }
[ "public", "function", "getTargets", "(", ")", "{", "if", "(", "!", "is_array", "(", "$", "this", "->", "_targets", ")", ")", "{", "$", "this", "->", "_targets", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "_getTargetMap", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "_getTargetMap", "(", ")", "as", "$", "_target", ")", "{", "$", "this", "->", "_targets", "[", "$", "_target", "[", "'name'", "]", "]", "=", "(", "string", ")", "$", "_target", "[", "'uri'", "]", ";", "}", "}", "}", "return", "$", "this", "->", "_targets", ";", "}" ]
Retrieve targets as associative array from target.xml. @return array
[ "Retrieve", "targets", "as", "associative", "array", "from", "target", ".", "xml", "." ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Target.php#L82-L93
mridang/magazine
lib/magento/Target.php
Mage_Connect_Package_Target.getLabelTargets
public function getLabelTargets() { $targets = array(); foreach ($this->_getTargetMap() as $_target) { $targets[$_target['name']] = $_target['label']; } return $targets; }
php
public function getLabelTargets() { $targets = array(); foreach ($this->_getTargetMap() as $_target) { $targets[$_target['name']] = $_target['label']; } return $targets; }
[ "public", "function", "getLabelTargets", "(", ")", "{", "$", "targets", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_getTargetMap", "(", ")", "as", "$", "_target", ")", "{", "$", "targets", "[", "$", "_target", "[", "'name'", "]", "]", "=", "$", "_target", "[", "'label'", "]", ";", "}", "return", "$", "targets", ";", "}" ]
Retrieve tragets with label for select options. @return array
[ "Retrieve", "tragets", "with", "label", "for", "select", "options", "." ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Target.php#L100-L107
mridang/magazine
lib/magento/Target.php
Mage_Connect_Package_Target.getTargetUri
public function getTargetUri($name) { foreach ($this->getTargets() as $_name=>$_uri) { if ($name == $_name) { return $_uri; } } return ''; }
php
public function getTargetUri($name) { foreach ($this->getTargets() as $_name=>$_uri) { if ($name == $_name) { return $_uri; } } return ''; }
[ "public", "function", "getTargetUri", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "getTargets", "(", ")", "as", "$", "_name", "=>", "$", "_uri", ")", "{", "if", "(", "$", "name", "==", "$", "_name", ")", "{", "return", "$", "_uri", ";", "}", "}", "return", "''", ";", "}" ]
Get uri by target's name. @param string $name @return string
[ "Get", "uri", "by", "target", "s", "name", "." ]
train
https://github.com/mridang/magazine/blob/5b3cfecc472c61fde6af63efe62690a30a267a04/lib/magento/Target.php#L115-L123
nabab/bbn
src/bbn/str.php
str.change_case
public static function change_case($st, $case = 'x'): string { $st = self::cast($st); $case = substr(strtolower((string)$case), 0, 1); switch ( $case ){ case "l": $case = MB_CASE_LOWER; break; case "u": $case = MB_CASE_UPPER; break; default: $case = MB_CASE_TITLE; } if ( !empty($st) ){ $st = mb_convert_case($st, $case); } return $st; }
php
public static function change_case($st, $case = 'x'): string { $st = self::cast($st); $case = substr(strtolower((string)$case), 0, 1); switch ( $case ){ case "l": $case = MB_CASE_LOWER; break; case "u": $case = MB_CASE_UPPER; break; default: $case = MB_CASE_TITLE; } if ( !empty($st) ){ $st = mb_convert_case($st, $case); } return $st; }
[ "public", "static", "function", "change_case", "(", "$", "st", ",", "$", "case", "=", "'x'", ")", ":", "string", "{", "$", "st", "=", "self", "::", "cast", "(", "$", "st", ")", ";", "$", "case", "=", "substr", "(", "strtolower", "(", "(", "string", ")", "$", "case", ")", ",", "0", ",", "1", ")", ";", "switch", "(", "$", "case", ")", "{", "case", "\"l\"", ":", "$", "case", "=", "MB_CASE_LOWER", ";", "break", ";", "case", "\"u\"", ":", "$", "case", "=", "MB_CASE_UPPER", ";", "break", ";", "default", ":", "$", "case", "=", "MB_CASE_TITLE", ";", "}", "if", "(", "!", "empty", "(", "$", "st", ")", ")", "{", "$", "st", "=", "mb_convert_case", "(", "$", "st", ",", "$", "case", ")", ";", "}", "return", "$", "st", ";", "}" ]
Converts the case of a string. ```php $st = 'TEST CASE'; \bbn\x::dump(\bbn\str::change_case($st, 'lower')); // (string) "test case" \bbn\x::dump(\bbn\str::change_case('TEsT Case', 'upper')); // (string) "TEST CASE" \bbn\x::dump(\bbn\str::change_case('test case')); // (string) "Test Case" ``` @param mixed $st The item to convert. @param mixed $case The case to convert to ("lower" or "upper"), default being the title case. @return string
[ "Converts", "the", "case", "of", "a", "string", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L62-L80
nabab/bbn
src/bbn/str.php
str.clean
public static function clean($st, $mode='all'): string { if ( \is_array($st) ){ reset($st); $i = \count($st); if ( trim($st[0]) == '' ){ array_splice($st,0,1); $i--; } if ( $i > 0 ){ if ( trim($st[$i-1]) === '' ){ array_splice($st, $i-1, 1); $i--; } } return $st; } else{ $st = self::cast($st); if ( $mode == 'all' ){ $st = mb_ereg_replace("\n",'\n',$st); $st = mb_ereg_replace("[\t\r]","",$st); $st = mb_ereg_replace('\s{2,}',' ',$st); } else if ( $mode == '2nl' ){ $st = mb_ereg_replace("[\r]","",$st); $st = mb_ereg_replace("\n{2,}","\n",$st); } else if ( $mode == 'html' ){ $st = mb_ereg_replace("[\t\r\n]",'',$st); $st = mb_ereg_replace('\s{2,}',' ',$st); } else if ( $mode == 'code' ){ $st = mb_ereg_replace("!/\*.*?\*/!s",'',$st); // comment_pattern $st = mb_ereg_replace("[\r\n]",'',$st); $st = mb_ereg_replace("\t"," ",$st); $chars = [';','=','+','-','\(','\)','\{','\}','\[','\]',',',':']; foreach ( $chars as $char ){ while ( mb_strpos($st,$char.' ') !== false ){ $st = mb_ereg_replace($char.' ',$char,$st); } while ( mb_strpos($st,' '.$char) !== false ){ $st = mb_ereg_replace(' '.$char,$char,$st); } } $st = mb_ereg_replace('<\?p'.'hp','<?p'.'hp ',$st); $st = mb_ereg_replace('\?'.'>','?'.'> ',$st); $st = mb_ereg_replace('\s{2,}',' ',$st); } return trim($st); } }
php
public static function clean($st, $mode='all'): string { if ( \is_array($st) ){ reset($st); $i = \count($st); if ( trim($st[0]) == '' ){ array_splice($st,0,1); $i--; } if ( $i > 0 ){ if ( trim($st[$i-1]) === '' ){ array_splice($st, $i-1, 1); $i--; } } return $st; } else{ $st = self::cast($st); if ( $mode == 'all' ){ $st = mb_ereg_replace("\n",'\n',$st); $st = mb_ereg_replace("[\t\r]","",$st); $st = mb_ereg_replace('\s{2,}',' ',$st); } else if ( $mode == '2nl' ){ $st = mb_ereg_replace("[\r]","",$st); $st = mb_ereg_replace("\n{2,}","\n",$st); } else if ( $mode == 'html' ){ $st = mb_ereg_replace("[\t\r\n]",'',$st); $st = mb_ereg_replace('\s{2,}',' ',$st); } else if ( $mode == 'code' ){ $st = mb_ereg_replace("!/\*.*?\*/!s",'',$st); // comment_pattern $st = mb_ereg_replace("[\r\n]",'',$st); $st = mb_ereg_replace("\t"," ",$st); $chars = [';','=','+','-','\(','\)','\{','\}','\[','\]',',',':']; foreach ( $chars as $char ){ while ( mb_strpos($st,$char.' ') !== false ){ $st = mb_ereg_replace($char.' ',$char,$st); } while ( mb_strpos($st,' '.$char) !== false ){ $st = mb_ereg_replace(' '.$char,$char,$st); } } $st = mb_ereg_replace('<\?p'.'hp','<?p'.'hp ',$st); $st = mb_ereg_replace('\?'.'>','?'.'> ',$st); $st = mb_ereg_replace('\s{2,}',' ',$st); } return trim($st); } }
[ "public", "static", "function", "clean", "(", "$", "st", ",", "$", "mode", "=", "'all'", ")", ":", "string", "{", "if", "(", "\\", "is_array", "(", "$", "st", ")", ")", "{", "reset", "(", "$", "st", ")", ";", "$", "i", "=", "\\", "count", "(", "$", "st", ")", ";", "if", "(", "trim", "(", "$", "st", "[", "0", "]", ")", "==", "''", ")", "{", "array_splice", "(", "$", "st", ",", "0", ",", "1", ")", ";", "$", "i", "--", ";", "}", "if", "(", "$", "i", ">", "0", ")", "{", "if", "(", "trim", "(", "$", "st", "[", "$", "i", "-", "1", "]", ")", "===", "''", ")", "{", "array_splice", "(", "$", "st", ",", "$", "i", "-", "1", ",", "1", ")", ";", "$", "i", "--", ";", "}", "}", "return", "$", "st", ";", "}", "else", "{", "$", "st", "=", "self", "::", "cast", "(", "$", "st", ")", ";", "if", "(", "$", "mode", "==", "'all'", ")", "{", "$", "st", "=", "mb_ereg_replace", "(", "\"\\n\"", ",", "'\\n'", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "\"[\\t\\r]\"", ",", "\"\"", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "'\\s{2,}'", ",", "' '", ",", "$", "st", ")", ";", "}", "else", "if", "(", "$", "mode", "==", "'2nl'", ")", "{", "$", "st", "=", "mb_ereg_replace", "(", "\"[\\r]\"", ",", "\"\"", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "\"\\n{2,}\"", ",", "\"\\n\"", ",", "$", "st", ")", ";", "}", "else", "if", "(", "$", "mode", "==", "'html'", ")", "{", "$", "st", "=", "mb_ereg_replace", "(", "\"[\\t\\r\\n]\"", ",", "''", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "'\\s{2,}'", ",", "' '", ",", "$", "st", ")", ";", "}", "else", "if", "(", "$", "mode", "==", "'code'", ")", "{", "$", "st", "=", "mb_ereg_replace", "(", "\"!/\\*.*?\\*/!s\"", ",", "''", ",", "$", "st", ")", ";", "// comment_pattern", "$", "st", "=", "mb_ereg_replace", "(", "\"[\\r\\n]\"", ",", "''", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "\"\\t\"", ",", "\" \"", ",", "$", "st", ")", ";", "$", "chars", "=", "[", "';'", ",", "'='", ",", "'+'", ",", "'-'", ",", "'\\('", ",", "'\\)'", ",", "'\\{'", ",", "'\\}'", ",", "'\\['", ",", "'\\]'", ",", "','", ",", "':'", "]", ";", "foreach", "(", "$", "chars", "as", "$", "char", ")", "{", "while", "(", "mb_strpos", "(", "$", "st", ",", "$", "char", ".", "' '", ")", "!==", "false", ")", "{", "$", "st", "=", "mb_ereg_replace", "(", "$", "char", ".", "' '", ",", "$", "char", ",", "$", "st", ")", ";", "}", "while", "(", "mb_strpos", "(", "$", "st", ",", "' '", ".", "$", "char", ")", "!==", "false", ")", "{", "$", "st", "=", "mb_ereg_replace", "(", "' '", ".", "$", "char", ",", "$", "char", ",", "$", "st", ")", ";", "}", "}", "$", "st", "=", "mb_ereg_replace", "(", "'<\\?p'", ".", "'hp'", ",", "'<?p'", ".", "'hp '", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "'\\?'", ".", "'>'", ",", "'?'", ".", "'> '", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "'\\s{2,}'", ",", "' '", ",", "$", "st", ")", ";", "}", "return", "trim", "(", "$", "st", ")", ";", "}", "}" ]
Returns an expunged string of several types of character(s) depending on the configuration. ```php $test="this is cold"; \bbn\x::dump(\bbn\str::clean($test)); // (string) "this is\n cold" $test1="this is cold"; \bbn\x::dump(\bbn\str::clean($test1,'2nl')); /* (string) "this is cold" \bbn\x::dump(\bbn\str::clean($test1,'html')); // (string) "this is cold" \bbn\x::dump(\bbn\str::clean('$x = 9993','code')); // (string) "$x=9993" ``` @param mixed $st The item to be. @param string $mode A selection of configuration: "all" (default), "2n1", "html", "code". @return string
[ "Returns", "an", "expunged", "string", "of", "several", "types", "of", "character", "(", "s", ")", "depending", "on", "the", "configuration", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L260-L311
nabab/bbn
src/bbn/str.php
str.cut
public static function cut(string $st, int $max = 15): string { $st = self::cast($st); $st = mb_ereg_replace('&nbsp;',' ',$st); $st = mb_ereg_replace('\n',' ',$st); $st = strip_tags($st); $st = html_entity_decode($st, ENT_QUOTES, 'UTF-8'); $st = self::clean($st); if ( mb_strlen($st) >= $max ){ // Chars forbidden to finish with a string $chars = [' ', '.']; // Final chars $ends = []; // The string gets cut at $max $st = mb_substr($st, 0, $max); while ( \in_array(substr($st, -1), $chars) ){ $st = substr($st, 0, -1); } $st .= '...'; } return $st; }
php
public static function cut(string $st, int $max = 15): string { $st = self::cast($st); $st = mb_ereg_replace('&nbsp;',' ',$st); $st = mb_ereg_replace('\n',' ',$st); $st = strip_tags($st); $st = html_entity_decode($st, ENT_QUOTES, 'UTF-8'); $st = self::clean($st); if ( mb_strlen($st) >= $max ){ // Chars forbidden to finish with a string $chars = [' ', '.']; // Final chars $ends = []; // The string gets cut at $max $st = mb_substr($st, 0, $max); while ( \in_array(substr($st, -1), $chars) ){ $st = substr($st, 0, -1); } $st .= '...'; } return $st; }
[ "public", "static", "function", "cut", "(", "string", "$", "st", ",", "int", "$", "max", "=", "15", ")", ":", "string", "{", "$", "st", "=", "self", "::", "cast", "(", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "'&nbsp;'", ",", "' '", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "'\\n'", ",", "' '", ",", "$", "st", ")", ";", "$", "st", "=", "strip_tags", "(", "$", "st", ")", ";", "$", "st", "=", "html_entity_decode", "(", "$", "st", ",", "ENT_QUOTES", ",", "'UTF-8'", ")", ";", "$", "st", "=", "self", "::", "clean", "(", "$", "st", ")", ";", "if", "(", "mb_strlen", "(", "$", "st", ")", ">=", "$", "max", ")", "{", "// Chars forbidden to finish with a string", "$", "chars", "=", "[", "' '", ",", "'.'", "]", ";", "// Final chars", "$", "ends", "=", "[", "]", ";", "// The string gets cut at $max", "$", "st", "=", "mb_substr", "(", "$", "st", ",", "0", ",", "$", "max", ")", ";", "while", "(", "\\", "in_array", "(", "substr", "(", "$", "st", ",", "-", "1", ")", ",", "$", "chars", ")", ")", "{", "$", "st", "=", "substr", "(", "$", "st", ",", "0", ",", "-", "1", ")", ";", "}", "$", "st", ".=", "'...'", ";", "}", "return", "$", "st", ";", "}" ]
Cuts a string (HTML and PHP tags stripped) to maximum length inserted. ```php \bbn\x::dump(\bbn\str::cut("<!-- HTML Document --> Example text", 7)); // (string) "Example..." ``` @param string $st The string to be cut. @param int $max The maximum string length. @return string
[ "Cuts", "a", "string", "(", "HTML", "and", "PHP", "tags", "stripped", ")", "to", "maximum", "length", "inserted", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L325-L346
nabab/bbn
src/bbn/str.php
str.encode_filename
public static function encode_filename($st, $maxlength = 50, $extension = null, $is_path = false): string { $st = self::remove_accents(self::cast($st)); $allowed = '~\-_.,\(\[\)\]'; // Arguments order doesn't matter $args = \func_get_args(); foreach ( $args as $i => $a ){ if ( $i > 0 ){ if ( \is_string($a) ){ $extension = $a; } else if ( \is_int($a) ){ $maxlength = $a; } else if ( \is_bool($a) ){ $is_path = $a; } } } if ( !\is_int($maxlength) ){ $maxlength = mb_strlen($st); } if ( $is_path ){ $allowed .= '/'; } if ( $extension && (self::file_ext($st) === self::change_case($extension, 'lower')) ){ $st = substr($st, 0, -(\strlen($extension)+1)); } else if ( $extension = self::file_ext($st) ){ $st = substr($st, 0, -(\strlen($extension)+1)); } $st = mb_ereg_replace("([^\w\s\d".$allowed.".])", '', $st); $st = mb_ereg_replace("([\.]{2,})", '', $st); $res = mb_substr($st, 0, $maxlength); if ( $extension ){ $res .= '.' . $extension; } return $res; }
php
public static function encode_filename($st, $maxlength = 50, $extension = null, $is_path = false): string { $st = self::remove_accents(self::cast($st)); $allowed = '~\-_.,\(\[\)\]'; // Arguments order doesn't matter $args = \func_get_args(); foreach ( $args as $i => $a ){ if ( $i > 0 ){ if ( \is_string($a) ){ $extension = $a; } else if ( \is_int($a) ){ $maxlength = $a; } else if ( \is_bool($a) ){ $is_path = $a; } } } if ( !\is_int($maxlength) ){ $maxlength = mb_strlen($st); } if ( $is_path ){ $allowed .= '/'; } if ( $extension && (self::file_ext($st) === self::change_case($extension, 'lower')) ){ $st = substr($st, 0, -(\strlen($extension)+1)); } else if ( $extension = self::file_ext($st) ){ $st = substr($st, 0, -(\strlen($extension)+1)); } $st = mb_ereg_replace("([^\w\s\d".$allowed.".])", '', $st); $st = mb_ereg_replace("([\.]{2,})", '', $st); $res = mb_substr($st, 0, $maxlength); if ( $extension ){ $res .= '.' . $extension; } return $res; }
[ "public", "static", "function", "encode_filename", "(", "$", "st", ",", "$", "maxlength", "=", "50", ",", "$", "extension", "=", "null", ",", "$", "is_path", "=", "false", ")", ":", "string", "{", "$", "st", "=", "self", "::", "remove_accents", "(", "self", "::", "cast", "(", "$", "st", ")", ")", ";", "$", "allowed", "=", "'~\\-_.,\\(\\[\\)\\]'", ";", "// Arguments order doesn't matter", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "foreach", "(", "$", "args", "as", "$", "i", "=>", "$", "a", ")", "{", "if", "(", "$", "i", ">", "0", ")", "{", "if", "(", "\\", "is_string", "(", "$", "a", ")", ")", "{", "$", "extension", "=", "$", "a", ";", "}", "else", "if", "(", "\\", "is_int", "(", "$", "a", ")", ")", "{", "$", "maxlength", "=", "$", "a", ";", "}", "else", "if", "(", "\\", "is_bool", "(", "$", "a", ")", ")", "{", "$", "is_path", "=", "$", "a", ";", "}", "}", "}", "if", "(", "!", "\\", "is_int", "(", "$", "maxlength", ")", ")", "{", "$", "maxlength", "=", "mb_strlen", "(", "$", "st", ")", ";", "}", "if", "(", "$", "is_path", ")", "{", "$", "allowed", ".=", "'/'", ";", "}", "if", "(", "$", "extension", "&&", "(", "self", "::", "file_ext", "(", "$", "st", ")", "===", "self", "::", "change_case", "(", "$", "extension", ",", "'lower'", ")", ")", ")", "{", "$", "st", "=", "substr", "(", "$", "st", ",", "0", ",", "-", "(", "\\", "strlen", "(", "$", "extension", ")", "+", "1", ")", ")", ";", "}", "else", "if", "(", "$", "extension", "=", "self", "::", "file_ext", "(", "$", "st", ")", ")", "{", "$", "st", "=", "substr", "(", "$", "st", ",", "0", ",", "-", "(", "\\", "strlen", "(", "$", "extension", ")", "+", "1", ")", ")", ";", "}", "$", "st", "=", "mb_ereg_replace", "(", "\"([^\\w\\s\\d\"", ".", "$", "allowed", ".", "\".])\"", ",", "''", ",", "$", "st", ")", ";", "$", "st", "=", "mb_ereg_replace", "(", "\"([\\.]{2,})\"", ",", "''", ",", "$", "st", ")", ";", "$", "res", "=", "mb_substr", "(", "$", "st", ",", "0", ",", "$", "maxlength", ")", ";", "if", "(", "$", "extension", ")", "{", "$", "res", ".=", "'.'", ".", "$", "extension", ";", "}", "return", "$", "res", ";", "}" ]
Returns a cross-platform filename for the file. ```php \bbn\x::dump(\bbn\str::encode_filename('test file/,1', 15, 'txt')); // (string) "test_file_1.txt" ``` @param string $st The name as string. @param int $maxlength The maximum filename length (without extension), default: "50". @param string $extension The extension of the file. @param bool $is_path Tells if the slashes (/) are authorized in the string @return string
[ "Returns", "a", "cross", "-", "platform", "filename", "for", "the", "file", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L373-L419
nabab/bbn
src/bbn/str.php
str.encode_dbname
public static function encode_dbname($st, $maxlength = 50): string { $st = self::remove_accents(self::cast($st)); $res = ''; if ( !\is_int($maxlength) ){ $maxlength = mb_strlen($st); } for ( $i = 0; $i < $maxlength; $i++ ){ if ( mb_ereg_match('[A-z0-9]',mb_substr($st,$i,1)) ){ $res .= mb_substr($st,$i,1); } else if ( (mb_strlen($res) > 0) && (mb_substr($res,-1) != '_') && ($i < ( mb_strlen($st) - 1 )) ){ $res .= '_'; } } if ( substr($res, -1) === '_' ){ $res = substr($res, 0, -1); } return $res; }
php
public static function encode_dbname($st, $maxlength = 50): string { $st = self::remove_accents(self::cast($st)); $res = ''; if ( !\is_int($maxlength) ){ $maxlength = mb_strlen($st); } for ( $i = 0; $i < $maxlength; $i++ ){ if ( mb_ereg_match('[A-z0-9]',mb_substr($st,$i,1)) ){ $res .= mb_substr($st,$i,1); } else if ( (mb_strlen($res) > 0) && (mb_substr($res,-1) != '_') && ($i < ( mb_strlen($st) - 1 )) ){ $res .= '_'; } } if ( substr($res, -1) === '_' ){ $res = substr($res, 0, -1); } return $res; }
[ "public", "static", "function", "encode_dbname", "(", "$", "st", ",", "$", "maxlength", "=", "50", ")", ":", "string", "{", "$", "st", "=", "self", "::", "remove_accents", "(", "self", "::", "cast", "(", "$", "st", ")", ")", ";", "$", "res", "=", "''", ";", "if", "(", "!", "\\", "is_int", "(", "$", "maxlength", ")", ")", "{", "$", "maxlength", "=", "mb_strlen", "(", "$", "st", ")", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "maxlength", ";", "$", "i", "++", ")", "{", "if", "(", "mb_ereg_match", "(", "'[A-z0-9]'", ",", "mb_substr", "(", "$", "st", ",", "$", "i", ",", "1", ")", ")", ")", "{", "$", "res", ".=", "mb_substr", "(", "$", "st", ",", "$", "i", ",", "1", ")", ";", "}", "else", "if", "(", "(", "mb_strlen", "(", "$", "res", ")", ">", "0", ")", "&&", "(", "mb_substr", "(", "$", "res", ",", "-", "1", ")", "!=", "'_'", ")", "&&", "(", "$", "i", "<", "(", "mb_strlen", "(", "$", "st", ")", "-", "1", ")", ")", ")", "{", "$", "res", ".=", "'_'", ";", "}", "}", "if", "(", "substr", "(", "$", "res", ",", "-", "1", ")", "===", "'_'", ")", "{", "$", "res", "=", "substr", "(", "$", "res", ",", "0", ",", "-", "1", ")", ";", "}", "return", "$", "res", ";", "}" ]
Returns a corrected string for database naming. ```php \bbn\x::dump(\bbn\str::encode_dbname('my.database_name ? test :,; !plus')); // (string) "my_database_name_test_plus" ``` @param string $st The name as string. @param int $maxlength The maximum length, default: "50". @return string
[ "Returns", "a", "corrected", "string", "for", "database", "naming", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L433-L456
nabab/bbn
src/bbn/str.php
str.file_ext
public static function file_ext(string $file, bool $ar = false) { $file = self::cast($file); if ( mb_strrpos($file, '/') !== false ){ $file = substr($file, mb_strrpos($file, '/') + 1); } if ( mb_strpos($file, '.') !== false ){ $p = mb_strrpos($file, '.'); $f = mb_substr($file, 0, $p); $ext = mb_convert_case(mb_substr($file, $p+1), MB_CASE_LOWER); return $ar ? [$f, $ext] : $ext; } return $ar ? [$file, ''] : ''; }
php
public static function file_ext(string $file, bool $ar = false) { $file = self::cast($file); if ( mb_strrpos($file, '/') !== false ){ $file = substr($file, mb_strrpos($file, '/') + 1); } if ( mb_strpos($file, '.') !== false ){ $p = mb_strrpos($file, '.'); $f = mb_substr($file, 0, $p); $ext = mb_convert_case(mb_substr($file, $p+1), MB_CASE_LOWER); return $ar ? [$f, $ext] : $ext; } return $ar ? [$file, ''] : ''; }
[ "public", "static", "function", "file_ext", "(", "string", "$", "file", ",", "bool", "$", "ar", "=", "false", ")", "{", "$", "file", "=", "self", "::", "cast", "(", "$", "file", ")", ";", "if", "(", "mb_strrpos", "(", "$", "file", ",", "'/'", ")", "!==", "false", ")", "{", "$", "file", "=", "substr", "(", "$", "file", ",", "mb_strrpos", "(", "$", "file", ",", "'/'", ")", "+", "1", ")", ";", "}", "if", "(", "mb_strpos", "(", "$", "file", ",", "'.'", ")", "!==", "false", ")", "{", "$", "p", "=", "mb_strrpos", "(", "$", "file", ",", "'.'", ")", ";", "$", "f", "=", "mb_substr", "(", "$", "file", ",", "0", ",", "$", "p", ")", ";", "$", "ext", "=", "mb_convert_case", "(", "mb_substr", "(", "$", "file", ",", "$", "p", "+", "1", ")", ",", "MB_CASE_LOWER", ")", ";", "return", "$", "ar", "?", "[", "$", "f", ",", "$", "ext", "]", ":", "$", "ext", ";", "}", "return", "$", "ar", "?", "[", "$", "file", ",", "''", "]", ":", "''", ";", "}" ]
Returns the file extension. ```php \bbn\x::dump(str::file_ext(\"c:\\Desktop\\test.txt\")); // (string) "txt" \bbn\x::dump(\bbn\str::file_ext('/home/user/Desktop/test.txt',1)); // (array) [ "test", "txt", ] ``` @param string $file The file path. @param bool $ar If "true" also returns the file path, default: "false". @return string|array
[ "Returns", "the", "file", "extension", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L472-L485
nabab/bbn
src/bbn/str.php
str.genpwd
public static function genpwd(int $int_max = 12, int $int_min = 6): string { mt_srand(); $len = ($int_min > 0) && ($int_min < $int_max) ? random_int($int_min, $int_max) : $int_max; $mdp = ''; for( $i = 0; $i < $len; $i++ ){ // First character is a letter $type = $i === 0 ? random_int(2, 3) : random_int(1, 3); switch ( $type ){ case 1: $mdp .= random_int(0,9); break; case 2: $mdp .= \chr(random_int(65,90)); break; case 3: $mdp .= \chr(random_int(97,122)); break; } } return $mdp; }
php
public static function genpwd(int $int_max = 12, int $int_min = 6): string { mt_srand(); $len = ($int_min > 0) && ($int_min < $int_max) ? random_int($int_min, $int_max) : $int_max; $mdp = ''; for( $i = 0; $i < $len; $i++ ){ // First character is a letter $type = $i === 0 ? random_int(2, 3) : random_int(1, 3); switch ( $type ){ case 1: $mdp .= random_int(0,9); break; case 2: $mdp .= \chr(random_int(65,90)); break; case 3: $mdp .= \chr(random_int(97,122)); break; } } return $mdp; }
[ "public", "static", "function", "genpwd", "(", "int", "$", "int_max", "=", "12", ",", "int", "$", "int_min", "=", "6", ")", ":", "string", "{", "mt_srand", "(", ")", ";", "$", "len", "=", "(", "$", "int_min", ">", "0", ")", "&&", "(", "$", "int_min", "<", "$", "int_max", ")", "?", "random_int", "(", "$", "int_min", ",", "$", "int_max", ")", ":", "$", "int_max", ";", "$", "mdp", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "len", ";", "$", "i", "++", ")", "{", "// First character is a letter", "$", "type", "=", "$", "i", "===", "0", "?", "random_int", "(", "2", ",", "3", ")", ":", "random_int", "(", "1", ",", "3", ")", ";", "switch", "(", "$", "type", ")", "{", "case", "1", ":", "$", "mdp", ".=", "random_int", "(", "0", ",", "9", ")", ";", "break", ";", "case", "2", ":", "$", "mdp", ".=", "\\", "chr", "(", "random_int", "(", "65", ",", "90", ")", ")", ";", "break", ";", "case", "3", ":", "$", "mdp", ".=", "\\", "chr", "(", "random_int", "(", "97", ",", "122", ")", ")", ";", "break", ";", "}", "}", "return", "$", "mdp", ";", "}" ]
Returns a random password. ```php \bbn\x::dump(\bbn\str::genpwd()); // (string) "khc9P871w" \bbn\x::dump(\bbn\str::genpwd(6, 4)); // (string) "dDEtxY" ``` @param int $int_max Maximum password characters, default: "12". @param int $int_min Minimum password characters, default: "6". @return string
[ "Returns", "a", "random", "password", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L501-L522
nabab/bbn
src/bbn/str.php
str.is_json
public static function is_json($st) { if ( \is_string($st) && !empty($st) && ( (substr($st, 0, 1) === '{') || (substr($st, 0, 1) === '[') )){ json_decode($st); return (json_last_error() == JSON_ERROR_NONE); } return false; }
php
public static function is_json($st) { if ( \is_string($st) && !empty($st) && ( (substr($st, 0, 1) === '{') || (substr($st, 0, 1) === '[') )){ json_decode($st); return (json_last_error() == JSON_ERROR_NONE); } return false; }
[ "public", "static", "function", "is_json", "(", "$", "st", ")", "{", "if", "(", "\\", "is_string", "(", "$", "st", ")", "&&", "!", "empty", "(", "$", "st", ")", "&&", "(", "(", "substr", "(", "$", "st", ",", "0", ",", "1", ")", "===", "'{'", ")", "||", "(", "substr", "(", "$", "st", ",", "0", ",", "1", ")", "===", "'['", ")", ")", ")", "{", "json_decode", "(", "$", "st", ")", ";", "return", "(", "json_last_error", "(", ")", "==", "JSON_ERROR_NONE", ")", ";", "}", "return", "false", ";", "}" ]
Checks if the string is a json string. ```php \bbn\x::dump(\bbn\str::is_json('{"firstName": "John", "lastName": "Smith", "age": 25}')); // (bool) true ``` @param string $st The string. @return bool
[ "Checks", "if", "the", "string", "is", "a", "json", "string", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L535-L543
nabab/bbn
src/bbn/str.php
str.is_number
public static function is_number(): bool { $args = \func_get_args(); foreach ( $args as $a ){ if ( \is_string($a) || (abs($a) > PHP_INT_MAX) ){ if ( !preg_match('/^-?(?:\d+|\d*\.\d+)$/', $a) ){ return false; } } else if ( !\is_int($a) && !\is_float($a) ){ return false; } } return 1; }
php
public static function is_number(): bool { $args = \func_get_args(); foreach ( $args as $a ){ if ( \is_string($a) || (abs($a) > PHP_INT_MAX) ){ if ( !preg_match('/^-?(?:\d+|\d*\.\d+)$/', $a) ){ return false; } } else if ( !\is_int($a) && !\is_float($a) ){ return false; } } return 1; }
[ "public", "static", "function", "is_number", "(", ")", ":", "bool", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "if", "(", "\\", "is_string", "(", "$", "a", ")", "||", "(", "abs", "(", "$", "a", ")", ">", "PHP_INT_MAX", ")", ")", "{", "if", "(", "!", "preg_match", "(", "'/^-?(?:\\d+|\\d*\\.\\d+)$/'", ",", "$", "a", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "\\", "is_int", "(", "$", "a", ")", "&&", "!", "\\", "is_float", "(", "$", "a", ")", ")", "{", "return", "false", ";", "}", "}", "return", "1", ";", "}" ]
Checks if the item is a number. Can take as many arguments and will return false if one of them is not a number. ```php \bbn\x::dump(\bbn\str::is_number([1, 2])); // (bool) false \bbn\x::dump(\bbn\str::is_number(150); // (bool) 1 \bbn\x::dump(\bbn\str::is_number('150')); // (bool) 1 \bbn\x::dump(\bbn\str::is_number(1.5); // (bool) 1 ``` @param mixed $st The item to be tested. @return bool
[ "Checks", "if", "the", "item", "is", "a", "number", ".", "Can", "take", "as", "many", "arguments", "and", "will", "return", "false", "if", "one", "of", "them", "is", "not", "a", "number", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L563-L577
nabab/bbn
src/bbn/str.php
str.is_integer
public static function is_integer(): bool { $args = \func_get_args(); foreach ( $args as $a ){ if ( \is_string($a) || (abs($a) > PHP_INT_MAX) ){ if ( !preg_match('/^-?(\d+)$/', (string)$a) ){ return false; } } else if ( !\is_int($a) ){ return false; } } return true; }
php
public static function is_integer(): bool { $args = \func_get_args(); foreach ( $args as $a ){ if ( \is_string($a) || (abs($a) > PHP_INT_MAX) ){ if ( !preg_match('/^-?(\d+)$/', (string)$a) ){ return false; } } else if ( !\is_int($a) ){ return false; } } return true; }
[ "public", "static", "function", "is_integer", "(", ")", ":", "bool", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "if", "(", "\\", "is_string", "(", "$", "a", ")", "||", "(", "abs", "(", "$", "a", ")", ">", "PHP_INT_MAX", ")", ")", "{", "if", "(", "!", "preg_match", "(", "'/^-?(\\d+)$/'", ",", "(", "string", ")", "$", "a", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "\\", "is_int", "(", "$", "a", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if the item is a integer. Can take as many arguments and will return false if one of them is not an integer or the string of an integer. ```php \bbn\x::dump(\bbn\str::is_integer(13.2)); // (bool) false \bbn\x::dump(\bbn\str::is_integer(14)); // (bool) true \bbn\x::dump(\bbn\str::is_integer('14')); // (bool) true ``` @param mixed $st The item to be tested. @return bool
[ "Checks", "if", "the", "item", "is", "a", "integer", ".", "Can", "take", "as", "many", "arguments", "and", "will", "return", "false", "if", "one", "of", "them", "is", "not", "an", "integer", "or", "the", "string", "of", "an", "integer", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L595-L609
nabab/bbn
src/bbn/str.php
str.is_decimal
public static function is_decimal(): bool { $args = \func_get_args(); foreach ( $args as $a ){ if ( \is_string($a) ){ if ( !preg_match('/^-?(\d*\.\d+)$/', $a) ){ return false; } } else if ( !\is_float($a) ){ return false; } } return true; }
php
public static function is_decimal(): bool { $args = \func_get_args(); foreach ( $args as $a ){ if ( \is_string($a) ){ if ( !preg_match('/^-?(\d*\.\d+)$/', $a) ){ return false; } } else if ( !\is_float($a) ){ return false; } } return true; }
[ "public", "static", "function", "is_decimal", "(", ")", ":", "bool", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "if", "(", "\\", "is_string", "(", "$", "a", ")", ")", "{", "if", "(", "!", "preg_match", "(", "'/^-?(\\d*\\.\\d+)$/'", ",", "$", "a", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "\\", "is_float", "(", "$", "a", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if the item is a decimal. Can take many arguments and it will return false if one of them is not a decimal or the string of a decimal (float). ```php \bbn\x::dump(\bbn\str::is_decimal(13.2)); // (bool) true \bbn\x::dump(\bbn\str::is_decimal('13.2')); // (bool) true \bbn\x::dump(\bbn\str::is_decimal(14)); // (bool) false ``` @param mixed $st The item to be tested. @return bool
[ "Checks", "if", "the", "item", "is", "a", "decimal", ".", "Can", "take", "many", "arguments", "and", "it", "will", "return", "false", "if", "one", "of", "them", "is", "not", "a", "decimal", "or", "the", "string", "of", "a", "decimal", "(", "float", ")", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L658-L672
nabab/bbn
src/bbn/str.php
str.is_buid
public static function is_buid($st): bool { if ( \is_string($st) && (\strlen($st) === 16) && !ctype_print($st) && !ctype_space($st) ){ $enc = mb_detect_encoding($st, ['8bit', 'UTF-8']); if ( !$enc || ($enc === '8bit') ){ return true; } } return false; }
php
public static function is_buid($st): bool { if ( \is_string($st) && (\strlen($st) === 16) && !ctype_print($st) && !ctype_space($st) ){ $enc = mb_detect_encoding($st, ['8bit', 'UTF-8']); if ( !$enc || ($enc === '8bit') ){ return true; } } return false; }
[ "public", "static", "function", "is_buid", "(", "$", "st", ")", ":", "bool", "{", "if", "(", "\\", "is_string", "(", "$", "st", ")", "&&", "(", "\\", "strlen", "(", "$", "st", ")", "===", "16", ")", "&&", "!", "ctype_print", "(", "$", "st", ")", "&&", "!", "ctype_space", "(", "$", "st", ")", ")", "{", "$", "enc", "=", "mb_detect_encoding", "(", "$", "st", ",", "[", "'8bit'", ",", "'UTF-8'", "]", ")", ";", "if", "(", "!", "$", "enc", "||", "(", "$", "enc", "===", "'8bit'", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the string is a valid binary UID string. @param string $st @return boolean
[ "Checks", "if", "the", "string", "is", "a", "valid", "binary", "UID", "string", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L691-L700
nabab/bbn
src/bbn/str.php
str.is_email
public static function is_email($email): bool { if ( function_exists('filter_var') ){ return filter_var($email,FILTER_VALIDATE_EMAIL) ? true : false; } else { $isValid = true; $atIndex = mb_strrpos($email, "@"); if (\is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = mb_substr($email, $atIndex+1); $local = mb_substr($email, 0, $atIndex); $localLen = mb_strlen($local); $domainLen = mb_strlen($domain); // local part length exceeded if ($localLen < 1 || $localLen > 64) $isValid = false; // domain part length exceeded else if ($domainLen < 1 || $domainLen > 255) $isValid = false; // local part starts or ends with '.' else if ($local[0] == '.' || $local[$localLen-1] == '.') $isValid = false; // local part has two consecutive dots else if (mb_ereg_match('\\.\\.', $local)) $isValid = false; // character not valid in domain part else if (!mb_ereg_match('^[A-Za-z0-9\\-\\.]+$', $domain)) $isValid = false; // domain part has two consecutive dots else if (mb_ereg_match('\\.\\.', $domain)) $isValid = false; // character not valid in local part unless else if ( !mb_ereg_match('^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$' ,str_replace("\\\\","",$local))) { // local part is quoted if ( !mb_ereg_match('^"(\\\\"|[^"])+"$',str_replace("\\\\","",$local)) ) $isValid = false; } } return $isValid; } }
php
public static function is_email($email): bool { if ( function_exists('filter_var') ){ return filter_var($email,FILTER_VALIDATE_EMAIL) ? true : false; } else { $isValid = true; $atIndex = mb_strrpos($email, "@"); if (\is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = mb_substr($email, $atIndex+1); $local = mb_substr($email, 0, $atIndex); $localLen = mb_strlen($local); $domainLen = mb_strlen($domain); // local part length exceeded if ($localLen < 1 || $localLen > 64) $isValid = false; // domain part length exceeded else if ($domainLen < 1 || $domainLen > 255) $isValid = false; // local part starts or ends with '.' else if ($local[0] == '.' || $local[$localLen-1] == '.') $isValid = false; // local part has two consecutive dots else if (mb_ereg_match('\\.\\.', $local)) $isValid = false; // character not valid in domain part else if (!mb_ereg_match('^[A-Za-z0-9\\-\\.]+$', $domain)) $isValid = false; // domain part has two consecutive dots else if (mb_ereg_match('\\.\\.', $domain)) $isValid = false; // character not valid in local part unless else if ( !mb_ereg_match('^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$' ,str_replace("\\\\","",$local))) { // local part is quoted if ( !mb_ereg_match('^"(\\\\"|[^"])+"$',str_replace("\\\\","",$local)) ) $isValid = false; } } return $isValid; } }
[ "public", "static", "function", "is_email", "(", "$", "email", ")", ":", "bool", "{", "if", "(", "function_exists", "(", "'filter_var'", ")", ")", "{", "return", "filter_var", "(", "$", "email", ",", "FILTER_VALIDATE_EMAIL", ")", "?", "true", ":", "false", ";", "}", "else", "{", "$", "isValid", "=", "true", ";", "$", "atIndex", "=", "mb_strrpos", "(", "$", "email", ",", "\"@\"", ")", ";", "if", "(", "\\", "is_bool", "(", "$", "atIndex", ")", "&&", "!", "$", "atIndex", ")", "{", "$", "isValid", "=", "false", ";", "}", "else", "{", "$", "domain", "=", "mb_substr", "(", "$", "email", ",", "$", "atIndex", "+", "1", ")", ";", "$", "local", "=", "mb_substr", "(", "$", "email", ",", "0", ",", "$", "atIndex", ")", ";", "$", "localLen", "=", "mb_strlen", "(", "$", "local", ")", ";", "$", "domainLen", "=", "mb_strlen", "(", "$", "domain", ")", ";", "// local part length exceeded", "if", "(", "$", "localLen", "<", "1", "||", "$", "localLen", ">", "64", ")", "$", "isValid", "=", "false", ";", "// domain part length exceeded", "else", "if", "(", "$", "domainLen", "<", "1", "||", "$", "domainLen", ">", "255", ")", "$", "isValid", "=", "false", ";", "// local part starts or ends with '.'", "else", "if", "(", "$", "local", "[", "0", "]", "==", "'.'", "||", "$", "local", "[", "$", "localLen", "-", "1", "]", "==", "'.'", ")", "$", "isValid", "=", "false", ";", "// local part has two consecutive dots", "else", "if", "(", "mb_ereg_match", "(", "'\\\\.\\\\.'", ",", "$", "local", ")", ")", "$", "isValid", "=", "false", ";", "// character not valid in domain part", "else", "if", "(", "!", "mb_ereg_match", "(", "'^[A-Za-z0-9\\\\-\\\\.]+$'", ",", "$", "domain", ")", ")", "$", "isValid", "=", "false", ";", "// domain part has two consecutive dots", "else", "if", "(", "mb_ereg_match", "(", "'\\\\.\\\\.'", ",", "$", "domain", ")", ")", "$", "isValid", "=", "false", ";", "// character not valid in local part unless", "else", "if", "(", "!", "mb_ereg_match", "(", "'^(\\\\\\\\.|[A-Za-z0-9!#%&`_=\\\\/$\\'*+?^{}|~.-])+$'", ",", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\"", ",", "$", "local", ")", ")", ")", "{", "// local part is quoted", "if", "(", "!", "mb_ereg_match", "(", "'^\"(\\\\\\\\\"|[^\"])+\"$'", ",", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\"", ",", "$", "local", ")", ")", ")", "$", "isValid", "=", "false", ";", "}", "}", "return", "$", "isValid", ";", "}", "}" ]
Checks if the string is the correct type of e-mail address. ```php \bbn\x::dump(\bbn\str::is_email('[email protected]')); // (bool) true \bbn\x::dump(\bbn\str::is_email('test@email')); // (bool) false \bbn\x::dump(\bbn\str::is_email('[email protected]')); // (bool) false \bbn\x::dump(\bbn\str::is_email('testemail.com')); // (bool) false ``` @param string $email E-mail address. @return bool
[ "Checks", "if", "the", "string", "is", "the", "correct", "type", "of", "e", "-", "mail", "address", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L719-L767
nabab/bbn
src/bbn/str.php
str.correct_types
public static function correct_types($st){ if ( \is_string($st) ){ if ( self::is_buid($st) ){ $st = bin2hex($st); } else{ if ( self::is_json($st) ){ if ( strpos($st, '": ') && ($json = json_decode($st)) ){ return json_encode($json); } return $st; } $st = trim($st); // Not starting with a zero or ending with a zero decimal if ( !preg_match('/^0[^.]+|\.[0-9]*0$/', $st) ){ if ( self::is_integer($st) && ((substr((string)$st, 0, 1) !== '0') || ($st === '0')) ){ $tmp = (int)$st; if ( ($tmp < PHP_INT_MAX) && ($tmp > -PHP_INT_MAX) ){ return $tmp; } } // If it is a decimal, not starting or ending with a zero else if ( self::is_decimal($st) ){ return (float)$st; } } } } else if ( \is_array($st) ){ foreach ( $st as $k => $v ){ $st[$k] = self::correct_types($v); } } else if ( \is_object($st) ){ $vs = get_object_vars($st); foreach ( $vs as $k => $v ){ $st->$k = self::correct_types($v); } } return $st; }
php
public static function correct_types($st){ if ( \is_string($st) ){ if ( self::is_buid($st) ){ $st = bin2hex($st); } else{ if ( self::is_json($st) ){ if ( strpos($st, '": ') && ($json = json_decode($st)) ){ return json_encode($json); } return $st; } $st = trim($st); // Not starting with a zero or ending with a zero decimal if ( !preg_match('/^0[^.]+|\.[0-9]*0$/', $st) ){ if ( self::is_integer($st) && ((substr((string)$st, 0, 1) !== '0') || ($st === '0')) ){ $tmp = (int)$st; if ( ($tmp < PHP_INT_MAX) && ($tmp > -PHP_INT_MAX) ){ return $tmp; } } // If it is a decimal, not starting or ending with a zero else if ( self::is_decimal($st) ){ return (float)$st; } } } } else if ( \is_array($st) ){ foreach ( $st as $k => $v ){ $st[$k] = self::correct_types($v); } } else if ( \is_object($st) ){ $vs = get_object_vars($st); foreach ( $vs as $k => $v ){ $st->$k = self::correct_types($v); } } return $st; }
[ "public", "static", "function", "correct_types", "(", "$", "st", ")", "{", "if", "(", "\\", "is_string", "(", "$", "st", ")", ")", "{", "if", "(", "self", "::", "is_buid", "(", "$", "st", ")", ")", "{", "$", "st", "=", "bin2hex", "(", "$", "st", ")", ";", "}", "else", "{", "if", "(", "self", "::", "is_json", "(", "$", "st", ")", ")", "{", "if", "(", "strpos", "(", "$", "st", ",", "'\": '", ")", "&&", "(", "$", "json", "=", "json_decode", "(", "$", "st", ")", ")", ")", "{", "return", "json_encode", "(", "$", "json", ")", ";", "}", "return", "$", "st", ";", "}", "$", "st", "=", "trim", "(", "$", "st", ")", ";", "// Not starting with a zero or ending with a zero decimal", "if", "(", "!", "preg_match", "(", "'/^0[^.]+|\\.[0-9]*0$/'", ",", "$", "st", ")", ")", "{", "if", "(", "self", "::", "is_integer", "(", "$", "st", ")", "&&", "(", "(", "substr", "(", "(", "string", ")", "$", "st", ",", "0", ",", "1", ")", "!==", "'0'", ")", "||", "(", "$", "st", "===", "'0'", ")", ")", ")", "{", "$", "tmp", "=", "(", "int", ")", "$", "st", ";", "if", "(", "(", "$", "tmp", "<", "PHP_INT_MAX", ")", "&&", "(", "$", "tmp", ">", "-", "PHP_INT_MAX", ")", ")", "{", "return", "$", "tmp", ";", "}", "}", "// If it is a decimal, not starting or ending with a zero", "else", "if", "(", "self", "::", "is_decimal", "(", "$", "st", ")", ")", "{", "return", "(", "float", ")", "$", "st", ";", "}", "}", "}", "}", "else", "if", "(", "\\", "is_array", "(", "$", "st", ")", ")", "{", "foreach", "(", "$", "st", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "st", "[", "$", "k", "]", "=", "self", "::", "correct_types", "(", "$", "v", ")", ";", "}", "}", "else", "if", "(", "\\", "is_object", "(", "$", "st", ")", ")", "{", "$", "vs", "=", "get_object_vars", "(", "$", "st", ")", ";", "foreach", "(", "$", "vs", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "st", "->", "$", "k", "=", "self", "::", "correct_types", "(", "$", "v", ")", ";", "}", "}", "return", "$", "st", ";", "}" ]
If it looks like an int or float type, the string variable is converted into the correct type. ```php \bbn\x::dump(\bbn\str::correct_types(1230)); // (int) 1230 \bbn\x::dump(\bbn\str::correct_types(12.30)); // (float) 12.3 \bbn\x::dump(\bbn\str::correct_types("12.3")); // (float) 12.3 \bbn\x::dump(\bbn\str::correct_types([1230])); // (int) [1230] ``` @param mixed $st @return mixed
[ "If", "it", "looks", "like", "an", "int", "or", "float", "type", "the", "string", "variable", "is", "converted", "into", "the", "correct", "type", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L851-L891
nabab/bbn
src/bbn/str.php
str.parse_url
public static function parse_url($url): array { $url = self::cast($url); $r = x::merge_arrays(parse_url($url), ['url' => $url,'query' => '','params' => []]); if ( strpos($url,'?') > 0 ) { $p = explode('?',$url); $r['url'] = $p[0]; $r['query'] = $p[1]; $ps = explode('&',$r['query']); foreach ( $ps as $p ){ $px = explode('=',$p); $r['params'][$px[0]] = $px[1]; } } return $r; }
php
public static function parse_url($url): array { $url = self::cast($url); $r = x::merge_arrays(parse_url($url), ['url' => $url,'query' => '','params' => []]); if ( strpos($url,'?') > 0 ) { $p = explode('?',$url); $r['url'] = $p[0]; $r['query'] = $p[1]; $ps = explode('&',$r['query']); foreach ( $ps as $p ){ $px = explode('=',$p); $r['params'][$px[0]] = $px[1]; } } return $r; }
[ "public", "static", "function", "parse_url", "(", "$", "url", ")", ":", "array", "{", "$", "url", "=", "self", "::", "cast", "(", "$", "url", ")", ";", "$", "r", "=", "x", "::", "merge_arrays", "(", "parse_url", "(", "$", "url", ")", ",", "[", "'url'", "=>", "$", "url", ",", "'query'", "=>", "''", ",", "'params'", "=>", "[", "]", "]", ")", ";", "if", "(", "strpos", "(", "$", "url", ",", "'?'", ")", ">", "0", ")", "{", "$", "p", "=", "explode", "(", "'?'", ",", "$", "url", ")", ";", "$", "r", "[", "'url'", "]", "=", "$", "p", "[", "0", "]", ";", "$", "r", "[", "'query'", "]", "=", "$", "p", "[", "1", "]", ";", "$", "ps", "=", "explode", "(", "'&'", ",", "$", "r", "[", "'query'", "]", ")", ";", "foreach", "(", "$", "ps", "as", "$", "p", ")", "{", "$", "px", "=", "explode", "(", "'='", ",", "$", "p", ")", ";", "$", "r", "[", "'params'", "]", "[", "$", "px", "[", "0", "]", "]", "=", "$", "px", "[", "1", "]", ";", "}", "}", "return", "$", "r", ";", "}" ]
Returns an array containing any of the various components of the URL that are present. ```php \bbn\x::hdump(\bbn\str::parse_url('http://localhost/phpmyadmin/?db=test&table=users&server=1&target=&token=e45a102c5672b2b4fe84ae75d9148981'); /* (array) [ 'scheme' => 'http', 'host' => 'localhost', 'path' => '/phpmyadmin/', 'query' => 'db=test&table=users&server=1&target=&token=e45a102c5672b2b4fe84ae75d9148981', 'url' => 'http://localhost/phpmyadmin/', 'params' => [ 'db' => 'test', 'table' => 'users', 'server' => '1', 'target' => '', 'token' => 'e45a102c5672b2b4fe84ae75d9148981', ], ] ``` @param string $url The url. @return array
[ "Returns", "an", "array", "containing", "any", "of", "the", "various", "components", "of", "the", "URL", "that", "are", "present", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L918-L934
nabab/bbn
src/bbn/str.php
str.parse_path
public static function parse_path(string $path, $allow_parent = false): string { $path = str_replace('\\', '/', \strval($path)); $path = str_replace('/./', '/', \strval($path)); while ( strpos($path, '//') !== false ){ $path = str_replace('//', '/', $path); } if ( strpos($path, '../') !== false ){ if ( !$allow_parent ){ return ''; } $bits = array_reverse(explode('/', $path)); $path = ''; $num_parent = 0; foreach ( $bits as $i => $b ){ if ( $b === '..' ){ $num_parent++; } else if ( $b !== '.' ){ if ( $num_parent ){ $num_parent--; } else{ $path = empty($path) ? $b : $b.'/'.$path; } } } } return $path; }
php
public static function parse_path(string $path, $allow_parent = false): string { $path = str_replace('\\', '/', \strval($path)); $path = str_replace('/./', '/', \strval($path)); while ( strpos($path, '//') !== false ){ $path = str_replace('//', '/', $path); } if ( strpos($path, '../') !== false ){ if ( !$allow_parent ){ return ''; } $bits = array_reverse(explode('/', $path)); $path = ''; $num_parent = 0; foreach ( $bits as $i => $b ){ if ( $b === '..' ){ $num_parent++; } else if ( $b !== '.' ){ if ( $num_parent ){ $num_parent--; } else{ $path = empty($path) ? $b : $b.'/'.$path; } } } } return $path; }
[ "public", "static", "function", "parse_path", "(", "string", "$", "path", ",", "$", "allow_parent", "=", "false", ")", ":", "string", "{", "$", "path", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "\\", "strval", "(", "$", "path", ")", ")", ";", "$", "path", "=", "str_replace", "(", "'/./'", ",", "'/'", ",", "\\", "strval", "(", "$", "path", ")", ")", ";", "while", "(", "strpos", "(", "$", "path", ",", "'//'", ")", "!==", "false", ")", "{", "$", "path", "=", "str_replace", "(", "'//'", ",", "'/'", ",", "$", "path", ")", ";", "}", "if", "(", "strpos", "(", "$", "path", ",", "'../'", ")", "!==", "false", ")", "{", "if", "(", "!", "$", "allow_parent", ")", "{", "return", "''", ";", "}", "$", "bits", "=", "array_reverse", "(", "explode", "(", "'/'", ",", "$", "path", ")", ")", ";", "$", "path", "=", "''", ";", "$", "num_parent", "=", "0", ";", "foreach", "(", "$", "bits", "as", "$", "i", "=>", "$", "b", ")", "{", "if", "(", "$", "b", "===", "'..'", ")", "{", "$", "num_parent", "++", ";", "}", "else", "if", "(", "$", "b", "!==", "'.'", ")", "{", "if", "(", "$", "num_parent", ")", "{", "$", "num_parent", "--", ";", "}", "else", "{", "$", "path", "=", "empty", "(", "$", "path", ")", "?", "$", "b", ":", "$", "b", ".", "'/'", ".", "$", "path", ";", "}", "}", "}", "}", "return", "$", "path", ";", "}" ]
Replaces backslash with slash in a path string. Forbids the use of ../ ```php \bbn\x::dump(\bbn\str::parse_path('\home\user\Desktop')); // (string) "/home/user/Desktop" ``` @param string $path The path. @param boolean $allow_parent If true ../ is allowed in the path (and will become normalized). @return string
[ "Replaces", "backslash", "with", "slash", "in", "a", "path", "string", ".", "Forbids", "the", "use", "of", "..", "/" ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L948-L977
nabab/bbn
src/bbn/str.php
str.remove_accents
public static function remove_accents($st): string { $st = trim(mb_ereg_replace('&(.)(tilde|circ|grave|acute|uml|ring|oelig);', '\\1', self::cast($st))); $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u,ą,ń,ł,ź,ę,À,Á,Â,Ã,Ä,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ñ,Ò,Ó,Ô,Õ,Ö,Ù,Ú,Û,Ü,Ý,Ł,Ś"); $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u,a,n,l,z,e,A,A,A,A,A,C,E,E,E,E,I,I,I,I,N,O,O,O,O,O,U,U,U,U,Y,L,S"); foreach ( $search as $i => $s ) $st = mb_ereg_replace($s, $replace[$i], $st); return $st; }
php
public static function remove_accents($st): string { $st = trim(mb_ereg_replace('&(.)(tilde|circ|grave|acute|uml|ring|oelig);', '\\1', self::cast($st))); $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u,ą,ń,ł,ź,ę,À,Á,Â,Ã,Ä,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ñ,Ò,Ó,Ô,Õ,Ö,Ù,Ú,Û,Ü,Ý,Ł,Ś"); $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u,a,n,l,z,e,A,A,A,A,A,C,E,E,E,E,I,I,I,I,N,O,O,O,O,O,U,U,U,U,Y,L,S"); foreach ( $search as $i => $s ) $st = mb_ereg_replace($s, $replace[$i], $st); return $st; }
[ "public", "static", "function", "remove_accents", "(", "$", "st", ")", ":", "string", "{", "$", "st", "=", "trim", "(", "mb_ereg_replace", "(", "'&(.)(tilde|circ|grave|acute|uml|ring|oelig);'", ",", "'\\\\1'", ",", "self", "::", "cast", "(", "$", "st", ")", ")", ")", ";", "$", "search", "=", "explode", "(", "\",\"", ",", "\"ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u,ą,ń,ł,ź,ę,À,Á,Â,Ã,Ä,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ñ,Ò,Ó,Ô,Õ,Ö,Ù,Ú,Û,Ü,Ý,Ł,Ś\");", "", "", "$", "replace", "=", "explode", "(", "\",\"", ",", "\"c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u,a,n,l,z,e,A,A,A,A,A,C,E,E,E,E,I,I,I,I,N,O,O,O,O,O,U,U,U,U,Y,L,S\"", ")", ";", "foreach", "(", "$", "search", "as", "$", "i", "=>", "$", "s", ")", "$", "st", "=", "mb_ereg_replace", "(", "$", "s", ",", "$", "replace", "[", "$", "i", "]", ",", "$", "st", ")", ";", "return", "$", "st", ";", "}" ]
Replaces accented characters with their character without the accent. ```php \bbn\x::dump(\bbn\str::remove_accents("Tèst Fìlè òèàùè")); // (string) "TA¨st FA¬lA¨ A²A¨A A¹e" ``` @param string $st The string. @return string
[ "Replaces", "accented", "characters", "with", "their", "character", "without", "the", "accent", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L990-L998
nabab/bbn
src/bbn/str.php
str.check_name
public static function check_name(): bool { $args = \func_get_args(); // Each argument must be a string starting with a letter, and having only one character made of letters, numbers and underscores foreach ( $args as $a ){ $a = self::cast($a); $t = preg_match('#[A-z0-9_]+#',$a,$m); if ( $t !== 1 || $m[0] !== $a ){ return false; } } return true; }
php
public static function check_name(): bool { $args = \func_get_args(); // Each argument must be a string starting with a letter, and having only one character made of letters, numbers and underscores foreach ( $args as $a ){ $a = self::cast($a); $t = preg_match('#[A-z0-9_]+#',$a,$m); if ( $t !== 1 || $m[0] !== $a ){ return false; } } return true; }
[ "public", "static", "function", "check_name", "(", ")", ":", "bool", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "// Each argument must be a string starting with a letter, and having only one character made of letters, numbers and underscores", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "$", "a", "=", "self", "::", "cast", "(", "$", "a", ")", ";", "$", "t", "=", "preg_match", "(", "'#[A-z0-9_]+#'", ",", "$", "a", ",", "$", "m", ")", ";", "if", "(", "$", "t", "!==", "1", "||", "$", "m", "[", "0", "]", "!==", "$", "a", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if a string complies with SQL naming convention. ```php \bbn\x::dump(\bbn\str::check_name("Paul")); // (bool) true \bbn\x::dump(\bbn\str::check_name("Pa ul")); // (bool) false ``` @return bool
[ "Checks", "if", "a", "string", "complies", "with", "SQL", "naming", "convention", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1012-L1026
nabab/bbn
src/bbn/str.php
str.check_filename
public static function check_filename(): bool { $args = \func_get_args(); // Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores foreach ( $args as $a ){ if ( !\is_string($a) || (strpos($a, '/') !== false) || (strpos($a, '\\') !== false) ){ return false; } } return true; }
php
public static function check_filename(): bool { $args = \func_get_args(); // Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores foreach ( $args as $a ){ if ( !\is_string($a) || (strpos($a, '/') !== false) || (strpos($a, '\\') !== false) ){ return false; } } return true; }
[ "public", "static", "function", "check_filename", "(", ")", ":", "bool", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "// Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "if", "(", "!", "\\", "is_string", "(", "$", "a", ")", "||", "(", "strpos", "(", "$", "a", ",", "'/'", ")", "!==", "false", ")", "||", "(", "strpos", "(", "$", "a", ",", "'\\\\'", ")", "!==", "false", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if a string doesn't contain a filesystem path. ```php \bbn\x::dump(\bbn\str::check_filename("Paul")); // (bool) true \bbn\x::dump(\bbn\str::check_filename("Paul/")); // (bool) false ``` @return bool
[ "Checks", "if", "a", "string", "doesn", "t", "contain", "a", "filesystem", "path", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1039-L1050
nabab/bbn
src/bbn/str.php
str.has_slash
public static function has_slash(): bool { $args = \func_get_args(); // Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores foreach ( $args as $a ){ if ( (strpos($a, '/') !== false) || (strpos($a, '\\') !== false) ){ return true; } } return false; }
php
public static function has_slash(): bool { $args = \func_get_args(); // Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores foreach ( $args as $a ){ if ( (strpos($a, '/') !== false) || (strpos($a, '\\') !== false) ){ return true; } } return false; }
[ "public", "static", "function", "has_slash", "(", ")", ":", "bool", "{", "$", "args", "=", "\\", "func_get_args", "(", ")", ";", "// Each argument must be a string starting with a letter, and having than one character made of letters, numbers and underscores", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "if", "(", "(", "strpos", "(", "$", "a", ",", "'/'", ")", "!==", "false", ")", "||", "(", "strpos", "(", "$", "a", ",", "'\\\\'", ")", "!==", "false", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if a string complies with SQL naming convention. Returns "true" if slash or backslash are present. ```php \bbn\x::dump(\bbn\str::has_slash("Paul")); // (bool) false \bbn\x::dump(\bbn\str::has_slash("Paul/"); // (bool) 1 \bbn\x::dump(\bbn\str::has_slash("Paul\\"); // (bool) 1 ``` @return bool
[ "Checks", "if", "a", "string", "complies", "with", "SQL", "naming", "convention", ".", "Returns", "true", "if", "slash", "or", "backslash", "are", "present", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1068-L1080
nabab/bbn
src/bbn/str.php
str.make_readable
public static function make_readable($o) { $is_array = false; if ( \is_object($o) ){ $class = \get_class($o); if ( $class === 'stdClass' ){ $is_array = 1; } else{ return $class; } } if ( \is_array($o) || $is_array ){ $r = []; foreach ( $o as $k => $v ){ $r[$k] = self::make_readable($v); } return $r; } return $o; }
php
public static function make_readable($o) { $is_array = false; if ( \is_object($o) ){ $class = \get_class($o); if ( $class === 'stdClass' ){ $is_array = 1; } else{ return $class; } } if ( \is_array($o) || $is_array ){ $r = []; foreach ( $o as $k => $v ){ $r[$k] = self::make_readable($v); } return $r; } return $o; }
[ "public", "static", "function", "make_readable", "(", "$", "o", ")", "{", "$", "is_array", "=", "false", ";", "if", "(", "\\", "is_object", "(", "$", "o", ")", ")", "{", "$", "class", "=", "\\", "get_class", "(", "$", "o", ")", ";", "if", "(", "$", "class", "===", "'stdClass'", ")", "{", "$", "is_array", "=", "1", ";", "}", "else", "{", "return", "$", "class", ";", "}", "}", "if", "(", "\\", "is_array", "(", "$", "o", ")", "||", "$", "is_array", ")", "{", "$", "r", "=", "[", "]", ";", "foreach", "(", "$", "o", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "r", "[", "$", "k", "]", "=", "self", "::", "make_readable", "(", "$", "v", ")", ";", "}", "return", "$", "r", ";", "}", "return", "$", "o", ";", "}" ]
Returns the argumented value, replacing not standard objects (not stdClass) by their class name. ```php $myObj = new stdClass(); $myObj->myProp1 = 23; $myObj->myProp2 = "world"; $myObj->myProp3 = [1, 5, 6]; $user = \bbn\user::get_instance(); $myArray = [ 'user' => $user, 'obj' => $myObj, 'val' => 23, 'text' => "Hello!" ]; \bbn\x::hdump(\bbn\str::make_readable($user)); // (string) "appui/user" \bbn\x::hdump(\bbn\str::make_readable($myArray)); /* (array) [ "user" => "appui\\user", "obj" => [ "myProp1" => 23, "myProp2" => "world", "myProp3" => [1, 5, 6,], ], "val" => 23, "text" => "Hello!", ] ``` @param mixed $o The item. @return array
[ "Returns", "the", "argumented", "value", "replacing", "not", "standard", "objects", "(", "not", "stdClass", ")", "by", "their", "class", "name", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1136-L1156
nabab/bbn
src/bbn/str.php
str.export
public static function export($o, $remove_empty=false, $lev=1): string { $st = ''; $space = ' '; if ( \is_object($o) && ($cls = \get_class($o)) && (strpos($cls, 'stdClass') === false) ){ $st .= "Object ".$cls; /* $o = array_filter((array)$o, function($k) use ($cls){ if ( strpos($k, '*') === 0 ){ return false; } if ( strpos($k, $cls) === 0 ){ return false; } return true; }, ARRAY_FILTER_USE_KEY); */ } else if ( \is_object($o) || \is_array($o) ){ $is_object = \is_object($o); $is_array = !$is_object && \is_array($o); $is_assoc = $is_object || ($is_array && x::is_assoc($o)); $st .= $is_assoc ? '{' : '['; $st .= PHP_EOL; foreach ( $o as $k => $v ){ if ( $remove_empty && ( ( \is_string($v) && empty($v) ) || ( \is_array($v) && \count($v) === 0 ) ) ){ continue; } $st .= str_repeat($space, $lev); if ( $is_assoc ){ $st .= ( \is_string($k) ? '"'.self::escape_dquote($k).'"' : $k ). ': '; } if ( \is_array($v) ){ $st .= self::export($v, $remove_empty, $lev+1); } else if ( $is_object ){ $cls = \get_class($v); if ( $cls === 'stdClass' ){ $st .= self::export($v, $remove_empty, $lev+1); } else{ /* $rc = new \ReflectionClass($cls); if ( $rc->hasMethod('__toString') ){ $st .= $v; } else{ $st .= 'Object '.$cls; } */ $st .= 'Object '.$cls; } } else if ( $v === 0 ){ $st .= '0'; } else if ( null === $v ){ $st .= 'null'; } else if ( \is_bool($v) ){ $st .= $v === false ? 'false' : 'true'; } else if ( \is_int($v) || \is_float($v) ){ $st .= $v; } else if ( !ctype_print($v) && (\strlen($v) === 16) ){ $st .= '0x'.bin2hex($v); } else if ( !$remove_empty || !empty($v) ){ $st .= '"'.self::escape_dquote($v).'"'; } $st .= ','.PHP_EOL; } $st .= str_repeat($space, $lev-1); $st .= $is_assoc ? '}' : ']'; //$st .= \is_object($o) ? '}' : ']'; } return $st; }
php
public static function export($o, $remove_empty=false, $lev=1): string { $st = ''; $space = ' '; if ( \is_object($o) && ($cls = \get_class($o)) && (strpos($cls, 'stdClass') === false) ){ $st .= "Object ".$cls; /* $o = array_filter((array)$o, function($k) use ($cls){ if ( strpos($k, '*') === 0 ){ return false; } if ( strpos($k, $cls) === 0 ){ return false; } return true; }, ARRAY_FILTER_USE_KEY); */ } else if ( \is_object($o) || \is_array($o) ){ $is_object = \is_object($o); $is_array = !$is_object && \is_array($o); $is_assoc = $is_object || ($is_array && x::is_assoc($o)); $st .= $is_assoc ? '{' : '['; $st .= PHP_EOL; foreach ( $o as $k => $v ){ if ( $remove_empty && ( ( \is_string($v) && empty($v) ) || ( \is_array($v) && \count($v) === 0 ) ) ){ continue; } $st .= str_repeat($space, $lev); if ( $is_assoc ){ $st .= ( \is_string($k) ? '"'.self::escape_dquote($k).'"' : $k ). ': '; } if ( \is_array($v) ){ $st .= self::export($v, $remove_empty, $lev+1); } else if ( $is_object ){ $cls = \get_class($v); if ( $cls === 'stdClass' ){ $st .= self::export($v, $remove_empty, $lev+1); } else{ /* $rc = new \ReflectionClass($cls); if ( $rc->hasMethod('__toString') ){ $st .= $v; } else{ $st .= 'Object '.$cls; } */ $st .= 'Object '.$cls; } } else if ( $v === 0 ){ $st .= '0'; } else if ( null === $v ){ $st .= 'null'; } else if ( \is_bool($v) ){ $st .= $v === false ? 'false' : 'true'; } else if ( \is_int($v) || \is_float($v) ){ $st .= $v; } else if ( !ctype_print($v) && (\strlen($v) === 16) ){ $st .= '0x'.bin2hex($v); } else if ( !$remove_empty || !empty($v) ){ $st .= '"'.self::escape_dquote($v).'"'; } $st .= ','.PHP_EOL; } $st .= str_repeat($space, $lev-1); $st .= $is_assoc ? '}' : ']'; //$st .= \is_object($o) ? '}' : ']'; } return $st; }
[ "public", "static", "function", "export", "(", "$", "o", ",", "$", "remove_empty", "=", "false", ",", "$", "lev", "=", "1", ")", ":", "string", "{", "$", "st", "=", "''", ";", "$", "space", "=", "' '", ";", "if", "(", "\\", "is_object", "(", "$", "o", ")", "&&", "(", "$", "cls", "=", "\\", "get_class", "(", "$", "o", ")", ")", "&&", "(", "strpos", "(", "$", "cls", ",", "'stdClass'", ")", "===", "false", ")", ")", "{", "$", "st", ".=", "\"Object \"", ".", "$", "cls", ";", "/*\n $o = array_filter((array)$o, function($k) use ($cls){\n if ( strpos($k, '*') === 0 ){\n return false;\n }\n if ( strpos($k, $cls) === 0 ){\n return false;\n }\n return true;\n }, ARRAY_FILTER_USE_KEY);\n */", "}", "else", "if", "(", "\\", "is_object", "(", "$", "o", ")", "||", "\\", "is_array", "(", "$", "o", ")", ")", "{", "$", "is_object", "=", "\\", "is_object", "(", "$", "o", ")", ";", "$", "is_array", "=", "!", "$", "is_object", "&&", "\\", "is_array", "(", "$", "o", ")", ";", "$", "is_assoc", "=", "$", "is_object", "||", "(", "$", "is_array", "&&", "x", "::", "is_assoc", "(", "$", "o", ")", ")", ";", "$", "st", ".=", "$", "is_assoc", "?", "'{'", ":", "'['", ";", "$", "st", ".=", "PHP_EOL", ";", "foreach", "(", "$", "o", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "remove_empty", "&&", "(", "(", "\\", "is_string", "(", "$", "v", ")", "&&", "empty", "(", "$", "v", ")", ")", "||", "(", "\\", "is_array", "(", "$", "v", ")", "&&", "\\", "count", "(", "$", "v", ")", "===", "0", ")", ")", ")", "{", "continue", ";", "}", "$", "st", ".=", "str_repeat", "(", "$", "space", ",", "$", "lev", ")", ";", "if", "(", "$", "is_assoc", ")", "{", "$", "st", ".=", "(", "\\", "is_string", "(", "$", "k", ")", "?", "'\"'", ".", "self", "::", "escape_dquote", "(", "$", "k", ")", ".", "'\"'", ":", "$", "k", ")", ".", "': '", ";", "}", "if", "(", "\\", "is_array", "(", "$", "v", ")", ")", "{", "$", "st", ".=", "self", "::", "export", "(", "$", "v", ",", "$", "remove_empty", ",", "$", "lev", "+", "1", ")", ";", "}", "else", "if", "(", "$", "is_object", ")", "{", "$", "cls", "=", "\\", "get_class", "(", "$", "v", ")", ";", "if", "(", "$", "cls", "===", "'stdClass'", ")", "{", "$", "st", ".=", "self", "::", "export", "(", "$", "v", ",", "$", "remove_empty", ",", "$", "lev", "+", "1", ")", ";", "}", "else", "{", "/*\n $rc = new \\ReflectionClass($cls);\n if ( $rc->hasMethod('__toString') ){\n $st .= $v;\n }\n else{\n $st .= 'Object '.$cls;\n }\n */", "$", "st", ".=", "'Object '", ".", "$", "cls", ";", "}", "}", "else", "if", "(", "$", "v", "===", "0", ")", "{", "$", "st", ".=", "'0'", ";", "}", "else", "if", "(", "null", "===", "$", "v", ")", "{", "$", "st", ".=", "'null'", ";", "}", "else", "if", "(", "\\", "is_bool", "(", "$", "v", ")", ")", "{", "$", "st", ".=", "$", "v", "===", "false", "?", "'false'", ":", "'true'", ";", "}", "else", "if", "(", "\\", "is_int", "(", "$", "v", ")", "||", "\\", "is_float", "(", "$", "v", ")", ")", "{", "$", "st", ".=", "$", "v", ";", "}", "else", "if", "(", "!", "ctype_print", "(", "$", "v", ")", "&&", "(", "\\", "strlen", "(", "$", "v", ")", "===", "16", ")", ")", "{", "$", "st", ".=", "'0x'", ".", "bin2hex", "(", "$", "v", ")", ";", "}", "else", "if", "(", "!", "$", "remove_empty", "||", "!", "empty", "(", "$", "v", ")", ")", "{", "$", "st", ".=", "'\"'", ".", "self", "::", "escape_dquote", "(", "$", "v", ")", ".", "'\"'", ";", "}", "$", "st", ".=", "','", ".", "PHP_EOL", ";", "}", "$", "st", ".=", "str_repeat", "(", "$", "space", ",", "$", "lev", "-", "1", ")", ";", "$", "st", ".=", "$", "is_assoc", "?", "'}'", ":", "']'", ";", "//$st .= \\is_object($o) ? '}' : ']';", "}", "return", "$", "st", ";", "}" ]
Returns a variable in a mode that is directly usable by PHP. ```php $myObj = new stdClass(); $myObj->myProp1 = 23; $myObj->myProp2 = "world"; $myObj->myProp3 = [1, 5, 6]; $myObj->myProp4 =""; \bbn\x::hdump(\bbn\str::export($myObj,true)); /*(string) "{ "myProp1" => 23, "myProp2" => "world", "myProp3" => [ 1, 5, 6, ], }" ``` @param mixed $o The item to be. @param bool $remove_empty Default: "false". @param int $lev Default: "1". @return string
[ "Returns", "a", "variable", "in", "a", "mode", "that", "is", "directly", "usable", "by", "PHP", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1182-L1260
nabab/bbn
src/bbn/str.php
str.say_size
public static function say_size($bytes, $unit = 'B', $stop = false): string { // pretty printer for byte values // $i = 0; $units = ['', 'K', 'M', 'G', 'T']; while ( $stop || ($bytes > 2000) ){ $i++; $bytes /= 1024; if ( $stop === $units[$i] ){ break; } } return sprintf("%5.2f %s".$unit, $bytes, $units[$i]); }
php
public static function say_size($bytes, $unit = 'B', $stop = false): string { // pretty printer for byte values // $i = 0; $units = ['', 'K', 'M', 'G', 'T']; while ( $stop || ($bytes > 2000) ){ $i++; $bytes /= 1024; if ( $stop === $units[$i] ){ break; } } return sprintf("%5.2f %s".$unit, $bytes, $units[$i]); }
[ "public", "static", "function", "say_size", "(", "$", "bytes", ",", "$", "unit", "=", "'B'", ",", "$", "stop", "=", "false", ")", ":", "string", "{", "// pretty printer for byte values", "//", "$", "i", "=", "0", ";", "$", "units", "=", "[", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", "]", ";", "while", "(", "$", "stop", "||", "(", "$", "bytes", ">", "2000", ")", ")", "{", "$", "i", "++", ";", "$", "bytes", "/=", "1024", ";", "if", "(", "$", "stop", "===", "$", "units", "[", "$", "i", "]", ")", "{", "break", ";", "}", "}", "return", "sprintf", "(", "\"%5.2f %s\"", ".", "$", "unit", ",", "$", "bytes", ",", "$", "units", "[", "$", "i", "]", ")", ";", "}" ]
Converts the bytes to another unit form. @param int $bytes The bytes @param string The unit you want to convert ('B', 'K', 'M', 'G', 'T') @parma boolean $stop @return string
[ "Converts", "the", "bytes", "to", "another", "unit", "form", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1311-L1325
nabab/bbn
src/bbn/str.php
str.check_json
function check_json(string $json, bool $return_error = false) { json_decode($json); $error = json_last_error(); if ( $error === JSON_ERROR_NONE ){ return true; } if ( !$return_error ){ return false; } switch ( $error ) { case JSON_ERROR_DEPTH: return _('Maximum stack depth exceeded'); case JSON_ERROR_STATE_MISMATCH: return _('State mismatch (invalid or malformed JSON)'); case JSON_ERROR_CTRL_CHAR: return _('Unexpected control character found'); case JSON_ERROR_SYNTAX: return _('Syntax error, malformed JSON'); case JSON_ERROR_UTF8: return _('Malformed UTF-8 characters, possibly incorrectly encoded'); default: return _('Unknown error'); } }
php
function check_json(string $json, bool $return_error = false) { json_decode($json); $error = json_last_error(); if ( $error === JSON_ERROR_NONE ){ return true; } if ( !$return_error ){ return false; } switch ( $error ) { case JSON_ERROR_DEPTH: return _('Maximum stack depth exceeded'); case JSON_ERROR_STATE_MISMATCH: return _('State mismatch (invalid or malformed JSON)'); case JSON_ERROR_CTRL_CHAR: return _('Unexpected control character found'); case JSON_ERROR_SYNTAX: return _('Syntax error, malformed JSON'); case JSON_ERROR_UTF8: return _('Malformed UTF-8 characters, possibly incorrectly encoded'); default: return _('Unknown error'); } }
[ "function", "check_json", "(", "string", "$", "json", ",", "bool", "$", "return_error", "=", "false", ")", "{", "json_decode", "(", "$", "json", ")", ";", "$", "error", "=", "json_last_error", "(", ")", ";", "if", "(", "$", "error", "===", "JSON_ERROR_NONE", ")", "{", "return", "true", ";", "}", "if", "(", "!", "$", "return_error", ")", "{", "return", "false", ";", "}", "switch", "(", "$", "error", ")", "{", "case", "JSON_ERROR_DEPTH", ":", "return", "_", "(", "'Maximum stack depth exceeded'", ")", ";", "case", "JSON_ERROR_STATE_MISMATCH", ":", "return", "_", "(", "'State mismatch (invalid or malformed JSON)'", ")", ";", "case", "JSON_ERROR_CTRL_CHAR", ":", "return", "_", "(", "'Unexpected control character found'", ")", ";", "case", "JSON_ERROR_SYNTAX", ":", "return", "_", "(", "'Syntax error, malformed JSON'", ")", ";", "case", "JSON_ERROR_UTF8", ":", "return", "_", "(", "'Malformed UTF-8 characters, possibly incorrectly encoded'", ")", ";", "default", ":", "return", "_", "(", "'Unknown error'", ")", ";", "}", "}" ]
Checks whether a JSON string is valid or not. If $return_error is set to true, the error will be returned. @param string $json @param bool $return_error @return bool|string
[ "Checks", "whether", "a", "JSON", "string", "is", "valid", "or", "not", ".", "If", "$return_error", "is", "set", "to", "true", "the", "error", "will", "be", "returned", "." ]
train
https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/str.php#L1354-L1378
99designs/ergo-http
src/Status.php
Status.getMessage
public function getMessage() { $code = $this->getCode(); if (!array_key_exists($code, $this->_messageMap)) throw new Error("Unknown HTTP status code: $code"); return $this->_messageMap[$code]; }
php
public function getMessage() { $code = $this->getCode(); if (!array_key_exists($code, $this->_messageMap)) throw new Error("Unknown HTTP status code: $code"); return $this->_messageMap[$code]; }
[ "public", "function", "getMessage", "(", ")", "{", "$", "code", "=", "$", "this", "->", "getCode", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "code", ",", "$", "this", "->", "_messageMap", ")", ")", "throw", "new", "Error", "(", "\"Unknown HTTP status code: $code\"", ")", ";", "return", "$", "this", "->", "_messageMap", "[", "$", "code", "]", ";", "}" ]
The message associated with, but not including, the status code. @return string
[ "The", "message", "associated", "with", "but", "not", "including", "the", "status", "code", "." ]
train
https://github.com/99designs/ergo-http/blob/979b789f2e011a1cb70a00161e6b7bcd0d2e9c71/src/Status.php#L91-L99
yuncms/yii2-authentication
backend/models/AuthenticationSearch.php
AuthenticationSearch.search
public function search($params) { $query = Authentication::find()->with('user'); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'user_id' => $this->user_id, 'status' => $this->status, ]); if ($this->created_at !== null) { $date = strtotime($this->created_at); $query->andWhere(['between', 'created_at', $date, $date + 3600 * 24]); } if ($this->updated_at !== null) { $date = strtotime($this->updated_at); $query->andWhere(['between', 'updated_at', $date, $date + 3600 * 24]); } $query->andFilterWhere(['like', 'real_name', $this->real_name]) ->andFilterWhere(['like', 'id_card', $this->id_card]); return $dataProvider; }
php
public function search($params) { $query = Authentication::find()->with('user'); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'user_id' => $this->user_id, 'status' => $this->status, ]); if ($this->created_at !== null) { $date = strtotime($this->created_at); $query->andWhere(['between', 'created_at', $date, $date + 3600 * 24]); } if ($this->updated_at !== null) { $date = strtotime($this->updated_at); $query->andWhere(['between', 'updated_at', $date, $date + 3600 * 24]); } $query->andFilterWhere(['like', 'real_name', $this->real_name]) ->andFilterWhere(['like', 'id_card', $this->id_card]); return $dataProvider; }
[ "public", "function", "search", "(", "$", "params", ")", "{", "$", "query", "=", "Authentication", "::", "find", "(", ")", "->", "with", "(", "'user'", ")", ";", "// add conditions that should always apply here", "$", "dataProvider", "=", "new", "ActiveDataProvider", "(", "[", "'query'", "=>", "$", "query", ",", "]", ")", ";", "if", "(", "!", "(", "$", "this", "->", "load", "(", "$", "params", ")", "&&", "$", "this", "->", "validate", "(", ")", ")", ")", "{", "return", "$", "dataProvider", ";", "}", "// grid filtering conditions", "$", "query", "->", "andFilterWhere", "(", "[", "'user_id'", "=>", "$", "this", "->", "user_id", ",", "'status'", "=>", "$", "this", "->", "status", ",", "]", ")", ";", "if", "(", "$", "this", "->", "created_at", "!==", "null", ")", "{", "$", "date", "=", "strtotime", "(", "$", "this", "->", "created_at", ")", ";", "$", "query", "->", "andWhere", "(", "[", "'between'", ",", "'created_at'", ",", "$", "date", ",", "$", "date", "+", "3600", "*", "24", "]", ")", ";", "}", "if", "(", "$", "this", "->", "updated_at", "!==", "null", ")", "{", "$", "date", "=", "strtotime", "(", "$", "this", "->", "updated_at", ")", ";", "$", "query", "->", "andWhere", "(", "[", "'between'", ",", "'updated_at'", ",", "$", "date", ",", "$", "date", "+", "3600", "*", "24", "]", ")", ";", "}", "$", "query", "->", "andFilterWhere", "(", "[", "'like'", ",", "'real_name'", ",", "$", "this", "->", "real_name", "]", ")", "->", "andFilterWhere", "(", "[", "'like'", ",", "'id_card'", ",", "$", "this", "->", "id_card", "]", ")", ";", "return", "$", "dataProvider", ";", "}" ]
Creates data provider instance with search query applied @param array $params @return ActiveDataProvider
[ "Creates", "data", "provider", "instance", "with", "search", "query", "applied" ]
train
https://github.com/yuncms/yii2-authentication/blob/02b70f7d2587480edb6dcc18ce256db662f1ed0d/backend/models/AuthenticationSearch.php#L50-L84
yuncms/yii2-authentication
backend/models/AuthenticationSearch.php
AuthenticationSearch.dropDown
public static function dropDown($column, $value = null) { $dropDownList = [ "status" => [ Authentication::STATUS_PENDING => Yii::t('authentication', 'Pending review'), Authentication::STATUS_REJECTED => Yii::t('authentication', 'Rejected'), Authentication::STATUS_AUTHENTICATED => Yii::t('authentication', 'Authenticated'), ], ]; //根据具体值显示对应的值 if ($value !== null) { return array_key_exists($column, $dropDownList) ? $dropDownList[$column][$value] : false; } else {//返回关联数组,用户下拉的filter实现 return array_key_exists($column, $dropDownList) ? $dropDownList[$column] : false; } }
php
public static function dropDown($column, $value = null) { $dropDownList = [ "status" => [ Authentication::STATUS_PENDING => Yii::t('authentication', 'Pending review'), Authentication::STATUS_REJECTED => Yii::t('authentication', 'Rejected'), Authentication::STATUS_AUTHENTICATED => Yii::t('authentication', 'Authenticated'), ], ]; //根据具体值显示对应的值 if ($value !== null) { return array_key_exists($column, $dropDownList) ? $dropDownList[$column][$value] : false; } else {//返回关联数组,用户下拉的filter实现 return array_key_exists($column, $dropDownList) ? $dropDownList[$column] : false; } }
[ "public", "static", "function", "dropDown", "(", "$", "column", ",", "$", "value", "=", "null", ")", "{", "$", "dropDownList", "=", "[", "\"status\"", "=>", "[", "Authentication", "::", "STATUS_PENDING", "=>", "Yii", "::", "t", "(", "'authentication'", ",", "'Pending review'", ")", ",", "Authentication", "::", "STATUS_REJECTED", "=>", "Yii", "::", "t", "(", "'authentication'", ",", "'Rejected'", ")", ",", "Authentication", "::", "STATUS_AUTHENTICATED", "=>", "Yii", "::", "t", "(", "'authentication'", ",", "'Authenticated'", ")", ",", "]", ",", "]", ";", "//根据具体值显示对应的值", "if", "(", "$", "value", "!==", "null", ")", "{", "return", "array_key_exists", "(", "$", "column", ",", "$", "dropDownList", ")", "?", "$", "dropDownList", "[", "$", "column", "]", "[", "$", "value", "]", ":", "false", ";", "}", "else", "{", "//返回关联数组,用户下拉的filter实现", "return", "array_key_exists", "(", "$", "column", ",", "$", "dropDownList", ")", "?", "$", "dropDownList", "[", "$", "column", "]", ":", "false", ";", "}", "}" ]
下拉筛选 @param string $column @param null|string $value @return bool|mixed
[ "下拉筛选" ]
train
https://github.com/yuncms/yii2-authentication/blob/02b70f7d2587480edb6dcc18ce256db662f1ed0d/backend/models/AuthenticationSearch.php#L92-L107
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/TagConverter.php
TagConverter.convert
public function convert(\DOMElement $parent, TagDescriptor $tag) { $description = $this->getDescription($tag); $child = new \DOMElement('tag'); $parent->appendChild($child); $child->setAttribute('name', str_replace('&', '&amp;', $tag->getName())); $child->setAttribute('line', $parent->getAttribute('line')); $child->setAttribute('description', str_replace('&', '&amp;', $description)); $this->addTypes($tag, $child); // TODO: make the tests below configurable from the outside so that more could be added using plugins if (method_exists($tag, 'getVariableName')) { $child->setAttribute('variable', str_replace('&', '&amp;', $tag->getVariableName())); } if (method_exists($tag, 'getReference')) { $child->setAttribute('link', str_replace('&', '&amp;', $tag->getReference())); } if (method_exists($tag, 'getLink')) { $child->setAttribute('link', str_replace('&', '&amp;', $tag->getLink())); } if (method_exists($tag, 'getMethodName')) { $child->setAttribute('method_name', str_replace('&', '&amp;', $tag->getMethodName())); } return $child; }
php
public function convert(\DOMElement $parent, TagDescriptor $tag) { $description = $this->getDescription($tag); $child = new \DOMElement('tag'); $parent->appendChild($child); $child->setAttribute('name', str_replace('&', '&amp;', $tag->getName())); $child->setAttribute('line', $parent->getAttribute('line')); $child->setAttribute('description', str_replace('&', '&amp;', $description)); $this->addTypes($tag, $child); // TODO: make the tests below configurable from the outside so that more could be added using plugins if (method_exists($tag, 'getVariableName')) { $child->setAttribute('variable', str_replace('&', '&amp;', $tag->getVariableName())); } if (method_exists($tag, 'getReference')) { $child->setAttribute('link', str_replace('&', '&amp;', $tag->getReference())); } if (method_exists($tag, 'getLink')) { $child->setAttribute('link', str_replace('&', '&amp;', $tag->getLink())); } if (method_exists($tag, 'getMethodName')) { $child->setAttribute('method_name', str_replace('&', '&amp;', $tag->getMethodName())); } return $child; }
[ "public", "function", "convert", "(", "\\", "DOMElement", "$", "parent", ",", "TagDescriptor", "$", "tag", ")", "{", "$", "description", "=", "$", "this", "->", "getDescription", "(", "$", "tag", ")", ";", "$", "child", "=", "new", "\\", "DOMElement", "(", "'tag'", ")", ";", "$", "parent", "->", "appendChild", "(", "$", "child", ")", ";", "$", "child", "->", "setAttribute", "(", "'name'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "$", "tag", "->", "getName", "(", ")", ")", ")", ";", "$", "child", "->", "setAttribute", "(", "'line'", ",", "$", "parent", "->", "getAttribute", "(", "'line'", ")", ")", ";", "$", "child", "->", "setAttribute", "(", "'description'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "$", "description", ")", ")", ";", "$", "this", "->", "addTypes", "(", "$", "tag", ",", "$", "child", ")", ";", "// TODO: make the tests below configurable from the outside so that more could be added using plugins", "if", "(", "method_exists", "(", "$", "tag", ",", "'getVariableName'", ")", ")", "{", "$", "child", "->", "setAttribute", "(", "'variable'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "$", "tag", "->", "getVariableName", "(", ")", ")", ")", ";", "}", "if", "(", "method_exists", "(", "$", "tag", ",", "'getReference'", ")", ")", "{", "$", "child", "->", "setAttribute", "(", "'link'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "$", "tag", "->", "getReference", "(", ")", ")", ")", ";", "}", "if", "(", "method_exists", "(", "$", "tag", ",", "'getLink'", ")", ")", "{", "$", "child", "->", "setAttribute", "(", "'link'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "$", "tag", "->", "getLink", "(", ")", ")", ")", ";", "}", "if", "(", "method_exists", "(", "$", "tag", ",", "'getMethodName'", ")", ")", "{", "$", "child", "->", "setAttribute", "(", "'method_name'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "$", "tag", "->", "getMethodName", "(", ")", ")", ")", ";", "}", "return", "$", "child", ";", "}" ]
Export this tag to the given DocBlock. @param \DOMElement $parent Element to augment. @param TagDescriptor $tag The tag to export. @return \DOMElement
[ "Export", "this", "tag", "to", "the", "given", "DocBlock", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/TagConverter.php#L35-L62
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/TagConverter.php
TagConverter.getDescription
protected function getDescription(TagDescriptor $tag) { $description = ''; //@version, @deprecated, @since if (method_exists($tag, 'getVersion')) { $description .= $tag->getVersion() . ' '; } $description .= $tag->getDescription(); return trim($description); }
php
protected function getDescription(TagDescriptor $tag) { $description = ''; //@version, @deprecated, @since if (method_exists($tag, 'getVersion')) { $description .= $tag->getVersion() . ' '; } $description .= $tag->getDescription(); return trim($description); }
[ "protected", "function", "getDescription", "(", "TagDescriptor", "$", "tag", ")", "{", "$", "description", "=", "''", ";", "//@version, @deprecated, @since", "if", "(", "method_exists", "(", "$", "tag", ",", "'getVersion'", ")", ")", "{", "$", "description", ".=", "$", "tag", "->", "getVersion", "(", ")", ".", "' '", ";", "}", "$", "description", ".=", "$", "tag", "->", "getDescription", "(", ")", ";", "return", "trim", "(", "$", "description", ")", ";", "}" ]
Returns the description from the Tag with the version prepended when applicable. @param TagDescriptor $tag @todo the version should not be prepended here but in templates; remove this. @return string
[ "Returns", "the", "description", "from", "the", "Tag", "with", "the", "version", "prepended", "when", "applicable", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/TagConverter.php#L73-L85
heidelpay/PhpDoc
src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/TagConverter.php
TagConverter.addTypes
protected function addTypes(TagDescriptor $tag, \DOMElement $child) { if (!method_exists($tag, 'getTypes')) { return; } $typeString = ''; foreach ($tag->getTypes() as $type) { $typeString .= $type . '|'; /** @var \DOMElement $typeNode */ $typeNode = $child->appendChild(new \DOMElement('type')); $typeNode->appendChild(new \DOMText($type)); } $child->setAttribute('type', str_replace('&', '&amp;', rtrim($typeString, '|'))); }
php
protected function addTypes(TagDescriptor $tag, \DOMElement $child) { if (!method_exists($tag, 'getTypes')) { return; } $typeString = ''; foreach ($tag->getTypes() as $type) { $typeString .= $type . '|'; /** @var \DOMElement $typeNode */ $typeNode = $child->appendChild(new \DOMElement('type')); $typeNode->appendChild(new \DOMText($type)); } $child->setAttribute('type', str_replace('&', '&amp;', rtrim($typeString, '|'))); }
[ "protected", "function", "addTypes", "(", "TagDescriptor", "$", "tag", ",", "\\", "DOMElement", "$", "child", ")", "{", "if", "(", "!", "method_exists", "(", "$", "tag", ",", "'getTypes'", ")", ")", "{", "return", ";", "}", "$", "typeString", "=", "''", ";", "foreach", "(", "$", "tag", "->", "getTypes", "(", ")", "as", "$", "type", ")", "{", "$", "typeString", ".=", "$", "type", ".", "'|'", ";", "/** @var \\DOMElement $typeNode */", "$", "typeNode", "=", "$", "child", "->", "appendChild", "(", "new", "\\", "DOMElement", "(", "'type'", ")", ")", ";", "$", "typeNode", "->", "appendChild", "(", "new", "\\", "DOMText", "(", "$", "type", ")", ")", ";", "}", "$", "child", "->", "setAttribute", "(", "'type'", ",", "str_replace", "(", "'&'", ",", "'&amp;'", ",", "rtrim", "(", "$", "typeString", ",", "'|'", ")", ")", ")", ";", "}" ]
Adds type elements and a type attribute to the tag if a method 'getTypes' is present. @param TagDescriptor $tag @param \DOMElement $child @return void
[ "Adds", "type", "elements", "and", "a", "type", "attribute", "to", "the", "tag", "if", "a", "method", "getTypes", "is", "present", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Transformer/Writer/Xml/TagConverter.php#L95-L111
BugBuster1701/contao-botdetection-bundle
src/Resources/contao/classes/Referrer/ProviderParser.php
ProviderParser.isUpdateProviderListNecessary
public function isUpdateProviderListNecessary() { $lastWeek = time() - (7 * 24 * 60 * 60); if (false === file_exists($this->cachePath .'/referrerblocked.txt') || $lastWeek > filemtime($this->cachePath .'/referrerblocked.txt') ) { return true; // update/anlegen notwendig } foreach($this->referrerProvider as $source => $url) { if (true === file_exists($this->cachePath .'/'. strtolower($source) . '.txt') && $lastWeek > filemtime($this->cachePath .'/'. strtolower($source) . '.txt') ) { return true; // update/anlegen notwendig, da eine Provider Datei neuer ist } } return false; }
php
public function isUpdateProviderListNecessary() { $lastWeek = time() - (7 * 24 * 60 * 60); if (false === file_exists($this->cachePath .'/referrerblocked.txt') || $lastWeek > filemtime($this->cachePath .'/referrerblocked.txt') ) { return true; // update/anlegen notwendig } foreach($this->referrerProvider as $source => $url) { if (true === file_exists($this->cachePath .'/'. strtolower($source) . '.txt') && $lastWeek > filemtime($this->cachePath .'/'. strtolower($source) . '.txt') ) { return true; // update/anlegen notwendig, da eine Provider Datei neuer ist } } return false; }
[ "public", "function", "isUpdateProviderListNecessary", "(", ")", "{", "$", "lastWeek", "=", "time", "(", ")", "-", "(", "7", "*", "24", "*", "60", "*", "60", ")", ";", "if", "(", "false", "===", "file_exists", "(", "$", "this", "->", "cachePath", ".", "'/referrerblocked.txt'", ")", "||", "$", "lastWeek", ">", "filemtime", "(", "$", "this", "->", "cachePath", ".", "'/referrerblocked.txt'", ")", ")", "{", "return", "true", ";", "// update/anlegen notwendig", "}", "foreach", "(", "$", "this", "->", "referrerProvider", "as", "$", "source", "=>", "$", "url", ")", "{", "if", "(", "true", "===", "file_exists", "(", "$", "this", "->", "cachePath", ".", "'/'", ".", "strtolower", "(", "$", "source", ")", ".", "'.txt'", ")", "&&", "$", "lastWeek", ">", "filemtime", "(", "$", "this", "->", "cachePath", ".", "'/'", ".", "strtolower", "(", "$", "source", ")", ".", "'.txt'", ")", ")", "{", "return", "true", ";", "// update/anlegen notwendig, da eine Provider Datei neuer ist", "}", "}", "return", "false", ";", "}" ]
Test ob Update/Generierung von referrerblocked.txt notwendig @return boolean true: ja, false nein
[ "Test", "ob", "Update", "/", "Generierung", "von", "referrerblocked", ".", "txt", "notwendig" ]
train
https://github.com/BugBuster1701/contao-botdetection-bundle/blob/50c964acc354aa9116fae0e509cd7d075bd52f55/src/Resources/contao/classes/Referrer/ProviderParser.php#L123-L144
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Translation/src/filters/leet_filter.php
ezcTranslationLeetFilter.leetify
static private function leetify( $text ) { $searchMap = array( '/to/i', '/for/i', '/ate/i', '/your/i', '/you/i', '/l/i', '/e/i', '/o/i', '/a/i', '/t/i' ); $replaceMap = array( '2', '4', '8', 'ur', 'u', '1', '3', '0', '4', '7' ); $textBlocks = preg_split( '/(%[^ ]+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); $newTextBlocks = array(); foreach ( $textBlocks as $text ) { if ( strlen( $text ) && $text[0] == '%' ) { $newTextBlocks[] = (string) $text; continue; } $text = preg_replace( $searchMap, $replaceMap, $text ); $newTextBlocks[] = (string) $text; } $text = implode( '', $newTextBlocks ); return $text; }
php
static private function leetify( $text ) { $searchMap = array( '/to/i', '/for/i', '/ate/i', '/your/i', '/you/i', '/l/i', '/e/i', '/o/i', '/a/i', '/t/i' ); $replaceMap = array( '2', '4', '8', 'ur', 'u', '1', '3', '0', '4', '7' ); $textBlocks = preg_split( '/(%[^ ]+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); $newTextBlocks = array(); foreach ( $textBlocks as $text ) { if ( strlen( $text ) && $text[0] == '%' ) { $newTextBlocks[] = (string) $text; continue; } $text = preg_replace( $searchMap, $replaceMap, $text ); $newTextBlocks[] = (string) $text; } $text = implode( '', $newTextBlocks ); return $text; }
[ "static", "private", "function", "leetify", "(", "$", "text", ")", "{", "$", "searchMap", "=", "array", "(", "'/to/i'", ",", "'/for/i'", ",", "'/ate/i'", ",", "'/your/i'", ",", "'/you/i'", ",", "'/l/i'", ",", "'/e/i'", ",", "'/o/i'", ",", "'/a/i'", ",", "'/t/i'", ")", ";", "$", "replaceMap", "=", "array", "(", "'2'", ",", "'4'", ",", "'8'", ",", "'ur'", ",", "'u'", ",", "'1'", ",", "'3'", ",", "'0'", ",", "'4'", ",", "'7'", ")", ";", "$", "textBlocks", "=", "preg_split", "(", "'/(%[^ ]+)/'", ",", "$", "text", ",", "-", "1", ",", "PREG_SPLIT_DELIM_CAPTURE", ")", ";", "$", "newTextBlocks", "=", "array", "(", ")", ";", "foreach", "(", "$", "textBlocks", "as", "$", "text", ")", "{", "if", "(", "strlen", "(", "$", "text", ")", "&&", "$", "text", "[", "0", "]", "==", "'%'", ")", "{", "$", "newTextBlocks", "[", "]", "=", "(", "string", ")", "$", "text", ";", "continue", ";", "}", "$", "text", "=", "preg_replace", "(", "$", "searchMap", ",", "$", "replaceMap", ",", "$", "text", ")", ";", "$", "newTextBlocks", "[", "]", "=", "(", "string", ")", "$", "text", ";", "}", "$", "text", "=", "implode", "(", "''", ",", "$", "newTextBlocks", ")", ";", "return", "$", "text", ";", "}" ]
This "leetify" the $text. @param string $text @return string
[ "This", "leetify", "the", "$text", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Translation/src/filters/leet_filter.php#L52-L72
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Translation/src/filters/leet_filter.php
ezcTranslationLeetFilter.runFilter
public function runFilter( array $context ) { foreach ( $context as $element ) { $element->translation = self::leetify( $element->translation ); } }
php
public function runFilter( array $context ) { foreach ( $context as $element ) { $element->translation = self::leetify( $element->translation ); } }
[ "public", "function", "runFilter", "(", "array", "$", "context", ")", "{", "foreach", "(", "$", "context", "as", "$", "element", ")", "{", "$", "element", "->", "translation", "=", "self", "::", "leetify", "(", "$", "element", "->", "translation", ")", ";", "}", "}" ]
Filters a context Applies the "1337" filter on the given context. This filter leetifies text old skool. It is, of course, just an example. @param array[ezcTranslationData] $context @return void
[ "Filters", "a", "context" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Translation/src/filters/leet_filter.php#L83-L89
inhere/php-librarys
src/Traits/NameAliasStaticTrait.php
NameAliasStaticTrait.alias
public static function alias($name, $alias = null) { // get real name for $id if (null === $alias) { return self::resolveAlias($name); } foreach ((array)$alias as $aliasName) { if (!isset(self::$aliases[$aliasName])) { self::$aliases[$aliasName] = $name; } } return true; }
php
public static function alias($name, $alias = null) { // get real name for $id if (null === $alias) { return self::resolveAlias($name); } foreach ((array)$alias as $aliasName) { if (!isset(self::$aliases[$aliasName])) { self::$aliases[$aliasName] = $name; } } return true; }
[ "public", "static", "function", "alias", "(", "$", "name", ",", "$", "alias", "=", "null", ")", "{", "// get real name for $id", "if", "(", "null", "===", "$", "alias", ")", "{", "return", "self", "::", "resolveAlias", "(", "$", "name", ")", ";", "}", "foreach", "(", "(", "array", ")", "$", "alias", "as", "$", "aliasName", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aliases", "[", "$", "aliasName", "]", ")", ")", "{", "self", "::", "$", "aliases", "[", "$", "aliasName", "]", "=", "$", "name", ";", "}", "}", "return", "true", ";", "}" ]
set/get name alias @param array|string $name @param string|null $alias @return bool|string
[ "set", "/", "get", "name", "alias" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Traits/NameAliasStaticTrait.php#L26-L40
zhouyl/mellivora
Mellivora/Database/Eloquent/Concerns/HasRelationships.php
HasRelationships.morphTo
public function morphTo($name = null, $type = null, $id = null) { // If no name is provided, we will use the backtrace to get the function name // since that is most likely the name of the polymorphic interface. We can // use that to get both the class and foreign key that will be utilized. $name = $name ?: $this->guessBelongsToRelation(); list($type, $id) = $this->getMorphs( Str::snake($name), $type, $id ); // If the type value is null it is probably safe to assume we're eager loading // the relationship. In this case we'll just pass in a dummy query where we // need to remove any eager loads that may already be defined on a model. return empty($class = $this->{$type}) ? $this->morphEagerTo($name, $type, $id) : $this->morphInstanceTo($class, $name, $type, $id); }
php
public function morphTo($name = null, $type = null, $id = null) { // If no name is provided, we will use the backtrace to get the function name // since that is most likely the name of the polymorphic interface. We can // use that to get both the class and foreign key that will be utilized. $name = $name ?: $this->guessBelongsToRelation(); list($type, $id) = $this->getMorphs( Str::snake($name), $type, $id ); // If the type value is null it is probably safe to assume we're eager loading // the relationship. In this case we'll just pass in a dummy query where we // need to remove any eager loads that may already be defined on a model. return empty($class = $this->{$type}) ? $this->morphEagerTo($name, $type, $id) : $this->morphInstanceTo($class, $name, $type, $id); }
[ "public", "function", "morphTo", "(", "$", "name", "=", "null", ",", "$", "type", "=", "null", ",", "$", "id", "=", "null", ")", "{", "// If no name is provided, we will use the backtrace to get the function name", "// since that is most likely the name of the polymorphic interface. We can", "// use that to get both the class and foreign key that will be utilized.", "$", "name", "=", "$", "name", "?", ":", "$", "this", "->", "guessBelongsToRelation", "(", ")", ";", "list", "(", "$", "type", ",", "$", "id", ")", "=", "$", "this", "->", "getMorphs", "(", "Str", "::", "snake", "(", "$", "name", ")", ",", "$", "type", ",", "$", "id", ")", ";", "// If the type value is null it is probably safe to assume we're eager loading", "// the relationship. In this case we'll just pass in a dummy query where we", "// need to remove any eager loads that may already be defined on a model.", "return", "empty", "(", "$", "class", "=", "$", "this", "->", "{", "$", "type", "}", ")", "?", "$", "this", "->", "morphEagerTo", "(", "$", "name", ",", "$", "type", ",", "$", "id", ")", ":", "$", "this", "->", "morphInstanceTo", "(", "$", "class", ",", "$", "name", ",", "$", "type", ",", "$", "id", ")", ";", "}" ]
Define a polymorphic, inverse one-to-one or many relationship. @param string $name @param string $type @param string $id @return \Mellivora\Database\Eloquent\Relations\MorphTo
[ "Define", "a", "polymorphic", "inverse", "one", "-", "to", "-", "one", "or", "many", "relationship", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Concerns/HasRelationships.php#L141-L160
zhouyl/mellivora
Mellivora/Database/Eloquent/Concerns/HasRelationships.php
HasRelationships.morphToMany
public function morphToMany($related, $name, $table = null, $foreignKey = null, $relatedKey = null, $inverse = false) { $caller = $this->guessBelongsToManyRelation(); // First, we will need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we will make the query // instances, as well as the relationship instances we need for these. $instance = $this->newRelatedInstance($related); $foreignKey = $foreignKey ?: $name . '_id'; $relatedKey = $relatedKey ?: $instance->getForeignKey(); // Now we're ready to create a new query builder for this related model and // the relationship instances for this relation. This relations will set // appropriate query constraints then entirely manages the hydrations. $table = $table ?: Str::plural($name); return new MorphToMany( $instance->newQuery(), $this, $name, $table, $foreignKey, $relatedKey, $caller, $inverse ); }
php
public function morphToMany($related, $name, $table = null, $foreignKey = null, $relatedKey = null, $inverse = false) { $caller = $this->guessBelongsToManyRelation(); // First, we will need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we will make the query // instances, as well as the relationship instances we need for these. $instance = $this->newRelatedInstance($related); $foreignKey = $foreignKey ?: $name . '_id'; $relatedKey = $relatedKey ?: $instance->getForeignKey(); // Now we're ready to create a new query builder for this related model and // the relationship instances for this relation. This relations will set // appropriate query constraints then entirely manages the hydrations. $table = $table ?: Str::plural($name); return new MorphToMany( $instance->newQuery(), $this, $name, $table, $foreignKey, $relatedKey, $caller, $inverse ); }
[ "public", "function", "morphToMany", "(", "$", "related", ",", "$", "name", ",", "$", "table", "=", "null", ",", "$", "foreignKey", "=", "null", ",", "$", "relatedKey", "=", "null", ",", "$", "inverse", "=", "false", ")", "{", "$", "caller", "=", "$", "this", "->", "guessBelongsToManyRelation", "(", ")", ";", "// First, we will need to determine the foreign key and \"other key\" for the", "// relationship. Once we have determined the keys we will make the query", "// instances, as well as the relationship instances we need for these.", "$", "instance", "=", "$", "this", "->", "newRelatedInstance", "(", "$", "related", ")", ";", "$", "foreignKey", "=", "$", "foreignKey", "?", ":", "$", "name", ".", "'_id'", ";", "$", "relatedKey", "=", "$", "relatedKey", "?", ":", "$", "instance", "->", "getForeignKey", "(", ")", ";", "// Now we're ready to create a new query builder for this related model and", "// the relationship instances for this relation. This relations will set", "// appropriate query constraints then entirely manages the hydrations.", "$", "table", "=", "$", "table", "?", ":", "Str", "::", "plural", "(", "$", "name", ")", ";", "return", "new", "MorphToMany", "(", "$", "instance", "->", "newQuery", "(", ")", ",", "$", "this", ",", "$", "name", ",", "$", "table", ",", "$", "foreignKey", ",", "$", "relatedKey", ",", "$", "caller", ",", "$", "inverse", ")", ";", "}" ]
Define a polymorphic many-to-many relationship. @param string $related @param string $name @param string $table @param string $foreignKey @param string $relatedKey @param bool $inverse @return \Mellivora\Database\Eloquent\Relations\MorphToMany
[ "Define", "a", "polymorphic", "many", "-", "to", "-", "many", "relationship", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Concerns/HasRelationships.php#L369-L397
zhouyl/mellivora
Mellivora/Database/Eloquent/Concerns/HasRelationships.php
HasRelationships.guessBelongsToManyRelation
protected function guessBelongsToManyRelation() { $caller = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) { return !in_array($trace['function'], Model::$manyMethods); }); return !is_null($caller) ? $caller['function'] : null; }
php
protected function guessBelongsToManyRelation() { $caller = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) { return !in_array($trace['function'], Model::$manyMethods); }); return !is_null($caller) ? $caller['function'] : null; }
[ "protected", "function", "guessBelongsToManyRelation", "(", ")", "{", "$", "caller", "=", "Arr", "::", "first", "(", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ",", "function", "(", "$", "trace", ")", "{", "return", "!", "in_array", "(", "$", "trace", "[", "'function'", "]", ",", "Model", "::", "$", "manyMethods", ")", ";", "}", ")", ";", "return", "!", "is_null", "(", "$", "caller", ")", "?", "$", "caller", "[", "'function'", "]", ":", "null", ";", "}" ]
Get the relationship name of the belongs to many. @return string
[ "Get", "the", "relationship", "name", "of", "the", "belongs", "to", "many", "." ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Concerns/HasRelationships.php#L427-L434
soloproyectos-php/text-parser
src/text/parser/exception/TextParserException.php
TextParserException.getPrintableMessage
public function getPrintableMessage() { $ret = $this->message; if ($this->_parser != null) { $string = rtrim($this->_parser->getString()); $offset = $this->_parser->getOffset(); $rightStr = substr($string, $offset); $offset0 = $offset + strlen($rightStr) - strlen(ltrim($rightStr)); $str1 = substr($string, 0, $offset0); $offset1 = strrpos($str1, "\n"); if ($offset1 !== false) { $offset1++; } $str2 = substr($string, $offset1); $offset2 = strpos($str2, "\n"); if ($offset2 === false) { $offset2 = strlen($str2); } $str3 = substr($str2, 0, $offset2); $line = $offset0 > 0? substr_count($string, "\n", 0, $offset0) : 0; $column = $offset0 - $offset1; $ret = "$str3\n" . str_repeat(" ", $column) . "^" . $this->message; if ($line > 0) { $ret .= " (line " . ($line + 1) . ")"; } } return $ret; }
php
public function getPrintableMessage() { $ret = $this->message; if ($this->_parser != null) { $string = rtrim($this->_parser->getString()); $offset = $this->_parser->getOffset(); $rightStr = substr($string, $offset); $offset0 = $offset + strlen($rightStr) - strlen(ltrim($rightStr)); $str1 = substr($string, 0, $offset0); $offset1 = strrpos($str1, "\n"); if ($offset1 !== false) { $offset1++; } $str2 = substr($string, $offset1); $offset2 = strpos($str2, "\n"); if ($offset2 === false) { $offset2 = strlen($str2); } $str3 = substr($str2, 0, $offset2); $line = $offset0 > 0? substr_count($string, "\n", 0, $offset0) : 0; $column = $offset0 - $offset1; $ret = "$str3\n" . str_repeat(" ", $column) . "^" . $this->message; if ($line > 0) { $ret .= " (line " . ($line + 1) . ")"; } } return $ret; }
[ "public", "function", "getPrintableMessage", "(", ")", "{", "$", "ret", "=", "$", "this", "->", "message", ";", "if", "(", "$", "this", "->", "_parser", "!=", "null", ")", "{", "$", "string", "=", "rtrim", "(", "$", "this", "->", "_parser", "->", "getString", "(", ")", ")", ";", "$", "offset", "=", "$", "this", "->", "_parser", "->", "getOffset", "(", ")", ";", "$", "rightStr", "=", "substr", "(", "$", "string", ",", "$", "offset", ")", ";", "$", "offset0", "=", "$", "offset", "+", "strlen", "(", "$", "rightStr", ")", "-", "strlen", "(", "ltrim", "(", "$", "rightStr", ")", ")", ";", "$", "str1", "=", "substr", "(", "$", "string", ",", "0", ",", "$", "offset0", ")", ";", "$", "offset1", "=", "strrpos", "(", "$", "str1", ",", "\"\\n\"", ")", ";", "if", "(", "$", "offset1", "!==", "false", ")", "{", "$", "offset1", "++", ";", "}", "$", "str2", "=", "substr", "(", "$", "string", ",", "$", "offset1", ")", ";", "$", "offset2", "=", "strpos", "(", "$", "str2", ",", "\"\\n\"", ")", ";", "if", "(", "$", "offset2", "===", "false", ")", "{", "$", "offset2", "=", "strlen", "(", "$", "str2", ")", ";", "}", "$", "str3", "=", "substr", "(", "$", "str2", ",", "0", ",", "$", "offset2", ")", ";", "$", "line", "=", "$", "offset0", ">", "0", "?", "substr_count", "(", "$", "string", ",", "\"\\n\"", ",", "0", ",", "$", "offset0", ")", ":", "0", ";", "$", "column", "=", "$", "offset0", "-", "$", "offset1", ";", "$", "ret", "=", "\"$str3\\n\"", ".", "str_repeat", "(", "\" \"", ",", "$", "column", ")", ".", "\"^\"", ".", "$", "this", "->", "message", ";", "if", "(", "$", "line", ">", "0", ")", "{", "$", "ret", ".=", "\" (line \"", ".", "(", "$", "line", "+", "1", ")", ".", "\")\"", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Gets a printable message. This function provides a method to get printable messages. @return string
[ "Gets", "a", "printable", "message", "." ]
train
https://github.com/soloproyectos-php/text-parser/blob/3ef2e8a26f7c53b170383d74ccf4106b0f3dd8b1/src/text/parser/exception/TextParserException.php#L48-L82
inhere/php-librarys
src/Traits/RuntimeProfileTrait.php
RuntimeProfileTrait.profileEnd
public static function profileEnd($msg = null, array $context = []) { if (!$latestKey = array_pop(self::$keyQueue)) { return false; } list($category, $name) = explode('|', $latestKey); if (isset(self::$profiles[$category][$name])) { $data = self::$profiles[$category][$name]; $old = $data['_profile_stats']; $data['_profile_stats'] = PhpHelper::runtime($old['startTime'], $old['startMem']); $data['_profile_end'] = $context; $data['_profile_msg'] = $msg; // $title = $category . ' - ' . ($title ?: $name); self::$profiles[$category][$name] = $data; // self::$log(Logger::DEBUG, $title, $data); return $data; } return false; }
php
public static function profileEnd($msg = null, array $context = []) { if (!$latestKey = array_pop(self::$keyQueue)) { return false; } list($category, $name) = explode('|', $latestKey); if (isset(self::$profiles[$category][$name])) { $data = self::$profiles[$category][$name]; $old = $data['_profile_stats']; $data['_profile_stats'] = PhpHelper::runtime($old['startTime'], $old['startMem']); $data['_profile_end'] = $context; $data['_profile_msg'] = $msg; // $title = $category . ' - ' . ($title ?: $name); self::$profiles[$category][$name] = $data; // self::$log(Logger::DEBUG, $title, $data); return $data; } return false; }
[ "public", "static", "function", "profileEnd", "(", "$", "msg", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "if", "(", "!", "$", "latestKey", "=", "array_pop", "(", "self", "::", "$", "keyQueue", ")", ")", "{", "return", "false", ";", "}", "list", "(", "$", "category", ",", "$", "name", ")", "=", "explode", "(", "'|'", ",", "$", "latestKey", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "profiles", "[", "$", "category", "]", "[", "$", "name", "]", ")", ")", "{", "$", "data", "=", "self", "::", "$", "profiles", "[", "$", "category", "]", "[", "$", "name", "]", ";", "$", "old", "=", "$", "data", "[", "'_profile_stats'", "]", ";", "$", "data", "[", "'_profile_stats'", "]", "=", "PhpHelper", "::", "runtime", "(", "$", "old", "[", "'startTime'", "]", ",", "$", "old", "[", "'startMem'", "]", ")", ";", "$", "data", "[", "'_profile_end'", "]", "=", "$", "context", ";", "$", "data", "[", "'_profile_msg'", "]", "=", "$", "msg", ";", "// $title = $category . ' - ' . ($title ?: $name);", "self", "::", "$", "profiles", "[", "$", "category", "]", "[", "$", "name", "]", "=", "$", "data", ";", "// self::$log(Logger::DEBUG, $title, $data);", "return", "$", "data", ";", "}", "return", "false", ";", "}" ]
mark data analysis end @param string|null $msg @param array $context @return bool|array
[ "mark", "data", "analysis", "end" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Traits/RuntimeProfileTrait.php#L70-L95
codezero-be/curl
src/ResponseFactory.php
ResponseFactory.make
public function make($responseBody, array $responseInfo) { $info = $this->makeResponseInfo($responseInfo); $response = $this->makeResponse($responseBody, $info); return $response; }
php
public function make($responseBody, array $responseInfo) { $info = $this->makeResponseInfo($responseInfo); $response = $this->makeResponse($responseBody, $info); return $response; }
[ "public", "function", "make", "(", "$", "responseBody", ",", "array", "$", "responseInfo", ")", "{", "$", "info", "=", "$", "this", "->", "makeResponseInfo", "(", "$", "responseInfo", ")", ";", "$", "response", "=", "$", "this", "->", "makeResponse", "(", "$", "responseBody", ",", "$", "info", ")", ";", "return", "$", "response", ";", "}" ]
Make a response @param $responseBody @param array $responseInfo @return Response
[ "Make", "a", "response" ]
train
https://github.com/codezero-be/curl/blob/c1385479886662b6276c18dd9140df529959d95c/src/ResponseFactory.php#L13-L19
graze/data-structure
src/Container/Container.php
Container.recursiveClone
protected function recursiveClone($item) { if (is_object($item)) { return clone $item; } elseif (is_array($item)) { return array_map([$this, 'recursiveClone'], $item); } return $item; }
php
protected function recursiveClone($item) { if (is_object($item)) { return clone $item; } elseif (is_array($item)) { return array_map([$this, 'recursiveClone'], $item); } return $item; }
[ "protected", "function", "recursiveClone", "(", "$", "item", ")", "{", "if", "(", "is_object", "(", "$", "item", ")", ")", "{", "return", "clone", "$", "item", ";", "}", "elseif", "(", "is_array", "(", "$", "item", ")", ")", "{", "return", "array_map", "(", "[", "$", "this", ",", "'recursiveClone'", "]", ",", "$", "item", ")", ";", "}", "return", "$", "item", ";", "}" ]
@param mixed $item @return mixed
[ "@param", "mixed", "$item" ]
train
https://github.com/graze/data-structure/blob/24e0544b7828f65b1b93ce69ad702c9efb4a64d0/src/Container/Container.php#L202-L210
hametuha/wpametu
src/WPametu/Http/Input.php
Input.file_info
public function file_info( $key ) { if ( isset( $_FILES[ $key ]['error'] ) && $_FILES[ $key ]['error'] == UPLOAD_ERR_OK ) { return $_FILES[ $key ]; } else { return []; } }
php
public function file_info( $key ) { if ( isset( $_FILES[ $key ]['error'] ) && $_FILES[ $key ]['error'] == UPLOAD_ERR_OK ) { return $_FILES[ $key ]; } else { return []; } }
[ "public", "function", "file_info", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "_FILES", "[", "$", "key", "]", "[", "'error'", "]", ")", "&&", "$", "_FILES", "[", "$", "key", "]", "[", "'error'", "]", "==", "UPLOAD_ERR_OK", ")", "{", "return", "$", "_FILES", "[", "$", "key", "]", ";", "}", "else", "{", "return", "[", "]", ";", "}", "}" ]
Get file input @param string $key @return array
[ "Get", "file", "input" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/Http/Input.php#L83-L89
hametuha/wpametu
src/WPametu/Http/Input.php
Input.file_error_message
public function file_error_message( $key ) { if ( $this->file_info( $key ) ) { return ''; } elseif ( ! isset( $_FILES[ $key ] ) ) { return $this->__( 'File is not specified.' ); } else { switch ( $_FILES[ $key ]['error'] ) { case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_INI_SIZE: return $this->__( 'Uploaded file size exceeds allowed limit.' ); break; default: return $this->__( 'Failed to upload' ); break; } } }
php
public function file_error_message( $key ) { if ( $this->file_info( $key ) ) { return ''; } elseif ( ! isset( $_FILES[ $key ] ) ) { return $this->__( 'File is not specified.' ); } else { switch ( $_FILES[ $key ]['error'] ) { case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_INI_SIZE: return $this->__( 'Uploaded file size exceeds allowed limit.' ); break; default: return $this->__( 'Failed to upload' ); break; } } }
[ "public", "function", "file_error_message", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "file_info", "(", "$", "key", ")", ")", "{", "return", "''", ";", "}", "elseif", "(", "!", "isset", "(", "$", "_FILES", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "__", "(", "'File is not specified.'", ")", ";", "}", "else", "{", "switch", "(", "$", "_FILES", "[", "$", "key", "]", "[", "'error'", "]", ")", "{", "case", "UPLOAD_ERR_FORM_SIZE", ":", "case", "UPLOAD_ERR_INI_SIZE", ":", "return", "$", "this", "->", "__", "(", "'Uploaded file size exceeds allowed limit.'", ")", ";", "break", ";", "default", ":", "return", "$", "this", "->", "__", "(", "'Failed to upload'", ")", ";", "break", ";", "}", "}", "}" ]
Get file upload error message @param string $key @return string
[ "Get", "file", "upload", "error", "message" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/Http/Input.php#L98-L114
dave-redfern/laravel-doctrine-entity-audit
src/AuditRegistry.php
AuditRegistry.get
public function get($entityManagerName = null) { $entityManagerName = $entityManagerName ?: $this->getDefaultEntityManagerName(); if (!$this->has($entityManagerName)) { throw new \InvalidArgumentException( sprintf('No AuditManager has been configured for "%s"', $entityManagerName) ); } return $this->managers[$entityManagerName]; }
php
public function get($entityManagerName = null) { $entityManagerName = $entityManagerName ?: $this->getDefaultEntityManagerName(); if (!$this->has($entityManagerName)) { throw new \InvalidArgumentException( sprintf('No AuditManager has been configured for "%s"', $entityManagerName) ); } return $this->managers[$entityManagerName]; }
[ "public", "function", "get", "(", "$", "entityManagerName", "=", "null", ")", "{", "$", "entityManagerName", "=", "$", "entityManagerName", "?", ":", "$", "this", "->", "getDefaultEntityManagerName", "(", ")", ";", "if", "(", "!", "$", "this", "->", "has", "(", "$", "entityManagerName", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'No AuditManager has been configured for \"%s\"'", ",", "$", "entityManagerName", ")", ")", ";", "}", "return", "$", "this", "->", "managers", "[", "$", "entityManagerName", "]", ";", "}" ]
@param string $entityManagerName @return AuditManager
[ "@param", "string", "$entityManagerName" ]
train
https://github.com/dave-redfern/laravel-doctrine-entity-audit/blob/ab79e305fe512ceefbc14d585fefe0a40cf911ab/src/AuditRegistry.php#L119-L130
odiaseo/pagebuilder
src/PageBuilder/Model/PageTemplateModel.php
PageTemplateModel.getPageThemeById
public function getPageThemeById($id, $mode = AbstractQuery::HYDRATE_OBJECT) { $qb = $this->getEntityManager()->createQueryBuilder(); /** @var $query \Doctrine\ORM\Query */ $query = $qb->select('e, m') ->from($this->getEntity(), 'e') ->innerJoin('e.pageId', 'm') ->where('e.id = :id') ->setMaxResults(1) ->setParameter('id', $id) ->getQuery(); return $query->getOneOrNullResult($mode); }
php
public function getPageThemeById($id, $mode = AbstractQuery::HYDRATE_OBJECT) { $qb = $this->getEntityManager()->createQueryBuilder(); /** @var $query \Doctrine\ORM\Query */ $query = $qb->select('e, m') ->from($this->getEntity(), 'e') ->innerJoin('e.pageId', 'm') ->where('e.id = :id') ->setMaxResults(1) ->setParameter('id', $id) ->getQuery(); return $query->getOneOrNullResult($mode); }
[ "public", "function", "getPageThemeById", "(", "$", "id", ",", "$", "mode", "=", "AbstractQuery", "::", "HYDRATE_OBJECT", ")", "{", "$", "qb", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "/** @var $query \\Doctrine\\ORM\\Query */", "$", "query", "=", "$", "qb", "->", "select", "(", "'e, m'", ")", "->", "from", "(", "$", "this", "->", "getEntity", "(", ")", ",", "'e'", ")", "->", "innerJoin", "(", "'e.pageId'", ",", "'m'", ")", "->", "where", "(", "'e.id = :id'", ")", "->", "setMaxResults", "(", "1", ")", "->", "setParameter", "(", "'id'", ",", "$", "id", ")", "->", "getQuery", "(", ")", ";", "return", "$", "query", "->", "getOneOrNullResult", "(", "$", "mode", ")", ";", "}" ]
@param $id @param int $mode @return mixed @throws \Doctrine\ORM\NonUniqueResultException
[ "@param", "$id", "@param", "int", "$mode" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/PageTemplateModel.php#L21-L35
odiaseo/pagebuilder
src/PageBuilder/Model/PageTemplateModel.php
PageTemplateModel.getActivePageThemeForSite
public function getActivePageThemeForSite($pageId, $themeId, $siteId = null, $mode = AbstractQuery::HYDRATE_OBJECT) { /** @var $query \Doctrine\ORM\QueryBuilder */ try { $qb = $this->getEntityManager()->createQueryBuilder(); $params = [ ':pageId' => $pageId, ':active' => 1, ':siteThemeId' => $themeId, ]; $query = $qb->select('e, p, t') ->from($this->getEntity(), 'e') ->innerJoin('e.template', 't') ->innerJoin('t.theme', 'th') ->innerJoin('e.page', 'p') ->where('e.page = :pageId') ->setParameters($params); if (is_numeric($themeId)) { $query->andWhere('t.theme = :siteThemeId'); } else { $query->andWhere('th.slug = :siteThemeId'); } $query->andWhere('e.isActive = :active'); if ($siteId) { //$this->disableSiteFilter(); $query->andWhere($query->expr()->eq('e.site', $siteId)); } $query->setMaxResults(1); $result = $query->getQuery()->getOneOrNullResult($mode); return $result; } catch (\Exception $exception) { $this->getLogger()->logException($exception); return null; } }
php
public function getActivePageThemeForSite($pageId, $themeId, $siteId = null, $mode = AbstractQuery::HYDRATE_OBJECT) { /** @var $query \Doctrine\ORM\QueryBuilder */ try { $qb = $this->getEntityManager()->createQueryBuilder(); $params = [ ':pageId' => $pageId, ':active' => 1, ':siteThemeId' => $themeId, ]; $query = $qb->select('e, p, t') ->from($this->getEntity(), 'e') ->innerJoin('e.template', 't') ->innerJoin('t.theme', 'th') ->innerJoin('e.page', 'p') ->where('e.page = :pageId') ->setParameters($params); if (is_numeric($themeId)) { $query->andWhere('t.theme = :siteThemeId'); } else { $query->andWhere('th.slug = :siteThemeId'); } $query->andWhere('e.isActive = :active'); if ($siteId) { //$this->disableSiteFilter(); $query->andWhere($query->expr()->eq('e.site', $siteId)); } $query->setMaxResults(1); $result = $query->getQuery()->getOneOrNullResult($mode); return $result; } catch (\Exception $exception) { $this->getLogger()->logException($exception); return null; } }
[ "public", "function", "getActivePageThemeForSite", "(", "$", "pageId", ",", "$", "themeId", ",", "$", "siteId", "=", "null", ",", "$", "mode", "=", "AbstractQuery", "::", "HYDRATE_OBJECT", ")", "{", "/** @var $query \\Doctrine\\ORM\\QueryBuilder */", "try", "{", "$", "qb", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "$", "params", "=", "[", "':pageId'", "=>", "$", "pageId", ",", "':active'", "=>", "1", ",", "':siteThemeId'", "=>", "$", "themeId", ",", "]", ";", "$", "query", "=", "$", "qb", "->", "select", "(", "'e, p, t'", ")", "->", "from", "(", "$", "this", "->", "getEntity", "(", ")", ",", "'e'", ")", "->", "innerJoin", "(", "'e.template'", ",", "'t'", ")", "->", "innerJoin", "(", "'t.theme'", ",", "'th'", ")", "->", "innerJoin", "(", "'e.page'", ",", "'p'", ")", "->", "where", "(", "'e.page = :pageId'", ")", "->", "setParameters", "(", "$", "params", ")", ";", "if", "(", "is_numeric", "(", "$", "themeId", ")", ")", "{", "$", "query", "->", "andWhere", "(", "'t.theme = :siteThemeId'", ")", ";", "}", "else", "{", "$", "query", "->", "andWhere", "(", "'th.slug = :siteThemeId'", ")", ";", "}", "$", "query", "->", "andWhere", "(", "'e.isActive = :active'", ")", ";", "if", "(", "$", "siteId", ")", "{", "//$this->disableSiteFilter();", "$", "query", "->", "andWhere", "(", "$", "query", "->", "expr", "(", ")", "->", "eq", "(", "'e.site'", ",", "$", "siteId", ")", ")", ";", "}", "$", "query", "->", "setMaxResults", "(", "1", ")", ";", "$", "result", "=", "$", "query", "->", "getQuery", "(", ")", "->", "getOneOrNullResult", "(", "$", "mode", ")", ";", "return", "$", "result", ";", "}", "catch", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "this", "->", "getLogger", "(", ")", "->", "logException", "(", "$", "exception", ")", ";", "return", "null", ";", "}", "}" ]
@param $pageId @param $themeId @param null $siteId @param int $mode @return PageTemplate @throws \Doctrine\ORM\NonUniqueResultException
[ "@param", "$pageId", "@param", "$themeId", "@param", "null", "$siteId", "@param", "int", "$mode" ]
train
https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Model/PageTemplateModel.php#L69-L109
eddiejaoude/symfony-translation-twig-collection-bundle
src/EddieJaoude/Bundle/SymfonyTranslationTwigCollectionBundle/Twig/TranslationLengthExtension.php
TranslationLengthExtension.translationLengthFilter
public function translationLengthFilter($id) { $total = 0; foreach ($this->translator->getMessages()['messages'] as $position => $message) { if (substr($position, 0, strlen($id)) === $id) { $total++; } } return $total - 1; }
php
public function translationLengthFilter($id) { $total = 0; foreach ($this->translator->getMessages()['messages'] as $position => $message) { if (substr($position, 0, strlen($id)) === $id) { $total++; } } return $total - 1; }
[ "public", "function", "translationLengthFilter", "(", "$", "id", ")", "{", "$", "total", "=", "0", ";", "foreach", "(", "$", "this", "->", "translator", "->", "getMessages", "(", ")", "[", "'messages'", "]", "as", "$", "position", "=>", "$", "message", ")", "{", "if", "(", "substr", "(", "$", "position", ",", "0", ",", "strlen", "(", "$", "id", ")", ")", "===", "$", "id", ")", "{", "$", "total", "++", ";", "}", "}", "return", "$", "total", "-", "1", ";", "}" ]
@param string $id @return int
[ "@param", "string", "$id" ]
train
https://github.com/eddiejaoude/symfony-translation-twig-collection-bundle/blob/62230953cf9001fa519792d9d25dfed02584d5d5/src/EddieJaoude/Bundle/SymfonyTranslationTwigCollectionBundle/Twig/TranslationLengthExtension.php#L47-L57
zyberspace/php-discovery-shell
lib/Zyberspace/DiscoveryShell.php
DiscoveryShell._runShell
protected function _runShell() { echo wordwrap('-- discovery-shell to help discover a class or library --' . PHP_EOL . PHP_EOL . 'Use TAB for autocompletion and your arrow-keys to navigate through your method-history.' . PHP_EOL . 'Beware! This is not a full-featured php-shell. The input gets parsed with PHP-Parser to avoid the usage' . ' of eval().' . PHP_EOL, exec('tput cols'), PHP_EOL); while (true) { $input = $this->_getInput(); list($method, $arguments) = $this->_parseInput($input); $answer = call_user_func_array(array($this->_object, $method), $arguments); $this->_outputAnswer($answer); } }
php
protected function _runShell() { echo wordwrap('-- discovery-shell to help discover a class or library --' . PHP_EOL . PHP_EOL . 'Use TAB for autocompletion and your arrow-keys to navigate through your method-history.' . PHP_EOL . 'Beware! This is not a full-featured php-shell. The input gets parsed with PHP-Parser to avoid the usage' . ' of eval().' . PHP_EOL, exec('tput cols'), PHP_EOL); while (true) { $input = $this->_getInput(); list($method, $arguments) = $this->_parseInput($input); $answer = call_user_func_array(array($this->_object, $method), $arguments); $this->_outputAnswer($answer); } }
[ "protected", "function", "_runShell", "(", ")", "{", "echo", "wordwrap", "(", "'-- discovery-shell to help discover a class or library --'", ".", "PHP_EOL", ".", "PHP_EOL", ".", "'Use TAB for autocompletion and your arrow-keys to navigate through your method-history.'", ".", "PHP_EOL", ".", "'Beware! This is not a full-featured php-shell. The input gets parsed with PHP-Parser to avoid the usage'", ".", "' of eval().'", ".", "PHP_EOL", ",", "exec", "(", "'tput cols'", ")", ",", "PHP_EOL", ")", ";", "while", "(", "true", ")", "{", "$", "input", "=", "$", "this", "->", "_getInput", "(", ")", ";", "list", "(", "$", "method", ",", "$", "arguments", ")", "=", "$", "this", "->", "_parseInput", "(", "$", "input", ")", ";", "$", "answer", "=", "call_user_func_array", "(", "array", "(", "$", "this", "->", "_object", ",", "$", "method", ")", ",", "$", "arguments", ")", ";", "$", "this", "->", "_outputAnswer", "(", "$", "answer", ")", ";", "}", "}" ]
Runs the shell
[ "Runs", "the", "shell" ]
train
https://github.com/zyberspace/php-discovery-shell/blob/a5b4bb268c06e2cafb25e0b0383435bf448263a8/lib/Zyberspace/DiscoveryShell.php#L90-L105
frdl/webfan
.ApplicationComposer/lib/webdof/wURI.php
wURI.parse_uri
static function parse_uri($protocoll, $SERVER_NAME, $REQUEST_URI) { $xw = new \stdclass; $xw->protocoll = $protocoll; $xw->protocoll = trim($xw->protocoll , ' :/'); $xw->location = $xw->protocoll.'://'.$SERVER_NAME.$REQUEST_URI; $xw->server = $SERVER_NAME; $xw->req_uri = $REQUEST_URI; if(substr($xw->req_uri, 0, 1) == '/' ) { $xw->uri = substr($xw->req_uri,1 , strlen($xw->req_uri) ); }else{ $xw->uri = $xw->req_uri; } $xw->dirs = explode('/', $xw->uri); $xw->dirs_rev = array_reverse($xw->dirs); $xw->dir = dirname( $xw->req_uri ); $xw->dots = explode('.', $xw->uri); $xw->dots_rev = array_reverse($xw->dots); $xw->host = explode('.',$xw->server); $xw->host_rev = array_reverse($xw->host); $xw->tld = @$xw->host_rev[0]; $xw->dom = @$xw->host_rev[1].'.'.$xw->host_rev[0]; $t = explode('?', $xw->req_uri); $xw->file = basename( $t[0] ); $xw->query = array(); if(isset($t[1]))parse_str($t[1], $xw->query); $t = explode('.', $xw->file); $t = array_reverse($t); $xw->file_ext = $t[0]; $xw->classic = parse_url($xw->location); /* http://php.net/manual/en/function.parse-url.php#106731 */ $xw->unparse_classic = function(Array $parsed = null) use($xw) { if(!is_array($parsed) && isset($xw->classic) && is_array($xw->classic))$parsed = $xw->classic; $scheme = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : ''; $host = isset($parsed['host']) ? $parsed['host'] : ''; $port = isset($parsed['port']) ? ':' . $parsed['port'] : ''; $user = isset($parsed['user']) ? $parsed['user'] : ''; $pass = isset($parsed['pass']) ? ':' . $parsed['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($parsed['path']) ? $parsed['path'] : ''; $query = isset($parsed['query']) ? '?' . $parsed['query'] : ''; $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : ''; return "$scheme$user$pass$host$port$path$query$fragment"; } ; return $xw; }
php
static function parse_uri($protocoll, $SERVER_NAME, $REQUEST_URI) { $xw = new \stdclass; $xw->protocoll = $protocoll; $xw->protocoll = trim($xw->protocoll , ' :/'); $xw->location = $xw->protocoll.'://'.$SERVER_NAME.$REQUEST_URI; $xw->server = $SERVER_NAME; $xw->req_uri = $REQUEST_URI; if(substr($xw->req_uri, 0, 1) == '/' ) { $xw->uri = substr($xw->req_uri,1 , strlen($xw->req_uri) ); }else{ $xw->uri = $xw->req_uri; } $xw->dirs = explode('/', $xw->uri); $xw->dirs_rev = array_reverse($xw->dirs); $xw->dir = dirname( $xw->req_uri ); $xw->dots = explode('.', $xw->uri); $xw->dots_rev = array_reverse($xw->dots); $xw->host = explode('.',$xw->server); $xw->host_rev = array_reverse($xw->host); $xw->tld = @$xw->host_rev[0]; $xw->dom = @$xw->host_rev[1].'.'.$xw->host_rev[0]; $t = explode('?', $xw->req_uri); $xw->file = basename( $t[0] ); $xw->query = array(); if(isset($t[1]))parse_str($t[1], $xw->query); $t = explode('.', $xw->file); $t = array_reverse($t); $xw->file_ext = $t[0]; $xw->classic = parse_url($xw->location); /* http://php.net/manual/en/function.parse-url.php#106731 */ $xw->unparse_classic = function(Array $parsed = null) use($xw) { if(!is_array($parsed) && isset($xw->classic) && is_array($xw->classic))$parsed = $xw->classic; $scheme = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : ''; $host = isset($parsed['host']) ? $parsed['host'] : ''; $port = isset($parsed['port']) ? ':' . $parsed['port'] : ''; $user = isset($parsed['user']) ? $parsed['user'] : ''; $pass = isset($parsed['pass']) ? ':' . $parsed['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($parsed['path']) ? $parsed['path'] : ''; $query = isset($parsed['query']) ? '?' . $parsed['query'] : ''; $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : ''; return "$scheme$user$pass$host$port$path$query$fragment"; } ; return $xw; }
[ "static", "function", "parse_uri", "(", "$", "protocoll", ",", "$", "SERVER_NAME", ",", "$", "REQUEST_URI", ")", "{", "$", "xw", "=", "new", "\\", "stdclass", ";", "$", "xw", "->", "protocoll", "=", "$", "protocoll", ";", "$", "xw", "->", "protocoll", "=", "trim", "(", "$", "xw", "->", "protocoll", ",", "' :/'", ")", ";", "$", "xw", "->", "location", "=", "$", "xw", "->", "protocoll", ".", "'://'", ".", "$", "SERVER_NAME", ".", "$", "REQUEST_URI", ";", "$", "xw", "->", "server", "=", "$", "SERVER_NAME", ";", "$", "xw", "->", "req_uri", "=", "$", "REQUEST_URI", ";", "if", "(", "substr", "(", "$", "xw", "->", "req_uri", ",", "0", ",", "1", ")", "==", "'/'", ")", "{", "$", "xw", "->", "uri", "=", "substr", "(", "$", "xw", "->", "req_uri", ",", "1", ",", "strlen", "(", "$", "xw", "->", "req_uri", ")", ")", ";", "}", "else", "{", "$", "xw", "->", "uri", "=", "$", "xw", "->", "req_uri", ";", "}", "$", "xw", "->", "dirs", "=", "explode", "(", "'/'", ",", "$", "xw", "->", "uri", ")", ";", "$", "xw", "->", "dirs_rev", "=", "array_reverse", "(", "$", "xw", "->", "dirs", ")", ";", "$", "xw", "->", "dir", "=", "dirname", "(", "$", "xw", "->", "req_uri", ")", ";", "$", "xw", "->", "dots", "=", "explode", "(", "'.'", ",", "$", "xw", "->", "uri", ")", ";", "$", "xw", "->", "dots_rev", "=", "array_reverse", "(", "$", "xw", "->", "dots", ")", ";", "$", "xw", "->", "host", "=", "explode", "(", "'.'", ",", "$", "xw", "->", "server", ")", ";", "$", "xw", "->", "host_rev", "=", "array_reverse", "(", "$", "xw", "->", "host", ")", ";", "$", "xw", "->", "tld", "=", "@", "$", "xw", "->", "host_rev", "[", "0", "]", ";", "$", "xw", "->", "dom", "=", "@", "$", "xw", "->", "host_rev", "[", "1", "]", ".", "'.'", ".", "$", "xw", "->", "host_rev", "[", "0", "]", ";", "$", "t", "=", "explode", "(", "'?'", ",", "$", "xw", "->", "req_uri", ")", ";", "$", "xw", "->", "file", "=", "basename", "(", "$", "t", "[", "0", "]", ")", ";", "$", "xw", "->", "query", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "t", "[", "1", "]", ")", ")", "parse_str", "(", "$", "t", "[", "1", "]", ",", "$", "xw", "->", "query", ")", ";", "$", "t", "=", "explode", "(", "'.'", ",", "$", "xw", "->", "file", ")", ";", "$", "t", "=", "array_reverse", "(", "$", "t", ")", ";", "$", "xw", "->", "file_ext", "=", "$", "t", "[", "0", "]", ";", "$", "xw", "->", "classic", "=", "parse_url", "(", "$", "xw", "->", "location", ")", ";", "/*\nhttp://php.net/manual/en/function.parse-url.php#106731\n*/", "$", "xw", "->", "unparse_classic", "=", "function", "(", "Array", "$", "parsed", "=", "null", ")", "use", "(", "$", "xw", ")", "{", "if", "(", "!", "is_array", "(", "$", "parsed", ")", "&&", "isset", "(", "$", "xw", "->", "classic", ")", "&&", "is_array", "(", "$", "xw", "->", "classic", ")", ")", "$", "parsed", "=", "$", "xw", "->", "classic", ";", "$", "scheme", "=", "isset", "(", "$", "parsed", "[", "'scheme'", "]", ")", "?", "$", "parsed", "[", "'scheme'", "]", ".", "'://'", ":", "''", ";", "$", "host", "=", "isset", "(", "$", "parsed", "[", "'host'", "]", ")", "?", "$", "parsed", "[", "'host'", "]", ":", "''", ";", "$", "port", "=", "isset", "(", "$", "parsed", "[", "'port'", "]", ")", "?", "':'", ".", "$", "parsed", "[", "'port'", "]", ":", "''", ";", "$", "user", "=", "isset", "(", "$", "parsed", "[", "'user'", "]", ")", "?", "$", "parsed", "[", "'user'", "]", ":", "''", ";", "$", "pass", "=", "isset", "(", "$", "parsed", "[", "'pass'", "]", ")", "?", "':'", ".", "$", "parsed", "[", "'pass'", "]", ":", "''", ";", "$", "pass", "=", "(", "$", "user", "||", "$", "pass", ")", "?", "\"$pass@\"", ":", "''", ";", "$", "path", "=", "isset", "(", "$", "parsed", "[", "'path'", "]", ")", "?", "$", "parsed", "[", "'path'", "]", ":", "''", ";", "$", "query", "=", "isset", "(", "$", "parsed", "[", "'query'", "]", ")", "?", "'?'", ".", "$", "parsed", "[", "'query'", "]", ":", "''", ";", "$", "fragment", "=", "isset", "(", "$", "parsed", "[", "'fragment'", "]", ")", "?", "'#'", ".", "$", "parsed", "[", "'fragment'", "]", ":", "''", ";", "return", "\"$scheme$user$pass$host$port$path$query$fragment\"", ";", "}", ";", "return", "$", "xw", ";", "}" ]
eof getU
[ "eof", "getU" ]
train
https://github.com/frdl/webfan/blob/84d270377685224e891cd9d571b103b36f05b845/.ApplicationComposer/lib/webdof/wURI.php#L80-L141
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/utilities_oracle.php
ezcDbUtilitiesOracle.createTemporaryTable
public function createTemporaryTable( $tableNamePattern, $tableDefinition ) { $tableNamePattern = $this->getPrefixedTableNames($tableNamePattern); if ( strpos( $tableNamePattern, '%' ) === false ) { $tableName = $tableNamePattern; } else // generate unique table name with the given pattern { $maxTries = 10; do { $num = rand( 10000000, 99999999 ); $tableName = strtoupper( str_replace( '%', $num, $tableNamePattern ) ); $query = "SELECT count(*) AS cnt FROM user_tables WHERE table_name='$tableName'"; $cnt = (int) $this->db->query( $query )->fetchColumn( 0 ); $maxTries--; } while ( $cnt > 0 && $maxTries > 0 ); if ( $maxTries == 0 ) { throw ezcDbException( ezcDbException::GENERIC_ERROR, "Tried to generate an uninque temp table name for {$maxTries} time with no luck." ); } } $this->db->exec( "CREATE GLOBAL TEMPORARY TABLE $tableName ($tableDefinition)" ); return $tableName; }
php
public function createTemporaryTable( $tableNamePattern, $tableDefinition ) { $tableNamePattern = $this->getPrefixedTableNames($tableNamePattern); if ( strpos( $tableNamePattern, '%' ) === false ) { $tableName = $tableNamePattern; } else // generate unique table name with the given pattern { $maxTries = 10; do { $num = rand( 10000000, 99999999 ); $tableName = strtoupper( str_replace( '%', $num, $tableNamePattern ) ); $query = "SELECT count(*) AS cnt FROM user_tables WHERE table_name='$tableName'"; $cnt = (int) $this->db->query( $query )->fetchColumn( 0 ); $maxTries--; } while ( $cnt > 0 && $maxTries > 0 ); if ( $maxTries == 0 ) { throw ezcDbException( ezcDbException::GENERIC_ERROR, "Tried to generate an uninque temp table name for {$maxTries} time with no luck." ); } } $this->db->exec( "CREATE GLOBAL TEMPORARY TABLE $tableName ($tableDefinition)" ); return $tableName; }
[ "public", "function", "createTemporaryTable", "(", "$", "tableNamePattern", ",", "$", "tableDefinition", ")", "{", "$", "tableNamePattern", "=", "$", "this", "->", "getPrefixedTableNames", "(", "$", "tableNamePattern", ")", ";", "if", "(", "strpos", "(", "$", "tableNamePattern", ",", "'%'", ")", "===", "false", ")", "{", "$", "tableName", "=", "$", "tableNamePattern", ";", "}", "else", "// generate unique table name with the given pattern", "{", "$", "maxTries", "=", "10", ";", "do", "{", "$", "num", "=", "rand", "(", "10000000", ",", "99999999", ")", ";", "$", "tableName", "=", "strtoupper", "(", "str_replace", "(", "'%'", ",", "$", "num", ",", "$", "tableNamePattern", ")", ")", ";", "$", "query", "=", "\"SELECT count(*) AS cnt FROM user_tables WHERE table_name='$tableName'\"", ";", "$", "cnt", "=", "(", "int", ")", "$", "this", "->", "db", "->", "query", "(", "$", "query", ")", "->", "fetchColumn", "(", "0", ")", ";", "$", "maxTries", "--", ";", "}", "while", "(", "$", "cnt", ">", "0", "&&", "$", "maxTries", ">", "0", ")", ";", "if", "(", "$", "maxTries", "==", "0", ")", "{", "throw", "ezcDbException", "(", "ezcDbException", "::", "GENERIC_ERROR", ",", "\"Tried to generate an uninque temp table name for {$maxTries} time with no luck.\"", ")", ";", "}", "}", "$", "this", "->", "db", "->", "exec", "(", "\"CREATE GLOBAL TEMPORARY TABLE $tableName ($tableDefinition)\"", ")", ";", "return", "$", "tableName", ";", "}" ]
Creates a new temporary table and returns the name. @throws ezcDbException::GENERIC_ERROR in case of inability to generate a unique temporary table name. @see ezcDbHandler::createTemporaryTable() @param string $tableNamePattern Name of temporary table user wants to create. @param string $tableDefinition Definition for the table, i.e. everything that goes between braces after CREATE TEMPORARY TABLE clause. @return string Table name, that might have been changed by the handler to guarantee its uniqueness. @todo move out
[ "Creates", "a", "new", "temporary", "table", "and", "returns", "the", "name", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/utilities_oracle.php#L89-L119
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/utilities_oracle.php
ezcDbUtilitiesOracle.dropTemporaryTable
public function dropTemporaryTable( $tableName ) { $tableName = $this->getPrefixedTableNames($tableName); $this->db->exec( "TRUNCATE TABLE $tableName" ); $this->db->exec( "DROP TABLE $tableName" ); }
php
public function dropTemporaryTable( $tableName ) { $tableName = $this->getPrefixedTableNames($tableName); $this->db->exec( "TRUNCATE TABLE $tableName" ); $this->db->exec( "DROP TABLE $tableName" ); }
[ "public", "function", "dropTemporaryTable", "(", "$", "tableName", ")", "{", "$", "tableName", "=", "$", "this", "->", "getPrefixedTableNames", "(", "$", "tableName", ")", ";", "$", "this", "->", "db", "->", "exec", "(", "\"TRUNCATE TABLE $tableName\"", ")", ";", "$", "this", "->", "db", "->", "exec", "(", "\"DROP TABLE $tableName\"", ")", ";", "}" ]
Drop specified temporary table in a portable way. Developers should use this method instead of dropping temporary tables with the appropriate SQL queries to maintain inter-DBMS portability. @see createTemporaryTable() @param string $tableName Name of temporary table to drop. @return void
[ "Drop", "specified", "temporary", "table", "in", "a", "portable", "way", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/sqlabstraction/implementations/utilities_oracle.php#L134-L139
ArrowSphere/Client
src/xAC/Entity.php
Entity.getBaseUri
public function getBaseUri() { return sprintf('%s%s' , $this->params['endpoint'] , ! empty($this->id) ? '/' . $this->id : null ); }
php
public function getBaseUri() { return sprintf('%s%s' , $this->params['endpoint'] , ! empty($this->id) ? '/' . $this->id : null ); }
[ "public", "function", "getBaseUri", "(", ")", "{", "return", "sprintf", "(", "'%s%s'", ",", "$", "this", "->", "params", "[", "'endpoint'", "]", ",", "!", "empty", "(", "$", "this", "->", "id", ")", "?", "'/'", ".", "$", "this", "->", "id", ":", "null", ")", ";", "}" ]
Return entity endpoint base uri
[ "Return", "entity", "endpoint", "base", "uri" ]
train
https://github.com/ArrowSphere/Client/blob/6608f8257060375e7d3a27c485b23268b73f6ef7/src/xAC/Entity.php#L56-L62
mergado/mergado-api-client-php
src/mergadoclient/ApiMiddleware.php
ApiMiddleware.auth
public static function auth() { return function (callable $handler) { return function (RequestInterface $request, array $options) use ($handler) { if (empty($options['http_errors'])) { return $handler($request, $options); } return $handler($request, $options)->then( function (ResponseInterface $response) use ($request, $handler) { $code = $response->getStatusCode(); if ($code == 401 || $code == 403) { // do your oauth authorization and retry throw UnauthorizedException::create($request, $response); } return $response; } ); }; }; }
php
public static function auth() { return function (callable $handler) { return function (RequestInterface $request, array $options) use ($handler) { if (empty($options['http_errors'])) { return $handler($request, $options); } return $handler($request, $options)->then( function (ResponseInterface $response) use ($request, $handler) { $code = $response->getStatusCode(); if ($code == 401 || $code == 403) { // do your oauth authorization and retry throw UnauthorizedException::create($request, $response); } return $response; } ); }; }; }
[ "public", "static", "function", "auth", "(", ")", "{", "return", "function", "(", "callable", "$", "handler", ")", "{", "return", "function", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", ")", "use", "(", "$", "handler", ")", "{", "if", "(", "empty", "(", "$", "options", "[", "'http_errors'", "]", ")", ")", "{", "return", "$", "handler", "(", "$", "request", ",", "$", "options", ")", ";", "}", "return", "$", "handler", "(", "$", "request", ",", "$", "options", ")", "->", "then", "(", "function", "(", "ResponseInterface", "$", "response", ")", "use", "(", "$", "request", ",", "$", "handler", ")", "{", "$", "code", "=", "$", "response", "->", "getStatusCode", "(", ")", ";", "if", "(", "$", "code", "==", "401", "||", "$", "code", "==", "403", ")", "{", "//\t\t\t\t\t\t\tdo your oauth authorization and retry", "throw", "UnauthorizedException", "::", "create", "(", "$", "request", ",", "$", "response", ")", ";", "}", "return", "$", "response", ";", "}", ")", ";", "}", ";", "}", ";", "}" ]
Middleware that throws exceptions for 4xx or 5xx responses when the "http_error" request option is set to true. @return callable Returns a function that accepts the next handler.
[ "Middleware", "that", "throws", "exceptions", "for", "4xx", "or", "5xx", "responses", "when", "the", "http_error", "request", "option", "is", "set", "to", "true", "." ]
train
https://github.com/mergado/mergado-api-client-php/blob/6c13b994a81bf5a3d6f3f791ea1dfbe2c420565f/src/mergadoclient/ApiMiddleware.php#L18-L38
i-lateral/silverstripe-users
code/extensions/Ext_Users_Member.php
Ext_Users_Member.Register
public function Register($data) { // If we have passed a confirm password field, clean the // data if (isset($data["Password"]) && is_array($data["Password"]) && isset($data["Password"]["_Password"])) { $data["Password"] = $data["Password"]["_Password"]; } $this->owner->update($data); // Set verification code for this user $this->owner->VerificationCode = sha1(mt_rand() . mt_rand()); $this->owner->write(); // Add member to any groups that have been specified if (count(Users::config()->new_user_groups)) { $groups = Group::get()->filter( array( "Code" => Users::config()->new_user_groups ) ); foreach ($groups as $group) { $group->Members()->add($this->owner); $group->write(); } } // Send a verification email, if needed if (Users::config()->send_verification_email) { $this->owner->sendVerificationEmail(); } // Login (if enabled) if (Users::config()->login_after_register) { $this->owner->LogIn(isset($data['Remember'])); } return $this->owner; }
php
public function Register($data) { // If we have passed a confirm password field, clean the // data if (isset($data["Password"]) && is_array($data["Password"]) && isset($data["Password"]["_Password"])) { $data["Password"] = $data["Password"]["_Password"]; } $this->owner->update($data); // Set verification code for this user $this->owner->VerificationCode = sha1(mt_rand() . mt_rand()); $this->owner->write(); // Add member to any groups that have been specified if (count(Users::config()->new_user_groups)) { $groups = Group::get()->filter( array( "Code" => Users::config()->new_user_groups ) ); foreach ($groups as $group) { $group->Members()->add($this->owner); $group->write(); } } // Send a verification email, if needed if (Users::config()->send_verification_email) { $this->owner->sendVerificationEmail(); } // Login (if enabled) if (Users::config()->login_after_register) { $this->owner->LogIn(isset($data['Remember'])); } return $this->owner; }
[ "public", "function", "Register", "(", "$", "data", ")", "{", "// If we have passed a confirm password field, clean the", "// data", "if", "(", "isset", "(", "$", "data", "[", "\"Password\"", "]", ")", "&&", "is_array", "(", "$", "data", "[", "\"Password\"", "]", ")", "&&", "isset", "(", "$", "data", "[", "\"Password\"", "]", "[", "\"_Password\"", "]", ")", ")", "{", "$", "data", "[", "\"Password\"", "]", "=", "$", "data", "[", "\"Password\"", "]", "[", "\"_Password\"", "]", ";", "}", "$", "this", "->", "owner", "->", "update", "(", "$", "data", ")", ";", "// Set verification code for this user", "$", "this", "->", "owner", "->", "VerificationCode", "=", "sha1", "(", "mt_rand", "(", ")", ".", "mt_rand", "(", ")", ")", ";", "$", "this", "->", "owner", "->", "write", "(", ")", ";", "// Add member to any groups that have been specified", "if", "(", "count", "(", "Users", "::", "config", "(", ")", "->", "new_user_groups", ")", ")", "{", "$", "groups", "=", "Group", "::", "get", "(", ")", "->", "filter", "(", "array", "(", "\"Code\"", "=>", "Users", "::", "config", "(", ")", "->", "new_user_groups", ")", ")", ";", "foreach", "(", "$", "groups", "as", "$", "group", ")", "{", "$", "group", "->", "Members", "(", ")", "->", "add", "(", "$", "this", "->", "owner", ")", ";", "$", "group", "->", "write", "(", ")", ";", "}", "}", "// Send a verification email, if needed", "if", "(", "Users", "::", "config", "(", ")", "->", "send_verification_email", ")", "{", "$", "this", "->", "owner", "->", "sendVerificationEmail", "(", ")", ";", "}", "// Login (if enabled)", "if", "(", "Users", "::", "config", "(", ")", "->", "login_after_register", ")", "{", "$", "this", "->", "owner", "->", "LogIn", "(", "isset", "(", "$", "data", "[", "'Remember'", "]", ")", ")", ";", "}", "return", "$", "this", "->", "owner", ";", "}" ]
Register a new user account using the provided data and then return the current member @param array $data Array of data to create member from @return Member
[ "Register", "a", "new", "user", "account", "using", "the", "provided", "data", "and", "then", "return", "the", "current", "member" ]
train
https://github.com/i-lateral/silverstripe-users/blob/27ddc38890fa2709ac419eccf854ab6b439f0d9a/code/extensions/Ext_Users_Member.php#L33-L72
i-lateral/silverstripe-users
code/extensions/Ext_Users_Member.php
Ext_Users_Member.sendVerificationEmail
public function sendVerificationEmail() { if ($this->owner->exists()) { $controller = Injector::inst()->get("Users_Register_Controller"); $subject = _t("Users.PleaseVerify", "Please verify your account"); if (Users::config()->send_email_from) { $from = Users::config()->send_email_from; } else { $from = Email::config()->admin_email; } $email = Email::create(); $email ->setFrom($from) ->setTo($this->owner->Email) ->setSubject($subject) ->setTemplate('UsersAccountVerification') ->populateTemplate( ArrayData::create( array( "Link" => Controller::join_links( $controller->AbsoluteLink("verify"), $this->owner->ID, $this->owner->VerificationCode ) ) ) ); $email->send(); return true; } return false; }
php
public function sendVerificationEmail() { if ($this->owner->exists()) { $controller = Injector::inst()->get("Users_Register_Controller"); $subject = _t("Users.PleaseVerify", "Please verify your account"); if (Users::config()->send_email_from) { $from = Users::config()->send_email_from; } else { $from = Email::config()->admin_email; } $email = Email::create(); $email ->setFrom($from) ->setTo($this->owner->Email) ->setSubject($subject) ->setTemplate('UsersAccountVerification') ->populateTemplate( ArrayData::create( array( "Link" => Controller::join_links( $controller->AbsoluteLink("verify"), $this->owner->ID, $this->owner->VerificationCode ) ) ) ); $email->send(); return true; } return false; }
[ "public", "function", "sendVerificationEmail", "(", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "controller", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "\"Users_Register_Controller\"", ")", ";", "$", "subject", "=", "_t", "(", "\"Users.PleaseVerify\"", ",", "\"Please verify your account\"", ")", ";", "if", "(", "Users", "::", "config", "(", ")", "->", "send_email_from", ")", "{", "$", "from", "=", "Users", "::", "config", "(", ")", "->", "send_email_from", ";", "}", "else", "{", "$", "from", "=", "Email", "::", "config", "(", ")", "->", "admin_email", ";", "}", "$", "email", "=", "Email", "::", "create", "(", ")", ";", "$", "email", "->", "setFrom", "(", "$", "from", ")", "->", "setTo", "(", "$", "this", "->", "owner", "->", "Email", ")", "->", "setSubject", "(", "$", "subject", ")", "->", "setTemplate", "(", "'UsersAccountVerification'", ")", "->", "populateTemplate", "(", "ArrayData", "::", "create", "(", "array", "(", "\"Link\"", "=>", "Controller", "::", "join_links", "(", "$", "controller", "->", "AbsoluteLink", "(", "\"verify\"", ")", ",", "$", "this", "->", "owner", "->", "ID", ",", "$", "this", "->", "owner", "->", "VerificationCode", ")", ")", ")", ")", ";", "$", "email", "->", "send", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Send a verification email to this user account @return boolean
[ "Send", "a", "verification", "email", "to", "this", "user", "account" ]
train
https://github.com/i-lateral/silverstripe-users/blob/27ddc38890fa2709ac419eccf854ab6b439f0d9a/code/extensions/Ext_Users_Member.php#L79-L115
surebert/surebert-framework
src/sb/PDO/Logger.php
Logger.setLogger
public function setLogger($logger = null) { if ($logger instanceOf \sb\Logger\Base) { $this->logger = $logger; } else { $this->logger = new \sb\Logger\FileSystem(); } }
php
public function setLogger($logger = null) { if ($logger instanceOf \sb\Logger\Base) { $this->logger = $logger; } else { $this->logger = new \sb\Logger\FileSystem(); } }
[ "public", "function", "setLogger", "(", "$", "logger", "=", "null", ")", "{", "if", "(", "$", "logger", "instanceOf", "\\", "sb", "\\", "Logger", "\\", "Base", ")", "{", "$", "this", "->", "logger", "=", "$", "logger", ";", "}", "else", "{", "$", "this", "->", "logger", "=", "new", "\\", "sb", "\\", "Logger", "\\", "FileSystem", "(", ")", ";", "}", "}" ]
Set the logger @param $logger \sb\Logger\Base An instance of \sb\Logger\Base or one is created using FileSystem logging
[ "Set", "the", "logger" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Logger.php#L54-L62
surebert/surebert-framework
src/sb/PDO/Logger.php
Logger.s2o
public function s2o($sql, $params = null, $class_name = '', $prepare_and_store = 1) { try { return parent::s2o($sql, $params, $class_name, $prepare_and_store); } catch (\Exception $e) { $trace = $e->getTrace(); $message = "Error: " . __CLASS__ . " Exception in " . $trace[1]['file'] . " on line " . $trace[1]['line'] . " with db message: \n" . $e->getMessage(); $this->writeToLog($message); return Array(); } }
php
public function s2o($sql, $params = null, $class_name = '', $prepare_and_store = 1) { try { return parent::s2o($sql, $params, $class_name, $prepare_and_store); } catch (\Exception $e) { $trace = $e->getTrace(); $message = "Error: " . __CLASS__ . " Exception in " . $trace[1]['file'] . " on line " . $trace[1]['line'] . " with db message: \n" . $e->getMessage(); $this->writeToLog($message); return Array(); } }
[ "public", "function", "s2o", "(", "$", "sql", ",", "$", "params", "=", "null", ",", "$", "class_name", "=", "''", ",", "$", "prepare_and_store", "=", "1", ")", "{", "try", "{", "return", "parent", "::", "s2o", "(", "$", "sql", ",", "$", "params", ",", "$", "class_name", ",", "$", "prepare_and_store", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "trace", "=", "$", "e", "->", "getTrace", "(", ")", ";", "$", "message", "=", "\"Error: \"", ".", "__CLASS__", ".", "\" Exception in \"", ".", "$", "trace", "[", "1", "]", "[", "'file'", "]", ".", "\" on line \"", ".", "$", "trace", "[", "1", "]", "[", "'line'", "]", ".", "\" with db message: \\n\"", ".", "$", "e", "->", "getMessage", "(", ")", ";", "$", "this", "->", "writeToLog", "(", "$", "message", ")", ";", "return", "Array", "(", ")", ";", "}", "}" ]
Additionally Logs the errors {@inheritdoc }
[ "Additionally", "Logs", "the", "errors", "{" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Logger.php#L77-L93
surebert/surebert-framework
src/sb/PDO/Logger.php
Logger.exec
public function exec($sql) { $this->writeToLog("Exec: " . $sql); $result = parent::exec($sql); return $result; }
php
public function exec($sql) { $this->writeToLog("Exec: " . $sql); $result = parent::exec($sql); return $result; }
[ "public", "function", "exec", "(", "$", "sql", ")", "{", "$", "this", "->", "writeToLog", "(", "\"Exec: \"", ".", "$", "sql", ")", ";", "$", "result", "=", "parent", "::", "exec", "(", "$", "sql", ")", ";", "return", "$", "result", ";", "}" ]
Used to issue statements which return no results but rather the number of rows affected @param string $sql @return integer The number of rows affected
[ "Used", "to", "issue", "statements", "which", "return", "no", "results", "but", "rather", "the", "number", "of", "rows", "affected" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Logger.php#L114-L119
surebert/surebert-framework
src/sb/PDO/Logger.php
Logger.prepare
public function prepare($sql, $options = null) { $md5 = md5($sql); if (isset($this->prepared_sql[$md5])) { return $this->prepared_sql[$md5]; } //$this->writeToLog("Preparing: ".$sql); $stmt = parent::prepare($sql); $this->prepared_sql[$md5] = $stmt; return $stmt; }
php
public function prepare($sql, $options = null) { $md5 = md5($sql); if (isset($this->prepared_sql[$md5])) { return $this->prepared_sql[$md5]; } //$this->writeToLog("Preparing: ".$sql); $stmt = parent::prepare($sql); $this->prepared_sql[$md5] = $stmt; return $stmt; }
[ "public", "function", "prepare", "(", "$", "sql", ",", "$", "options", "=", "null", ")", "{", "$", "md5", "=", "md5", "(", "$", "sql", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "prepared_sql", "[", "$", "md5", "]", ")", ")", "{", "return", "$", "this", "->", "prepared_sql", "[", "$", "md5", "]", ";", "}", "//$this->writeToLog(\"Preparing: \".$sql);", "$", "stmt", "=", "parent", "::", "prepare", "(", "$", "sql", ")", ";", "$", "this", "->", "prepared_sql", "[", "$", "md5", "]", "=", "$", "stmt", ";", "return", "$", "stmt", ";", "}" ]
Used to prepare sql statements for value binding @param string $sql @return PDO_Statement A PDO_statment instance
[ "Used", "to", "prepare", "sql", "statements", "for", "value", "binding" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Logger.php#L127-L140
surebert/surebert-framework
src/sb/PDO/Logger.php
Logger.writeToLog
public function writeToLog($message) { if (is_null($this->logger)) { $this->setLogger(); } if (empty($this->sbf_id) || $this->sbf_id == \sb\Gateway::$cookie['SBF_ID']) { $message = preg_replace("~\t~", " ", $message); return $this->logger->{$this->log_str}($message); } }
php
public function writeToLog($message) { if (is_null($this->logger)) { $this->setLogger(); } if (empty($this->sbf_id) || $this->sbf_id == \sb\Gateway::$cookie['SBF_ID']) { $message = preg_replace("~\t~", " ", $message); return $this->logger->{$this->log_str}($message); } }
[ "public", "function", "writeToLog", "(", "$", "message", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "logger", ")", ")", "{", "$", "this", "->", "setLogger", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "sbf_id", ")", "||", "$", "this", "->", "sbf_id", "==", "\\", "sb", "\\", "Gateway", "::", "$", "cookie", "[", "'SBF_ID'", "]", ")", "{", "$", "message", "=", "preg_replace", "(", "\"~\\t~\"", ",", "\" \"", ",", "$", "message", ")", ";", "return", "$", "this", "->", "logger", "->", "{", "$", "this", "->", "log_str", "}", "(", "$", "message", ")", ";", "}", "}" ]
Logs all sql statements to a file, if the log file is specified @param string $message The string to log
[ "Logs", "all", "sql", "statements", "to", "a", "file", "if", "the", "log", "file", "is", "specified" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Logger.php#L147-L159
gregorybesson/PlaygroundCms
src/Service/Slide.php
Slide.getSlideMapper
public function getSlideMapper() { if (null === $this->slideMapper) { $this->slideMapper = $this->serviceLocator->get('playgroundcms_slide_mapper'); } return $this->slideMapper; }
php
public function getSlideMapper() { if (null === $this->slideMapper) { $this->slideMapper = $this->serviceLocator->get('playgroundcms_slide_mapper'); } return $this->slideMapper; }
[ "public", "function", "getSlideMapper", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "slideMapper", ")", "{", "$", "this", "->", "slideMapper", "=", "$", "this", "->", "serviceLocator", "->", "get", "(", "'playgroundcms_slide_mapper'", ")", ";", "}", "return", "$", "this", "->", "slideMapper", ";", "}" ]
getSlideMapper @return SlideMapper
[ "getSlideMapper" ]
train
https://github.com/gregorybesson/PlaygroundCms/blob/e929a283f2a6e82d4f248c930f7aa454ce20cbc3/src/Service/Slide.php#L149-L156
SachaMorard/phalcon-model-annotations
Library/Phalcon/Annotations/ModelStrategy.php
ModelStrategy.getMetaData
public function getMetaData(ModelInterface $model, DiInterface $di) { /** @var Reflection $reflection */ $reflection = $di->getAnnotations()->get($model); $properties = $reflection->getPropertiesAnnotations(); if (!$properties) { throw new \Exception('There are no properties defined on the class'); } $tableProperties = $reflection->getClassAnnotations(); if ($tableProperties && $tableProperties->has('Source')) { $source = $tableProperties->get('Source')->getArguments()[0]; } else { throw new \Exception('Model ' . get_class($model) . ' has no Source defined'); } /** @var \Phalcon\Db\Adapter $database */ $database = $di->get($source); $dbType = ucfirst($database->getType()); $indexes = $this->getIndexes($reflection); return call_user_func_array(['\Phalcon\Annotations\DbStrategies\\'.$dbType, 'getMetaData'], [$reflection, $properties, $indexes]); }
php
public function getMetaData(ModelInterface $model, DiInterface $di) { /** @var Reflection $reflection */ $reflection = $di->getAnnotations()->get($model); $properties = $reflection->getPropertiesAnnotations(); if (!$properties) { throw new \Exception('There are no properties defined on the class'); } $tableProperties = $reflection->getClassAnnotations(); if ($tableProperties && $tableProperties->has('Source')) { $source = $tableProperties->get('Source')->getArguments()[0]; } else { throw new \Exception('Model ' . get_class($model) . ' has no Source defined'); } /** @var \Phalcon\Db\Adapter $database */ $database = $di->get($source); $dbType = ucfirst($database->getType()); $indexes = $this->getIndexes($reflection); return call_user_func_array(['\Phalcon\Annotations\DbStrategies\\'.$dbType, 'getMetaData'], [$reflection, $properties, $indexes]); }
[ "public", "function", "getMetaData", "(", "ModelInterface", "$", "model", ",", "DiInterface", "$", "di", ")", "{", "/** @var Reflection $reflection */", "$", "reflection", "=", "$", "di", "->", "getAnnotations", "(", ")", "->", "get", "(", "$", "model", ")", ";", "$", "properties", "=", "$", "reflection", "->", "getPropertiesAnnotations", "(", ")", ";", "if", "(", "!", "$", "properties", ")", "{", "throw", "new", "\\", "Exception", "(", "'There are no properties defined on the class'", ")", ";", "}", "$", "tableProperties", "=", "$", "reflection", "->", "getClassAnnotations", "(", ")", ";", "if", "(", "$", "tableProperties", "&&", "$", "tableProperties", "->", "has", "(", "'Source'", ")", ")", "{", "$", "source", "=", "$", "tableProperties", "->", "get", "(", "'Source'", ")", "->", "getArguments", "(", ")", "[", "0", "]", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "'Model '", ".", "get_class", "(", "$", "model", ")", ".", "' has no Source defined'", ")", ";", "}", "/** @var \\Phalcon\\Db\\Adapter $database */", "$", "database", "=", "$", "di", "->", "get", "(", "$", "source", ")", ";", "$", "dbType", "=", "ucfirst", "(", "$", "database", "->", "getType", "(", ")", ")", ";", "$", "indexes", "=", "$", "this", "->", "getIndexes", "(", "$", "reflection", ")", ";", "return", "call_user_func_array", "(", "[", "'\\Phalcon\\Annotations\\DbStrategies\\\\'", ".", "$", "dbType", ",", "'getMetaData'", "]", ",", "[", "$", "reflection", ",", "$", "properties", ",", "$", "indexes", "]", ")", ";", "}" ]
Initializes the model's meta-data @param ModelInterface $model @param DiInterface $di @return mixed @throws \Exception
[ "Initializes", "the", "model", "s", "meta", "-", "data" ]
train
https://github.com/SachaMorard/phalcon-model-annotations/blob/64cb04903f101c1fd85e8067c0dcdfc6ca133fb5/Library/Phalcon/Annotations/ModelStrategy.php#L32-L55
SachaMorard/phalcon-model-annotations
Library/Phalcon/Annotations/ModelStrategy.php
ModelStrategy.getColumnMaps
public function getColumnMaps(ModelInterface $model, DiInterface $di) { $reflection = $di['annotations']->get($model); $columnMap = array(); $reverseColumnMap = array(); $renamed = false; foreach ($reflection->getPropertiesAnnotations() as $name => $collection) { if ($collection->has('Column')) { $arguments = $collection->get('Column')->getArguments(); /** * Get the column's name */ if (isset($arguments['column'])) { $columnName = $arguments['column']; } else { $columnName = $name; } $columnMap[$columnName] = $name; $reverseColumnMap[$name] = $columnName; if (!$renamed) { if ($columnName != $name) { $renamed = true; } } } } return array( MetaData::MODELS_COLUMN_MAP => $columnMap, MetaData::MODELS_REVERSE_COLUMN_MAP => $reverseColumnMap ); }
php
public function getColumnMaps(ModelInterface $model, DiInterface $di) { $reflection = $di['annotations']->get($model); $columnMap = array(); $reverseColumnMap = array(); $renamed = false; foreach ($reflection->getPropertiesAnnotations() as $name => $collection) { if ($collection->has('Column')) { $arguments = $collection->get('Column')->getArguments(); /** * Get the column's name */ if (isset($arguments['column'])) { $columnName = $arguments['column']; } else { $columnName = $name; } $columnMap[$columnName] = $name; $reverseColumnMap[$name] = $columnName; if (!$renamed) { if ($columnName != $name) { $renamed = true; } } } } return array( MetaData::MODELS_COLUMN_MAP => $columnMap, MetaData::MODELS_REVERSE_COLUMN_MAP => $reverseColumnMap ); }
[ "public", "function", "getColumnMaps", "(", "ModelInterface", "$", "model", ",", "DiInterface", "$", "di", ")", "{", "$", "reflection", "=", "$", "di", "[", "'annotations'", "]", "->", "get", "(", "$", "model", ")", ";", "$", "columnMap", "=", "array", "(", ")", ";", "$", "reverseColumnMap", "=", "array", "(", ")", ";", "$", "renamed", "=", "false", ";", "foreach", "(", "$", "reflection", "->", "getPropertiesAnnotations", "(", ")", "as", "$", "name", "=>", "$", "collection", ")", "{", "if", "(", "$", "collection", "->", "has", "(", "'Column'", ")", ")", "{", "$", "arguments", "=", "$", "collection", "->", "get", "(", "'Column'", ")", "->", "getArguments", "(", ")", ";", "/**\n * Get the column's name\n */", "if", "(", "isset", "(", "$", "arguments", "[", "'column'", "]", ")", ")", "{", "$", "columnName", "=", "$", "arguments", "[", "'column'", "]", ";", "}", "else", "{", "$", "columnName", "=", "$", "name", ";", "}", "$", "columnMap", "[", "$", "columnName", "]", "=", "$", "name", ";", "$", "reverseColumnMap", "[", "$", "name", "]", "=", "$", "columnName", ";", "if", "(", "!", "$", "renamed", ")", "{", "if", "(", "$", "columnName", "!=", "$", "name", ")", "{", "$", "renamed", "=", "true", ";", "}", "}", "}", "}", "return", "array", "(", "MetaData", "::", "MODELS_COLUMN_MAP", "=>", "$", "columnMap", ",", "MetaData", "::", "MODELS_REVERSE_COLUMN_MAP", "=>", "$", "reverseColumnMap", ")", ";", "}" ]
Initializes the model's column map @param \Phalcon\Mvc\ModelInterface $model @param \Phalcon\DiInterface $di @return array
[ "Initializes", "the", "model", "s", "column", "map" ]
train
https://github.com/SachaMorard/phalcon-model-annotations/blob/64cb04903f101c1fd85e8067c0dcdfc6ca133fb5/Library/Phalcon/Annotations/ModelStrategy.php#L106-L136
GreenCape/joomla-cli
src/GreenCape/JoomlaCLI/Driver/Joomla1.5.php
Joomla1Dot5Driver.setupEnvironment
public function setupEnvironment($basePath, $application = 'site') { if ($application != 'site') { $basePath .= '/' . $application; } $server = array( 'HTTP_HOST' => 'undefined', 'HTTP_USER_AGENT' => 'undefined', 'REQUEST_METHOD' => 'GET', ); $_SERVER = array_merge($_SERVER, $server); define('JPATH_BASE', $basePath); define('DS', DIRECTORY_SEPARATOR); require_once JPATH_BASE . '/includes/defines.php'; require_once JPATH_LIBRARIES . '/loader.php'; spl_autoload_register('__autoload'); require_once JPATH_BASE . '/includes/framework.php'; if ($application == 'administrator') { require_once JPATH_BASE . '/includes/helper.php'; require_once JPATH_BASE . '/includes/toolbar.php'; // JUri uses $_SERVER['HTTP_HOST'] without check $_SERVER['HTTP_HOST'] = 'CLI'; } jimport('joomla.installer.installer'); jimport('joomla.installer.helper'); $mainframe = \JFactory::getApplication($application); $mainframe->initialise(); }
php
public function setupEnvironment($basePath, $application = 'site') { if ($application != 'site') { $basePath .= '/' . $application; } $server = array( 'HTTP_HOST' => 'undefined', 'HTTP_USER_AGENT' => 'undefined', 'REQUEST_METHOD' => 'GET', ); $_SERVER = array_merge($_SERVER, $server); define('JPATH_BASE', $basePath); define('DS', DIRECTORY_SEPARATOR); require_once JPATH_BASE . '/includes/defines.php'; require_once JPATH_LIBRARIES . '/loader.php'; spl_autoload_register('__autoload'); require_once JPATH_BASE . '/includes/framework.php'; if ($application == 'administrator') { require_once JPATH_BASE . '/includes/helper.php'; require_once JPATH_BASE . '/includes/toolbar.php'; // JUri uses $_SERVER['HTTP_HOST'] without check $_SERVER['HTTP_HOST'] = 'CLI'; } jimport('joomla.installer.installer'); jimport('joomla.installer.helper'); $mainframe = \JFactory::getApplication($application); $mainframe->initialise(); }
[ "public", "function", "setupEnvironment", "(", "$", "basePath", ",", "$", "application", "=", "'site'", ")", "{", "if", "(", "$", "application", "!=", "'site'", ")", "{", "$", "basePath", ".=", "'/'", ".", "$", "application", ";", "}", "$", "server", "=", "array", "(", "'HTTP_HOST'", "=>", "'undefined'", ",", "'HTTP_USER_AGENT'", "=>", "'undefined'", ",", "'REQUEST_METHOD'", "=>", "'GET'", ",", ")", ";", "$", "_SERVER", "=", "array_merge", "(", "$", "_SERVER", ",", "$", "server", ")", ";", "define", "(", "'JPATH_BASE'", ",", "$", "basePath", ")", ";", "define", "(", "'DS'", ",", "DIRECTORY_SEPARATOR", ")", ";", "require_once", "JPATH_BASE", ".", "'/includes/defines.php'", ";", "require_once", "JPATH_LIBRARIES", ".", "'/loader.php'", ";", "spl_autoload_register", "(", "'__autoload'", ")", ";", "require_once", "JPATH_BASE", ".", "'/includes/framework.php'", ";", "if", "(", "$", "application", "==", "'administrator'", ")", "{", "require_once", "JPATH_BASE", ".", "'/includes/helper.php'", ";", "require_once", "JPATH_BASE", ".", "'/includes/toolbar.php'", ";", "// JUri uses $_SERVER['HTTP_HOST'] without check", "$", "_SERVER", "[", "'HTTP_HOST'", "]", "=", "'CLI'", ";", "}", "jimport", "(", "'joomla.installer.installer'", ")", ";", "jimport", "(", "'joomla.installer.helper'", ")", ";", "$", "mainframe", "=", "\\", "JFactory", "::", "getApplication", "(", "$", "application", ")", ";", "$", "mainframe", "->", "initialise", "(", ")", ";", "}" ]
Setup the environment @param string $basePath The root of the Joomla! application @param string $application The application, eg., 'site' or 'administration' @return void
[ "Setup", "the", "environment" ]
train
https://github.com/GreenCape/joomla-cli/blob/74a6940f27b1f66c99330d4f9e2c5ac314cdd369/src/GreenCape/JoomlaCLI/Driver/Joomla1.5.php#L51-L89