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
PeekAndPoke/psi
src/Operation/FullSet/ChunkOperation.php
ChunkOperation.apply
public function apply(\Iterator $set) { $group = 0; $counter = $this->chunkSize; $ret = []; foreach ($set as $item) { $ret[$group][] = $item; if (--$counter === 0) { $counter = $this->chunkSize; ++$group; } } return new \ArrayIterator($ret); }
php
public function apply(\Iterator $set) { $group = 0; $counter = $this->chunkSize; $ret = []; foreach ($set as $item) { $ret[$group][] = $item; if (--$counter === 0) { $counter = $this->chunkSize; ++$group; } } return new \ArrayIterator($ret); }
[ "public", "function", "apply", "(", "\\", "Iterator", "$", "set", ")", "{", "$", "group", "=", "0", ";", "$", "counter", "=", "$", "this", "->", "chunkSize", ";", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "set", "as", "$", "item", ")", "{", "$", "ret", "[", "$", "group", "]", "[", "]", "=", "$", "item", ";", "if", "(", "--", "$", "counter", "===", "0", ")", "{", "$", "counter", "=", "$", "this", "->", "chunkSize", ";", "++", "$", "group", ";", "}", "}", "return", "new", "\\", "ArrayIterator", "(", "$", "ret", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/PeekAndPoke/psi/blob/cfd45d995d3a2c2ea6ba5b1ce7b5fcc71179456f/src/Operation/FullSet/ChunkOperation.php#L31-L48
yuncms/framework
src/authclient/WeChat.php
WeChat.refreshAccessToken
public function refreshAccessToken(OAuthToken $token) { $params = [ 'grant_type' => 'refresh_token' ]; $params = array_merge($token->getParams(), $params); $request = $this->createRequest() ->setMethod('POST') ->setUrl($this->refreshTokenUrl) ->setData($params); $this->applyClientCredentialsToRequest($request); $response = $this->sendRequest($request); $token = $this->createToken(['params' => $response]); $this->setAccessToken($token); return $token; }
php
public function refreshAccessToken(OAuthToken $token) { $params = [ 'grant_type' => 'refresh_token' ]; $params = array_merge($token->getParams(), $params); $request = $this->createRequest() ->setMethod('POST') ->setUrl($this->refreshTokenUrl) ->setData($params); $this->applyClientCredentialsToRequest($request); $response = $this->sendRequest($request); $token = $this->createToken(['params' => $response]); $this->setAccessToken($token); return $token; }
[ "public", "function", "refreshAccessToken", "(", "OAuthToken", "$", "token", ")", "{", "$", "params", "=", "[", "'grant_type'", "=>", "'refresh_token'", "]", ";", "$", "params", "=", "array_merge", "(", "$", "token", "->", "getParams", "(", ")", ",", "$", "params", ")", ";", "$", "request", "=", "$", "this", "->", "createRequest", "(", ")", "->", "setMethod", "(", "'POST'", ")", "->", "setUrl", "(", "$", "this", "->", "refreshTokenUrl", ")", "->", "setData", "(", "$", "params", ")", ";", "$", "this", "->", "applyClientCredentialsToRequest", "(", "$", "request", ")", ";", "$", "response", "=", "$", "this", "->", "sendRequest", "(", "$", "request", ")", ";", "$", "token", "=", "$", "this", "->", "createToken", "(", "[", "'params'", "=>", "$", "response", "]", ")", ";", "$", "this", "->", "setAccessToken", "(", "$", "token", ")", ";", "return", "$", "token", ";", "}" ]
Gets new auth token to replace expired one. @param OAuthToken $token expired auth token. @return OAuthToken new auth token. @throws \yii\authclient\InvalidResponseException
[ "Gets", "new", "auth", "token", "to", "replace", "expired", "one", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/authclient/WeChat.php#L144-L164
jfusion/org.jfusion.framework
src/Application/Application.php
Application.enqueueMessage
public function enqueueMessage($msg, $type = 'message') { if ($this->messageStatus) { $event = new Event('onApplicationEnqueueMessage'); $event->addArgument('message', $msg); $event->addArgument('type', $type); Factory::getDispatcher()->triggerEvent($event); } }
php
public function enqueueMessage($msg, $type = 'message') { if ($this->messageStatus) { $event = new Event('onApplicationEnqueueMessage'); $event->addArgument('message', $msg); $event->addArgument('type', $type); Factory::getDispatcher()->triggerEvent($event); } }
[ "public", "function", "enqueueMessage", "(", "$", "msg", ",", "$", "type", "=", "'message'", ")", "{", "if", "(", "$", "this", "->", "messageStatus", ")", "{", "$", "event", "=", "new", "Event", "(", "'onApplicationEnqueueMessage'", ")", ";", "$", "event", "->", "addArgument", "(", "'message'", ",", "$", "msg", ")", ";", "$", "event", "->", "addArgument", "(", "'type'", ",", "$", "type", ")", ";", "Factory", "::", "getDispatcher", "(", ")", "->", "triggerEvent", "(", "$", "event", ")", ";", "}", "}" ]
Enqueue a system message. @param string $msg The message to enqueue. @param string $type The message type. Default is message. @return void @since 3.2
[ "Enqueue", "a", "system", "message", "." ]
train
https://github.com/jfusion/org.jfusion.framework/blob/65771963f23ccabcf1f867eb17c9452299cfe683/src/Application/Application.php#L88-L96
jfusion/org.jfusion.framework
src/Application/Application.php
Application.loadScriptLanguage
public static function loadScriptLanguage($keys) { if (!empty($keys)) { $event = new Event('onApplicationLoadScriptLanguage'); $event->setArgument('keys', $keys); Factory::getDispatcher()->triggerEvent($event); } }
php
public static function loadScriptLanguage($keys) { if (!empty($keys)) { $event = new Event('onApplicationLoadScriptLanguage'); $event->setArgument('keys', $keys); Factory::getDispatcher()->triggerEvent($event); } }
[ "public", "static", "function", "loadScriptLanguage", "(", "$", "keys", ")", "{", "if", "(", "!", "empty", "(", "$", "keys", ")", ")", "{", "$", "event", "=", "new", "Event", "(", "'onApplicationLoadScriptLanguage'", ")", ";", "$", "event", "->", "setArgument", "(", "'keys'", ",", "$", "keys", ")", ";", "Factory", "::", "getDispatcher", "(", ")", "->", "triggerEvent", "(", "$", "event", ")", ";", "}", "}" ]
Load Script language @param string|array $keys
[ "Load", "Script", "language" ]
train
https://github.com/jfusion/org.jfusion.framework/blob/65771963f23ccabcf1f867eb17c9452299cfe683/src/Application/Application.php#L111-L119
jfusion/org.jfusion.framework
src/Application/Application.php
Application.getUser
public static function getUser() { $event = new Event('onApplicationGetUser'); Factory::getDispatcher()->triggerEvent($event); $user = $event->getArgument('user', null); if ($user instanceof Userinfo) { return $user; } else { return new Userinfo(null); } }
php
public static function getUser() { $event = new Event('onApplicationGetUser'); Factory::getDispatcher()->triggerEvent($event); $user = $event->getArgument('user', null); if ($user instanceof Userinfo) { return $user; } else { return new Userinfo(null); } }
[ "public", "static", "function", "getUser", "(", ")", "{", "$", "event", "=", "new", "Event", "(", "'onApplicationGetUser'", ")", ";", "Factory", "::", "getDispatcher", "(", ")", "->", "triggerEvent", "(", "$", "event", ")", ";", "$", "user", "=", "$", "event", "->", "getArgument", "(", "'user'", ",", "null", ")", ";", "if", "(", "$", "user", "instanceof", "Userinfo", ")", "{", "return", "$", "user", ";", "}", "else", "{", "return", "new", "Userinfo", "(", "null", ")", ";", "}", "}" ]
Load Script language
[ "Load", "Script", "language" ]
train
https://github.com/jfusion/org.jfusion.framework/blob/65771963f23ccabcf1f867eb17c9452299cfe683/src/Application/Application.php#L124-L136
afrittella/back-project
src/app/Repositories/Users.php
Users.transform
public function transform($data = [], $options = []) { if (empty($data)) { $data = $this->all(); } // Table header $head = [ 'columns' => [ "", //trans('back-project::users.active'), trans('back-project::users.username'), trans('back-project::users.email'), trans('back-project::users.roles'), trans('back-project::crud.actions'), ] ]; $body = []; foreach ($data as $row): $body[] = [ 'columns' => [ ['content' => '<img src="'.\Avatar::create(strtoupper($row->username))->toBase64().'" alt="'.$row->username.'" width="40px" height="40px" /> '], //['content' => false, 'action' => false, 'icon' => ($row->isConfirmed() ? "check" : 'times')], ['content' => $row->username], ['content' => $row->email], ['content' => implode(',', $row->roles()->pluck('name')->toArray())], ['content' => false, 'actions' => [ 'edit' => ['url' => route('bp.users.edit', [$row['id']])], //url('/admin/users/edit', [$row['id']])], 'delete' => ['url' => route('bp.users.delete', [$row['id']])] ] ], ] ]; endforeach; return [ 'head' => $head, 'body' => $body ]; }
php
public function transform($data = [], $options = []) { if (empty($data)) { $data = $this->all(); } // Table header $head = [ 'columns' => [ "", //trans('back-project::users.active'), trans('back-project::users.username'), trans('back-project::users.email'), trans('back-project::users.roles'), trans('back-project::crud.actions'), ] ]; $body = []; foreach ($data as $row): $body[] = [ 'columns' => [ ['content' => '<img src="'.\Avatar::create(strtoupper($row->username))->toBase64().'" alt="'.$row->username.'" width="40px" height="40px" /> '], //['content' => false, 'action' => false, 'icon' => ($row->isConfirmed() ? "check" : 'times')], ['content' => $row->username], ['content' => $row->email], ['content' => implode(',', $row->roles()->pluck('name')->toArray())], ['content' => false, 'actions' => [ 'edit' => ['url' => route('bp.users.edit', [$row['id']])], //url('/admin/users/edit', [$row['id']])], 'delete' => ['url' => route('bp.users.delete', [$row['id']])] ] ], ] ]; endforeach; return [ 'head' => $head, 'body' => $body ]; }
[ "public", "function", "transform", "(", "$", "data", "=", "[", "]", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "$", "data", "=", "$", "this", "->", "all", "(", ")", ";", "}", "// Table header", "$", "head", "=", "[", "'columns'", "=>", "[", "\"\"", ",", "//trans('back-project::users.active'),", "trans", "(", "'back-project::users.username'", ")", ",", "trans", "(", "'back-project::users.email'", ")", ",", "trans", "(", "'back-project::users.roles'", ")", ",", "trans", "(", "'back-project::crud.actions'", ")", ",", "]", "]", ";", "$", "body", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "row", ")", ":", "$", "body", "[", "]", "=", "[", "'columns'", "=>", "[", "[", "'content'", "=>", "'<img src=\"'", ".", "\\", "Avatar", "::", "create", "(", "strtoupper", "(", "$", "row", "->", "username", ")", ")", "->", "toBase64", "(", ")", ".", "'\" alt=\"'", ".", "$", "row", "->", "username", ".", "'\" width=\"40px\" height=\"40px\" /> '", "]", ",", "//['content' => false, 'action' => false, 'icon' => ($row->isConfirmed() ? \"check\" : 'times')],", "[", "'content'", "=>", "$", "row", "->", "username", "]", ",", "[", "'content'", "=>", "$", "row", "->", "email", "]", ",", "[", "'content'", "=>", "implode", "(", "','", ",", "$", "row", "->", "roles", "(", ")", "->", "pluck", "(", "'name'", ")", "->", "toArray", "(", ")", ")", "]", ",", "[", "'content'", "=>", "false", ",", "'actions'", "=>", "[", "'edit'", "=>", "[", "'url'", "=>", "route", "(", "'bp.users.edit'", ",", "[", "$", "row", "[", "'id'", "]", "]", ")", "]", ",", "//url('/admin/users/edit', [$row['id']])],", "'delete'", "=>", "[", "'url'", "=>", "route", "(", "'bp.users.delete'", ",", "[", "$", "row", "[", "'id'", "]", "]", ")", "]", "]", "]", ",", "]", "]", ";", "endforeach", ";", "return", "[", "'head'", "=>", "$", "head", ",", "'body'", "=>", "$", "body", "]", ";", "}" ]
Transform data in a table array for view @param $data @param array $options @return array
[ "Transform", "data", "in", "a", "table", "array", "for", "view" ]
train
https://github.com/afrittella/back-project/blob/e1aa2e3ee03d453033f75a4b16f073c60b5f32d1/src/app/Repositories/Users.php#L114-L155
fsi-open/doctrine-extensions-bundle
Form/Type/FSi/RemovableFileType.php
RemovableFileType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $fileOptions = array_merge($this->getDefaultFileOptions(), $options['file_options']); $builder->add($builder->getName(), $options['file_type'], $fileOptions); $removeOptions = array_merge($this->getDefaultRemoveOptions(), $options['remove_options']); $builder->add($options['remove_name'], $options['remove_type'], $removeOptions); $this->removeFSiFileEventSubscriber($builder); $builder->addEventSubscriber($this->fileSubscriber); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $fileOptions = array_merge($this->getDefaultFileOptions(), $options['file_options']); $builder->add($builder->getName(), $options['file_type'], $fileOptions); $removeOptions = array_merge($this->getDefaultRemoveOptions(), $options['remove_options']); $builder->add($options['remove_name'], $options['remove_type'], $removeOptions); $this->removeFSiFileEventSubscriber($builder); $builder->addEventSubscriber($this->fileSubscriber); }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "$", "fileOptions", "=", "array_merge", "(", "$", "this", "->", "getDefaultFileOptions", "(", ")", ",", "$", "options", "[", "'file_options'", "]", ")", ";", "$", "builder", "->", "add", "(", "$", "builder", "->", "getName", "(", ")", ",", "$", "options", "[", "'file_type'", "]", ",", "$", "fileOptions", ")", ";", "$", "removeOptions", "=", "array_merge", "(", "$", "this", "->", "getDefaultRemoveOptions", "(", ")", ",", "$", "options", "[", "'remove_options'", "]", ")", ";", "$", "builder", "->", "add", "(", "$", "options", "[", "'remove_name'", "]", ",", "$", "options", "[", "'remove_type'", "]", ",", "$", "removeOptions", ")", ";", "$", "this", "->", "removeFSiFileEventSubscriber", "(", "$", "builder", ")", ";", "$", "builder", "->", "addEventSubscriber", "(", "$", "this", "->", "fileSubscriber", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fsi-open/doctrine-extensions-bundle/blob/1b9c01e0b216b2c1b2af087de233abbf3c84b9fe/Form/Type/FSi/RemovableFileType.php#L67-L77
fsi-open/doctrine-extensions-bundle
Form/Type/FSi/RemovableFileType.php
RemovableFileType.finishView
public function finishView(FormView $view, FormInterface $form, array $options) { $view->vars['label_attr']['for'] = $view[$form->getName()]->vars['id']; }
php
public function finishView(FormView $view, FormInterface $form, array $options) { $view->vars['label_attr']['for'] = $view[$form->getName()]->vars['id']; }
[ "public", "function", "finishView", "(", "FormView", "$", "view", ",", "FormInterface", "$", "form", ",", "array", "$", "options", ")", "{", "$", "view", "->", "vars", "[", "'label_attr'", "]", "[", "'for'", "]", "=", "$", "view", "[", "$", "form", "->", "getName", "(", ")", "]", "->", "vars", "[", "'id'", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fsi-open/doctrine-extensions-bundle/blob/1b9c01e0b216b2c1b2af087de233abbf3c84b9fe/Form/Type/FSi/RemovableFileType.php#L82-L85
fsi-open/doctrine-extensions-bundle
Form/Type/FSi/RemovableFileType.php
RemovableFileType.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'compound' => true, 'error_bubbling' => false, 'inherit_data' => true, 'required' => false, 'remove_name' => 'remove', 'remove_type' => $this->isSymfony3() ? CheckboxType::class : 'checkbox', 'remove_options' => [], 'file_type' => $this->isSymfony3() ? FileType::class : 'fsi_file', 'file_options' => [], ]); $resolver->setAllowedTypes('remove_name', 'string'); $resolver->setAllowedTypes('remove_type', 'string'); $resolver->setAllowedTypes('remove_options', 'array'); $resolver->setAllowedTypes('file_type', 'string'); $resolver->setAllowedTypes('file_options', 'array'); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'compound' => true, 'error_bubbling' => false, 'inherit_data' => true, 'required' => false, 'remove_name' => 'remove', 'remove_type' => $this->isSymfony3() ? CheckboxType::class : 'checkbox', 'remove_options' => [], 'file_type' => $this->isSymfony3() ? FileType::class : 'fsi_file', 'file_options' => [], ]); $resolver->setAllowedTypes('remove_name', 'string'); $resolver->setAllowedTypes('remove_type', 'string'); $resolver->setAllowedTypes('remove_options', 'array'); $resolver->setAllowedTypes('file_type', 'string'); $resolver->setAllowedTypes('file_options', 'array'); }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'compound'", "=>", "true", ",", "'error_bubbling'", "=>", "false", ",", "'inherit_data'", "=>", "true", ",", "'required'", "=>", "false", ",", "'remove_name'", "=>", "'remove'", ",", "'remove_type'", "=>", "$", "this", "->", "isSymfony3", "(", ")", "?", "CheckboxType", "::", "class", ":", "'checkbox'", ",", "'remove_options'", "=>", "[", "]", ",", "'file_type'", "=>", "$", "this", "->", "isSymfony3", "(", ")", "?", "FileType", "::", "class", ":", "'fsi_file'", ",", "'file_options'", "=>", "[", "]", ",", "]", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'remove_name'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'remove_type'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'remove_options'", ",", "'array'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'file_type'", ",", "'string'", ")", ";", "$", "resolver", "->", "setAllowedTypes", "(", "'file_options'", ",", "'array'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fsi-open/doctrine-extensions-bundle/blob/1b9c01e0b216b2c1b2af087de233abbf3c84b9fe/Form/Type/FSi/RemovableFileType.php#L98-L117
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension._initialize
protected function _initialize() { $config = $this->_config->get('joomla'); if(is_null($config) || !is_array($config)) { $config = array(); } $defaults = array( 'name' => 'root', 'username' => 'root', 'groups' => array(8), 'email' => '[email protected]' ); $this->_credentials = array_merge($defaults, $config); $this->_bootstrap(); $this->_loadFramework(); }
php
protected function _initialize() { $config = $this->_config->get('joomla'); if(is_null($config) || !is_array($config)) { $config = array(); } $defaults = array( 'name' => 'root', 'username' => 'root', 'groups' => array(8), 'email' => '[email protected]' ); $this->_credentials = array_merge($defaults, $config); $this->_bootstrap(); $this->_loadFramework(); }
[ "protected", "function", "_initialize", "(", ")", "{", "$", "config", "=", "$", "this", "->", "_config", "->", "get", "(", "'joomla'", ")", ";", "if", "(", "is_null", "(", "$", "config", ")", "||", "!", "is_array", "(", "$", "config", ")", ")", "{", "$", "config", "=", "array", "(", ")", ";", "}", "$", "defaults", "=", "array", "(", "'name'", "=>", "'root'", ",", "'username'", "=>", "'root'", ",", "'groups'", "=>", "array", "(", "8", ")", ",", "'email'", "=>", "'[email protected]'", ")", ";", "$", "this", "->", "_credentials", "=", "array_merge", "(", "$", "defaults", ",", "$", "config", ")", ";", "$", "this", "->", "_bootstrap", "(", ")", ";", "$", "this", "->", "_loadFramework", "(", ")", ";", "}" ]
Initializes extension installer. @return void
[ "Initializes", "extension", "installer", "." ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L60-L79
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension.install
public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { parent::install($repo, $package); if(!$this->_application->install($this->getInstallPath($package))) { // Get all error messages that were stored in the message queue $descriptions = $this->_getApplicationMessages(); $error = 'Error while installing '.$package->getPrettyName(); if(count($descriptions)) { $error .= ':'.PHP_EOL.implode(PHP_EOL, $descriptions); } throw new \RuntimeException($error); } }
php
public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { parent::install($repo, $package); if(!$this->_application->install($this->getInstallPath($package))) { // Get all error messages that were stored in the message queue $descriptions = $this->_getApplicationMessages(); $error = 'Error while installing '.$package->getPrettyName(); if(count($descriptions)) { $error .= ':'.PHP_EOL.implode(PHP_EOL, $descriptions); } throw new \RuntimeException($error); } }
[ "public", "function", "install", "(", "InstalledRepositoryInterface", "$", "repo", ",", "PackageInterface", "$", "package", ")", "{", "parent", "::", "install", "(", "$", "repo", ",", "$", "package", ")", ";", "if", "(", "!", "$", "this", "->", "_application", "->", "install", "(", "$", "this", "->", "getInstallPath", "(", "$", "package", ")", ")", ")", "{", "// Get all error messages that were stored in the message queue", "$", "descriptions", "=", "$", "this", "->", "_getApplicationMessages", "(", ")", ";", "$", "error", "=", "'Error while installing '", ".", "$", "package", "->", "getPrettyName", "(", ")", ";", "if", "(", "count", "(", "$", "descriptions", ")", ")", "{", "$", "error", ".=", "':'", ".", "PHP_EOL", ".", "implode", "(", "PHP_EOL", ",", "$", "descriptions", ")", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "$", "error", ")", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L84-L100
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension.update
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { parent::update($repo, $initial, $target); if(!$this->_application->update($this->getInstallPath($target))) { // Get all error messages that were stored in the message queue $descriptions = $this->_getApplicationMessages(); $error = 'Error while updating '.$target->getPrettyName(); if(count($descriptions)) { $error .= ':'.PHP_EOL.implode(PHP_EOL, $descriptions); } throw new \RuntimeException($error); } }
php
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { parent::update($repo, $initial, $target); if(!$this->_application->update($this->getInstallPath($target))) { // Get all error messages that were stored in the message queue $descriptions = $this->_getApplicationMessages(); $error = 'Error while updating '.$target->getPrettyName(); if(count($descriptions)) { $error .= ':'.PHP_EOL.implode(PHP_EOL, $descriptions); } throw new \RuntimeException($error); } }
[ "public", "function", "update", "(", "InstalledRepositoryInterface", "$", "repo", ",", "PackageInterface", "$", "initial", ",", "PackageInterface", "$", "target", ")", "{", "parent", "::", "update", "(", "$", "repo", ",", "$", "initial", ",", "$", "target", ")", ";", "if", "(", "!", "$", "this", "->", "_application", "->", "update", "(", "$", "this", "->", "getInstallPath", "(", "$", "target", ")", ")", ")", "{", "// Get all error messages that were stored in the message queue", "$", "descriptions", "=", "$", "this", "->", "_getApplicationMessages", "(", ")", ";", "$", "error", "=", "'Error while updating '", ".", "$", "target", "->", "getPrettyName", "(", ")", ";", "if", "(", "count", "(", "$", "descriptions", ")", ")", "{", "$", "error", ".=", "':'", ".", "PHP_EOL", ".", "implode", "(", "PHP_EOL", ",", "$", "descriptions", ")", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "$", "error", ")", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L105-L121
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension.isInstalled
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { $installer = $this->_application->getInstaller(); $installer->setPath('source', $this->getInstallPath($package)); $manifest = $installer->getManifest(); $manifestPath = $installer->getPath('manifest'); if(file_exists($manifestPath) && $manifest) { $type = (string) $manifest->attributes()->type; $element = $this->_getElementFromManifest($manifest, $manifestPath); if (!empty($element)) { return $this->_application->hasExtension($element, $type); } } return parent::isInstalled($repo, $package); }
php
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { $installer = $this->_application->getInstaller(); $installer->setPath('source', $this->getInstallPath($package)); $manifest = $installer->getManifest(); $manifestPath = $installer->getPath('manifest'); if(file_exists($manifestPath) && $manifest) { $type = (string) $manifest->attributes()->type; $element = $this->_getElementFromManifest($manifest, $manifestPath); if (!empty($element)) { return $this->_application->hasExtension($element, $type); } } return parent::isInstalled($repo, $package); }
[ "public", "function", "isInstalled", "(", "InstalledRepositoryInterface", "$", "repo", ",", "PackageInterface", "$", "package", ")", "{", "$", "installer", "=", "$", "this", "->", "_application", "->", "getInstaller", "(", ")", ";", "$", "installer", "->", "setPath", "(", "'source'", ",", "$", "this", "->", "getInstallPath", "(", "$", "package", ")", ")", ";", "$", "manifest", "=", "$", "installer", "->", "getManifest", "(", ")", ";", "$", "manifestPath", "=", "$", "installer", "->", "getPath", "(", "'manifest'", ")", ";", "if", "(", "file_exists", "(", "$", "manifestPath", ")", "&&", "$", "manifest", ")", "{", "$", "type", "=", "(", "string", ")", "$", "manifest", "->", "attributes", "(", ")", "->", "type", ";", "$", "element", "=", "$", "this", "->", "_getElementFromManifest", "(", "$", "manifest", ",", "$", "manifestPath", ")", ";", "if", "(", "!", "empty", "(", "$", "element", ")", ")", "{", "return", "$", "this", "->", "_application", "->", "hasExtension", "(", "$", "element", ",", "$", "type", ")", ";", "}", "}", "return", "parent", "::", "isInstalled", "(", "$", "repo", ",", "$", "package", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L126-L145
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension._getApplicationMessages
protected function _getApplicationMessages() { $messages = $this->_application->getMessageQueue(); $descriptions = array(); foreach($messages as $message) { if($message['type'] == 'error') { $descriptions[] = $message['message']; } } return $descriptions; }
php
protected function _getApplicationMessages() { $messages = $this->_application->getMessageQueue(); $descriptions = array(); foreach($messages as $message) { if($message['type'] == 'error') { $descriptions[] = $message['message']; } } return $descriptions; }
[ "protected", "function", "_getApplicationMessages", "(", ")", "{", "$", "messages", "=", "$", "this", "->", "_application", "->", "getMessageQueue", "(", ")", ";", "$", "descriptions", "=", "array", "(", ")", ";", "foreach", "(", "$", "messages", "as", "$", "message", ")", "{", "if", "(", "$", "message", "[", "'type'", "]", "==", "'error'", ")", "{", "$", "descriptions", "[", "]", "=", "$", "message", "[", "'message'", "]", ";", "}", "}", "return", "$", "descriptions", ";", "}" ]
Fetches the enqueued flash messages from the Joomla application object. @return array
[ "Fetches", "the", "enqueued", "flash", "messages", "from", "the", "Joomla", "application", "object", "." ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L152-L165
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension._getElementFromManifest
protected function _getElementFromManifest($manifest, $manifestPath) { $element = ''; $type = (string) $manifest->attributes()->type; switch($type) { case 'component': $name = strtolower((string) $manifest->name); $element = preg_replace('/[^A-Z0-9_\.-]/i', '', $name); if (substr($element, 0, 4) != 'com_') { $element = 'com_'.$element; } break; case 'module': case 'plugin': if(count($manifest->files->children())) { foreach($manifest->files->children() as $file) { if ((string) $file->attributes()->$type) { $element = (string) $file->attributes()->$type; break; } } } break; case 'file': case 'library': $element = substr($manifestPath, 0, -strlen('.xml')); break; case 'package': $element = preg_replace('/[^A-Z0-9_\.-]/i', '', $manifest->packagename); if (substr($element, 0, 4) != 'pkg_') { $element = 'pkg_'.$element; } break; case 'language': $element = $manifest->get('tag'); break; case 'template': $name = preg_replace('/[^A-Z0-9_ \.-]/i', '', $manifest->name); $element = strtolower(str_replace(' ', '_', $name)); break; default: break; } return $element; }
php
protected function _getElementFromManifest($manifest, $manifestPath) { $element = ''; $type = (string) $manifest->attributes()->type; switch($type) { case 'component': $name = strtolower((string) $manifest->name); $element = preg_replace('/[^A-Z0-9_\.-]/i', '', $name); if (substr($element, 0, 4) != 'com_') { $element = 'com_'.$element; } break; case 'module': case 'plugin': if(count($manifest->files->children())) { foreach($manifest->files->children() as $file) { if ((string) $file->attributes()->$type) { $element = (string) $file->attributes()->$type; break; } } } break; case 'file': case 'library': $element = substr($manifestPath, 0, -strlen('.xml')); break; case 'package': $element = preg_replace('/[^A-Z0-9_\.-]/i', '', $manifest->packagename); if (substr($element, 0, 4) != 'pkg_') { $element = 'pkg_'.$element; } break; case 'language': $element = $manifest->get('tag'); break; case 'template': $name = preg_replace('/[^A-Z0-9_ \.-]/i', '', $manifest->name); $element = strtolower(str_replace(' ', '_', $name)); break; default: break; } return $element; }
[ "protected", "function", "_getElementFromManifest", "(", "$", "manifest", ",", "$", "manifestPath", ")", "{", "$", "element", "=", "''", ";", "$", "type", "=", "(", "string", ")", "$", "manifest", "->", "attributes", "(", ")", "->", "type", ";", "switch", "(", "$", "type", ")", "{", "case", "'component'", ":", "$", "name", "=", "strtolower", "(", "(", "string", ")", "$", "manifest", "->", "name", ")", ";", "$", "element", "=", "preg_replace", "(", "'/[^A-Z0-9_\\.-]/i'", ",", "''", ",", "$", "name", ")", ";", "if", "(", "substr", "(", "$", "element", ",", "0", ",", "4", ")", "!=", "'com_'", ")", "{", "$", "element", "=", "'com_'", ".", "$", "element", ";", "}", "break", ";", "case", "'module'", ":", "case", "'plugin'", ":", "if", "(", "count", "(", "$", "manifest", "->", "files", "->", "children", "(", ")", ")", ")", "{", "foreach", "(", "$", "manifest", "->", "files", "->", "children", "(", ")", "as", "$", "file", ")", "{", "if", "(", "(", "string", ")", "$", "file", "->", "attributes", "(", ")", "->", "$", "type", ")", "{", "$", "element", "=", "(", "string", ")", "$", "file", "->", "attributes", "(", ")", "->", "$", "type", ";", "break", ";", "}", "}", "}", "break", ";", "case", "'file'", ":", "case", "'library'", ":", "$", "element", "=", "substr", "(", "$", "manifestPath", ",", "0", ",", "-", "strlen", "(", "'.xml'", ")", ")", ";", "break", ";", "case", "'package'", ":", "$", "element", "=", "preg_replace", "(", "'/[^A-Z0-9_\\.-]/i'", ",", "''", ",", "$", "manifest", "->", "packagename", ")", ";", "if", "(", "substr", "(", "$", "element", ",", "0", ",", "4", ")", "!=", "'pkg_'", ")", "{", "$", "element", "=", "'pkg_'", ".", "$", "element", ";", "}", "break", ";", "case", "'language'", ":", "$", "element", "=", "$", "manifest", "->", "get", "(", "'tag'", ")", ";", "break", ";", "case", "'template'", ":", "$", "name", "=", "preg_replace", "(", "'/[^A-Z0-9_ \\.-]/i'", ",", "''", ",", "$", "manifest", "->", "name", ")", ";", "$", "element", "=", "strtolower", "(", "str_replace", "(", "' '", ",", "'_'", ",", "$", "name", ")", ")", ";", "break", ";", "default", ":", "break", ";", "}", "return", "$", "element", ";", "}" ]
Load the element name from the installation manifest. @param $manifest @return mixed|string
[ "Load", "the", "element", "name", "from", "the", "installation", "manifest", "." ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L173-L225
nooku/nooku-installer
src/Nooku/Composer/Installer/JoomlaExtension.php
JoomlaExtension._bootstrap
protected function _bootstrap() { if(!defined('_JEXEC')) { $_SERVER['HTTP_HOST'] = 'localhost'; $_SERVER['HTTP_USER_AGENT'] = 'Composer'; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; define('_JEXEC', 1); define('DS', DIRECTORY_SEPARATOR); define('JPATH_BASE', realpath('.')); if (!file_exists(JPATH_BASE . '/includes/defines.php')) { throw new \RuntimeException('Could not find Joomla files. Make sure to run `composer install` from inside the root folder of your Joomla installation!'); } require_once JPATH_BASE . '/includes/defines.php'; require_once JPATH_BASE . '/includes/framework.php'; require_once JPATH_LIBRARIES . '/import.php'; require_once JPATH_LIBRARIES . '/cms.php'; } if(!($this->_application instanceof Application)) { $options = array( 'root_user' => $this->_credentials['username'], 'loglevel' => $this->_verbosity ); $this->_application = new Application($options); $this->_application->authenticate($this->_credentials); } }
php
protected function _bootstrap() { if(!defined('_JEXEC')) { $_SERVER['HTTP_HOST'] = 'localhost'; $_SERVER['HTTP_USER_AGENT'] = 'Composer'; $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; define('_JEXEC', 1); define('DS', DIRECTORY_SEPARATOR); define('JPATH_BASE', realpath('.')); if (!file_exists(JPATH_BASE . '/includes/defines.php')) { throw new \RuntimeException('Could not find Joomla files. Make sure to run `composer install` from inside the root folder of your Joomla installation!'); } require_once JPATH_BASE . '/includes/defines.php'; require_once JPATH_BASE . '/includes/framework.php'; require_once JPATH_LIBRARIES . '/import.php'; require_once JPATH_LIBRARIES . '/cms.php'; } if(!($this->_application instanceof Application)) { $options = array( 'root_user' => $this->_credentials['username'], 'loglevel' => $this->_verbosity ); $this->_application = new Application($options); $this->_application->authenticate($this->_credentials); } }
[ "protected", "function", "_bootstrap", "(", ")", "{", "if", "(", "!", "defined", "(", "'_JEXEC'", ")", ")", "{", "$", "_SERVER", "[", "'HTTP_HOST'", "]", "=", "'localhost'", ";", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", "=", "'Composer'", ";", "$", "_SERVER", "[", "'REMOTE_ADDR'", "]", "=", "'127.0.0.1'", ";", "define", "(", "'_JEXEC'", ",", "1", ")", ";", "define", "(", "'DS'", ",", "DIRECTORY_SEPARATOR", ")", ";", "define", "(", "'JPATH_BASE'", ",", "realpath", "(", "'.'", ")", ")", ";", "if", "(", "!", "file_exists", "(", "JPATH_BASE", ".", "'/includes/defines.php'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Could not find Joomla files. Make sure to run `composer install` from inside the root folder of your Joomla installation!'", ")", ";", "}", "require_once", "JPATH_BASE", ".", "'/includes/defines.php'", ";", "require_once", "JPATH_BASE", ".", "'/includes/framework.php'", ";", "require_once", "JPATH_LIBRARIES", ".", "'/import.php'", ";", "require_once", "JPATH_LIBRARIES", ".", "'/cms.php'", ";", "}", "if", "(", "!", "(", "$", "this", "->", "_application", "instanceof", "Application", ")", ")", "{", "$", "options", "=", "array", "(", "'root_user'", "=>", "$", "this", "->", "_credentials", "[", "'username'", "]", ",", "'loglevel'", "=>", "$", "this", "->", "_verbosity", ")", ";", "$", "this", "->", "_application", "=", "new", "Application", "(", "$", "options", ")", ";", "$", "this", "->", "_application", "->", "authenticate", "(", "$", "this", "->", "_credentials", ")", ";", "}", "}" ]
Bootstraps the Joomla application @return void
[ "Bootstraps", "the", "Joomla", "application" ]
train
https://github.com/nooku/nooku-installer/blob/2aa82ed08983bccd51905426cfff4980ba960d89/src/Nooku/Composer/Installer/JoomlaExtension.php#L232-L267
yuncms/framework
src/helpers/ISO3166Helper.php
ISO3166Helper.country
public static function country($code, $translate = true): string { return Locale::getDisplayRegion("_$code", $translate ? Yii::$app->language : 'en'); }
php
public static function country($code, $translate = true): string { return Locale::getDisplayRegion("_$code", $translate ? Yii::$app->language : 'en'); }
[ "public", "static", "function", "country", "(", "$", "code", ",", "$", "translate", "=", "true", ")", ":", "string", "{", "return", "Locale", "::", "getDisplayRegion", "(", "\"_$code\"", ",", "$", "translate", "?", "Yii", "::", "$", "app", "->", "language", ":", "'en'", ")", ";", "}" ]
获取国家名称 @param string $code @param bool $translate @return string
[ "获取国家名称" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/ISO3166Helper.php#L528-L531
yuncms/framework
src/helpers/ISO3166Helper.php
ISO3166Helper.phoneCode
public static function phoneCode($code): string { return (isset(static::$phoneCodes[strtoupper($code)])) ? static::$phoneCodes[strtoupper($code)] : 'N/A'; }
php
public static function phoneCode($code): string { return (isset(static::$phoneCodes[strtoupper($code)])) ? static::$phoneCodes[strtoupper($code)] : 'N/A'; }
[ "public", "static", "function", "phoneCode", "(", "$", "code", ")", ":", "string", "{", "return", "(", "isset", "(", "static", "::", "$", "phoneCodes", "[", "strtoupper", "(", "$", "code", ")", "]", ")", ")", "?", "static", "::", "$", "phoneCodes", "[", "strtoupper", "(", "$", "code", ")", "]", ":", "'N/A'", ";", "}" ]
获取国际区号 @param string $code @return mixed|string
[ "获取国际区号" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/ISO3166Helper.php#L538-L541
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.php
public function php() { $cr = "\n"; $php = $this->phpDocBlock(0); $ms = array(self::MODIFIER_ABSTRACT => 'abstract', self::MODIFIER_FINAL => 'final' ); foreach ($ms as $const => $modifier) { if (($const & $this->modifiers) == $const) $php .= $modifier.' '; } $php .= 'class '.$this->getClassName().' '; /* Extends */ if (isset($this->parentClass)) { if ($this->parentClass->getNamespace() === $this->getNamespace()) { $php .= 'extends '.$this->parentClass->getClassName().' '; // don't prefix namespace } else { $php .= 'extends '.'\\'.$this->parentClass->getFQN().' '; } } /* Interfaces */ if (count($this->getInterfaces()) > 0) { $php .= 'implements '; $that = $this; $php .= A::implode($this->getInterfaces(), ', ', function (GClass $iClass) use ($that) { if ($that->getNamespace() === $iClass->getNamespace()) { return $iClass->getClassName(); } else { return '\\'.$iClass->getFQN(); } }); $php .= ' '; } $php .= '{'.$cr; /* Die Funktionen machen immer den Abstand nach oben. Also vor jedem Property und jeder Methode macht dies ein "\n" */ /* Constants */ $php .= A::joinc($this->getConstants(), ' '.$cr.'%s;'.$cr, function ($constant) { return $constant->php(2); }); /* Properties */ $php .= A::joinc($this->getProperties(), ' '.$cr.'%s;'.$cr, function ($property) { return $property->php(2); // hier jetzt auch wegen DocBlock einrücken }); /* Methods */ $php .= A::joinc($this->getMethods(), ' '.$cr.'%s'.$cr, function ($method) { return $method->php(2); // rückt selbst zwischen den Klammern ein, aber wir wollen ja den body z.b. auf 4 haben nicht auf 2 }); $php .= '}'; // kein umbruch hinten, immer abstand nach oben! return $php; }
php
public function php() { $cr = "\n"; $php = $this->phpDocBlock(0); $ms = array(self::MODIFIER_ABSTRACT => 'abstract', self::MODIFIER_FINAL => 'final' ); foreach ($ms as $const => $modifier) { if (($const & $this->modifiers) == $const) $php .= $modifier.' '; } $php .= 'class '.$this->getClassName().' '; /* Extends */ if (isset($this->parentClass)) { if ($this->parentClass->getNamespace() === $this->getNamespace()) { $php .= 'extends '.$this->parentClass->getClassName().' '; // don't prefix namespace } else { $php .= 'extends '.'\\'.$this->parentClass->getFQN().' '; } } /* Interfaces */ if (count($this->getInterfaces()) > 0) { $php .= 'implements '; $that = $this; $php .= A::implode($this->getInterfaces(), ', ', function (GClass $iClass) use ($that) { if ($that->getNamespace() === $iClass->getNamespace()) { return $iClass->getClassName(); } else { return '\\'.$iClass->getFQN(); } }); $php .= ' '; } $php .= '{'.$cr; /* Die Funktionen machen immer den Abstand nach oben. Also vor jedem Property und jeder Methode macht dies ein "\n" */ /* Constants */ $php .= A::joinc($this->getConstants(), ' '.$cr.'%s;'.$cr, function ($constant) { return $constant->php(2); }); /* Properties */ $php .= A::joinc($this->getProperties(), ' '.$cr.'%s;'.$cr, function ($property) { return $property->php(2); // hier jetzt auch wegen DocBlock einrücken }); /* Methods */ $php .= A::joinc($this->getMethods(), ' '.$cr.'%s'.$cr, function ($method) { return $method->php(2); // rückt selbst zwischen den Klammern ein, aber wir wollen ja den body z.b. auf 4 haben nicht auf 2 }); $php .= '}'; // kein umbruch hinten, immer abstand nach oben! return $php; }
[ "public", "function", "php", "(", ")", "{", "$", "cr", "=", "\"\\n\"", ";", "$", "php", "=", "$", "this", "->", "phpDocBlock", "(", "0", ")", ";", "$", "ms", "=", "array", "(", "self", "::", "MODIFIER_ABSTRACT", "=>", "'abstract'", ",", "self", "::", "MODIFIER_FINAL", "=>", "'final'", ")", ";", "foreach", "(", "$", "ms", "as", "$", "const", "=>", "$", "modifier", ")", "{", "if", "(", "(", "$", "const", "&", "$", "this", "->", "modifiers", ")", "==", "$", "const", ")", "$", "php", ".=", "$", "modifier", ".", "' '", ";", "}", "$", "php", ".=", "'class '", ".", "$", "this", "->", "getClassName", "(", ")", ".", "' '", ";", "/* Extends */", "if", "(", "isset", "(", "$", "this", "->", "parentClass", ")", ")", "{", "if", "(", "$", "this", "->", "parentClass", "->", "getNamespace", "(", ")", "===", "$", "this", "->", "getNamespace", "(", ")", ")", "{", "$", "php", ".=", "'extends '", ".", "$", "this", "->", "parentClass", "->", "getClassName", "(", ")", ".", "' '", ";", "// don't prefix namespace", "}", "else", "{", "$", "php", ".=", "'extends '", ".", "'\\\\'", ".", "$", "this", "->", "parentClass", "->", "getFQN", "(", ")", ".", "' '", ";", "}", "}", "/* Interfaces */", "if", "(", "count", "(", "$", "this", "->", "getInterfaces", "(", ")", ")", ">", "0", ")", "{", "$", "php", ".=", "'implements '", ";", "$", "that", "=", "$", "this", ";", "$", "php", ".=", "A", "::", "implode", "(", "$", "this", "->", "getInterfaces", "(", ")", ",", "', '", ",", "function", "(", "GClass", "$", "iClass", ")", "use", "(", "$", "that", ")", "{", "if", "(", "$", "that", "->", "getNamespace", "(", ")", "===", "$", "iClass", "->", "getNamespace", "(", ")", ")", "{", "return", "$", "iClass", "->", "getClassName", "(", ")", ";", "}", "else", "{", "return", "'\\\\'", ".", "$", "iClass", "->", "getFQN", "(", ")", ";", "}", "}", ")", ";", "$", "php", ".=", "' '", ";", "}", "$", "php", ".=", "'{'", ".", "$", "cr", ";", "/* Die Funktionen machen immer den Abstand nach oben. Also vor jedem Property und jeder Methode macht dies ein \"\\n\" */", "/* Constants */", "$", "php", ".=", "A", "::", "joinc", "(", "$", "this", "->", "getConstants", "(", ")", ",", "' '", ".", "$", "cr", ".", "'%s;'", ".", "$", "cr", ",", "function", "(", "$", "constant", ")", "{", "return", "$", "constant", "->", "php", "(", "2", ")", ";", "}", ")", ";", "/* Properties */", "$", "php", ".=", "A", "::", "joinc", "(", "$", "this", "->", "getProperties", "(", ")", ",", "' '", ".", "$", "cr", ".", "'%s;'", ".", "$", "cr", ",", "function", "(", "$", "property", ")", "{", "return", "$", "property", "->", "php", "(", "2", ")", ";", "// hier jetzt auch wegen DocBlock einrücken", "}", ")", ";", "/* Methods */", "$", "php", ".=", "A", "::", "joinc", "(", "$", "this", "->", "getMethods", "(", ")", ",", "' '", ".", "$", "cr", ".", "'%s'", ".", "$", "cr", ",", "function", "(", "$", "method", ")", "{", "return", "$", "method", "->", "php", "(", "2", ")", ";", "// rückt selbst zwischen den Klammern ein, aber wir wollen ja den body z.b. auf 4 haben nicht auf 2", "}", ")", ";", "$", "php", ".=", "'}'", ";", "// kein umbruch hinten, immer abstand nach oben!", "return", "$", "php", ";", "}" ]
Gibt die Klasse als PHP Code zurück die Klasse ist noch nicht mit Namespace vor class notiert! Eingerückt wird mit 2 whitespaces. Em Ende befindet sich hinter der schließenden Klammer ein LF
[ "Gibt", "die", "Klasse", "als", "PHP", "Code", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L172-L231
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.getProperties
public function getProperties() { $properties = array(); foreach ($this->properties as $property) { if ($property->getDeclaringClass() instanceof GClass && $property->getDeclaringClass()->equals($this)) { $properties[$property->getName()] = $property; } } return $properties; }
php
public function getProperties() { $properties = array(); foreach ($this->properties as $property) { if ($property->getDeclaringClass() instanceof GClass && $property->getDeclaringClass()->equals($this)) { $properties[$property->getName()] = $property; } } return $properties; }
[ "public", "function", "getProperties", "(", ")", "{", "$", "properties", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "properties", "as", "$", "property", ")", "{", "if", "(", "$", "property", "->", "getDeclaringClass", "(", ")", "instanceof", "GClass", "&&", "$", "property", "->", "getDeclaringClass", "(", ")", "->", "equals", "(", "$", "this", ")", ")", "{", "$", "properties", "[", "$", "property", "->", "getName", "(", ")", "]", "=", "$", "property", ";", "}", "}", "return", "$", "properties", ";", "}" ]
Gibt nur die Properties der Klasse zurück @return GProperty[]
[ "Gibt", "nur", "die", "Properties", "der", "Klasse", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L335-L344
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.hasOwnProperty
public function hasOwnProperty($name) { if (!$this->hasProperty($name)) return FALSE; $property = $this->getProperty($name); return $property->getDeclaringClass() instanceof GClass && $property->getDeclaringClass()->equals($this); }
php
public function hasOwnProperty($name) { if (!$this->hasProperty($name)) return FALSE; $property = $this->getProperty($name); return $property->getDeclaringClass() instanceof GClass && $property->getDeclaringClass()->equals($this); }
[ "public", "function", "hasOwnProperty", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "hasProperty", "(", "$", "name", ")", ")", "return", "FALSE", ";", "$", "property", "=", "$", "this", "->", "getProperty", "(", "$", "name", ")", ";", "return", "$", "property", "->", "getDeclaringClass", "(", ")", "instanceof", "GClass", "&&", "$", "property", "->", "getDeclaringClass", "(", ")", "->", "equals", "(", "$", "this", ")", ";", "}" ]
Gibt zurück ob die Klasse das Property hat @return bool
[ "Gibt", "zurück", "ob", "die", "Klasse", "das", "Property", "hat" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L378-L383
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.createProperty
public function createProperty($name, $modifiers = GProperty::MODIFIER_PROTECTED, $default = 'undefined') { $gProperty = new GProperty($this); $gProperty->setName($name); $gProperty->setModifiers($modifiers); if (func_num_args() == 3) { $this->setDefaultValue($gProperty,$default); } $this->addProperty($gProperty); return $gProperty; }
php
public function createProperty($name, $modifiers = GProperty::MODIFIER_PROTECTED, $default = 'undefined') { $gProperty = new GProperty($this); $gProperty->setName($name); $gProperty->setModifiers($modifiers); if (func_num_args() == 3) { $this->setDefaultValue($gProperty,$default); } $this->addProperty($gProperty); return $gProperty; }
[ "public", "function", "createProperty", "(", "$", "name", ",", "$", "modifiers", "=", "GProperty", "::", "MODIFIER_PROTECTED", ",", "$", "default", "=", "'undefined'", ")", "{", "$", "gProperty", "=", "new", "GProperty", "(", "$", "this", ")", ";", "$", "gProperty", "->", "setName", "(", "$", "name", ")", ";", "$", "gProperty", "->", "setModifiers", "(", "$", "modifiers", ")", ";", "if", "(", "func_num_args", "(", ")", "==", "3", ")", "{", "$", "this", "->", "setDefaultValue", "(", "$", "gProperty", ",", "$", "default", ")", ";", "}", "$", "this", "->", "addProperty", "(", "$", "gProperty", ")", ";", "return", "$", "gProperty", ";", "}" ]
Erstellt ein neues Property und fügt dieses der Klasse hinzu @return GProperty
[ "Erstellt", "ein", "neues", "Property", "und", "fügt", "dieses", "der", "Klasse", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L390-L399
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.createMethod
public function createMethod($name, $params = array(), $body = NULL, $modifiers = GMethod::MODIFIER_PUBLIC) { $method = new GMethod($name, $params, $body, $modifiers); $this->addMethod($method); return $method; }
php
public function createMethod($name, $params = array(), $body = NULL, $modifiers = GMethod::MODIFIER_PUBLIC) { $method = new GMethod($name, $params, $body, $modifiers); $this->addMethod($method); return $method; }
[ "public", "function", "createMethod", "(", "$", "name", ",", "$", "params", "=", "array", "(", ")", ",", "$", "body", "=", "NULL", ",", "$", "modifiers", "=", "GMethod", "::", "MODIFIER_PUBLIC", ")", "{", "$", "method", "=", "new", "GMethod", "(", "$", "name", ",", "$", "params", ",", "$", "body", ",", "$", "modifiers", ")", ";", "$", "this", "->", "addMethod", "(", "$", "method", ")", ";", "return", "$", "method", ";", "}" ]
Erstellt eine neue Methode und fügt diese der Klasse hinzu @return GMethod
[ "Erstellt", "eine", "neue", "Methode", "und", "fügt", "diese", "der", "Klasse", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L406-L410
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.hasConcreteMethod
public function hasConcreteMethod($name) { if (!array_key_exists($name,$this->methods)) { return FALSE; } $method = $this->getMethod($name); return !$method->getDeclaringClass()->isInterface(); }
php
public function hasConcreteMethod($name) { if (!array_key_exists($name,$this->methods)) { return FALSE; } $method = $this->getMethod($name); return !$method->getDeclaringClass()->isInterface(); }
[ "public", "function", "hasConcreteMethod", "(", "$", "name", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "methods", ")", ")", "{", "return", "FALSE", ";", "}", "$", "method", "=", "$", "this", "->", "getMethod", "(", "$", "name", ")", ";", "return", "!", "$", "method", "->", "getDeclaringClass", "(", ")", "->", "isInterface", "(", ")", ";", "}" ]
Gibt zurück ob die Klasse eine implementierung für diese Methode hat hasMethod gibt auch TRUE zurück wenn die Klassenhierarchy ein Interface hat, was diese Methode hat diese Funktion gibt dann FALSE zurück @TODO isInterface @return bool
[ "Gibt", "zurück", "ob", "die", "Klasse", "eine", "implementierung", "für", "diese", "Methode", "hat" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L472-L479
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.getMethods
public function getMethods() { $methods = array(); foreach ($this->methodsOrder as $methodName) { $method = $this->methods[$methodName]; if ($method->getDeclaringClass()->equals($this)) { $methods[$method->getName()] = $method; } } return $methods; }
php
public function getMethods() { $methods = array(); foreach ($this->methodsOrder as $methodName) { $method = $this->methods[$methodName]; if ($method->getDeclaringClass()->equals($this)) { $methods[$method->getName()] = $method; } } return $methods; }
[ "public", "function", "getMethods", "(", ")", "{", "$", "methods", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "methodsOrder", "as", "$", "methodName", ")", "{", "$", "method", "=", "$", "this", "->", "methods", "[", "$", "methodName", "]", ";", "if", "(", "$", "method", "->", "getDeclaringClass", "(", ")", "->", "equals", "(", "$", "this", ")", ")", "{", "$", "methods", "[", "$", "method", "->", "getName", "(", ")", "]", "=", "$", "method", ";", "}", "}", "return", "$", "methods", ";", "}" ]
Gibt die Methoden der Klasse zurück, die die Klasse definiert @return array
[ "Gibt", "die", "Methoden", "der", "Klasse", "zurück", "die", "die", "Klasse", "definiert" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L493-L502
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.getAllMethods
public function getAllMethods() { $methods = array(); foreach ($this->methodsOrder as $methodName) { $method = $this->methods[$methodName]; $methods[$method->getName()] = $method; } return $methods; }
php
public function getAllMethods() { $methods = array(); foreach ($this->methodsOrder as $methodName) { $method = $this->methods[$methodName]; $methods[$method->getName()] = $method; } return $methods; }
[ "public", "function", "getAllMethods", "(", ")", "{", "$", "methods", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "methodsOrder", "as", "$", "methodName", ")", "{", "$", "method", "=", "$", "this", "->", "methods", "[", "$", "methodName", "]", ";", "$", "methods", "[", "$", "method", "->", "getName", "(", ")", "]", "=", "$", "method", ";", "}", "return", "$", "methods", ";", "}" ]
Gibt die Methoden der Klasse und die Methoden der Parents der Klasse zurück @return array
[ "Gibt", "die", "Methoden", "der", "Klasse", "und", "die", "Methoden", "der", "Parents", "der", "Klasse", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L509-L516
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.createAbstractMethodStubs
public function createAbstractMethodStubs() { if ($this->isAbstract()) return $this; if (($parent = $this->getParentClass()) !== NULL) { $parent->elevateClass(); foreach ($parent->getAllMethods() as $method) { if ($method->isAbstract()) { $this->createMethodStub($method); } } } foreach ($this->getAllInterfaces() as $interface) { $interface->elevateClass(); foreach ($interface->getAllMethods() as $method) { $this->createMethodStub($method); } } return $this; }
php
public function createAbstractMethodStubs() { if ($this->isAbstract()) return $this; if (($parent = $this->getParentClass()) !== NULL) { $parent->elevateClass(); foreach ($parent->getAllMethods() as $method) { if ($method->isAbstract()) { $this->createMethodStub($method); } } } foreach ($this->getAllInterfaces() as $interface) { $interface->elevateClass(); foreach ($interface->getAllMethods() as $method) { $this->createMethodStub($method); } } return $this; }
[ "public", "function", "createAbstractMethodStubs", "(", ")", "{", "if", "(", "$", "this", "->", "isAbstract", "(", ")", ")", "return", "$", "this", ";", "if", "(", "(", "$", "parent", "=", "$", "this", "->", "getParentClass", "(", ")", ")", "!==", "NULL", ")", "{", "$", "parent", "->", "elevateClass", "(", ")", ";", "foreach", "(", "$", "parent", "->", "getAllMethods", "(", ")", "as", "$", "method", ")", "{", "if", "(", "$", "method", "->", "isAbstract", "(", ")", ")", "{", "$", "this", "->", "createMethodStub", "(", "$", "method", ")", ";", "}", "}", "}", "foreach", "(", "$", "this", "->", "getAllInterfaces", "(", ")", "as", "$", "interface", ")", "{", "$", "interface", "->", "elevateClass", "(", ")", ";", "foreach", "(", "$", "interface", "->", "getAllMethods", "(", ")", "as", "$", "method", ")", "{", "$", "this", "->", "createMethodStub", "(", "$", "method", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Erstellt Stubs (Prototypen) für alle abstrakten Methoden der Klasse
[ "Erstellt", "Stubs", "(", "Prototypen", ")", "für", "alle", "abstrakten", "Methoden", "der", "Klasse" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L521-L540
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.createMethodStub
public function createMethodStub(GMethod $method) { // method is not abstract (thats strange) if (!$method->isAbstract()) return $this; // no need to implement if ($this->hasMethod($method->getName()) && !$method->isAbstract()) return $this; $cMethod = clone $method; $cMethod->setAbstract(FALSE); $cMethod->setDeclaringClass($this); return $this->addMethod($cMethod); }
php
public function createMethodStub(GMethod $method) { // method is not abstract (thats strange) if (!$method->isAbstract()) return $this; // no need to implement if ($this->hasMethod($method->getName()) && !$method->isAbstract()) return $this; $cMethod = clone $method; $cMethod->setAbstract(FALSE); $cMethod->setDeclaringClass($this); return $this->addMethod($cMethod); }
[ "public", "function", "createMethodStub", "(", "GMethod", "$", "method", ")", "{", "// method is not abstract (thats strange)", "if", "(", "!", "$", "method", "->", "isAbstract", "(", ")", ")", "return", "$", "this", ";", "// no need to implement", "if", "(", "$", "this", "->", "hasMethod", "(", "$", "method", "->", "getName", "(", ")", ")", "&&", "!", "$", "method", "->", "isAbstract", "(", ")", ")", "return", "$", "this", ";", "$", "cMethod", "=", "clone", "$", "method", ";", "$", "cMethod", "->", "setAbstract", "(", "FALSE", ")", ";", "$", "cMethod", "->", "setDeclaringClass", "(", "$", "this", ")", ";", "return", "$", "this", "->", "addMethod", "(", "$", "cMethod", ")", ";", "}" ]
Erstellt einen Stub für eine gegebene abstrakte Methode
[ "Erstellt", "einen", "Stub", "für", "eine", "gegebene", "abstrakte", "Methode" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L545-L556
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.getConstants
public function getConstants() { if (!isset($this->parentClass)) return $this->constants; $constants = array(); foreach ($this->constants as $constant) { if (!$this->parentClass->hasConstant($constant->getName())) { $constants[$constant->getName()] = $constant; } } return $constants; }
php
public function getConstants() { if (!isset($this->parentClass)) return $this->constants; $constants = array(); foreach ($this->constants as $constant) { if (!$this->parentClass->hasConstant($constant->getName())) { $constants[$constant->getName()] = $constant; } } return $constants; }
[ "public", "function", "getConstants", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "parentClass", ")", ")", "return", "$", "this", "->", "constants", ";", "$", "constants", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "constants", "as", "$", "constant", ")", "{", "if", "(", "!", "$", "this", "->", "parentClass", "->", "hasConstant", "(", "$", "constant", "->", "getName", "(", ")", ")", ")", "{", "$", "constants", "[", "$", "constant", "->", "getName", "(", ")", "]", "=", "$", "constant", ";", "}", "}", "return", "$", "constants", ";", "}" ]
Gibt alle Konstanten der Klasse (selbst) zurück @return array
[ "Gibt", "alle", "Konstanten", "der", "Klasse", "(", "selbst", ")", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L564-L575
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.setName
public function setName($name) { if (mb_strpos($name,'\\') !== FALSE) { $this->setNamespace(Code::getNamespace($name)); $this->name = Code::getClassName($name); } else { $this->name = $name; $this->namespace = NULL; } return $this; }
php
public function setName($name) { if (mb_strpos($name,'\\') !== FALSE) { $this->setNamespace(Code::getNamespace($name)); $this->name = Code::getClassName($name); } else { $this->name = $name; $this->namespace = NULL; } return $this; }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "if", "(", "mb_strpos", "(", "$", "name", ",", "'\\\\'", ")", "!==", "FALSE", ")", "{", "$", "this", "->", "setNamespace", "(", "Code", "::", "getNamespace", "(", "$", "name", ")", ")", ";", "$", "this", "->", "name", "=", "Code", "::", "getClassName", "(", "$", "name", ")", ";", "}", "else", "{", "$", "this", "->", "name", "=", "$", "name", ";", "$", "this", "->", "namespace", "=", "NULL", ";", "}", "return", "$", "this", ";", "}" ]
Setzt den Namen der Klasse Namespace wird immer mitgesetzt! D. h. übergibt man hier nur den ShortName wird der Namespace auf NULL gesetzt Wenn man nur den Namen der Klasse und nicht den Namespace wechseln will, muss man setClassName() nehmen @param string FQN;
[ "Setzt", "den", "Namen", "der", "Klasse" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L652-L661
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.getInterfaces
public function getInterfaces() { /* das hier ist etwas mehr tricky, als bei property und method weil interfaces auch in reflection eine reflectionClass sind und deshalb keine getDeclaringClass() Methode haben deshalb gucken wir ob parent das Interface implementiert. Wenn ja tun wir so als wäre dies nicht unser eigenes implements dies hilft beim Klasse-Schreiben jedoch nicht. Dort würde das Interface dann immer wieder verschwinden, auch wenn es explizit hinzugefügt worden wäre das ist nicht so trivial: InterfaceC extends InterfaceA, InterfaceB dann dürfen InterfacA und InterfaceB nicht implementiert werden (nur C) */ if (!isset($this->parentClass)) return $this->interfaces; $interfaces = array(); foreach ($this->interfaces as $interface) { if (!$this->parentClass->hasInterface($interface)) { $interfaces[$interface->getFQN()] = $interface; } } return $interfaces; }
php
public function getInterfaces() { /* das hier ist etwas mehr tricky, als bei property und method weil interfaces auch in reflection eine reflectionClass sind und deshalb keine getDeclaringClass() Methode haben deshalb gucken wir ob parent das Interface implementiert. Wenn ja tun wir so als wäre dies nicht unser eigenes implements dies hilft beim Klasse-Schreiben jedoch nicht. Dort würde das Interface dann immer wieder verschwinden, auch wenn es explizit hinzugefügt worden wäre das ist nicht so trivial: InterfaceC extends InterfaceA, InterfaceB dann dürfen InterfacA und InterfaceB nicht implementiert werden (nur C) */ if (!isset($this->parentClass)) return $this->interfaces; $interfaces = array(); foreach ($this->interfaces as $interface) { if (!$this->parentClass->hasInterface($interface)) { $interfaces[$interface->getFQN()] = $interface; } } return $interfaces; }
[ "public", "function", "getInterfaces", "(", ")", "{", "/* das hier ist etwas mehr tricky, als bei property und method weil interfaces auch in reflection\n eine reflectionClass sind und deshalb keine getDeclaringClass() Methode haben\n deshalb gucken wir ob parent das Interface implementiert. Wenn ja tun wir so als wäre dies nicht unser eigenes implements\n \n dies hilft beim Klasse-Schreiben jedoch nicht. Dort würde das Interface dann immer wieder verschwinden,\n auch wenn es explizit hinzugefügt worden wäre\n \n das ist nicht so trivial:\n InterfaceC extends InterfaceA, InterfaceB\n dann dürfen InterfacA und InterfaceB nicht implementiert werden (nur C)\n */", "if", "(", "!", "isset", "(", "$", "this", "->", "parentClass", ")", ")", "return", "$", "this", "->", "interfaces", ";", "$", "interfaces", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "interfaces", "as", "$", "interface", ")", "{", "if", "(", "!", "$", "this", "->", "parentClass", "->", "hasInterface", "(", "$", "interface", ")", ")", "{", "$", "interfaces", "[", "$", "interface", "->", "getFQN", "(", ")", "]", "=", "$", "interface", ";", "}", "}", "return", "$", "interfaces", ";", "}" ]
Gibt nur die Interfaces der Klasse zurück @TODO fixme: interfaces die subinterfaces von interfaces sind die wir schon hinzugefügt haben, dürfen auch nicht rein @return GClass[]
[ "Gibt", "nur", "die", "Interfaces", "der", "Klasse", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L757-L778
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.removeInterface
public function removeInterface(GClass $class) { if (array_key_exists($n = $class->getFQN(), $this->interfaces)) { unset($this->interfaces[$n]); } return $this; }
php
public function removeInterface(GClass $class) { if (array_key_exists($n = $class->getFQN(), $this->interfaces)) { unset($this->interfaces[$n]); } return $this; }
[ "public", "function", "removeInterface", "(", "GClass", "$", "class", ")", "{", "if", "(", "array_key_exists", "(", "$", "n", "=", "$", "class", "->", "getFQN", "(", ")", ",", "$", "this", "->", "interfaces", ")", ")", "{", "unset", "(", "$", "this", "->", "interfaces", "[", "$", "n", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
Entfernt das Interface aus der Klasse @chainable
[ "Entfernt", "das", "Interface", "aus", "der", "Klasse" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L804-L809
webforge-labs/psc-cms
lib/Psc/Code/Generate/GClass.php
GClass.addUsedClass
public function addUsedClass(GClass $class, $requestedAlias = NULL) { if (array_key_exists($fqn = $class->getFQN(), $this->usedClasses)) { if ($this->usedClasses[$fqn][1] != $requestedAlias) { throw new Exception(sprintf("Die Klasse '%s' kann nicht mit alias '%s' hinzugefügt werden, da sie schon als Alias '%s' hinzugefügt wurde", $fqn, $requestedAlias, $this->usedClasses[$fqn][1] )); } } else { $this->usedClasses[$fqn] = array($class, $requestedAlias); } return $this; }
php
public function addUsedClass(GClass $class, $requestedAlias = NULL) { if (array_key_exists($fqn = $class->getFQN(), $this->usedClasses)) { if ($this->usedClasses[$fqn][1] != $requestedAlias) { throw new Exception(sprintf("Die Klasse '%s' kann nicht mit alias '%s' hinzugefügt werden, da sie schon als Alias '%s' hinzugefügt wurde", $fqn, $requestedAlias, $this->usedClasses[$fqn][1] )); } } else { $this->usedClasses[$fqn] = array($class, $requestedAlias); } return $this; }
[ "public", "function", "addUsedClass", "(", "GClass", "$", "class", ",", "$", "requestedAlias", "=", "NULL", ")", "{", "if", "(", "array_key_exists", "(", "$", "fqn", "=", "$", "class", "->", "getFQN", "(", ")", ",", "$", "this", "->", "usedClasses", ")", ")", "{", "if", "(", "$", "this", "->", "usedClasses", "[", "$", "fqn", "]", "[", "1", "]", "!=", "$", "requestedAlias", ")", "{", "throw", "new", "Exception", "(", "sprintf", "(", "\"Die Klasse '%s' kann nicht mit alias '%s' hinzugefügt werden, da sie schon als Alias '%s' hinzugefügt wurde\",", "", "$", "fqn", ",", "$", "requestedAlias", ",", "$", "this", "->", "usedClasses", "[", "$", "fqn", "]", "[", "1", "]", ")", ")", ";", "}", "}", "else", "{", "$", "this", "->", "usedClasses", "[", "$", "fqn", "]", "=", "array", "(", "$", "class", ",", "$", "requestedAlias", ")", ";", "}", "return", "$", "this", ";", "}" ]
Fügt eine Klasse der GClass hinzu, die ins "use" geschrieben werden soll, wenn die GClass mit einem GClassWriter geschrieben wird @deprecated lieber das dem GClassWriter direkt hinzufügen
[ "Fügt", "eine", "Klasse", "der", "GClass", "hinzu", "die", "ins", "use", "geschrieben", "werden", "soll", "wenn", "die", "GClass", "mit", "einem", "GClassWriter", "geschrieben", "wird" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Code/Generate/GClass.php#L827-L838
mustardandrew/muan-laravel-comments
app/Traits/Commentable.php
Commentable.addComment
public function addComment($user, string $comment) : Comment { return $this->comments()->create([ 'user_id' => $user->id, 'comment' => $comment, ]); }
php
public function addComment($user, string $comment) : Comment { return $this->comments()->create([ 'user_id' => $user->id, 'comment' => $comment, ]); }
[ "public", "function", "addComment", "(", "$", "user", ",", "string", "$", "comment", ")", ":", "Comment", "{", "return", "$", "this", "->", "comments", "(", ")", "->", "create", "(", "[", "'user_id'", "=>", "$", "user", "->", "id", ",", "'comment'", "=>", "$", "comment", ",", "]", ")", ";", "}" ]
Add comment @param mixed $user @param string $comment @return Comment
[ "Add", "comment" ]
train
https://github.com/mustardandrew/muan-laravel-comments/blob/4dea64e6a2269f6a780df110a382acf9c97fa9b3/app/Traits/Commentable.php#L30-L36
redaigbaria/oauth2
examples/relational/Storage/AuthCodeStorage.php
AuthCodeStorage.get
public function get($code) { $result = Capsule::table('oauth_auth_codes') ->where('auth_code', $code) ->where('expire_time', '>=', time()) ->get(); if (count($result) === 1) { $token = new AuthCodeEntity($this->server); $token->setId($result[0]['auth_code']); $token->setRedirectUri($result[0]['client_redirect_uri']); $token->setExpireTime($result[0]['expire_time']); return $token; } return; }
php
public function get($code) { $result = Capsule::table('oauth_auth_codes') ->where('auth_code', $code) ->where('expire_time', '>=', time()) ->get(); if (count($result) === 1) { $token = new AuthCodeEntity($this->server); $token->setId($result[0]['auth_code']); $token->setRedirectUri($result[0]['client_redirect_uri']); $token->setExpireTime($result[0]['expire_time']); return $token; } return; }
[ "public", "function", "get", "(", "$", "code", ")", "{", "$", "result", "=", "Capsule", "::", "table", "(", "'oauth_auth_codes'", ")", "->", "where", "(", "'auth_code'", ",", "$", "code", ")", "->", "where", "(", "'expire_time'", ",", "'>='", ",", "time", "(", ")", ")", "->", "get", "(", ")", ";", "if", "(", "count", "(", "$", "result", ")", "===", "1", ")", "{", "$", "token", "=", "new", "AuthCodeEntity", "(", "$", "this", "->", "server", ")", ";", "$", "token", "->", "setId", "(", "$", "result", "[", "0", "]", "[", "'auth_code'", "]", ")", ";", "$", "token", "->", "setRedirectUri", "(", "$", "result", "[", "0", "]", "[", "'client_redirect_uri'", "]", ")", ";", "$", "token", "->", "setExpireTime", "(", "$", "result", "[", "0", "]", "[", "'expire_time'", "]", ")", ";", "return", "$", "token", ";", "}", "return", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/examples/relational/Storage/AuthCodeStorage.php#L16-L33
redaigbaria/oauth2
examples/relational/Storage/AuthCodeStorage.php
AuthCodeStorage.getScopes
public function getScopes(AuthCodeEntity $token) { $result = Capsule::table('oauth_auth_code_scopes') ->select(['oauth_scopes.id', 'oauth_scopes.description']) ->join('oauth_scopes', 'oauth_auth_code_scopes.scope', '=', 'oauth_scopes.id') ->where('auth_code', $token->getId()) ->get(); $response = []; if (count($result) > 0) { foreach ($result as $row) { $scope = (new ScopeEntity($this->server))->hydrate([ 'id' => $row['id'], 'description' => $row['description'], ]); $response[] = $scope; } } return $response; }
php
public function getScopes(AuthCodeEntity $token) { $result = Capsule::table('oauth_auth_code_scopes') ->select(['oauth_scopes.id', 'oauth_scopes.description']) ->join('oauth_scopes', 'oauth_auth_code_scopes.scope', '=', 'oauth_scopes.id') ->where('auth_code', $token->getId()) ->get(); $response = []; if (count($result) > 0) { foreach ($result as $row) { $scope = (new ScopeEntity($this->server))->hydrate([ 'id' => $row['id'], 'description' => $row['description'], ]); $response[] = $scope; } } return $response; }
[ "public", "function", "getScopes", "(", "AuthCodeEntity", "$", "token", ")", "{", "$", "result", "=", "Capsule", "::", "table", "(", "'oauth_auth_code_scopes'", ")", "->", "select", "(", "[", "'oauth_scopes.id'", ",", "'oauth_scopes.description'", "]", ")", "->", "join", "(", "'oauth_scopes'", ",", "'oauth_auth_code_scopes.scope'", ",", "'='", ",", "'oauth_scopes.id'", ")", "->", "where", "(", "'auth_code'", ",", "$", "token", "->", "getId", "(", ")", ")", "->", "get", "(", ")", ";", "$", "response", "=", "[", "]", ";", "if", "(", "count", "(", "$", "result", ")", ">", "0", ")", "{", "foreach", "(", "$", "result", "as", "$", "row", ")", "{", "$", "scope", "=", "(", "new", "ScopeEntity", "(", "$", "this", "->", "server", ")", ")", "->", "hydrate", "(", "[", "'id'", "=>", "$", "row", "[", "'id'", "]", ",", "'description'", "=>", "$", "row", "[", "'description'", "]", ",", "]", ")", ";", "$", "response", "[", "]", "=", "$", "scope", ";", "}", "}", "return", "$", "response", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/examples/relational/Storage/AuthCodeStorage.php#L49-L70
webforge-labs/psc-cms
lib/Psc/Entities/ContentStream/ContentStream.php
ContentStream.getContextLabel
public function getContextLabel($context = 'default') { if ($context === self::CONTEXT_DEFAULT) { return parent::getContextLabel($context); } return parent::getContextLabel($context); }
php
public function getContextLabel($context = 'default') { if ($context === self::CONTEXT_DEFAULT) { return parent::getContextLabel($context); } return parent::getContextLabel($context); }
[ "public", "function", "getContextLabel", "(", "$", "context", "=", "'default'", ")", "{", "if", "(", "$", "context", "===", "self", "::", "CONTEXT_DEFAULT", ")", "{", "return", "parent", "::", "getContextLabel", "(", "$", "context", ")", ";", "}", "return", "parent", "::", "getContextLabel", "(", "$", "context", ")", ";", "}" ]
/* public static function convertTypeName($typeName) { return __NAMESPACE__.'\\'.$typeName; } public static function convertClassName($classFQN) { return Code::getClassName($classFQN); }
[ "/", "*", "public", "static", "function", "convertTypeName", "(", "$typeName", ")", "{", "return", "__NAMESPACE__", ".", "\\\\", ".", "$typeName", ";", "}" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Entities/ContentStream/ContentStream.php#L31-L37
lode/fem
src/login_github.php
login_github.get_config
protected static function get_config() { $config_file = \alsvanzelf\fem\ROOT_DIR.'config/github.ini'; if (file_exists($config_file) == false) { $exception = bootstrap::get_library('exception'); throw new $exception('no github application config found'); } return parse_ini_file($config_file); }
php
protected static function get_config() { $config_file = \alsvanzelf\fem\ROOT_DIR.'config/github.ini'; if (file_exists($config_file) == false) { $exception = bootstrap::get_library('exception'); throw new $exception('no github application config found'); } return parse_ini_file($config_file); }
[ "protected", "static", "function", "get_config", "(", ")", "{", "$", "config_file", "=", "\\", "alsvanzelf", "\\", "fem", "\\", "ROOT_DIR", ".", "'config/github.ini'", ";", "if", "(", "file_exists", "(", "$", "config_file", ")", "==", "false", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'no github application config found'", ")", ";", "}", "return", "parse_ini_file", "(", "$", "config_file", ")", ";", "}" ]
collects a config containing the github app codes from a ini file @return array with 'client_id', 'client_secret', 'callback_url' values
[ "collects", "a", "config", "containing", "the", "github", "app", "codes", "from", "a", "ini", "file" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L63-L71
lode/fem
src/login_github.php
login_github.get_by_info
public static function get_by_info($info, $update_oauth_token=true) { $mysql = bootstrap::get_library('mysql'); // find via the oauth token $sql = "SELECT * FROM `login_github` WHERE `oauth_token` = '%s';"; $login = $mysql::select('row', $sql, $info['oauth_token']); if (!empty($login)) { return new static($login['id']); } // find via the github username $sql = "SELECT * FROM `login_github` WHERE `github_username` = '%s';"; $login = $mysql::select('row', $sql, $info['github_username']); if (empty($login)) { return false; } $object = new static($login['id']); // keep token up to date if ($update_oauth_token && $info['oauth_token'] != $login['oauth_token']) { $object->update_oauth_token($info['oauth_token']); } return $object; }
php
public static function get_by_info($info, $update_oauth_token=true) { $mysql = bootstrap::get_library('mysql'); // find via the oauth token $sql = "SELECT * FROM `login_github` WHERE `oauth_token` = '%s';"; $login = $mysql::select('row', $sql, $info['oauth_token']); if (!empty($login)) { return new static($login['id']); } // find via the github username $sql = "SELECT * FROM `login_github` WHERE `github_username` = '%s';"; $login = $mysql::select('row', $sql, $info['github_username']); if (empty($login)) { return false; } $object = new static($login['id']); // keep token up to date if ($update_oauth_token && $info['oauth_token'] != $login['oauth_token']) { $object->update_oauth_token($info['oauth_token']); } return $object; }
[ "public", "static", "function", "get_by_info", "(", "$", "info", ",", "$", "update_oauth_token", "=", "true", ")", "{", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "// find via the oauth token", "$", "sql", "=", "\"SELECT * FROM `login_github` WHERE `oauth_token` = '%s';\"", ";", "$", "login", "=", "$", "mysql", "::", "select", "(", "'row'", ",", "$", "sql", ",", "$", "info", "[", "'oauth_token'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "login", ")", ")", "{", "return", "new", "static", "(", "$", "login", "[", "'id'", "]", ")", ";", "}", "// find via the github username", "$", "sql", "=", "\"SELECT * FROM `login_github` WHERE `github_username` = '%s';\"", ";", "$", "login", "=", "$", "mysql", "::", "select", "(", "'row'", ",", "$", "sql", ",", "$", "info", "[", "'github_username'", "]", ")", ";", "if", "(", "empty", "(", "$", "login", ")", ")", "{", "return", "false", ";", "}", "$", "object", "=", "new", "static", "(", "$", "login", "[", "'id'", "]", ")", ";", "// keep token up to date", "if", "(", "$", "update_oauth_token", "&&", "$", "info", "[", "'oauth_token'", "]", "!=", "$", "login", "[", "'oauth_token'", "]", ")", "{", "$", "object", "->", "update_oauth_token", "(", "$", "info", "[", "'oauth_token'", "]", ")", ";", "}", "return", "$", "object", ";", "}" ]
checks whether the login match one on file and returns the found login $info needs to contain both 'oauth_token' and 'github_username' use ::get_by_oauth_token() if only the 'oauth_token' is known magic alert: also update the token on file if the token is different but the username is found to do manually, set $update_oauth_token to false and call $login->update_oauth_token() @param array $info as returned by ::is_valid() @param boolean $update_oauth_token defaults to true @return $this|boolean false when the token is not found
[ "checks", "whether", "the", "login", "match", "one", "on", "file", "and", "returns", "the", "found", "login" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L87-L112
lode/fem
src/login_github.php
login_github.get_by_user_id
public static function get_by_user_id($user_id) { $mysql = bootstrap::get_library('mysql'); $sql = "SELECT * FROM `login_github` WHERE `user_id` = %d;"; $login = $mysql::select('row', $sql, $user_id); if (empty($login)) { return false; } return new static($login['id']); }
php
public static function get_by_user_id($user_id) { $mysql = bootstrap::get_library('mysql'); $sql = "SELECT * FROM `login_github` WHERE `user_id` = %d;"; $login = $mysql::select('row', $sql, $user_id); if (empty($login)) { return false; } return new static($login['id']); }
[ "public", "static", "function", "get_by_user_id", "(", "$", "user_id", ")", "{", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "$", "sql", "=", "\"SELECT * FROM `login_github` WHERE `user_id` = %d;\"", ";", "$", "login", "=", "$", "mysql", "::", "select", "(", "'row'", ",", "$", "sql", ",", "$", "user_id", ")", ";", "if", "(", "empty", "(", "$", "login", ")", ")", "{", "return", "false", ";", "}", "return", "new", "static", "(", "$", "login", "[", "'id'", "]", ")", ";", "}" ]
checks whether the given user id match a login on file and returns the found login @param int $user_id @return $this|boolean false when the user id is not found
[ "checks", "whether", "the", "given", "user", "id", "match", "a", "login", "on", "file", "and", "returns", "the", "found", "login" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L121-L131
lode/fem
src/login_github.php
login_github.get_by_github_username
public static function get_by_github_username($github_username) { $mysql = bootstrap::get_library('mysql'); $sql = "SELECT * FROM `login_github` WHERE `github_username` = '%s';"; $login = $mysql::select('row', $sql, $github_username); if (empty($login)) { return false; } return new static($login['id']); }
php
public static function get_by_github_username($github_username) { $mysql = bootstrap::get_library('mysql'); $sql = "SELECT * FROM `login_github` WHERE `github_username` = '%s';"; $login = $mysql::select('row', $sql, $github_username); if (empty($login)) { return false; } return new static($login['id']); }
[ "public", "static", "function", "get_by_github_username", "(", "$", "github_username", ")", "{", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "$", "sql", "=", "\"SELECT * FROM `login_github` WHERE `github_username` = '%s';\"", ";", "$", "login", "=", "$", "mysql", "::", "select", "(", "'row'", ",", "$", "sql", ",", "$", "github_username", ")", ";", "if", "(", "empty", "(", "$", "login", ")", ")", "{", "return", "false", ";", "}", "return", "new", "static", "(", "$", "login", "[", "'id'", "]", ")", ";", "}" ]
checks whether the given github username match one on file and returns the found login @param string $github_username @return $this|boolean false when the username is not found
[ "checks", "whether", "the", "given", "github", "username", "match", "one", "on", "file", "and", "returns", "the", "found", "login" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L140-L150
lode/fem
src/login_github.php
login_github.get_by_oauth_token
public static function get_by_oauth_token($oauth_token) { $mysql = bootstrap::get_library('mysql'); $sql = "SELECT * FROM `login_github` WHERE `oauth_token` = '%s';"; $login = $mysql::select('row', $sql, $oauth_token); if (empty($login)) { return false; } return new static($login['id']); }
php
public static function get_by_oauth_token($oauth_token) { $mysql = bootstrap::get_library('mysql'); $sql = "SELECT * FROM `login_github` WHERE `oauth_token` = '%s';"; $login = $mysql::select('row', $sql, $oauth_token); if (empty($login)) { return false; } return new static($login['id']); }
[ "public", "static", "function", "get_by_oauth_token", "(", "$", "oauth_token", ")", "{", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "$", "sql", "=", "\"SELECT * FROM `login_github` WHERE `oauth_token` = '%s';\"", ";", "$", "login", "=", "$", "mysql", "::", "select", "(", "'row'", ",", "$", "sql", ",", "$", "oauth_token", ")", ";", "if", "(", "empty", "(", "$", "login", ")", ")", "{", "return", "false", ";", "}", "return", "new", "static", "(", "$", "login", "[", "'id'", "]", ")", ";", "}" ]
checks whether the given oauth token match one on file and returns the found login @param string $oauth_token @return $this|boolean false when the token is not found
[ "checks", "whether", "the", "given", "oauth", "token", "match", "one", "on", "file", "and", "returns", "the", "found", "login" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L159-L169
lode/fem
src/login_github.php
login_github.signup
public static function signup($user_id, $info) { if (empty($info['github_username']) || empty($info['oauth_token']) || empty($info['scope'])) { $exception = bootstrap::get_library('exception'); throw new $exception('all info from ::is_valid() is needed for signup'); } $mysql = bootstrap::get_library('mysql'); $sql = "INSERT INTO `login_github` SET `user_id` = %d, `github_username` = '%s', `oauth_token` = '%s', `scope` = '%s' ;"; $binds = [$user_id, $info['github_username'], $info['oauth_token'], $info['scope']]; $mysql::query($sql, $binds); return new static($mysql::$insert_id); }
php
public static function signup($user_id, $info) { if (empty($info['github_username']) || empty($info['oauth_token']) || empty($info['scope'])) { $exception = bootstrap::get_library('exception'); throw new $exception('all info from ::is_valid() is needed for signup'); } $mysql = bootstrap::get_library('mysql'); $sql = "INSERT INTO `login_github` SET `user_id` = %d, `github_username` = '%s', `oauth_token` = '%s', `scope` = '%s' ;"; $binds = [$user_id, $info['github_username'], $info['oauth_token'], $info['scope']]; $mysql::query($sql, $binds); return new static($mysql::$insert_id); }
[ "public", "static", "function", "signup", "(", "$", "user_id", ",", "$", "info", ")", "{", "if", "(", "empty", "(", "$", "info", "[", "'github_username'", "]", ")", "||", "empty", "(", "$", "info", "[", "'oauth_token'", "]", ")", "||", "empty", "(", "$", "info", "[", "'scope'", "]", ")", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'all info from ::is_valid() is needed for signup'", ")", ";", "}", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "$", "sql", "=", "\"INSERT INTO `login_github` SET\n\t\t`user_id` = %d,\n\t\t`github_username` = '%s',\n\t\t`oauth_token` = '%s',\n\t\t`scope` = '%s'\n\t;\"", ";", "$", "binds", "=", "[", "$", "user_id", ",", "$", "info", "[", "'github_username'", "]", ",", "$", "info", "[", "'oauth_token'", "]", ",", "$", "info", "[", "'scope'", "]", "]", ";", "$", "mysql", "::", "query", "(", "$", "sql", ",", "$", "binds", ")", ";", "return", "new", "static", "(", "$", "mysql", "::", "$", "insert_id", ")", ";", "}" ]
adds a new login connection between a local user and a github account @param int $user_id @param array $info as returned by ::is_valid() @return $this
[ "adds", "a", "new", "login", "connection", "between", "a", "local", "user", "and", "a", "github", "account" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L178-L196
lode/fem
src/login_github.php
login_github.update_oauth_token
public function update_oauth_token($new_oauth_token) { $mysql = bootstrap::get_library('mysql'); $sql = "UPDATE `login_github` SET `oauth_token` = '%s' WHERE `id` = %d;"; $binds = [$new_oauth_token, $this->id]; $mysql::query($sql, $binds); }
php
public function update_oauth_token($new_oauth_token) { $mysql = bootstrap::get_library('mysql'); $sql = "UPDATE `login_github` SET `oauth_token` = '%s' WHERE `id` = %d;"; $binds = [$new_oauth_token, $this->id]; $mysql::query($sql, $binds); }
[ "public", "function", "update_oauth_token", "(", "$", "new_oauth_token", ")", "{", "$", "mysql", "=", "bootstrap", "::", "get_library", "(", "'mysql'", ")", ";", "$", "sql", "=", "\"UPDATE `login_github` SET `oauth_token` = '%s' WHERE `id` = %d;\"", ";", "$", "binds", "=", "[", "$", "new_oauth_token", ",", "$", "this", "->", "id", "]", ";", "$", "mysql", "::", "query", "(", "$", "sql", ",", "$", "binds", ")", ";", "}" ]
updates the oauth token for the login @param string $new_oauth_token @return void
[ "updates", "the", "oauth", "token", "for", "the", "login" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L237-L243
lode/fem
src/login_github.php
login_github.request_authorization
public static function request_authorization($scope=null, $callback_url=null) { $config = static::get_config(); if (!empty($callback_url) && strpos($callback_url, $config['callback_url']) !== 0) { $exception = bootstrap::get_library('exception'); throw new $exception('custom callback url needs to start with defined callback url'); } if (empty($callback_url)) { $callback_url = $config['callback_url']; } $text = bootstrap::get_library('text'); $session = bootstrap::get_library('session'); $request = bootstrap::get_library('request'); // state is a shared secret to prevent people faking the callback $state = $text::generate_token($length=40); $session::start(session::TYPE_TEMPORARY); $_SESSION['fem/login_github/state'] = $state; $_SESSION['fem/login_github/scope'] = $scope; // let the user authorize at github $url = 'https://github.com/login/oauth/authorize'; $arguments = [ 'client_id' => $config['client_id'], 'scope' => $scope, 'state' => $state, ]; $request::redirect($url.'?'.http_build_query($arguments)); }
php
public static function request_authorization($scope=null, $callback_url=null) { $config = static::get_config(); if (!empty($callback_url) && strpos($callback_url, $config['callback_url']) !== 0) { $exception = bootstrap::get_library('exception'); throw new $exception('custom callback url needs to start with defined callback url'); } if (empty($callback_url)) { $callback_url = $config['callback_url']; } $text = bootstrap::get_library('text'); $session = bootstrap::get_library('session'); $request = bootstrap::get_library('request'); // state is a shared secret to prevent people faking the callback $state = $text::generate_token($length=40); $session::start(session::TYPE_TEMPORARY); $_SESSION['fem/login_github/state'] = $state; $_SESSION['fem/login_github/scope'] = $scope; // let the user authorize at github $url = 'https://github.com/login/oauth/authorize'; $arguments = [ 'client_id' => $config['client_id'], 'scope' => $scope, 'state' => $state, ]; $request::redirect($url.'?'.http_build_query($arguments)); }
[ "public", "static", "function", "request_authorization", "(", "$", "scope", "=", "null", ",", "$", "callback_url", "=", "null", ")", "{", "$", "config", "=", "static", "::", "get_config", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "callback_url", ")", "&&", "strpos", "(", "$", "callback_url", ",", "$", "config", "[", "'callback_url'", "]", ")", "!==", "0", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'custom callback url needs to start with defined callback url'", ")", ";", "}", "if", "(", "empty", "(", "$", "callback_url", ")", ")", "{", "$", "callback_url", "=", "$", "config", "[", "'callback_url'", "]", ";", "}", "$", "text", "=", "bootstrap", "::", "get_library", "(", "'text'", ")", ";", "$", "session", "=", "bootstrap", "::", "get_library", "(", "'session'", ")", ";", "$", "request", "=", "bootstrap", "::", "get_library", "(", "'request'", ")", ";", "// state is a shared secret to prevent people faking the callback", "$", "state", "=", "$", "text", "::", "generate_token", "(", "$", "length", "=", "40", ")", ";", "$", "session", "::", "start", "(", "session", "::", "TYPE_TEMPORARY", ")", ";", "$", "_SESSION", "[", "'fem/login_github/state'", "]", "=", "$", "state", ";", "$", "_SESSION", "[", "'fem/login_github/scope'", "]", "=", "$", "scope", ";", "// let the user authorize at github", "$", "url", "=", "'https://github.com/login/oauth/authorize'", ";", "$", "arguments", "=", "[", "'client_id'", "=>", "$", "config", "[", "'client_id'", "]", ",", "'scope'", "=>", "$", "scope", ",", "'state'", "=>", "$", "state", ",", "]", ";", "$", "request", "::", "redirect", "(", "$", "url", ".", "'?'", ".", "http_build_query", "(", "$", "arguments", ")", ")", ";", "}" ]
send a user to github to authorize our application @param string $scope defaults to the scope of the previous authorization or no scopes at all if authorization is never done yet see https://developer.github.com/v3/oauth/#parameters @param string $callback_url defaults to what is set in the config @return void even more so, the user is gone
[ "send", "a", "user", "to", "github", "to", "authorize", "our", "application" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L254-L284
lode/fem
src/login_github.php
login_github.is_valid
public static function is_valid($callback_data, $extended=true) { $exception = bootstrap::get_library('exception'); if (empty($callback_data['state'])) { throw new $exception('state expected in oauth callback'); } $session = bootstrap::get_library('session'); $session::start($session::TYPE_TEMPORARY); if ($callback_data['state'] != $_SESSION['fem/login_github/state']) { throw new $exception('state is different, someone tries to fake the callback?'); } if (empty($callback_data['code'])) { return false; } if ($extended) { return static::is_valid_extended($callback_data); } return true; }
php
public static function is_valid($callback_data, $extended=true) { $exception = bootstrap::get_library('exception'); if (empty($callback_data['state'])) { throw new $exception('state expected in oauth callback'); } $session = bootstrap::get_library('session'); $session::start($session::TYPE_TEMPORARY); if ($callback_data['state'] != $_SESSION['fem/login_github/state']) { throw new $exception('state is different, someone tries to fake the callback?'); } if (empty($callback_data['code'])) { return false; } if ($extended) { return static::is_valid_extended($callback_data); } return true; }
[ "public", "static", "function", "is_valid", "(", "$", "callback_data", ",", "$", "extended", "=", "true", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "if", "(", "empty", "(", "$", "callback_data", "[", "'state'", "]", ")", ")", "{", "throw", "new", "$", "exception", "(", "'state expected in oauth callback'", ")", ";", "}", "$", "session", "=", "bootstrap", "::", "get_library", "(", "'session'", ")", ";", "$", "session", "::", "start", "(", "$", "session", "::", "TYPE_TEMPORARY", ")", ";", "if", "(", "$", "callback_data", "[", "'state'", "]", "!=", "$", "_SESSION", "[", "'fem/login_github/state'", "]", ")", "{", "throw", "new", "$", "exception", "(", "'state is different, someone tries to fake the callback?'", ")", ";", "}", "if", "(", "empty", "(", "$", "callback_data", "[", "'code'", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "extended", ")", "{", "return", "static", "::", "is_valid_extended", "(", "$", "callback_data", ")", ";", "}", "return", "true", ";", "}" ]
checks whether an oauth callback contains a valid state and code magic alert: this also does a lot more validation and info gathering to do manually, set $extended to false and call ::is_valid_extended() or .. .. call ::exchange_for_oauth_token(), ::verify_scope(), ::get_user_info() and ::verify_user() can return an info array containing 'oauth_token', 'github_username', etc. @see ::is_valid_extended() @param array $callback_data as received from github, containing 'state', 'code' and 'scope' @param boolean $extended defaults to true @return boolean|array returns array on successful validation and $extended set to true
[ "checks", "whether", "an", "oauth", "callback", "contains", "a", "valid", "state", "and", "code" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L300-L321
lode/fem
src/login_github.php
login_github.is_valid_extended
public static function is_valid_extended($callback_data) { // get oauth token $info = static::exchange_for_oauth_token($callback_data['code']); // check scope if (static::verify_scope($info['scope']) == false) { return false; } // get user $github_userinfo = static::get_user_info($info['oauth_token']); $info['github_username'] = $github_userinfo['login']; $info['github_userinfo'] = $github_userinfo; // check github account if (static::verify_user($info['oauth_token'], $info['github_username']) == false) { return false; } return $info; }
php
public static function is_valid_extended($callback_data) { // get oauth token $info = static::exchange_for_oauth_token($callback_data['code']); // check scope if (static::verify_scope($info['scope']) == false) { return false; } // get user $github_userinfo = static::get_user_info($info['oauth_token']); $info['github_username'] = $github_userinfo['login']; $info['github_userinfo'] = $github_userinfo; // check github account if (static::verify_user($info['oauth_token'], $info['github_username']) == false) { return false; } return $info; }
[ "public", "static", "function", "is_valid_extended", "(", "$", "callback_data", ")", "{", "// get oauth token", "$", "info", "=", "static", "::", "exchange_for_oauth_token", "(", "$", "callback_data", "[", "'code'", "]", ")", ";", "// check scope", "if", "(", "static", "::", "verify_scope", "(", "$", "info", "[", "'scope'", "]", ")", "==", "false", ")", "{", "return", "false", ";", "}", "// get user", "$", "github_userinfo", "=", "static", "::", "get_user_info", "(", "$", "info", "[", "'oauth_token'", "]", ")", ";", "$", "info", "[", "'github_username'", "]", "=", "$", "github_userinfo", "[", "'login'", "]", ";", "$", "info", "[", "'github_userinfo'", "]", "=", "$", "github_userinfo", ";", "// check github account", "if", "(", "static", "::", "verify_user", "(", "$", "info", "[", "'oauth_token'", "]", ",", "$", "info", "[", "'github_username'", "]", ")", "==", "false", ")", "{", "return", "false", ";", "}", "return", "$", "info", ";", "}" ]
does extended validation by checking: - the code can be exchanged for an oauth token, @see ::exchange_for_oauth_token() - the scope meets the minimul user:email, @see ::verify_scope() - the github account is known for the received oauth_token, @see ::verify_user() returns info array with: - oauth_token - scope - github_username - github_userinfo @param array $callback_data as received from github, containing 'state', 'code' and 'scope' @return array|boolean returns false if a validaiton check fails @throws exception if code can not be exchanged for a token
[ "does", "extended", "validation", "by", "checking", ":", "-", "the", "code", "can", "be", "exchanged", "for", "an", "oauth", "token", "@see", "::", "exchange_for_oauth_token", "()", "-", "the", "scope", "meets", "the", "minimul", "user", ":", "email", "@see", "::", "verify_scope", "()", "-", "the", "github", "account", "is", "known", "for", "the", "received", "oauth_token", "@see", "::", "verify_user", "()" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L339-L359
lode/fem
src/login_github.php
login_github.exchange_for_oauth_token
public static function exchange_for_oauth_token($code) { $config = static::get_config(); $url = 'https://github.com/login/oauth/access_token'; $options = [ 'body' => [ // 'json' || 'body' || 'query' 'client_id' => $config['client_id'], 'client_secret' => $config['client_secret'], 'code' => $code, ], 'headers' => [ 'Accept' => 'application/json', ], ]; $http = new \GuzzleHttp\Client(); $response = $http->post($url, $options)->json(); if (empty($response['access_token'])) { $exception = bootstrap::get_library('exception'); throw new $exception('can not get oauth token for temporary code'); } return [ 'oauth_token' => $response['access_token'], 'scope' => $response['scope'], ]; }
php
public static function exchange_for_oauth_token($code) { $config = static::get_config(); $url = 'https://github.com/login/oauth/access_token'; $options = [ 'body' => [ // 'json' || 'body' || 'query' 'client_id' => $config['client_id'], 'client_secret' => $config['client_secret'], 'code' => $code, ], 'headers' => [ 'Accept' => 'application/json', ], ]; $http = new \GuzzleHttp\Client(); $response = $http->post($url, $options)->json(); if (empty($response['access_token'])) { $exception = bootstrap::get_library('exception'); throw new $exception('can not get oauth token for temporary code'); } return [ 'oauth_token' => $response['access_token'], 'scope' => $response['scope'], ]; }
[ "public", "static", "function", "exchange_for_oauth_token", "(", "$", "code", ")", "{", "$", "config", "=", "static", "::", "get_config", "(", ")", ";", "$", "url", "=", "'https://github.com/login/oauth/access_token'", ";", "$", "options", "=", "[", "'body'", "=>", "[", "// 'json' || 'body' || 'query'", "'client_id'", "=>", "$", "config", "[", "'client_id'", "]", ",", "'client_secret'", "=>", "$", "config", "[", "'client_secret'", "]", ",", "'code'", "=>", "$", "code", ",", "]", ",", "'headers'", "=>", "[", "'Accept'", "=>", "'application/json'", ",", "]", ",", "]", ";", "$", "http", "=", "new", "\\", "GuzzleHttp", "\\", "Client", "(", ")", ";", "$", "response", "=", "$", "http", "->", "post", "(", "$", "url", ",", "$", "options", ")", "->", "json", "(", ")", ";", "if", "(", "empty", "(", "$", "response", "[", "'access_token'", "]", ")", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'can not get oauth token for temporary code'", ")", ";", "}", "return", "[", "'oauth_token'", "=>", "$", "response", "[", "'access_token'", "]", ",", "'scope'", "=>", "$", "response", "[", "'scope'", "]", ",", "]", ";", "}" ]
exchange the temporary code for a lasting oauth token @param string $code @return string @throws exception if the exchange fails
[ "exchange", "the", "temporary", "code", "for", "a", "lasting", "oauth", "token" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L368-L395
lode/fem
src/login_github.php
login_github.verify_scope
public static function verify_scope($received_scope, $requested_scope='user:email') { if (strpos($received_scope, $requested_scope) !== false) { return true; } if (strpos($requested_scope, ':')) { $parent_requested_scope = substr($requested_scope, 0, strpos($requested_scope, ':')); if (strpos($received_scope, $parent_requested_scope) !== false) { return true; } } return false; }
php
public static function verify_scope($received_scope, $requested_scope='user:email') { if (strpos($received_scope, $requested_scope) !== false) { return true; } if (strpos($requested_scope, ':')) { $parent_requested_scope = substr($requested_scope, 0, strpos($requested_scope, ':')); if (strpos($received_scope, $parent_requested_scope) !== false) { return true; } } return false; }
[ "public", "static", "function", "verify_scope", "(", "$", "received_scope", ",", "$", "requested_scope", "=", "'user:email'", ")", "{", "if", "(", "strpos", "(", "$", "received_scope", ",", "$", "requested_scope", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "if", "(", "strpos", "(", "$", "requested_scope", ",", "':'", ")", ")", "{", "$", "parent_requested_scope", "=", "substr", "(", "$", "requested_scope", ",", "0", ",", "strpos", "(", "$", "requested_scope", ",", "':'", ")", ")", ";", "if", "(", "strpos", "(", "$", "received_scope", ",", "$", "parent_requested_scope", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
checks whether the received scope meets the requested scope @param string $received_scope @param string $requested_scope defaults to 'user:email' @return boolean
[ "checks", "whether", "the", "received", "scope", "meets", "the", "requested", "scope" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L404-L417
lode/fem
src/login_github.php
login_github.get_user_info
public static function get_user_info($oauth_token) { $url = 'https://api.github.com/user'; $options = [ 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'token '.$oauth_token, ], ]; $http = new \GuzzleHttp\Client(); return $http->get($url, $options)->json(); }
php
public static function get_user_info($oauth_token) { $url = 'https://api.github.com/user'; $options = [ 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'token '.$oauth_token, ], ]; $http = new \GuzzleHttp\Client(); return $http->get($url, $options)->json(); }
[ "public", "static", "function", "get_user_info", "(", "$", "oauth_token", ")", "{", "$", "url", "=", "'https://api.github.com/user'", ";", "$", "options", "=", "[", "'headers'", "=>", "[", "'Accept'", "=>", "'application/json'", ",", "'Authorization'", "=>", "'token '", ".", "$", "oauth_token", ",", "]", ",", "]", ";", "$", "http", "=", "new", "\\", "GuzzleHttp", "\\", "Client", "(", ")", ";", "return", "$", "http", "->", "get", "(", "$", "url", ",", "$", "options", ")", "->", "json", "(", ")", ";", "}" ]
gets a users github account details for a given oauth token @param string $oauth_token @return array can be expected to contain a 'login' key with the github username
[ "gets", "a", "users", "github", "account", "details", "for", "a", "given", "oauth", "token" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L425-L436
lode/fem
src/login_github.php
login_github.verify_user
public static function verify_user($oauth_token, $github_username) { $known_login = static::get_by_oauth_token($oauth_token); if (empty($known_login)) { return true; } if ($known_login->github_username != $github_username) { $exception = bootstrap::get_library('exception'); throw new $exception('oauth token switched user'); } return true; }
php
public static function verify_user($oauth_token, $github_username) { $known_login = static::get_by_oauth_token($oauth_token); if (empty($known_login)) { return true; } if ($known_login->github_username != $github_username) { $exception = bootstrap::get_library('exception'); throw new $exception('oauth token switched user'); } return true; }
[ "public", "static", "function", "verify_user", "(", "$", "oauth_token", ",", "$", "github_username", ")", "{", "$", "known_login", "=", "static", "::", "get_by_oauth_token", "(", "$", "oauth_token", ")", ";", "if", "(", "empty", "(", "$", "known_login", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "known_login", "->", "github_username", "!=", "$", "github_username", ")", "{", "$", "exception", "=", "bootstrap", "::", "get_library", "(", "'exception'", ")", ";", "throw", "new", "$", "exception", "(", "'oauth token switched user'", ")", ";", "}", "return", "true", ";", "}" ]
checks whether the username belongs to the user identified by the oauth token @param string $oauth_token as received by the oauth process @param strign $github_username as received by ::get_user_info() @return boolean returns true if there is no login for this token .. .. or the usernames match never returns false @throws exception if the usernames don't match
[ "checks", "whether", "the", "username", "belongs", "to", "the", "user", "identified", "by", "the", "oauth", "token" ]
train
https://github.com/lode/fem/blob/c1c466c1a904d99452b341c5ae7cbc3e22b106e1/src/login_github.php#L448-L460
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.getFieldNames
public static function getFieldNames($type = BasePeer::TYPE_PHPNAME) { if (!array_key_exists($type, UserPeer::$fieldNames)) { throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); } return UserPeer::$fieldNames[$type]; }
php
public static function getFieldNames($type = BasePeer::TYPE_PHPNAME) { if (!array_key_exists($type, UserPeer::$fieldNames)) { throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.'); } return UserPeer::$fieldNames[$type]; }
[ "public", "static", "function", "getFieldNames", "(", "$", "type", "=", "BasePeer", "::", "TYPE_PHPNAME", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "type", ",", "UserPeer", "::", "$", "fieldNames", ")", ")", "{", "throw", "new", "PropelException", "(", "'Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. '", ".", "$", "type", ".", "' was given.'", ")", ";", "}", "return", "UserPeer", "::", "$", "fieldNames", "[", "$", "type", "]", ";", "}" ]
Returns an array of field names. @param string $type The type of fieldnames to return: One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM @return array A list of field names @throws PropelException - if the type is not valid.
[ "Returns", "an", "array", "of", "field", "names", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L153-L160
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.addSelectColumns
public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { $criteria->addSelectColumn(UserPeer::ID); $criteria->addSelectColumn(UserPeer::USERNAME); $criteria->addSelectColumn(UserPeer::PASSWORD); $criteria->addSelectColumn(UserPeer::SALT); $criteria->addSelectColumn(UserPeer::FIRSTNAME); $criteria->addSelectColumn(UserPeer::LASTNAME); $criteria->addSelectColumn(UserPeer::EMAIL); $criteria->addSelectColumn(UserPeer::PHONE); $criteria->addSelectColumn(UserPeer::MEMO); $criteria->addSelectColumn(UserPeer::ACTIVATED); $criteria->addSelectColumn(UserPeer::LAST_LOGIN); $criteria->addSelectColumn(UserPeer::NOTIFICATION_CHANGE); $criteria->addSelectColumn(UserPeer::NOTIFICATION_ERROR); } else { $criteria->addSelectColumn($alias . '.id'); $criteria->addSelectColumn($alias . '.username'); $criteria->addSelectColumn($alias . '.password'); $criteria->addSelectColumn($alias . '.salt'); $criteria->addSelectColumn($alias . '.firstname'); $criteria->addSelectColumn($alias . '.lastname'); $criteria->addSelectColumn($alias . '.email'); $criteria->addSelectColumn($alias . '.phone'); $criteria->addSelectColumn($alias . '.memo'); $criteria->addSelectColumn($alias . '.activated'); $criteria->addSelectColumn($alias . '.last_login'); $criteria->addSelectColumn($alias . '.notification_change'); $criteria->addSelectColumn($alias . '.notification_error'); } }
php
public static function addSelectColumns(Criteria $criteria, $alias = null) { if (null === $alias) { $criteria->addSelectColumn(UserPeer::ID); $criteria->addSelectColumn(UserPeer::USERNAME); $criteria->addSelectColumn(UserPeer::PASSWORD); $criteria->addSelectColumn(UserPeer::SALT); $criteria->addSelectColumn(UserPeer::FIRSTNAME); $criteria->addSelectColumn(UserPeer::LASTNAME); $criteria->addSelectColumn(UserPeer::EMAIL); $criteria->addSelectColumn(UserPeer::PHONE); $criteria->addSelectColumn(UserPeer::MEMO); $criteria->addSelectColumn(UserPeer::ACTIVATED); $criteria->addSelectColumn(UserPeer::LAST_LOGIN); $criteria->addSelectColumn(UserPeer::NOTIFICATION_CHANGE); $criteria->addSelectColumn(UserPeer::NOTIFICATION_ERROR); } else { $criteria->addSelectColumn($alias . '.id'); $criteria->addSelectColumn($alias . '.username'); $criteria->addSelectColumn($alias . '.password'); $criteria->addSelectColumn($alias . '.salt'); $criteria->addSelectColumn($alias . '.firstname'); $criteria->addSelectColumn($alias . '.lastname'); $criteria->addSelectColumn($alias . '.email'); $criteria->addSelectColumn($alias . '.phone'); $criteria->addSelectColumn($alias . '.memo'); $criteria->addSelectColumn($alias . '.activated'); $criteria->addSelectColumn($alias . '.last_login'); $criteria->addSelectColumn($alias . '.notification_change'); $criteria->addSelectColumn($alias . '.notification_error'); } }
[ "public", "static", "function", "addSelectColumns", "(", "Criteria", "$", "criteria", ",", "$", "alias", "=", "null", ")", "{", "if", "(", "null", "===", "$", "alias", ")", "{", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "ID", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "USERNAME", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "PASSWORD", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "SALT", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "FIRSTNAME", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "LASTNAME", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "EMAIL", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "PHONE", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "MEMO", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "ACTIVATED", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "LAST_LOGIN", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "NOTIFICATION_CHANGE", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "UserPeer", "::", "NOTIFICATION_ERROR", ")", ";", "}", "else", "{", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.id'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.username'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.password'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.salt'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.firstname'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.lastname'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.email'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.phone'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.memo'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.activated'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.last_login'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.notification_change'", ")", ";", "$", "criteria", "->", "addSelectColumn", "(", "$", "alias", ".", "'.notification_error'", ")", ";", "}", "}" ]
Add all the columns needed to create a new object. Note: any columns that were marked with lazyLoad="true" in the XML schema will not be added to the select list and only loaded on demand. @param Criteria $criteria object containing the columns to add. @param string $alias optional table alias @throws PropelException Any exceptions caught during processing will be rethrown wrapped into a PropelException.
[ "Add", "all", "the", "columns", "needed", "to", "create", "a", "new", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L191-L222
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.doCount
public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) { // we may modify criteria, so copy it first $criteria = clone $criteria; // We need to set the primary table name, since in the case that there are no WHERE columns // it will be impossible for the BasePeer::createSelectSql() method to determine which // tables go into the FROM clause. $criteria->setPrimaryTableName(UserPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { UserPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count $criteria->setDbName(UserPeer::DATABASE_NAME); // Set the correct dbName if ($con === null) { $con = Propel::getConnection(UserPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); if ($row = $stmt->fetch(PDO::FETCH_NUM)) { $count = (int) $row[0]; } else { $count = 0; // no rows returned; we infer that means 0 matches. } $stmt->closeCursor(); return $count; }
php
public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null) { // we may modify criteria, so copy it first $criteria = clone $criteria; // We need to set the primary table name, since in the case that there are no WHERE columns // it will be impossible for the BasePeer::createSelectSql() method to determine which // tables go into the FROM clause. $criteria->setPrimaryTableName(UserPeer::TABLE_NAME); if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) { $criteria->setDistinct(); } if (!$criteria->hasSelectClause()) { UserPeer::addSelectColumns($criteria); } $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count $criteria->setDbName(UserPeer::DATABASE_NAME); // Set the correct dbName if ($con === null) { $con = Propel::getConnection(UserPeer::DATABASE_NAME, Propel::CONNECTION_READ); } // BasePeer returns a PDOStatement $stmt = BasePeer::doCount($criteria, $con); if ($row = $stmt->fetch(PDO::FETCH_NUM)) { $count = (int) $row[0]; } else { $count = 0; // no rows returned; we infer that means 0 matches. } $stmt->closeCursor(); return $count; }
[ "public", "static", "function", "doCount", "(", "Criteria", "$", "criteria", ",", "$", "distinct", "=", "false", ",", "PropelPDO", "$", "con", "=", "null", ")", "{", "// we may modify criteria, so copy it first", "$", "criteria", "=", "clone", "$", "criteria", ";", "// We need to set the primary table name, since in the case that there are no WHERE columns", "// it will be impossible for the BasePeer::createSelectSql() method to determine which", "// tables go into the FROM clause.", "$", "criteria", "->", "setPrimaryTableName", "(", "UserPeer", "::", "TABLE_NAME", ")", ";", "if", "(", "$", "distinct", "&&", "!", "in_array", "(", "Criteria", "::", "DISTINCT", ",", "$", "criteria", "->", "getSelectModifiers", "(", ")", ")", ")", "{", "$", "criteria", "->", "setDistinct", "(", ")", ";", "}", "if", "(", "!", "$", "criteria", "->", "hasSelectClause", "(", ")", ")", "{", "UserPeer", "::", "addSelectColumns", "(", "$", "criteria", ")", ";", "}", "$", "criteria", "->", "clearOrderByColumns", "(", ")", ";", "// ORDER BY won't ever affect the count", "$", "criteria", "->", "setDbName", "(", "UserPeer", "::", "DATABASE_NAME", ")", ";", "// Set the correct dbName", "if", "(", "$", "con", "===", "null", ")", "{", "$", "con", "=", "Propel", "::", "getConnection", "(", "UserPeer", "::", "DATABASE_NAME", ",", "Propel", "::", "CONNECTION_READ", ")", ";", "}", "// BasePeer returns a PDOStatement", "$", "stmt", "=", "BasePeer", "::", "doCount", "(", "$", "criteria", ",", "$", "con", ")", ";", "if", "(", "$", "row", "=", "$", "stmt", "->", "fetch", "(", "PDO", "::", "FETCH_NUM", ")", ")", "{", "$", "count", "=", "(", "int", ")", "$", "row", "[", "0", "]", ";", "}", "else", "{", "$", "count", "=", "0", ";", "// no rows returned; we infer that means 0 matches.", "}", "$", "stmt", "->", "closeCursor", "(", ")", ";", "return", "$", "count", ";", "}" ]
Returns the number of rows matching criteria. @param Criteria $criteria @param boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead. @param PropelPDO $con @return int Number of matching rows.
[ "Returns", "the", "number", "of", "rows", "matching", "criteria", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L232-L267
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.getInstanceFromPool
public static function getInstanceFromPool($key) { if (Propel::isInstancePoolingEnabled()) { if (isset(UserPeer::$instances[$key])) { return UserPeer::$instances[$key]; } } return null; // just to be explicit }
php
public static function getInstanceFromPool($key) { if (Propel::isInstancePoolingEnabled()) { if (isset(UserPeer::$instances[$key])) { return UserPeer::$instances[$key]; } } return null; // just to be explicit }
[ "public", "static", "function", "getInstanceFromPool", "(", "$", "key", ")", "{", "if", "(", "Propel", "::", "isInstancePoolingEnabled", "(", ")", ")", "{", "if", "(", "isset", "(", "UserPeer", "::", "$", "instances", "[", "$", "key", "]", ")", ")", "{", "return", "UserPeer", "::", "$", "instances", "[", "$", "key", "]", ";", "}", "}", "return", "null", ";", "// just to be explicit", "}" ]
Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. For tables with a single-column primary key, that simple pkey value will be returned. For tables with a multi-column primary key, a serialize()d version of the primary key will be returned. @param string $key The key (@see getPrimaryKeyHash()) for this instance. @return User Found object or null if 1) no instance exists for specified key or 2) instance pooling has been disabled. @see getPrimaryKeyHash()
[ "Retrieves", "a", "string", "version", "of", "the", "primary", "key", "from", "the", "DB", "resultset", "row", "that", "can", "be", "used", "to", "uniquely", "identify", "a", "row", "in", "this", "table", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L393-L402
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.buildTableMap
public static function buildTableMap() { $dbMap = Propel::getDatabaseMap(BaseUserPeer::DATABASE_NAME); if (!$dbMap->hasTable(BaseUserPeer::TABLE_NAME)) { $dbMap->addTableObject(new \Slashworks\BackendBundle\Model\map\UserTableMap()); } }
php
public static function buildTableMap() { $dbMap = Propel::getDatabaseMap(BaseUserPeer::DATABASE_NAME); if (!$dbMap->hasTable(BaseUserPeer::TABLE_NAME)) { $dbMap->addTableObject(new \Slashworks\BackendBundle\Model\map\UserTableMap()); } }
[ "public", "static", "function", "buildTableMap", "(", ")", "{", "$", "dbMap", "=", "Propel", "::", "getDatabaseMap", "(", "BaseUserPeer", "::", "DATABASE_NAME", ")", ";", "if", "(", "!", "$", "dbMap", "->", "hasTable", "(", "BaseUserPeer", "::", "TABLE_NAME", ")", ")", "{", "$", "dbMap", "->", "addTableObject", "(", "new", "\\", "Slashworks", "\\", "BackendBundle", "\\", "Model", "\\", "map", "\\", "UserTableMap", "(", ")", ")", ";", "}", "}" ]
Add a TableMap instance to the database for this peer class.
[ "Add", "a", "TableMap", "instance", "to", "the", "database", "for", "this", "peer", "class", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L542-L548
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.doDeleteAll
public static function doDeleteAll(PropelPDO $con = null) { if ($con === null) { $con = Propel::getConnection(UserPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); $affectedRows += UserPeer::doOnDeleteCascade(new Criteria(UserPeer::DATABASE_NAME), $con); $affectedRows += BasePeer::doDeleteAll(UserPeer::TABLE_NAME, $con, UserPeer::DATABASE_NAME); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). UserPeer::clearInstancePool(); UserPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } }
php
public static function doDeleteAll(PropelPDO $con = null) { if ($con === null) { $con = Propel::getConnection(UserPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); $affectedRows += UserPeer::doOnDeleteCascade(new Criteria(UserPeer::DATABASE_NAME), $con); $affectedRows += BasePeer::doDeleteAll(UserPeer::TABLE_NAME, $con, UserPeer::DATABASE_NAME); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). UserPeer::clearInstancePool(); UserPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } }
[ "public", "static", "function", "doDeleteAll", "(", "PropelPDO", "$", "con", "=", "null", ")", "{", "if", "(", "$", "con", "===", "null", ")", "{", "$", "con", "=", "Propel", "::", "getConnection", "(", "UserPeer", "::", "DATABASE_NAME", ",", "Propel", "::", "CONNECTION_WRITE", ")", ";", "}", "$", "affectedRows", "=", "0", ";", "// initialize var to track total num of affected rows", "try", "{", "// use transaction because $criteria could contain info", "// for more than one table or we could emulating ON DELETE CASCADE, etc.", "$", "con", "->", "beginTransaction", "(", ")", ";", "$", "affectedRows", "+=", "UserPeer", "::", "doOnDeleteCascade", "(", "new", "Criteria", "(", "UserPeer", "::", "DATABASE_NAME", ")", ",", "$", "con", ")", ";", "$", "affectedRows", "+=", "BasePeer", "::", "doDeleteAll", "(", "UserPeer", "::", "TABLE_NAME", ",", "$", "con", ",", "UserPeer", "::", "DATABASE_NAME", ")", ";", "// Because this db requires some delete cascade/set null emulation, we have to", "// clear the cached instance *after* the emulation has happened (since", "// instances get re-added by the select statement contained therein).", "UserPeer", "::", "clearInstancePool", "(", ")", ";", "UserPeer", "::", "clearRelatedInstancePool", "(", ")", ";", "$", "con", "->", "commit", "(", ")", ";", "return", "$", "affectedRows", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "con", "->", "rollBack", "(", ")", ";", "throw", "$", "e", ";", "}", "}" ]
Deletes all rows from the user table. @param PropelPDO $con the connection to use @return int The number of affected rows (if supported by underlying database driver). @throws PropelException
[ "Deletes", "all", "rows", "from", "the", "user", "table", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L650-L674
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.doDelete
public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { $con = Propel::getConnection(UserPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { // rename for clarity $criteria = clone $values; } elseif ($values instanceof User) { // it's a model object // create criteria based on pk values $criteria = $values->buildPkeyCriteria(); } else { // it's a primary key, or an array of pks $criteria = new Criteria(UserPeer::DATABASE_NAME); $criteria->add(UserPeer::ID, (array) $values, Criteria::IN); } // Set the correct dbName $criteria->setDbName(UserPeer::DATABASE_NAME); $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); // cloning the Criteria in case it's modified by doSelect() or doSelectStmt() $c = clone $criteria; $affectedRows += UserPeer::doOnDeleteCascade($c, $con); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). if ($values instanceof Criteria) { UserPeer::clearInstancePool(); } elseif ($values instanceof User) { // it's a model object UserPeer::removeInstanceFromPool($values); } else { // it's a primary key, or an array of pks foreach ((array) $values as $singleval) { UserPeer::removeInstanceFromPool($singleval); } } $affectedRows += BasePeer::doDelete($criteria, $con); UserPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } }
php
public static function doDelete($values, PropelPDO $con = null) { if ($con === null) { $con = Propel::getConnection(UserPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } if ($values instanceof Criteria) { // rename for clarity $criteria = clone $values; } elseif ($values instanceof User) { // it's a model object // create criteria based on pk values $criteria = $values->buildPkeyCriteria(); } else { // it's a primary key, or an array of pks $criteria = new Criteria(UserPeer::DATABASE_NAME); $criteria->add(UserPeer::ID, (array) $values, Criteria::IN); } // Set the correct dbName $criteria->setDbName(UserPeer::DATABASE_NAME); $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); // cloning the Criteria in case it's modified by doSelect() or doSelectStmt() $c = clone $criteria; $affectedRows += UserPeer::doOnDeleteCascade($c, $con); // Because this db requires some delete cascade/set null emulation, we have to // clear the cached instance *after* the emulation has happened (since // instances get re-added by the select statement contained therein). if ($values instanceof Criteria) { UserPeer::clearInstancePool(); } elseif ($values instanceof User) { // it's a model object UserPeer::removeInstanceFromPool($values); } else { // it's a primary key, or an array of pks foreach ((array) $values as $singleval) { UserPeer::removeInstanceFromPool($singleval); } } $affectedRows += BasePeer::doDelete($criteria, $con); UserPeer::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (Exception $e) { $con->rollBack(); throw $e; } }
[ "public", "static", "function", "doDelete", "(", "$", "values", ",", "PropelPDO", "$", "con", "=", "null", ")", "{", "if", "(", "$", "con", "===", "null", ")", "{", "$", "con", "=", "Propel", "::", "getConnection", "(", "UserPeer", "::", "DATABASE_NAME", ",", "Propel", "::", "CONNECTION_WRITE", ")", ";", "}", "if", "(", "$", "values", "instanceof", "Criteria", ")", "{", "// rename for clarity", "$", "criteria", "=", "clone", "$", "values", ";", "}", "elseif", "(", "$", "values", "instanceof", "User", ")", "{", "// it's a model object", "// create criteria based on pk values", "$", "criteria", "=", "$", "values", "->", "buildPkeyCriteria", "(", ")", ";", "}", "else", "{", "// it's a primary key, or an array of pks", "$", "criteria", "=", "new", "Criteria", "(", "UserPeer", "::", "DATABASE_NAME", ")", ";", "$", "criteria", "->", "add", "(", "UserPeer", "::", "ID", ",", "(", "array", ")", "$", "values", ",", "Criteria", "::", "IN", ")", ";", "}", "// Set the correct dbName", "$", "criteria", "->", "setDbName", "(", "UserPeer", "::", "DATABASE_NAME", ")", ";", "$", "affectedRows", "=", "0", ";", "// initialize var to track total num of affected rows", "try", "{", "// use transaction because $criteria could contain info", "// for more than one table or we could emulating ON DELETE CASCADE, etc.", "$", "con", "->", "beginTransaction", "(", ")", ";", "// cloning the Criteria in case it's modified by doSelect() or doSelectStmt()", "$", "c", "=", "clone", "$", "criteria", ";", "$", "affectedRows", "+=", "UserPeer", "::", "doOnDeleteCascade", "(", "$", "c", ",", "$", "con", ")", ";", "// Because this db requires some delete cascade/set null emulation, we have to", "// clear the cached instance *after* the emulation has happened (since", "// instances get re-added by the select statement contained therein).", "if", "(", "$", "values", "instanceof", "Criteria", ")", "{", "UserPeer", "::", "clearInstancePool", "(", ")", ";", "}", "elseif", "(", "$", "values", "instanceof", "User", ")", "{", "// it's a model object", "UserPeer", "::", "removeInstanceFromPool", "(", "$", "values", ")", ";", "}", "else", "{", "// it's a primary key, or an array of pks", "foreach", "(", "(", "array", ")", "$", "values", "as", "$", "singleval", ")", "{", "UserPeer", "::", "removeInstanceFromPool", "(", "$", "singleval", ")", ";", "}", "}", "$", "affectedRows", "+=", "BasePeer", "::", "doDelete", "(", "$", "criteria", ",", "$", "con", ")", ";", "UserPeer", "::", "clearRelatedInstancePool", "(", ")", ";", "$", "con", "->", "commit", "(", ")", ";", "return", "$", "affectedRows", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "con", "->", "rollBack", "(", ")", ";", "throw", "$", "e", ";", "}", "}" ]
Performs a DELETE on the database, given a User or Criteria object OR a primary key value. @param mixed $values Criteria or User object or primary key or array of primary keys which is used to create the DELETE statement @param PropelPDO $con the connection to use @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows if supported by native driver or if emulated using Propel. @throws PropelException Any exceptions caught during processing will be rethrown wrapped into a PropelException.
[ "Performs", "a", "DELETE", "on", "the", "database", "given", "a", "User", "or", "Criteria", "object", "OR", "a", "primary", "key", "value", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L687-L740
slashworks/control-bundle
src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php
BaseUserPeer.doOnDeleteCascade
protected static function doOnDeleteCascade(Criteria $criteria, PropelPDO $con) { // initialize var to track total num of affected rows $affectedRows = 0; // first find the objects that are implicated by the $criteria $objects = UserPeer::doSelect($criteria, $con); foreach ($objects as $obj) { // delete related UserCustomerRelation objects $criteria = new Criteria(UserCustomerRelationPeer::DATABASE_NAME); $criteria->add(UserCustomerRelationPeer::USER_ID, $obj->getId()); $affectedRows += UserCustomerRelationPeer::doDelete($criteria, $con); // delete related UserRole objects $criteria = new Criteria(UserRolePeer::DATABASE_NAME); $criteria->add(UserRolePeer::USER_ID, $obj->getId()); $affectedRows += UserRolePeer::doDelete($criteria, $con); } return $affectedRows; }
php
protected static function doOnDeleteCascade(Criteria $criteria, PropelPDO $con) { // initialize var to track total num of affected rows $affectedRows = 0; // first find the objects that are implicated by the $criteria $objects = UserPeer::doSelect($criteria, $con); foreach ($objects as $obj) { // delete related UserCustomerRelation objects $criteria = new Criteria(UserCustomerRelationPeer::DATABASE_NAME); $criteria->add(UserCustomerRelationPeer::USER_ID, $obj->getId()); $affectedRows += UserCustomerRelationPeer::doDelete($criteria, $con); // delete related UserRole objects $criteria = new Criteria(UserRolePeer::DATABASE_NAME); $criteria->add(UserRolePeer::USER_ID, $obj->getId()); $affectedRows += UserRolePeer::doDelete($criteria, $con); } return $affectedRows; }
[ "protected", "static", "function", "doOnDeleteCascade", "(", "Criteria", "$", "criteria", ",", "PropelPDO", "$", "con", ")", "{", "// initialize var to track total num of affected rows", "$", "affectedRows", "=", "0", ";", "// first find the objects that are implicated by the $criteria", "$", "objects", "=", "UserPeer", "::", "doSelect", "(", "$", "criteria", ",", "$", "con", ")", ";", "foreach", "(", "$", "objects", "as", "$", "obj", ")", "{", "// delete related UserCustomerRelation objects", "$", "criteria", "=", "new", "Criteria", "(", "UserCustomerRelationPeer", "::", "DATABASE_NAME", ")", ";", "$", "criteria", "->", "add", "(", "UserCustomerRelationPeer", "::", "USER_ID", ",", "$", "obj", "->", "getId", "(", ")", ")", ";", "$", "affectedRows", "+=", "UserCustomerRelationPeer", "::", "doDelete", "(", "$", "criteria", ",", "$", "con", ")", ";", "// delete related UserRole objects", "$", "criteria", "=", "new", "Criteria", "(", "UserRolePeer", "::", "DATABASE_NAME", ")", ";", "$", "criteria", "->", "add", "(", "UserRolePeer", "::", "USER_ID", ",", "$", "obj", "->", "getId", "(", ")", ")", ";", "$", "affectedRows", "+=", "UserRolePeer", "::", "doDelete", "(", "$", "criteria", ",", "$", "con", ")", ";", "}", "return", "$", "affectedRows", ";", "}" ]
This is a method for emulating ON DELETE CASCADE for DBs that don't support this feature (like MySQL or SQLite). This method is not very speedy because it must perform a query first to get the implicated records and then perform the deletes by calling those Peer classes. This method should be used within a transaction if possible. @param Criteria $criteria @param PropelPDO $con @return int The number of affected rows (if supported by underlying database driver).
[ "This", "is", "a", "method", "for", "emulating", "ON", "DELETE", "CASCADE", "for", "DBs", "that", "don", "t", "support", "this", "feature", "(", "like", "MySQL", "or", "SQLite", ")", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Model/om/BaseUserPeer.php#L755-L779
phore/phore-micro-app
src/Auth/BasicUserProvider.php
BasicUserProvider.getUserById
public function getUserById(string $userName, array $roleMap) : AuthUser { if ( ! isset ($this->users[$userName])) throw new InvalidUserException("Invalid userId: '$userName'"); $user = $this->users[$userName]; if (!isset ($roleMap[$user["role"]])) throw new \InvalidArgumentException("User role '{$user["role"]}' is not defined in roleMap."); return new AuthUser([ "userName" => $userName, "role" => $user["role"], "roleMap" => $roleMap, "roleId" => $roleMap[$user["role"]], "meta" => $user["meta"] ]); }
php
public function getUserById(string $userName, array $roleMap) : AuthUser { if ( ! isset ($this->users[$userName])) throw new InvalidUserException("Invalid userId: '$userName'"); $user = $this->users[$userName]; if (!isset ($roleMap[$user["role"]])) throw new \InvalidArgumentException("User role '{$user["role"]}' is not defined in roleMap."); return new AuthUser([ "userName" => $userName, "role" => $user["role"], "roleMap" => $roleMap, "roleId" => $roleMap[$user["role"]], "meta" => $user["meta"] ]); }
[ "public", "function", "getUserById", "(", "string", "$", "userName", ",", "array", "$", "roleMap", ")", ":", "AuthUser", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "users", "[", "$", "userName", "]", ")", ")", "throw", "new", "InvalidUserException", "(", "\"Invalid userId: '$userName'\"", ")", ";", "$", "user", "=", "$", "this", "->", "users", "[", "$", "userName", "]", ";", "if", "(", "!", "isset", "(", "$", "roleMap", "[", "$", "user", "[", "\"role\"", "]", "]", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "\"User role '{$user[\"", "role", "\"]}' is not defined in roleMap.\"", ")", ";", "return", "new", "AuthUser", "(", "[", "\"userName\"", "=>", "$", "userName", ",", "\"role\"", "=>", "$", "user", "[", "\"role\"", "]", ",", "\"roleMap\"", "=>", "$", "roleMap", ",", "\"roleId\"", "=>", "$", "roleMap", "[", "$", "user", "[", "\"role\"", "]", "]", ",", "\"meta\"", "=>", "$", "user", "[", "\"meta\"", "]", "]", ")", ";", "}" ]
@param string $userId @param array $roleMap @return AuthUser @throws InvalidUserException
[ "@param", "string", "$userId", "@param", "array", "$roleMap" ]
train
https://github.com/phore/phore-micro-app/blob/6cf87a647b8b0be05afbfe6bd020650e98558c23/src/Auth/BasicUserProvider.php#L82-L97
dms-org/package.blog
src/Cms/BlogPackage.php
BlogPackage.boot
public static function boot(ICms $cms) { $repositories = [ IBlogCategoryRepository::class => DbBlogCategoryRepository::class, IBlogAuthorRepository::class => DbBlogAuthorRepository::class, IBlogArticleRepository::class => DbBlogArticleRepository::class, IBlogArticleCommentRepository::class => DbBlogArticleCommentRepository::class, ]; foreach ($repositories as $interface => $implementation) { $cms->getIocContainer()->bind(IIocContainer::SCOPE_SINGLETON, $interface, $implementation); } }
php
public static function boot(ICms $cms) { $repositories = [ IBlogCategoryRepository::class => DbBlogCategoryRepository::class, IBlogAuthorRepository::class => DbBlogAuthorRepository::class, IBlogArticleRepository::class => DbBlogArticleRepository::class, IBlogArticleCommentRepository::class => DbBlogArticleCommentRepository::class, ]; foreach ($repositories as $interface => $implementation) { $cms->getIocContainer()->bind(IIocContainer::SCOPE_SINGLETON, $interface, $implementation); } }
[ "public", "static", "function", "boot", "(", "ICms", "$", "cms", ")", "{", "$", "repositories", "=", "[", "IBlogCategoryRepository", "::", "class", "=>", "DbBlogCategoryRepository", "::", "class", ",", "IBlogAuthorRepository", "::", "class", "=>", "DbBlogAuthorRepository", "::", "class", ",", "IBlogArticleRepository", "::", "class", "=>", "DbBlogArticleRepository", "::", "class", ",", "IBlogArticleCommentRepository", "::", "class", "=>", "DbBlogArticleCommentRepository", "::", "class", ",", "]", ";", "foreach", "(", "$", "repositories", "as", "$", "interface", "=>", "$", "implementation", ")", "{", "$", "cms", "->", "getIocContainer", "(", ")", "->", "bind", "(", "IIocContainer", "::", "SCOPE_SINGLETON", ",", "$", "interface", ",", "$", "implementation", ")", ";", "}", "}" ]
@param ICms $cms @return void
[ "@param", "ICms", "$cms" ]
train
https://github.com/dms-org/package.blog/blob/1500f6fad20d81289a0dfa617fc1c54699f01e16/src/Cms/BlogPackage.php#L28-L40
dms-org/package.blog
src/Cms/BlogPackage.php
BlogPackage.define
protected function define(PackageDefinition $package) { $package->name('blog'); $package->metadata([ 'icon' => 'rss', ]); $package->modules([ 'categories' => BlogCategoryModule::class, 'authors' => BlogAuthorModule::class, 'articles' => BlogArticleModule::class, ]); }
php
protected function define(PackageDefinition $package) { $package->name('blog'); $package->metadata([ 'icon' => 'rss', ]); $package->modules([ 'categories' => BlogCategoryModule::class, 'authors' => BlogAuthorModule::class, 'articles' => BlogArticleModule::class, ]); }
[ "protected", "function", "define", "(", "PackageDefinition", "$", "package", ")", "{", "$", "package", "->", "name", "(", "'blog'", ")", ";", "$", "package", "->", "metadata", "(", "[", "'icon'", "=>", "'rss'", ",", "]", ")", ";", "$", "package", "->", "modules", "(", "[", "'categories'", "=>", "BlogCategoryModule", "::", "class", ",", "'authors'", "=>", "BlogAuthorModule", "::", "class", ",", "'articles'", "=>", "BlogArticleModule", "::", "class", ",", "]", ")", ";", "}" ]
Defines the structure of this cms package. @param PackageDefinition $package @return void
[ "Defines", "the", "structure", "of", "this", "cms", "package", "." ]
train
https://github.com/dms-org/package.blog/blob/1500f6fad20d81289a0dfa617fc1c54699f01e16/src/Cms/BlogPackage.php#L49-L62
GrahamDeprecated/CMS-Core
src/Seeds/DatabaseSeeder.php
DatabaseSeeder.run
public function run() { Eloquent::unguard(); $this->call('GrahamCampbell\CMSCore\Seeds\GroupsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\UsersTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\UsersGroupsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\PagesTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\PostsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\CommentsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\EventsTableSeeder'); }
php
public function run() { Eloquent::unguard(); $this->call('GrahamCampbell\CMSCore\Seeds\GroupsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\UsersTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\UsersGroupsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\PagesTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\PostsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\CommentsTableSeeder'); $this->call('GrahamCampbell\CMSCore\Seeds\EventsTableSeeder'); }
[ "public", "function", "run", "(", ")", "{", "Eloquent", "::", "unguard", "(", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\GroupsTableSeeder'", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\UsersTableSeeder'", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\UsersGroupsTableSeeder'", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\PagesTableSeeder'", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\PostsTableSeeder'", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\CommentsTableSeeder'", ")", ";", "$", "this", "->", "call", "(", "'GrahamCampbell\\CMSCore\\Seeds\\EventsTableSeeder'", ")", ";", "}" ]
Run the database seeding. @return void
[ "Run", "the", "database", "seeding", "." ]
train
https://github.com/GrahamDeprecated/CMS-Core/blob/5603e2bfa2fac6cf46ca3ed62d21518f2f653675/src/Seeds/DatabaseSeeder.php#L38-L50
vi-kon/laravel-auth
src/ViKon/Auth/RouterAuth.php
RouterAuth.hasAccess
public function hasAccess($name) { $permissions = $this->getPermissions($name); $roles = $this->getRoles($name); if ($permissions === null && $roles === null) { return null; } return $this->keeper->hasPermissions($permissions) === true && $this->keeper->hasRoles($roles) === true; }
php
public function hasAccess($name) { $permissions = $this->getPermissions($name); $roles = $this->getRoles($name); if ($permissions === null && $roles === null) { return null; } return $this->keeper->hasPermissions($permissions) === true && $this->keeper->hasRoles($roles) === true; }
[ "public", "function", "hasAccess", "(", "$", "name", ")", "{", "$", "permissions", "=", "$", "this", "->", "getPermissions", "(", "$", "name", ")", ";", "$", "roles", "=", "$", "this", "->", "getRoles", "(", "$", "name", ")", ";", "if", "(", "$", "permissions", "===", "null", "&&", "$", "roles", "===", "null", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "keeper", "->", "hasPermissions", "(", "$", "permissions", ")", "===", "true", "&&", "$", "this", "->", "keeper", "->", "hasRoles", "(", "$", "roles", ")", "===", "true", ";", "}" ]
Check if current user has access to named route @param string $name named route name @return bool|null NULL if route not found, otherwise TRUE or FALSE depend if user has access to route or not
[ "Check", "if", "current", "user", "has", "access", "to", "named", "route" ]
train
https://github.com/vi-kon/laravel-auth/blob/501c20128f43347a2ca271a53435297f9ef7f567/src/ViKon/Auth/RouterAuth.php#L40-L50
vi-kon/laravel-auth
src/ViKon/Auth/RouterAuth.php
RouterAuth.getPermissions
public function getPermissions($name) { $route = $this->router->getRoutes()->getByName($name); // If route not exists, return NULL if ($route === null) { return null; } $permissions = []; // Get permission from permission middleware foreach ($route->middleware() as $middleware) { if (strpos($middleware, 'permission:') === 0) { list(, $permission) = explode(':', $middleware, 2); $permissions[] = $permission; } } // Get permissions from array syntax $action = $route->getAction(); if (array_key_exists('permission', $action)) { $permissions[] = $action['permission']; } if (array_key_exists('permissions', $action)) { $permissions = array_merge($permissions, $action['permissions']); } return array_unique($permissions); }
php
public function getPermissions($name) { $route = $this->router->getRoutes()->getByName($name); // If route not exists, return NULL if ($route === null) { return null; } $permissions = []; // Get permission from permission middleware foreach ($route->middleware() as $middleware) { if (strpos($middleware, 'permission:') === 0) { list(, $permission) = explode(':', $middleware, 2); $permissions[] = $permission; } } // Get permissions from array syntax $action = $route->getAction(); if (array_key_exists('permission', $action)) { $permissions[] = $action['permission']; } if (array_key_exists('permissions', $action)) { $permissions = array_merge($permissions, $action['permissions']); } return array_unique($permissions); }
[ "public", "function", "getPermissions", "(", "$", "name", ")", "{", "$", "route", "=", "$", "this", "->", "router", "->", "getRoutes", "(", ")", "->", "getByName", "(", "$", "name", ")", ";", "// If route not exists, return NULL", "if", "(", "$", "route", "===", "null", ")", "{", "return", "null", ";", "}", "$", "permissions", "=", "[", "]", ";", "// Get permission from permission middleware", "foreach", "(", "$", "route", "->", "middleware", "(", ")", "as", "$", "middleware", ")", "{", "if", "(", "strpos", "(", "$", "middleware", ",", "'permission:'", ")", "===", "0", ")", "{", "list", "(", ",", "$", "permission", ")", "=", "explode", "(", "':'", ",", "$", "middleware", ",", "2", ")", ";", "$", "permissions", "[", "]", "=", "$", "permission", ";", "}", "}", "// Get permissions from array syntax", "$", "action", "=", "$", "route", "->", "getAction", "(", ")", ";", "if", "(", "array_key_exists", "(", "'permission'", ",", "$", "action", ")", ")", "{", "$", "permissions", "[", "]", "=", "$", "action", "[", "'permission'", "]", ";", "}", "if", "(", "array_key_exists", "(", "'permissions'", ",", "$", "action", ")", ")", "{", "$", "permissions", "=", "array_merge", "(", "$", "permissions", ",", "$", "action", "[", "'permissions'", "]", ")", ";", "}", "return", "array_unique", "(", "$", "permissions", ")", ";", "}" ]
Get permissions for named route @param string $name named route named @return string[]|null NULL if route not found, otherwise array of permissions
[ "Get", "permissions", "for", "named", "route" ]
train
https://github.com/vi-kon/laravel-auth/blob/501c20128f43347a2ca271a53435297f9ef7f567/src/ViKon/Auth/RouterAuth.php#L71-L102
vi-kon/laravel-auth
src/ViKon/Auth/RouterAuth.php
RouterAuth.getRoles
public function getRoles($name) { $route = $this->router->getRoutes()->getByName($name); // If route not exists, return NULL if ($route === null) { return null; } $roles = []; // Get permissions from array syntax $action = $route->getAction(); if (array_key_exists('role', $action)) { $roles[] = $action['role']; } if (array_key_exists('roles', $action)) { $roles = array_merge($roles, $action['roles']); } return array_unique($roles); }
php
public function getRoles($name) { $route = $this->router->getRoutes()->getByName($name); // If route not exists, return NULL if ($route === null) { return null; } $roles = []; // Get permissions from array syntax $action = $route->getAction(); if (array_key_exists('role', $action)) { $roles[] = $action['role']; } if (array_key_exists('roles', $action)) { $roles = array_merge($roles, $action['roles']); } return array_unique($roles); }
[ "public", "function", "getRoles", "(", "$", "name", ")", "{", "$", "route", "=", "$", "this", "->", "router", "->", "getRoutes", "(", ")", "->", "getByName", "(", "$", "name", ")", ";", "// If route not exists, return NULL", "if", "(", "$", "route", "===", "null", ")", "{", "return", "null", ";", "}", "$", "roles", "=", "[", "]", ";", "// Get permissions from array syntax", "$", "action", "=", "$", "route", "->", "getAction", "(", ")", ";", "if", "(", "array_key_exists", "(", "'role'", ",", "$", "action", ")", ")", "{", "$", "roles", "[", "]", "=", "$", "action", "[", "'role'", "]", ";", "}", "if", "(", "array_key_exists", "(", "'roles'", ",", "$", "action", ")", ")", "{", "$", "roles", "=", "array_merge", "(", "$", "roles", ",", "$", "action", "[", "'roles'", "]", ")", ";", "}", "return", "array_unique", "(", "$", "roles", ")", ";", "}" ]
Get roles for named route @param string $name named route named @return string[]|null NULL if route not found, otherwise array of roles
[ "Get", "roles", "for", "named", "route" ]
train
https://github.com/vi-kon/laravel-auth/blob/501c20128f43347a2ca271a53435297f9ef7f567/src/ViKon/Auth/RouterAuth.php#L111-L134
vi-kon/laravel-auth
src/ViKon/Auth/RouterAuth.php
RouterAuth.isPublic
public function isPublic($name) { // If route not exists, return NULL if (($permissions = $this->getPermissions($name)) === null) { return null; } return count($permissions) === 0; }
php
public function isPublic($name) { // If route not exists, return NULL if (($permissions = $this->getPermissions($name)) === null) { return null; } return count($permissions) === 0; }
[ "public", "function", "isPublic", "(", "$", "name", ")", "{", "// If route not exists, return NULL", "if", "(", "(", "$", "permissions", "=", "$", "this", "->", "getPermissions", "(", "$", "name", ")", ")", "===", "null", ")", "{", "return", "null", ";", "}", "return", "count", "(", "$", "permissions", ")", "===", "0", ";", "}" ]
Check if route has is public (no permission restriction found) @param string $name named route name @return bool|null NULL if route not found, otherwise TRUE or FALSE depend if route has any permission or not
[ "Check", "if", "route", "has", "is", "public", "(", "no", "permission", "restriction", "found", ")" ]
train
https://github.com/vi-kon/laravel-auth/blob/501c20128f43347a2ca271a53435297f9ef7f567/src/ViKon/Auth/RouterAuth.php#L143-L151
shinjin/freezer
src/Storage.php
Storage.store
public function store($object) { if (!is_object($object)) { throw new InvalidArgumentException(1, 'object'); } $objects = array(); $id = $this->doStore($this->freezer->freeze($object, $objects)); if ($id !== null) { $object->{$this->freezer->getIdProperty()} = $id; } return $object->{$this->freezer->getIdProperty()}; }
php
public function store($object) { if (!is_object($object)) { throw new InvalidArgumentException(1, 'object'); } $objects = array(); $id = $this->doStore($this->freezer->freeze($object, $objects)); if ($id !== null) { $object->{$this->freezer->getIdProperty()} = $id; } return $object->{$this->freezer->getIdProperty()}; }
[ "public", "function", "store", "(", "$", "object", ")", "{", "if", "(", "!", "is_object", "(", "$", "object", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "1", ",", "'object'", ")", ";", "}", "$", "objects", "=", "array", "(", ")", ";", "$", "id", "=", "$", "this", "->", "doStore", "(", "$", "this", "->", "freezer", "->", "freeze", "(", "$", "object", ",", "$", "objects", ")", ")", ";", "if", "(", "$", "id", "!==", "null", ")", "{", "$", "object", "->", "{", "$", "this", "->", "freezer", "->", "getIdProperty", "(", ")", "}", "=", "$", "id", ";", "}", "return", "$", "object", "->", "{", "$", "this", "->", "freezer", "->", "getIdProperty", "(", ")", "}", ";", "}" ]
Freezes an object and stores it in the object storage. @param object $object The object that is to be stored. @return string
[ "Freezes", "an", "object", "and", "stores", "it", "in", "the", "object", "storage", "." ]
train
https://github.com/shinjin/freezer/blob/f5955fb5476fa8ac456e27c0edafaae331d02cd3/src/Storage.php#L79-L93
shinjin/freezer
src/Storage.php
Storage.fetch
public function fetch($id) { if (!is_string($id)) { throw new InvalidArgumentException(1, 'string'); } if (($frozenObject = $this->doFetch($id)) !== false) { $this->fetchArray($frozenObject['objects'][$id]['state']); $object = $this->freezer->thaw($frozenObject); } else { throw new ObjectNotFoundException( sprintf('Object with id "%s" could not be fetched.', $id) ); } return $object; }
php
public function fetch($id) { if (!is_string($id)) { throw new InvalidArgumentException(1, 'string'); } if (($frozenObject = $this->doFetch($id)) !== false) { $this->fetchArray($frozenObject['objects'][$id]['state']); $object = $this->freezer->thaw($frozenObject); } else { throw new ObjectNotFoundException( sprintf('Object with id "%s" could not be fetched.', $id) ); } return $object; }
[ "public", "function", "fetch", "(", "$", "id", ")", "{", "if", "(", "!", "is_string", "(", "$", "id", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "1", ",", "'string'", ")", ";", "}", "if", "(", "(", "$", "frozenObject", "=", "$", "this", "->", "doFetch", "(", "$", "id", ")", ")", "!==", "false", ")", "{", "$", "this", "->", "fetchArray", "(", "$", "frozenObject", "[", "'objects'", "]", "[", "$", "id", "]", "[", "'state'", "]", ")", ";", "$", "object", "=", "$", "this", "->", "freezer", "->", "thaw", "(", "$", "frozenObject", ")", ";", "}", "else", "{", "throw", "new", "ObjectNotFoundException", "(", "sprintf", "(", "'Object with id \"%s\" could not be fetched.'", ",", "$", "id", ")", ")", ";", "}", "return", "$", "object", ";", "}" ]
Fetches a frozen object from the object storage and thaws it. @param string $id The ID of the object that is to be fetched. @return object
[ "Fetches", "a", "frozen", "object", "from", "the", "object", "storage", "and", "thaws", "it", "." ]
train
https://github.com/shinjin/freezer/blob/f5955fb5476fa8ac456e27c0edafaae331d02cd3/src/Storage.php#L101-L117
shinjin/freezer
src/Storage.php
Storage.fetchArray
protected function fetchArray(array &$array, array &$objects = array()) { foreach ($array as &$value) { if (is_array($value)) { $this->fetchArray($value, $objects); } elseif (is_string($value) && strpos($value, '__freezer_') === 0) { $id = str_replace('__freezer_', '', $value); if (!$this->useLazyLoad) { $this->doFetch($id, $objects); } else { $value = new LazyProxy($this, $id); } } } }
php
protected function fetchArray(array &$array, array &$objects = array()) { foreach ($array as &$value) { if (is_array($value)) { $this->fetchArray($value, $objects); } elseif (is_string($value) && strpos($value, '__freezer_') === 0) { $id = str_replace('__freezer_', '', $value); if (!$this->useLazyLoad) { $this->doFetch($id, $objects); } else { $value = new LazyProxy($this, $id); } } } }
[ "protected", "function", "fetchArray", "(", "array", "&", "$", "array", ",", "array", "&", "$", "objects", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "array", "as", "&", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "this", "->", "fetchArray", "(", "$", "value", ",", "$", "objects", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "value", ")", "&&", "strpos", "(", "$", "value", ",", "'__freezer_'", ")", "===", "0", ")", "{", "$", "id", "=", "str_replace", "(", "'__freezer_'", ",", "''", ",", "$", "value", ")", ";", "if", "(", "!", "$", "this", "->", "useLazyLoad", ")", "{", "$", "this", "->", "doFetch", "(", "$", "id", ",", "$", "objects", ")", ";", "}", "else", "{", "$", "value", "=", "new", "LazyProxy", "(", "$", "this", ",", "$", "id", ")", ";", "}", "}", "}", "}" ]
Fetches a frozen array from the object storage and thaws it. @param array $array @param array $objects
[ "Fetches", "a", "frozen", "array", "from", "the", "object", "storage", "and", "thaws", "it", "." ]
train
https://github.com/shinjin/freezer/blob/f5955fb5476fa8ac456e27c0edafaae331d02cd3/src/Storage.php#L125-L140
jacobemerick/pqp
src/Console.php
Console.logMemory
public function logMemory($object = null, $name = 'PHP', $literal = false) { $memory = memory_get_usage(); $dataType = ''; if (!is_null($object) && !$literal) { $memory = strlen(serialize($object)); $dataType = gettype($object); } else if (is_numeric($object) && $literal) { $memory = floatval($object); } array_push($this->store, array( 'name' => $name, 'data' => $memory, 'data_type' => $dataType, 'type' => 'memory' )); }
php
public function logMemory($object = null, $name = 'PHP', $literal = false) { $memory = memory_get_usage(); $dataType = ''; if (!is_null($object) && !$literal) { $memory = strlen(serialize($object)); $dataType = gettype($object); } else if (is_numeric($object) && $literal) { $memory = floatval($object); } array_push($this->store, array( 'name' => $name, 'data' => $memory, 'data_type' => $dataType, 'type' => 'memory' )); }
[ "public", "function", "logMemory", "(", "$", "object", "=", "null", ",", "$", "name", "=", "'PHP'", ",", "$", "literal", "=", "false", ")", "{", "$", "memory", "=", "memory_get_usage", "(", ")", ";", "$", "dataType", "=", "''", ";", "if", "(", "!", "is_null", "(", "$", "object", ")", "&&", "!", "$", "literal", ")", "{", "$", "memory", "=", "strlen", "(", "serialize", "(", "$", "object", ")", ")", ";", "$", "dataType", "=", "gettype", "(", "$", "object", ")", ";", "}", "else", "if", "(", "is_numeric", "(", "$", "object", ")", "&&", "$", "literal", ")", "{", "$", "memory", "=", "floatval", "(", "$", "object", ")", ";", "}", "array_push", "(", "$", "this", "->", "store", ",", "array", "(", "'name'", "=>", "$", "name", ",", "'data'", "=>", "$", "memory", ",", "'data_type'", "=>", "$", "dataType", ",", "'type'", "=>", "'memory'", ")", ")", ";", "}" ]
Logs memory usage of a variable If no parameter is passed in, logs current memory usage @param mixed $object @param string $name @param boolean $literal
[ "Logs", "memory", "usage", "of", "a", "variable", "If", "no", "parameter", "is", "passed", "in", "logs", "current", "memory", "usage" ]
train
https://github.com/jacobemerick/pqp/blob/08276f050425d1ab71e7ca3b897eb8c409ccbe70/src/Console.php#L43-L60
jacobemerick/pqp
src/Console.php
Console.logError
public function logError(Exception $exception, $message = '') { if (empty($message)) { $message = $exception->getMessage(); } array_push($this->store, array( 'data' => $message, 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'type' => 'error' )); }
php
public function logError(Exception $exception, $message = '') { if (empty($message)) { $message = $exception->getMessage(); } array_push($this->store, array( 'data' => $message, 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'type' => 'error' )); }
[ "public", "function", "logError", "(", "Exception", "$", "exception", ",", "$", "message", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "message", ")", ")", "{", "$", "message", "=", "$", "exception", "->", "getMessage", "(", ")", ";", "}", "array_push", "(", "$", "this", "->", "store", ",", "array", "(", "'data'", "=>", "$", "message", ",", "'file'", "=>", "$", "exception", "->", "getFile", "(", ")", ",", "'line'", "=>", "$", "exception", "->", "getLine", "(", ")", ",", "'type'", "=>", "'error'", ")", ")", ";", "}" ]
Logs exception with optional message override @param Exception $exception @param string $message
[ "Logs", "exception", "with", "optional", "message", "override" ]
train
https://github.com/jacobemerick/pqp/blob/08276f050425d1ab71e7ca3b897eb8c409ccbe70/src/Console.php#L68-L80
jacobemerick/pqp
src/Console.php
Console.logSpeed
public function logSpeed($name = 'Point in Time', $literalTime = null) { $time = microtime(true); if (!is_null($literalTime) && is_float($literalTime)) { $time = $literalTime; } array_push($this->store, array( 'data' => $time, 'name' => $name, 'type' => 'speed' )); }
php
public function logSpeed($name = 'Point in Time', $literalTime = null) { $time = microtime(true); if (!is_null($literalTime) && is_float($literalTime)) { $time = $literalTime; } array_push($this->store, array( 'data' => $time, 'name' => $name, 'type' => 'speed' )); }
[ "public", "function", "logSpeed", "(", "$", "name", "=", "'Point in Time'", ",", "$", "literalTime", "=", "null", ")", "{", "$", "time", "=", "microtime", "(", "true", ")", ";", "if", "(", "!", "is_null", "(", "$", "literalTime", ")", "&&", "is_float", "(", "$", "literalTime", ")", ")", "{", "$", "time", "=", "$", "literalTime", ";", "}", "array_push", "(", "$", "this", "->", "store", ",", "array", "(", "'data'", "=>", "$", "time", ",", "'name'", "=>", "$", "name", ",", "'type'", "=>", "'speed'", ")", ")", ";", "}" ]
Logs current time with optional message @param string $name @param float $literalTime
[ "Logs", "current", "time", "with", "optional", "message" ]
train
https://github.com/jacobemerick/pqp/blob/08276f050425d1ab71e7ca3b897eb8c409ccbe70/src/Console.php#L88-L100
Aurora-Framework/Router
src/Router.php
Router.setMatchTypes
public function setMatchTypes($matchTypes) { if (is_array($matchTypes)) { $this->matchTypes = $matchTypes; } else { foreach ( (array) $matchTypes as $key => $matchType) { $this->matchTypes[$key] = $matchType; } } }
php
public function setMatchTypes($matchTypes) { if (is_array($matchTypes)) { $this->matchTypes = $matchTypes; } else { foreach ( (array) $matchTypes as $key => $matchType) { $this->matchTypes[$key] = $matchType; } } }
[ "public", "function", "setMatchTypes", "(", "$", "matchTypes", ")", "{", "if", "(", "is_array", "(", "$", "matchTypes", ")", ")", "{", "$", "this", "->", "matchTypes", "=", "$", "matchTypes", ";", "}", "else", "{", "foreach", "(", "(", "array", ")", "$", "matchTypes", "as", "$", "key", "=>", "$", "matchType", ")", "{", "$", "this", "->", "matchTypes", "[", "$", "key", "]", "=", "$", "matchType", ";", "}", "}", "}" ]
Match types are used to replace given search with replace @param array|string $matchTypes Array containg search and replace
[ "Match", "types", "are", "used", "to", "replace", "given", "search", "with", "replace" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L118-L127
Aurora-Framework/Router
src/Router.php
Router.mount
public function mount($baseroute, $callable, $extra = []) { $Route = clone $this->Route; $this->Route->addExtra($extra); // Track current baseroute $curBaseroute = $this->baseUri; $this->baseUri .= $baseroute; // Call the callable $callable($this); $this->Route = $Route; // Restore original baseroute $this->baseUri = $curBaseroute; }
php
public function mount($baseroute, $callable, $extra = []) { $Route = clone $this->Route; $this->Route->addExtra($extra); // Track current baseroute $curBaseroute = $this->baseUri; $this->baseUri .= $baseroute; // Call the callable $callable($this); $this->Route = $Route; // Restore original baseroute $this->baseUri = $curBaseroute; }
[ "public", "function", "mount", "(", "$", "baseroute", ",", "$", "callable", ",", "$", "extra", "=", "[", "]", ")", "{", "$", "Route", "=", "clone", "$", "this", "->", "Route", ";", "$", "this", "->", "Route", "->", "addExtra", "(", "$", "extra", ")", ";", "// Track current baseroute", "$", "curBaseroute", "=", "$", "this", "->", "baseUri", ";", "$", "this", "->", "baseUri", ".=", "$", "baseroute", ";", "// Call the callable", "$", "callable", "(", "$", "this", ")", ";", "$", "this", "->", "Route", "=", "$", "Route", ";", "// Restore original baseroute", "$", "this", "->", "baseUri", "=", "$", "curBaseroute", ";", "}" ]
Mount multiple routes via callabck @param string $baseroute Base route for all routes in given callback @param callable $callable Callable to execute
[ "Mount", "multiple", "routes", "via", "callabck" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L232-L247
Aurora-Framework/Router
src/Router.php
Router.findRequestMethod
public function findRequestMethod() { $method = $_SERVER["REQUEST_METHOD"]; if ($method === "POST") { if (isset($_SERVER["X-HTTP-Method-Override"])) { $method = $_SERVER["X-HTTP-Method-Override"]; } } return $this->method = $method; }
php
public function findRequestMethod() { $method = $_SERVER["REQUEST_METHOD"]; if ($method === "POST") { if (isset($_SERVER["X-HTTP-Method-Override"])) { $method = $_SERVER["X-HTTP-Method-Override"]; } } return $this->method = $method; }
[ "public", "function", "findRequestMethod", "(", ")", "{", "$", "method", "=", "$", "_SERVER", "[", "\"REQUEST_METHOD\"", "]", ";", "if", "(", "$", "method", "===", "\"POST\"", ")", "{", "if", "(", "isset", "(", "$", "_SERVER", "[", "\"X-HTTP-Method-Override\"", "]", ")", ")", "{", "$", "method", "=", "$", "_SERVER", "[", "\"X-HTTP-Method-Override\"", "]", ";", "}", "}", "return", "$", "this", "->", "method", "=", "$", "method", ";", "}" ]
Automatically find the request method @return string Found method
[ "Automatically", "find", "the", "request", "method" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L253-L264
Aurora-Framework/Router
src/Router.php
Router.findUri
public function findUri() { $uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); return ($this->lowerCase) ? strtolower($uri) : $uri; }
php
public function findUri() { $uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); return ($this->lowerCase) ? strtolower($uri) : $uri; }
[ "public", "function", "findUri", "(", ")", "{", "$", "uri", "=", "parse_url", "(", "$", "_SERVER", "[", "\"REQUEST_URI\"", "]", ",", "PHP_URL_PATH", ")", ";", "return", "(", "$", "this", "->", "lowerCase", ")", "?", "strtolower", "(", "$", "uri", ")", ":", "$", "uri", ";", "}" ]
Automatically find the current uri using baseuri @return string Returns found uri
[ "Automatically", "find", "the", "current", "uri", "using", "baseuri" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L296-L301
Aurora-Framework/Router
src/Router.php
Router.addRoute
public function addRoute($method, $route, $action, $extra = []) { $name = (isset($extra["name"])) ? $extra["name"] : $route; if (isset($this->rawRoutes[$name])) { $Route = $this->rawRoutes[$name]; } else { $Route = clone $this->Route; $Route->route = $this->baseUri.$route; $Route->name = $name; } $Route->addExtra($extra); $methods = []; if ("ANY" === $method) { $methods["GET"] = $action; $methods["POST"] =& $methods["GET"]; $methods["PUT"] =& $methods["GET"]; $Route->methods = $methods; $Route->action = $action; $this->rawRoutes[$name] = $Route; } else { $arrayedMethod = (array) $method; $count = count($arrayedMethod); for ($i = 0; $i < $count; $i++) { if (!isset($this->allowedMethods[$arrayedMethod[$i]])) { throw new InvalidMethodException("Method: " . $arrayedMethod[$i] . " is not valid"); } $method = $arrayedMethod[$i]; $Route->action = $action; $Route->method = $method; $Route->name = $name; $this->rawRoutes[$name] = $Route; } } return $Route; }
php
public function addRoute($method, $route, $action, $extra = []) { $name = (isset($extra["name"])) ? $extra["name"] : $route; if (isset($this->rawRoutes[$name])) { $Route = $this->rawRoutes[$name]; } else { $Route = clone $this->Route; $Route->route = $this->baseUri.$route; $Route->name = $name; } $Route->addExtra($extra); $methods = []; if ("ANY" === $method) { $methods["GET"] = $action; $methods["POST"] =& $methods["GET"]; $methods["PUT"] =& $methods["GET"]; $Route->methods = $methods; $Route->action = $action; $this->rawRoutes[$name] = $Route; } else { $arrayedMethod = (array) $method; $count = count($arrayedMethod); for ($i = 0; $i < $count; $i++) { if (!isset($this->allowedMethods[$arrayedMethod[$i]])) { throw new InvalidMethodException("Method: " . $arrayedMethod[$i] . " is not valid"); } $method = $arrayedMethod[$i]; $Route->action = $action; $Route->method = $method; $Route->name = $name; $this->rawRoutes[$name] = $Route; } } return $Route; }
[ "public", "function", "addRoute", "(", "$", "method", ",", "$", "route", ",", "$", "action", ",", "$", "extra", "=", "[", "]", ")", "{", "$", "name", "=", "(", "isset", "(", "$", "extra", "[", "\"name\"", "]", ")", ")", "?", "$", "extra", "[", "\"name\"", "]", ":", "$", "route", ";", "if", "(", "isset", "(", "$", "this", "->", "rawRoutes", "[", "$", "name", "]", ")", ")", "{", "$", "Route", "=", "$", "this", "->", "rawRoutes", "[", "$", "name", "]", ";", "}", "else", "{", "$", "Route", "=", "clone", "$", "this", "->", "Route", ";", "$", "Route", "->", "route", "=", "$", "this", "->", "baseUri", ".", "$", "route", ";", "$", "Route", "->", "name", "=", "$", "name", ";", "}", "$", "Route", "->", "addExtra", "(", "$", "extra", ")", ";", "$", "methods", "=", "[", "]", ";", "if", "(", "\"ANY\"", "===", "$", "method", ")", "{", "$", "methods", "[", "\"GET\"", "]", "=", "$", "action", ";", "$", "methods", "[", "\"POST\"", "]", "=", "&", "$", "methods", "[", "\"GET\"", "]", ";", "$", "methods", "[", "\"PUT\"", "]", "=", "&", "$", "methods", "[", "\"GET\"", "]", ";", "$", "Route", "->", "methods", "=", "$", "methods", ";", "$", "Route", "->", "action", "=", "$", "action", ";", "$", "this", "->", "rawRoutes", "[", "$", "name", "]", "=", "$", "Route", ";", "}", "else", "{", "$", "arrayedMethod", "=", "(", "array", ")", "$", "method", ";", "$", "count", "=", "count", "(", "$", "arrayedMethod", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "allowedMethods", "[", "$", "arrayedMethod", "[", "$", "i", "]", "]", ")", ")", "{", "throw", "new", "InvalidMethodException", "(", "\"Method: \"", ".", "$", "arrayedMethod", "[", "$", "i", "]", ".", "\" is not valid\"", ")", ";", "}", "$", "method", "=", "$", "arrayedMethod", "[", "$", "i", "]", ";", "$", "Route", "->", "action", "=", "$", "action", ";", "$", "Route", "->", "method", "=", "$", "method", ";", "$", "Route", "->", "name", "=", "$", "name", ";", "$", "this", "->", "rawRoutes", "[", "$", "name", "]", "=", "$", "Route", ";", "}", "}", "return", "$", "Route", ";", "}" ]
Add new route to list of available routes @param $method @param $route @param $action @throws InvalidMethodException
[ "Add", "new", "route", "to", "list", "of", "available", "routes" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L312-L354
Aurora-Framework/Router
src/Router.php
Router.findRoute
public function findRoute($method, $uri) { $this->method = $method; if ($this->routesTree === null) { $this->routesTree = $this->parseRoutes($this->rawRoutes); } $search = $this->normalize($uri); $node = $this->routesTree; $params = []; //loop every segment in request url, compare it, collect parameters names and values foreach ($search as $key => $v) { if (isset($node[$v["use"]])) { $node = $node[$v["use"]]; } else if (isset($node["*"])) { $subnode = $node["*"]; if (($definitions = $this->rawRoutes[$subnode["routeName"]]["definitions"]) !== null) { if (isset($definitions[$subnode["name"]])) { $definition = $definitions[$subnode["name"]]; $regex = ($definition[0] === "(") ? $definition : $this->getMatchType($definition, "(.*)"); if ($regex === "(.*)") { break; } else { if (!preg_match($regex, $v['name'])) { throw new RouteNotFoundException("Route for uri: {$uri} was not found"); } } } } // This sets node to continue $node = $subnode; $params[$subnode["name"]] = $v["name"]; } else if (isset($node["?"])) { $node = $node["?"]; if (($definitions = $this->rawRoutes[$method][$node["routeName"]]["definitions"]) !== null) { if (isset($definitions[$node["name"]])) { $definition = $definitions[$node["name"]]; $regex = ($definition[0] === "(") ? $definition : $this->getMatchType($definition, "any"); if ($regex === "(.*)") { $c = count($search); for ($i=$key; $i < $c; $i++) { $b[] = $search[$i]["use"]; } $params[$node["name"]] = $b; break; } else { if (!preg_match($regex, $v['name'])) { continue; } $node = $node["?"]; $params[$node["name"]] = $v["name"]; } } } $params[$node["name"]] = $v["name"]; } else { throw new RouteNotFoundException("Route for uri: {$uri} was not found"); } } // Check for route with optional parameters that are not in request url until valid action is found // This make tree to go to last key while (!isset($node["exec"]) && isset($node["?"])) { $node = $node["?"]; } if (isset($node["exec"])) { if (!isset($node["exec"]["method"][$method]) && !isset($node["exec"]["method"]["any"]) ) { throw new MethodNotAllowedException("Method: {$method} is not allowed for this route"); } $Route = $node["exec"]["method"][$method]; $Route->params = $params; if ($a = is_array($Route->action) || is_string($Route->action)) { if ($a) { $Route->action = [$Route->namespace.$Route->action[0], $Route->action[1]]; } else { $Route->action = $Route->namespace.$Route->action; } } return $Route; } throw new RouteNotFoundException("Route for uri: {$uri} was not found"); }
php
public function findRoute($method, $uri) { $this->method = $method; if ($this->routesTree === null) { $this->routesTree = $this->parseRoutes($this->rawRoutes); } $search = $this->normalize($uri); $node = $this->routesTree; $params = []; //loop every segment in request url, compare it, collect parameters names and values foreach ($search as $key => $v) { if (isset($node[$v["use"]])) { $node = $node[$v["use"]]; } else if (isset($node["*"])) { $subnode = $node["*"]; if (($definitions = $this->rawRoutes[$subnode["routeName"]]["definitions"]) !== null) { if (isset($definitions[$subnode["name"]])) { $definition = $definitions[$subnode["name"]]; $regex = ($definition[0] === "(") ? $definition : $this->getMatchType($definition, "(.*)"); if ($regex === "(.*)") { break; } else { if (!preg_match($regex, $v['name'])) { throw new RouteNotFoundException("Route for uri: {$uri} was not found"); } } } } // This sets node to continue $node = $subnode; $params[$subnode["name"]] = $v["name"]; } else if (isset($node["?"])) { $node = $node["?"]; if (($definitions = $this->rawRoutes[$method][$node["routeName"]]["definitions"]) !== null) { if (isset($definitions[$node["name"]])) { $definition = $definitions[$node["name"]]; $regex = ($definition[0] === "(") ? $definition : $this->getMatchType($definition, "any"); if ($regex === "(.*)") { $c = count($search); for ($i=$key; $i < $c; $i++) { $b[] = $search[$i]["use"]; } $params[$node["name"]] = $b; break; } else { if (!preg_match($regex, $v['name'])) { continue; } $node = $node["?"]; $params[$node["name"]] = $v["name"]; } } } $params[$node["name"]] = $v["name"]; } else { throw new RouteNotFoundException("Route for uri: {$uri} was not found"); } } // Check for route with optional parameters that are not in request url until valid action is found // This make tree to go to last key while (!isset($node["exec"]) && isset($node["?"])) { $node = $node["?"]; } if (isset($node["exec"])) { if (!isset($node["exec"]["method"][$method]) && !isset($node["exec"]["method"]["any"]) ) { throw new MethodNotAllowedException("Method: {$method} is not allowed for this route"); } $Route = $node["exec"]["method"][$method]; $Route->params = $params; if ($a = is_array($Route->action) || is_string($Route->action)) { if ($a) { $Route->action = [$Route->namespace.$Route->action[0], $Route->action[1]]; } else { $Route->action = $Route->namespace.$Route->action; } } return $Route; } throw new RouteNotFoundException("Route for uri: {$uri} was not found"); }
[ "public", "function", "findRoute", "(", "$", "method", ",", "$", "uri", ")", "{", "$", "this", "->", "method", "=", "$", "method", ";", "if", "(", "$", "this", "->", "routesTree", "===", "null", ")", "{", "$", "this", "->", "routesTree", "=", "$", "this", "->", "parseRoutes", "(", "$", "this", "->", "rawRoutes", ")", ";", "}", "$", "search", "=", "$", "this", "->", "normalize", "(", "$", "uri", ")", ";", "$", "node", "=", "$", "this", "->", "routesTree", ";", "$", "params", "=", "[", "]", ";", "//loop every segment in request url, compare it, collect parameters names and values", "foreach", "(", "$", "search", "as", "$", "key", "=>", "$", "v", ")", "{", "if", "(", "isset", "(", "$", "node", "[", "$", "v", "[", "\"use\"", "]", "]", ")", ")", "{", "$", "node", "=", "$", "node", "[", "$", "v", "[", "\"use\"", "]", "]", ";", "}", "else", "if", "(", "isset", "(", "$", "node", "[", "\"*\"", "]", ")", ")", "{", "$", "subnode", "=", "$", "node", "[", "\"*\"", "]", ";", "if", "(", "(", "$", "definitions", "=", "$", "this", "->", "rawRoutes", "[", "$", "subnode", "[", "\"routeName\"", "]", "]", "[", "\"definitions\"", "]", ")", "!==", "null", ")", "{", "if", "(", "isset", "(", "$", "definitions", "[", "$", "subnode", "[", "\"name\"", "]", "]", ")", ")", "{", "$", "definition", "=", "$", "definitions", "[", "$", "subnode", "[", "\"name\"", "]", "]", ";", "$", "regex", "=", "(", "$", "definition", "[", "0", "]", "===", "\"(\"", ")", "?", "$", "definition", ":", "$", "this", "->", "getMatchType", "(", "$", "definition", ",", "\"(.*)\"", ")", ";", "if", "(", "$", "regex", "===", "\"(.*)\"", ")", "{", "break", ";", "}", "else", "{", "if", "(", "!", "preg_match", "(", "$", "regex", ",", "$", "v", "[", "'name'", "]", ")", ")", "{", "throw", "new", "RouteNotFoundException", "(", "\"Route for uri: {$uri} was not found\"", ")", ";", "}", "}", "}", "}", "// This sets node to continue", "$", "node", "=", "$", "subnode", ";", "$", "params", "[", "$", "subnode", "[", "\"name\"", "]", "]", "=", "$", "v", "[", "\"name\"", "]", ";", "}", "else", "if", "(", "isset", "(", "$", "node", "[", "\"?\"", "]", ")", ")", "{", "$", "node", "=", "$", "node", "[", "\"?\"", "]", ";", "if", "(", "(", "$", "definitions", "=", "$", "this", "->", "rawRoutes", "[", "$", "method", "]", "[", "$", "node", "[", "\"routeName\"", "]", "]", "[", "\"definitions\"", "]", ")", "!==", "null", ")", "{", "if", "(", "isset", "(", "$", "definitions", "[", "$", "node", "[", "\"name\"", "]", "]", ")", ")", "{", "$", "definition", "=", "$", "definitions", "[", "$", "node", "[", "\"name\"", "]", "]", ";", "$", "regex", "=", "(", "$", "definition", "[", "0", "]", "===", "\"(\"", ")", "?", "$", "definition", ":", "$", "this", "->", "getMatchType", "(", "$", "definition", ",", "\"any\"", ")", ";", "if", "(", "$", "regex", "===", "\"(.*)\"", ")", "{", "$", "c", "=", "count", "(", "$", "search", ")", ";", "for", "(", "$", "i", "=", "$", "key", ";", "$", "i", "<", "$", "c", ";", "$", "i", "++", ")", "{", "$", "b", "[", "]", "=", "$", "search", "[", "$", "i", "]", "[", "\"use\"", "]", ";", "}", "$", "params", "[", "$", "node", "[", "\"name\"", "]", "]", "=", "$", "b", ";", "break", ";", "}", "else", "{", "if", "(", "!", "preg_match", "(", "$", "regex", ",", "$", "v", "[", "'name'", "]", ")", ")", "{", "continue", ";", "}", "$", "node", "=", "$", "node", "[", "\"?\"", "]", ";", "$", "params", "[", "$", "node", "[", "\"name\"", "]", "]", "=", "$", "v", "[", "\"name\"", "]", ";", "}", "}", "}", "$", "params", "[", "$", "node", "[", "\"name\"", "]", "]", "=", "$", "v", "[", "\"name\"", "]", ";", "}", "else", "{", "throw", "new", "RouteNotFoundException", "(", "\"Route for uri: {$uri} was not found\"", ")", ";", "}", "}", "// Check for route with optional parameters that are not in request url until valid action is found", "// This make tree to go to last key", "while", "(", "!", "isset", "(", "$", "node", "[", "\"exec\"", "]", ")", "&&", "isset", "(", "$", "node", "[", "\"?\"", "]", ")", ")", "{", "$", "node", "=", "$", "node", "[", "\"?\"", "]", ";", "}", "if", "(", "isset", "(", "$", "node", "[", "\"exec\"", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "node", "[", "\"exec\"", "]", "[", "\"method\"", "]", "[", "$", "method", "]", ")", "&&", "!", "isset", "(", "$", "node", "[", "\"exec\"", "]", "[", "\"method\"", "]", "[", "\"any\"", "]", ")", ")", "{", "throw", "new", "MethodNotAllowedException", "(", "\"Method: {$method} is not allowed for this route\"", ")", ";", "}", "$", "Route", "=", "$", "node", "[", "\"exec\"", "]", "[", "\"method\"", "]", "[", "$", "method", "]", ";", "$", "Route", "->", "params", "=", "$", "params", ";", "if", "(", "$", "a", "=", "is_array", "(", "$", "Route", "->", "action", ")", "||", "is_string", "(", "$", "Route", "->", "action", ")", ")", "{", "if", "(", "$", "a", ")", "{", "$", "Route", "->", "action", "=", "[", "$", "Route", "->", "namespace", ".", "$", "Route", "->", "action", "[", "0", "]", ",", "$", "Route", "->", "action", "[", "1", "]", "]", ";", "}", "else", "{", "$", "Route", "->", "action", "=", "$", "Route", "->", "namespace", ".", "$", "Route", "->", "action", ";", "}", "}", "return", "$", "Route", ";", "}", "throw", "new", "RouteNotFoundException", "(", "\"Route for uri: {$uri} was not found\"", ")", ";", "}" ]
Find route in route tree structure. @param $method @param $uri @return array @throws MethodNotAllowedException @throws RouteNotFoundException
[ "Find", "route", "in", "route", "tree", "structure", "." ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L365-L460
Aurora-Framework/Router
src/Router.php
Router.getMatchType
public function getMatchType($type, $default = null) { if (isset($this->matchTypes[$type])) { return $this->matchTypes[$type]; } else if ($default !== null) { return $default; } else { throw new MatchTypeNotFoundExeption("Unknow match type"); } }
php
public function getMatchType($type, $default = null) { if (isset($this->matchTypes[$type])) { return $this->matchTypes[$type]; } else if ($default !== null) { return $default; } else { throw new MatchTypeNotFoundExeption("Unknow match type"); } }
[ "public", "function", "getMatchType", "(", "$", "type", ",", "$", "default", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "matchTypes", "[", "$", "type", "]", ")", ")", "{", "return", "$", "this", "->", "matchTypes", "[", "$", "type", "]", ";", "}", "else", "if", "(", "$", "default", "!==", "null", ")", "{", "return", "$", "default", ";", "}", "else", "{", "throw", "new", "MatchTypeNotFoundExeption", "(", "\"Unknow match type\"", ")", ";", "}", "}" ]
Return regex if type is defined otherwise, returns default value. @method getMatchType @throws MatchTypeNotFoundExeption If regex of type wasn"t found @param string $type Type of allowed regex @param string $default Default return value if type is not found @return string Found Regex
[ "Return", "regex", "if", "type", "is", "defined", "otherwise", "returns", "default", "value", "." ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L474-L483
Aurora-Framework/Router
src/Router.php
Router.dump
public function dump() { if ($this->routesTree === null) { $this->routesTree = $this->parseRoutes($this->rawRoutes); } return $this->routesTree; }
php
public function dump() { if ($this->routesTree === null) { $this->routesTree = $this->parseRoutes($this->rawRoutes); } return $this->routesTree; }
[ "public", "function", "dump", "(", ")", "{", "if", "(", "$", "this", "->", "routesTree", "===", "null", ")", "{", "$", "this", "->", "routesTree", "=", "$", "this", "->", "parseRoutes", "(", "$", "this", "->", "rawRoutes", ")", ";", "}", "return", "$", "this", "->", "routesTree", ";", "}" ]
Get routes tree structure. Can be cashed and later loaded using load() method @return array|null
[ "Get", "routes", "tree", "structure", ".", "Can", "be", "cashed", "and", "later", "loaded", "using", "load", "()", "method" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L489-L496
Aurora-Framework/Router
src/Router.php
Router.normalize
public function normalize($route) { //make sure that all urls have the same structure /* Fix trailling shash */ if (mb_substr($route, -1, 1) == "/") { $route = substr($route, 0, -1); } $result = explode("/", $route); $result[0] = $this->baseUri; $ret = []; //check for dynamic and optional parameters foreach ($result as $v) { if (!$v) { continue; } if (($v[0]) === "?{") { $ret[] = [ "name" => explode("?}", mb_substr($v, 1))[0], "use" => "?" ]; } else if (($v[0]) === "{") { $ret[] = [ "name" => explode("}", mb_substr($v, 1))[0], "use" => "*" ]; } else { $ret[] = [ "name" => $v, "use" => $v ]; } } return $ret; }
php
public function normalize($route) { //make sure that all urls have the same structure /* Fix trailling shash */ if (mb_substr($route, -1, 1) == "/") { $route = substr($route, 0, -1); } $result = explode("/", $route); $result[0] = $this->baseUri; $ret = []; //check for dynamic and optional parameters foreach ($result as $v) { if (!$v) { continue; } if (($v[0]) === "?{") { $ret[] = [ "name" => explode("?}", mb_substr($v, 1))[0], "use" => "?" ]; } else if (($v[0]) === "{") { $ret[] = [ "name" => explode("}", mb_substr($v, 1))[0], "use" => "*" ]; } else { $ret[] = [ "name" => $v, "use" => $v ]; } } return $ret; }
[ "public", "function", "normalize", "(", "$", "route", ")", "{", "//make sure that all urls have the same structure", "/* Fix trailling shash */", "if", "(", "mb_substr", "(", "$", "route", ",", "-", "1", ",", "1", ")", "==", "\"/\"", ")", "{", "$", "route", "=", "substr", "(", "$", "route", ",", "0", ",", "-", "1", ")", ";", "}", "$", "result", "=", "explode", "(", "\"/\"", ",", "$", "route", ")", ";", "$", "result", "[", "0", "]", "=", "$", "this", "->", "baseUri", ";", "$", "ret", "=", "[", "]", ";", "//check for dynamic and optional parameters", "foreach", "(", "$", "result", "as", "$", "v", ")", "{", "if", "(", "!", "$", "v", ")", "{", "continue", ";", "}", "if", "(", "(", "$", "v", "[", "0", "]", ")", "===", "\"?{\"", ")", "{", "$", "ret", "[", "]", "=", "[", "\"name\"", "=>", "explode", "(", "\"?}\"", ",", "mb_substr", "(", "$", "v", ",", "1", ")", ")", "[", "0", "]", ",", "\"use\"", "=>", "\"?\"", "]", ";", "}", "else", "if", "(", "(", "$", "v", "[", "0", "]", ")", "===", "\"{\"", ")", "{", "$", "ret", "[", "]", "=", "[", "\"name\"", "=>", "explode", "(", "\"}\"", ",", "mb_substr", "(", "$", "v", ",", "1", ")", ")", "[", "0", "]", ",", "\"use\"", "=>", "\"*\"", "]", ";", "}", "else", "{", "$", "ret", "[", "]", "=", "[", "\"name\"", "=>", "$", "v", ",", "\"use\"", "=>", "$", "v", "]", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Normalize route structure and extract dynamic and optional parts @param $route @return array
[ "Normalize", "route", "structure", "and", "extract", "dynamic", "and", "optional", "parts" ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L514-L551
Aurora-Framework/Router
src/Router.php
Router.parseRoutes
protected function parseRoutes($routes) { $tree = []; foreach ($routes as $Route) { $node = &$tree; $routeSegments = $this->normalize($Route->route); foreach ($routeSegments as $segment) { if (!isset($node[$segment["use"]])) { $node[$segment["use"]] = [ "name" => $segment["name"], "routeName" => $Route->name ]; } $node = &$node[$segment["use"]]; } $Route->segments = $routeSegments; //node exec can exists only if a route is already added. //This happens when a route is added more than once with different methods. $node["exec"]["method"][$Route->method] = $Route; } return $tree; }
php
protected function parseRoutes($routes) { $tree = []; foreach ($routes as $Route) { $node = &$tree; $routeSegments = $this->normalize($Route->route); foreach ($routeSegments as $segment) { if (!isset($node[$segment["use"]])) { $node[$segment["use"]] = [ "name" => $segment["name"], "routeName" => $Route->name ]; } $node = &$node[$segment["use"]]; } $Route->segments = $routeSegments; //node exec can exists only if a route is already added. //This happens when a route is added more than once with different methods. $node["exec"]["method"][$Route->method] = $Route; } return $tree; }
[ "protected", "function", "parseRoutes", "(", "$", "routes", ")", "{", "$", "tree", "=", "[", "]", ";", "foreach", "(", "$", "routes", "as", "$", "Route", ")", "{", "$", "node", "=", "&", "$", "tree", ";", "$", "routeSegments", "=", "$", "this", "->", "normalize", "(", "$", "Route", "->", "route", ")", ";", "foreach", "(", "$", "routeSegments", "as", "$", "segment", ")", "{", "if", "(", "!", "isset", "(", "$", "node", "[", "$", "segment", "[", "\"use\"", "]", "]", ")", ")", "{", "$", "node", "[", "$", "segment", "[", "\"use\"", "]", "]", "=", "[", "\"name\"", "=>", "$", "segment", "[", "\"name\"", "]", ",", "\"routeName\"", "=>", "$", "Route", "->", "name", "]", ";", "}", "$", "node", "=", "&", "$", "node", "[", "$", "segment", "[", "\"use\"", "]", "]", ";", "}", "$", "Route", "->", "segments", "=", "$", "routeSegments", ";", "//node exec can exists only if a route is already added.", "//This happens when a route is added more than once with different methods.", "$", "node", "[", "\"exec\"", "]", "[", "\"method\"", "]", "[", "$", "Route", "->", "method", "]", "=", "$", "Route", ";", "}", "return", "$", "tree", ";", "}" ]
Build tree structure from all routes. @param $routes @return array
[ "Build", "tree", "structure", "from", "all", "routes", "." ]
train
https://github.com/Aurora-Framework/Router/blob/2731e9185a681db286cfa7da3bf1dda4db4c3685/src/Router.php#L559-L583
discordier/justtextwidgets
src/Widgets/JustASmallText.php
JustASmallText.generate
public function generate() { return sprintf( '<input type="hidden" id="ctrl_%s" name="%s" value="%s" /><div%s>%s</div>', $this->strId, $this->strName, StringUtil::specialchars($this->label ?: $this->varValue), $this->style ? ' style="' . $this->style . '"' : '', $this->label ); }
php
public function generate() { return sprintf( '<input type="hidden" id="ctrl_%s" name="%s" value="%s" /><div%s>%s</div>', $this->strId, $this->strName, StringUtil::specialchars($this->label ?: $this->varValue), $this->style ? ' style="' . $this->style . '"' : '', $this->label ); }
[ "public", "function", "generate", "(", ")", "{", "return", "sprintf", "(", "'<input type=\"hidden\" id=\"ctrl_%s\" name=\"%s\" value=\"%s\" /><div%s>%s</div>'", ",", "$", "this", "->", "strId", ",", "$", "this", "->", "strName", ",", "StringUtil", "::", "specialchars", "(", "$", "this", "->", "label", "?", ":", "$", "this", "->", "varValue", ")", ",", "$", "this", "->", "style", "?", "' style=\"'", ".", "$", "this", "->", "style", ".", "'\"'", ":", "''", ",", "$", "this", "->", "label", ")", ";", "}" ]
Generate the widget and return it as string. @return string
[ "Generate", "the", "widget", "and", "return", "it", "as", "string", "." ]
train
https://github.com/discordier/justtextwidgets/blob/585f20eec05d592bb13281ca8ef0972e956d3f06/src/Widgets/JustASmallText.php#L45-L55
bpolaszek/where
src/InsertQuery/InsertQueryBuilder.php
InsertQueryBuilder.split
public function split(int $max): iterable { $pos = 0; $total = count($this->values); while ($pos < $total) { $clone = clone $this; $clone->values = array_slice($this->values, $pos, $max); $pos += $max; yield $clone; } }
php
public function split(int $max): iterable { $pos = 0; $total = count($this->values); while ($pos < $total) { $clone = clone $this; $clone->values = array_slice($this->values, $pos, $max); $pos += $max; yield $clone; } }
[ "public", "function", "split", "(", "int", "$", "max", ")", ":", "iterable", "{", "$", "pos", "=", "0", ";", "$", "total", "=", "count", "(", "$", "this", "->", "values", ")", ";", "while", "(", "$", "pos", "<", "$", "total", ")", "{", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "values", "=", "array_slice", "(", "$", "this", "->", "values", ",", "$", "pos", ",", "$", "max", ")", ";", "$", "pos", "+=", "$", "max", ";", "yield", "$", "clone", ";", "}", "}" ]
Split into multiple INSERT statements. @param int $max @return iterable|self[]
[ "Split", "into", "multiple", "INSERT", "statements", "." ]
train
https://github.com/bpolaszek/where/blob/f40c6a97bca831c633ee3b87e2c7e3591af4fdff/src/InsertQuery/InsertQueryBuilder.php#L233-L243
qcubed/orm
src/Codegen/OptionFile.php
OptionFile.save
function save() { if (!$this->blnChanged) { return; } $flags = JSON_PRETTY_PRINT; $strContent = json_encode($this->options, $flags); file_put_contents(__CODEGEN_OPTION_FILE__, $strContent); $this->blnChanged = false; }
php
function save() { if (!$this->blnChanged) { return; } $flags = JSON_PRETTY_PRINT; $strContent = json_encode($this->options, $flags); file_put_contents(__CODEGEN_OPTION_FILE__, $strContent); $this->blnChanged = false; }
[ "function", "save", "(", ")", "{", "if", "(", "!", "$", "this", "->", "blnChanged", ")", "{", "return", ";", "}", "$", "flags", "=", "JSON_PRETTY_PRINT", ";", "$", "strContent", "=", "json_encode", "(", "$", "this", "->", "options", ",", "$", "flags", ")", ";", "file_put_contents", "(", "__CODEGEN_OPTION_FILE__", ",", "$", "strContent", ")", ";", "$", "this", "->", "blnChanged", "=", "false", ";", "}" ]
Save the current configuration into the options file.
[ "Save", "the", "current", "configuration", "into", "the", "options", "file", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Codegen/OptionFile.php#L65-L75
qcubed/orm
src/Codegen/OptionFile.php
OptionFile.setOption
public function setOption($strTableName, $strFieldName, $strOptionName, $mixValue) { $this->options[$strTableName][$strFieldName][$strOptionName] = $mixValue; $this->blnChanged = true; }
php
public function setOption($strTableName, $strFieldName, $strOptionName, $mixValue) { $this->options[$strTableName][$strFieldName][$strOptionName] = $mixValue; $this->blnChanged = true; }
[ "public", "function", "setOption", "(", "$", "strTableName", ",", "$", "strFieldName", ",", "$", "strOptionName", ",", "$", "mixValue", ")", "{", "$", "this", "->", "options", "[", "$", "strTableName", "]", "[", "$", "strFieldName", "]", "[", "$", "strOptionName", "]", "=", "$", "mixValue", ";", "$", "this", "->", "blnChanged", "=", "true", ";", "}" ]
Set an option for a widget associated with the given table and field. @param $strTableName @param $strFieldName @param $strOptionName @param $mixValue
[ "Set", "an", "option", "for", "a", "widget", "associated", "with", "the", "given", "table", "and", "field", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Codegen/OptionFile.php#L94-L98
qcubed/orm
src/Codegen/OptionFile.php
OptionFile.setOptions
public function setOptions($strClassName, $strFieldName, $mixValue) { if (empty ($mixValue)) { unset($this->options[$strClassName][$strFieldName]); } else { $this->options[$strClassName][$strFieldName] = $mixValue; } $this->blnChanged = true; }
php
public function setOptions($strClassName, $strFieldName, $mixValue) { if (empty ($mixValue)) { unset($this->options[$strClassName][$strFieldName]); } else { $this->options[$strClassName][$strFieldName] = $mixValue; } $this->blnChanged = true; }
[ "public", "function", "setOptions", "(", "$", "strClassName", ",", "$", "strFieldName", ",", "$", "mixValue", ")", "{", "if", "(", "empty", "(", "$", "mixValue", ")", ")", "{", "unset", "(", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", ")", ";", "}", "else", "{", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", "=", "$", "mixValue", ";", "}", "$", "this", "->", "blnChanged", "=", "true", ";", "}" ]
Bulk option setting. @param $strClassName @param $strFieldName @param $mixValue
[ "Bulk", "option", "setting", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Codegen/OptionFile.php#L107-L115
qcubed/orm
src/Codegen/OptionFile.php
OptionFile.unsetOption
public function unsetOption($strClassName, $strFieldName, $strOptionName) { unset ($this->options[$strClassName][$strFieldName][$strOptionName]); $this->blnChanged = true; }
php
public function unsetOption($strClassName, $strFieldName, $strOptionName) { unset ($this->options[$strClassName][$strFieldName][$strOptionName]); $this->blnChanged = true; }
[ "public", "function", "unsetOption", "(", "$", "strClassName", ",", "$", "strFieldName", ",", "$", "strOptionName", ")", "{", "unset", "(", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", "[", "$", "strOptionName", "]", ")", ";", "$", "this", "->", "blnChanged", "=", "true", ";", "}" ]
Remove the option @param $strClassName @param $strFieldName @param $strOptionName
[ "Remove", "the", "option" ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Codegen/OptionFile.php#L124-L128
qcubed/orm
src/Codegen/OptionFile.php
OptionFile.getOption
public function getOption($strClassName, $strFieldName, $strOptionName) { if (isset ($this->options[$strClassName][$strFieldName][$strOptionName])) { return $this->options[$strClassName][$strFieldName][$strOptionName]; } else { return null; } }
php
public function getOption($strClassName, $strFieldName, $strOptionName) { if (isset ($this->options[$strClassName][$strFieldName][$strOptionName])) { return $this->options[$strClassName][$strFieldName][$strOptionName]; } else { return null; } }
[ "public", "function", "getOption", "(", "$", "strClassName", ",", "$", "strFieldName", ",", "$", "strOptionName", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", "[", "$", "strOptionName", "]", ")", ")", "{", "return", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", "[", "$", "strOptionName", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Lookup an option. @param $strClassName @param $strFieldName @param $strOptionName @return mixed
[ "Lookup", "an", "option", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Codegen/OptionFile.php#L138-L145
qcubed/orm
src/Codegen/OptionFile.php
OptionFile.getOptions
public function getOptions($strClassName, $strFieldName) { if (isset($this->options[$strClassName][$strFieldName])) { return $this->options[$strClassName][$strFieldName]; } else { return array(); } }
php
public function getOptions($strClassName, $strFieldName) { if (isset($this->options[$strClassName][$strFieldName])) { return $this->options[$strClassName][$strFieldName]; } else { return array(); } }
[ "public", "function", "getOptions", "(", "$", "strClassName", ",", "$", "strFieldName", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", ")", ")", "{", "return", "$", "this", "->", "options", "[", "$", "strClassName", "]", "[", "$", "strFieldName", "]", ";", "}", "else", "{", "return", "array", "(", ")", ";", "}", "}" ]
Return all the options associated with the given table and field. @param $strClassName @param $strFieldName @return mixed
[ "Return", "all", "the", "options", "associated", "with", "the", "given", "table", "and", "field", "." ]
train
https://github.com/qcubed/orm/blob/f320eba671f20874b1f3809c5293f8c02d5b1204/src/Codegen/OptionFile.php#L153-L160
mle86/php-wq
src/WQ/Job/AbstractJob.php
AbstractJob.serialize
public function serialize() { $raw = []; foreach ($this->listProperties() as $propName) { $raw[$propName] = $this->{$propName}; } $raw['_try_index'] = $this->_try_index + 1; // ! return serialize($raw); }
php
public function serialize() { $raw = []; foreach ($this->listProperties() as $propName) { $raw[$propName] = $this->{$propName}; } $raw['_try_index'] = $this->_try_index + 1; // ! return serialize($raw); }
[ "public", "function", "serialize", "(", ")", "{", "$", "raw", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "listProperties", "(", ")", "as", "$", "propName", ")", "{", "$", "raw", "[", "$", "propName", "]", "=", "$", "this", "->", "{", "$", "propName", "}", ";", "}", "$", "raw", "[", "'_try_index'", "]", "=", "$", "this", "->", "_try_index", "+", "1", ";", "// !", "return", "serialize", "(", "$", "raw", ")", ";", "}" ]
This default implementation stores all public and protected properties. Override this method if that's not enough or if you want to do some additional pre-serialize processing, but don't forget to include <tt>{@see $_try_index}+1</tt> in the serialization!
[ "This", "default", "implementation", "stores", "all", "public", "and", "protected", "properties", "." ]
train
https://github.com/mle86/php-wq/blob/e1ca1dcfd3d40edb0085f6dfa83d90db74253de4/src/WQ/Job/AbstractJob.php#L64-L72
mle86/php-wq
src/WQ/Job/AbstractJob.php
AbstractJob.unserialize
public function unserialize($serialized) { $raw = unserialize($serialized); foreach ($this->listProperties() as $propName) { if (array_key_exists($propName, $raw)) { $this->{$propName} = $raw[$propName]; } } }
php
public function unserialize($serialized) { $raw = unserialize($serialized); foreach ($this->listProperties() as $propName) { if (array_key_exists($propName, $raw)) { $this->{$propName} = $raw[$propName]; } } }
[ "public", "function", "unserialize", "(", "$", "serialized", ")", "{", "$", "raw", "=", "unserialize", "(", "$", "serialized", ")", ";", "foreach", "(", "$", "this", "->", "listProperties", "(", ")", "as", "$", "propName", ")", "{", "if", "(", "array_key_exists", "(", "$", "propName", ",", "$", "raw", ")", ")", "{", "$", "this", "->", "{", "$", "propName", "}", "=", "$", "raw", "[", "$", "propName", "]", ";", "}", "}", "}" ]
This default implementation simply writes all serialized values to their corresponding object property. That includes the {@see $_try_index} counter. Private and/or static properties will never be written to. @param string $serialized
[ "This", "default", "implementation", "simply", "writes", "all", "serialized", "values", "to", "their", "corresponding", "object", "property", ".", "That", "includes", "the", "{", "@see", "$_try_index", "}", "counter", ".", "Private", "and", "/", "or", "static", "properties", "will", "never", "be", "written", "to", "." ]
train
https://github.com/mle86/php-wq/blob/e1ca1dcfd3d40edb0085f6dfa83d90db74253de4/src/WQ/Job/AbstractJob.php#L82-L90
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.getFolders
public function getFolders($databaseConnectionName = null, $organizationId = null) { $file = array(); if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId(); } $this->File->byTypeAndByOrganization('C', $organizationId, $databaseConnectionName)->each(function($File) use (&$file) { array_push($file, array('label'=> $File->name , 'value'=>$File->id)); }); return $file; }
php
public function getFolders($databaseConnectionName = null, $organizationId = null) { $file = array(); if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId(); } $this->File->byTypeAndByOrganization('C', $organizationId, $databaseConnectionName)->each(function($File) use (&$file) { array_push($file, array('label'=> $File->name , 'value'=>$File->id)); }); return $file; }
[ "public", "function", "getFolders", "(", "$", "databaseConnectionName", "=", "null", ",", "$", "organizationId", "=", "null", ")", "{", "$", "file", "=", "array", "(", ")", ";", "if", "(", "empty", "(", "$", "organizationId", ")", ")", "{", "$", "organizationId", "=", "$", "this", "->", "AuthenticationManager", "->", "getCurrentUserOrganizationId", "(", ")", ";", "}", "$", "this", "->", "File", "->", "byTypeAndByOrganization", "(", "'C'", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ")", "->", "each", "(", "function", "(", "$", "File", ")", "use", "(", "&", "$", "file", ")", "{", "array_push", "(", "$", "file", ",", "array", "(", "'label'", "=>", "$", "File", "->", "name", ",", "'value'", "=>", "$", "File", "->", "id", ")", ")", ";", "}", ")", ";", "return", "$", "file", ";", "}" ]
Get ... @return array An array of arrays as follows: array( array('label'=>$name0, 'value'=>$id0), array('label'=>$name1, 'value'=>$id1),…)
[ "Get", "..." ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L295-L310
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.getExtensions
public function getExtensions() { $ext = array(); foreach ($this->Config->get('file-extensions') as $key => $value) { $ext = array_merge($ext, $value['extensions']); } return $ext; }
php
public function getExtensions() { $ext = array(); foreach ($this->Config->get('file-extensions') as $key => $value) { $ext = array_merge($ext, $value['extensions']); } return $ext; }
[ "public", "function", "getExtensions", "(", ")", "{", "$", "ext", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "Config", "->", "get", "(", "'file-extensions'", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "ext", "=", "array_merge", "(", "$", "ext", ",", "$", "value", "[", "'extensions'", "]", ")", ";", "}", "return", "$", "ext", ";", "}" ]
Get extensions @param void @return array An array as follows: []
[ "Get", "extensions" ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L320-L330
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.getExtensionsByType
public function getExtensionsByType() { $ext = array(); foreach ($this->Config->get('file-extensions') as $key => $value) { $ext[$key] = $value['extensions']; } return $ext; }
php
public function getExtensionsByType() { $ext = array(); foreach ($this->Config->get('file-extensions') as $key => $value) { $ext[$key] = $value['extensions']; } return $ext; }
[ "public", "function", "getExtensionsByType", "(", ")", "{", "$", "ext", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "Config", "->", "get", "(", "'file-extensions'", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "ext", "[", "$", "key", "]", "=", "$", "value", "[", "'extensions'", "]", ";", "}", "return", "$", "ext", ";", "}" ]
Get extensions @param void @return array An array as follows: []
[ "Get", "extensions" ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L340-L350
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.getFolderChildrens
public function getFolderChildrens(array $input) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); $file = $this->File->byId($input['id']); $fileTree = array('text' => $file->name, 'state' => array('opened' => true) , 'icon' => $file->icon, 'children' => array()); $this->File->byParentId($input['id'], $organizationId)->each(function($file) use (&$fileTree) { if($file->type == 'C') { array_push($fileTree['children'], array('text' => $file->name, 'icon' => $file->icon)); } else { array_push($fileTree['children'], array('text' => $file->name, 'icon' => $file->icon)); } }); //return json_encode(array('fileTree' => $FileTree, 'balanceTypeName' => $this->Lang->get('decima-Fileing::File-management.' . $File->balance_type), 'balanceTypeValue' => $File->balance_type, 'FileTypeName' => $FileType->name, 'FileTypeValue' => $File->File_type_id)); return json_encode(array('fileTree' => $fileTree)); }
php
public function getFolderChildrens(array $input) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganization('id'); $file = $this->File->byId($input['id']); $fileTree = array('text' => $file->name, 'state' => array('opened' => true) , 'icon' => $file->icon, 'children' => array()); $this->File->byParentId($input['id'], $organizationId)->each(function($file) use (&$fileTree) { if($file->type == 'C') { array_push($fileTree['children'], array('text' => $file->name, 'icon' => $file->icon)); } else { array_push($fileTree['children'], array('text' => $file->name, 'icon' => $file->icon)); } }); //return json_encode(array('fileTree' => $FileTree, 'balanceTypeName' => $this->Lang->get('decima-Fileing::File-management.' . $File->balance_type), 'balanceTypeValue' => $File->balance_type, 'FileTypeName' => $FileType->name, 'FileTypeValue' => $File->File_type_id)); return json_encode(array('fileTree' => $fileTree)); }
[ "public", "function", "getFolderChildrens", "(", "array", "$", "input", ")", "{", "$", "organizationId", "=", "$", "this", "->", "AuthenticationManager", "->", "getCurrentUserOrganization", "(", "'id'", ")", ";", "$", "file", "=", "$", "this", "->", "File", "->", "byId", "(", "$", "input", "[", "'id'", "]", ")", ";", "$", "fileTree", "=", "array", "(", "'text'", "=>", "$", "file", "->", "name", ",", "'state'", "=>", "array", "(", "'opened'", "=>", "true", ")", ",", "'icon'", "=>", "$", "file", "->", "icon", ",", "'children'", "=>", "array", "(", ")", ")", ";", "$", "this", "->", "File", "->", "byParentId", "(", "$", "input", "[", "'id'", "]", ",", "$", "organizationId", ")", "->", "each", "(", "function", "(", "$", "file", ")", "use", "(", "&", "$", "fileTree", ")", "{", "if", "(", "$", "file", "->", "type", "==", "'C'", ")", "{", "array_push", "(", "$", "fileTree", "[", "'children'", "]", ",", "array", "(", "'text'", "=>", "$", "file", "->", "name", ",", "'icon'", "=>", "$", "file", "->", "icon", ")", ")", ";", "}", "else", "{", "array_push", "(", "$", "fileTree", "[", "'children'", "]", ",", "array", "(", "'text'", "=>", "$", "file", "->", "name", ",", "'icon'", "=>", "$", "file", "->", "icon", ")", ")", ";", "}", "}", ")", ";", "//return json_encode(array('fileTree' => $FileTree, 'balanceTypeName' => $this->Lang->get('decima-Fileing::File-management.' . $File->balance_type), 'balanceTypeValue' => $File->balance_type, 'FileTypeName' => $FileType->name, 'FileTypeValue' => $File->File_type_id));", "return", "json_encode", "(", "array", "(", "'fileTree'", "=>", "$", "fileTree", ")", ")", ";", "}" ]
Get Files children @param array $input An array as follows: array(id => $id); @return JSON encoded string A string as follows: [{"text" : $FileKey . " " . $accountName, "state" : {"opened" : true }, "icon" : $icon, "children" : [{"text" : $childAccountKey0 . " " . $childAccountName0, "icon" : $childIcon0}, …]}]
[ "Get", "Files", "children" ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L361-L379
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.getElementFiles
public function getElementFiles(array $systemReferences, $formatAsHtml = true, $databaseConnectionName = null, $organizationId = null) { $files = array(); if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId(); } foreach ($systemReferences as $systemReference) { $this->File->bySystemReferenceTypeBySystemReferenceIdAndByOrganization($this->journalConfigurations[$systemReference['appId']]['journalizedType'][0], $systemReference['systemReferenceId'], $organizationId, $databaseConnectionName)->each(function($File) use (&$files) { // array_push($files, array('id' => $File->id, 'name' => $File->name, 'size' => $this->Storage->size($File->system_route), 'url' => $File->url, 'icon' => str_replace('font-size: 2em;', '', $File->icon_html))); array_push($files, array('id' => $File->id, 'name' => $File->name, 'size' => 0, 'url' => $File->url, 'icon' => str_replace('font-size: 2em;', '', $File->icon_html))); }); } return json_encode($files); }
php
public function getElementFiles(array $systemReferences, $formatAsHtml = true, $databaseConnectionName = null, $organizationId = null) { $files = array(); if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId(); } foreach ($systemReferences as $systemReference) { $this->File->bySystemReferenceTypeBySystemReferenceIdAndByOrganization($this->journalConfigurations[$systemReference['appId']]['journalizedType'][0], $systemReference['systemReferenceId'], $organizationId, $databaseConnectionName)->each(function($File) use (&$files) { // array_push($files, array('id' => $File->id, 'name' => $File->name, 'size' => $this->Storage->size($File->system_route), 'url' => $File->url, 'icon' => str_replace('font-size: 2em;', '', $File->icon_html))); array_push($files, array('id' => $File->id, 'name' => $File->name, 'size' => 0, 'url' => $File->url, 'icon' => str_replace('font-size: 2em;', '', $File->icon_html))); }); } return json_encode($files); }
[ "public", "function", "getElementFiles", "(", "array", "$", "systemReferences", ",", "$", "formatAsHtml", "=", "true", ",", "$", "databaseConnectionName", "=", "null", ",", "$", "organizationId", "=", "null", ")", "{", "$", "files", "=", "array", "(", ")", ";", "if", "(", "empty", "(", "$", "organizationId", ")", ")", "{", "$", "organizationId", "=", "$", "this", "->", "AuthenticationManager", "->", "getCurrentUserOrganizationId", "(", ")", ";", "}", "foreach", "(", "$", "systemReferences", "as", "$", "systemReference", ")", "{", "$", "this", "->", "File", "->", "bySystemReferenceTypeBySystemReferenceIdAndByOrganization", "(", "$", "this", "->", "journalConfigurations", "[", "$", "systemReference", "[", "'appId'", "]", "]", "[", "'journalizedType'", "]", "[", "0", "]", ",", "$", "systemReference", "[", "'systemReferenceId'", "]", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ")", "->", "each", "(", "function", "(", "$", "File", ")", "use", "(", "&", "$", "files", ")", "{", "// array_push($files, array('id' => $File->id, 'name' => $File->name, 'size' => $this->Storage->size($File->system_route), 'url' => $File->url, 'icon' => str_replace('font-size: 2em;', '', $File->icon_html)));", "array_push", "(", "$", "files", ",", "array", "(", "'id'", "=>", "$", "File", "->", "id", ",", "'name'", "=>", "$", "File", "->", "name", ",", "'size'", "=>", "0", ",", "'url'", "=>", "$", "File", "->", "url", ",", "'icon'", "=>", "str_replace", "(", "'font-size: 2em;'", ",", "''", ",", "$", "File", "->", "icon_html", ")", ")", ")", ";", "}", ")", ";", "}", "return", "json_encode", "(", "$", "files", ")", ";", "}" ]
Get element files by system parent type and by system parent id @param array $systemReferences An array of array as follows: array(array(appId => $appId, systemReferenceId = $systemReferenceId), array(appId => $appId, systemReferenceId = $systemReferenceId)); @param boolean $formatAsHtml @return mixed $files An ..
[ "Get", "element", "files", "by", "system", "parent", "type", "and", "by", "system", "parent", "id" ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L391-L410
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.getLocalFilePath
public function getLocalFilePath($filename, $route, &$isTempFile, $includeStoragePath = false) { $isTempFile = false; if($this->Config->get('filesystems.default') == 'gcs') { $isTempFile = true; $this->Storage->disk('local')->put('//temp/' . $filename, $this->Storage->read($route)); $route = 'temp/' . $filename; } if($includeStoragePath) { return storage_path('app') . '/' . $route; } return $route; }
php
public function getLocalFilePath($filename, $route, &$isTempFile, $includeStoragePath = false) { $isTempFile = false; if($this->Config->get('filesystems.default') == 'gcs') { $isTempFile = true; $this->Storage->disk('local')->put('//temp/' . $filename, $this->Storage->read($route)); $route = 'temp/' . $filename; } if($includeStoragePath) { return storage_path('app') . '/' . $route; } return $route; }
[ "public", "function", "getLocalFilePath", "(", "$", "filename", ",", "$", "route", ",", "&", "$", "isTempFile", ",", "$", "includeStoragePath", "=", "false", ")", "{", "$", "isTempFile", "=", "false", ";", "if", "(", "$", "this", "->", "Config", "->", "get", "(", "'filesystems.default'", ")", "==", "'gcs'", ")", "{", "$", "isTempFile", "=", "true", ";", "$", "this", "->", "Storage", "->", "disk", "(", "'local'", ")", "->", "put", "(", "'//temp/'", ".", "$", "filename", ",", "$", "this", "->", "Storage", "->", "read", "(", "$", "route", ")", ")", ";", "$", "route", "=", "'temp/'", ".", "$", "filename", ";", "}", "if", "(", "$", "includeStoragePath", ")", "{", "return", "storage_path", "(", "'app'", ")", ".", "'/'", ".", "$", "route", ";", "}", "return", "$", "route", ";", "}" ]
Get local file path @param string $filename @param string $route @param boolean $isTempFile @param string $key @return Response
[ "Get", "local", "file", "path" ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L423-L442
mgallegos/decima-file
src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php
FileManager.saveFile
public function saveFile(array $input, $file, $openTransaction = true, $databaseConnectionName = null, $organizationId = null, $loggedUserId = null, $organizationName = null) { if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId(); } if(empty($loggedUserId)) { $loggedUserId = $this->AuthenticationManager->getLoggedUserId(); } if(empty($organizationName)) { $organizationName = $this->AuthenticationManager->getCurrentUserOrganizationName(); } //Saca la extension del archivo $ext = $file->getClientOriginalExtension(); //Solo si es Imagen $type = ''; //Recorre el arreglo en busca de coincidencias foreach ($this->Config->get('file-extensions') as $key => $value) { if(in_array(strtolower($ext), $value['extensions'])) { //Cuando lo encuentra lo asigna el icono y el color $icon = $value['icon']; $color = $value['color']; $type = $key; break; } } //El nombre del archivo sin extencion y el key que se guardara en la base $name = str_replace(' ', '_', pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)); $fileName = str_replace(' ', '_', $file->getClientOriginalName()); //Sacamos lo que nos importa de los arreglos $icon_url = $this->Config->get('file-general.url.icon'); $color_url = $this->Config->get('file-general.url.color'); $route = $storageLocation = 'organizations/'. $organizationId . '/'; //La ruta donde se guardará el archivo // if($this->Config->get('filesystems.default') == 'gcs') // { // $route = $storageLocation; // } // else // { // $route = storage_path('app/'. $storageLocation); // } $key = $this->generateFileKey($name, $organizationId, $organizationName); $url = $this->generateURL($key, $input['isPublic'], $route . $fileName, false); //Se agrega informacion importante $input = eloquent_array_filter_for_insert($input); $input = array_add($input, 'name', $fileName); $input = array_add($input, 'type', 'A'); $input = array_add($input, 'system_type', $type); $input = array_add($input, 'system_route', $route . $fileName); $input = array_add($input, 'url', $url); $input = array_add($input, 'url_html', '<a href="'. $url .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'); $input = array_add($input, 'is_public', $input['isPublic'] == '0'?false:true); $input = array_add($input, 'key', $key); $input = array_add($input, 'icon', $icon); $input = array_add($input, 'icon_html', '<i class="'. $icon .'" aria-hidden="true" style="font-size: 2em;color:'. $color .';"></i>'); $input = array_add($input, 'organization_id', $organizationId); if(!empty($input['system_reference_id'])) { $input['system_reference_type'] = $this->journalConfigurations[$input['journal_id']]['journalizedType'][0]; } //como no trae parent_file_id viene de otro form if(!empty($input['parent_folder'])) { //la informacion viene de mi form y procedo normalmente $parents = explode('/', $input['parent_folder']); $parentId = null; //Foreach invencible foreach ($parents as $folderName) { // $result = $this->File->byParentAndByOrganization($key, $organizationId); $result = $this->File->byParentByFolderNameAndByOrganization($parentId, $folderName, $organizationId, $databaseConnectionName); $count = $result->count(); if($count == 0) { //Si no existe el parent $response = json_decode($this->create(array('name' => $folderName , 'parent_file_id' => $parentId), false, $databaseConnectionName, $organizationId, $loggedUserId), true); $parentId = $response['id']; } else { //Si existe el parent $Folder = $result->first(); $parentId = $Folder->id; } } //El ultimo parentId sera donde se inserte el archivo $input['parent_file_id'] = $parentId; } $result = $this->File->byFileNameAndByOrganization($input['name'], $organizationId, $databaseConnectionName); //Verificar el nombre de los archivos if($result->count() > 0) { //Error, dos carpetas no pueden tener el mismo nombre en la misma raiz return json_encode(array('error' => $this->Lang->get('decima-file::file-management.fileAlreadyExistValidation'))); } //Quitando informacion no requerida unset($input['_token'] , $input['parent_label'] , $input['file_id'] , $input['file-uploader-file'] , $input['journal_id'], $input['parent_folder']); //Se introduce el archivo en el storage $storageLocationWithName = $storageLocation . $input['name']; $this->Storage->put( $storageLocationWithName, file_get_contents($file->getPathname()) ); if($this->Config->get('filesystems.default') == 'gcs' && $input['is_public']) { $this->Storage->setVisibility($storageLocationWithName, 'public'); $input['url'] = $this->Storage->getDriver()->getAdapter()->getUrl($storageLocationWithName); $input['url_html'] = '<a href="'. $input['url'] .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'; } //El min $minWidth = $imgWidth = ''; $sizes = array(); //El if maestro if($type == 'image') { //Instancia del driver para la redimencionar las imagenes //$this->Image->configure(array('driver' => 'imagick')); // $Img = $this->makeImage($input['system_route']); $Img = $this->Image->make($file->getPathname()); $input['width'] = $imgWidth = $Img->width(); $input['height'] = $imgHeight = $Img->height(); if(!empty($input['minWidth']) && $imgWidth < (int)$input['minWidth']) { //Desmadre para borrar el archivo $this->Storage->delete( 'organizations/'. $organizationId . '/' . $input['name']); return json_encode(array('error' => $this->Lang->get('decima-file::file-management.minWidthValidation', array('minWidth' => $input['minWidth'])))); } if(!empty($input['sameWidthAsHeight'])) { if($imgWidth != $imgHeight) { return json_encode(array('error' => $this->Lang->get('decima-file::file-management.imageNotSquareValidation'))); } } if(!empty($input['sizes'])) { //Se crea el arreglo de los sizes $sizes = explode(',' , $input['sizes']); } } //Borro el size de $input, ya que no los usare unset($input['sizes'] , $input['minWidth'], $input['isPublic'], $input['sameWidthAsHeight']); $dataFiles = array(); $this->DB->transaction(function() use ($input, $loggedUserId, $organizationId, $databaseConnectionName, $route, $sizes, $name, $ext , $organizationName , $type, $imgWidth, $icon_url, $color_url, $file, $storageLocation, &$dataFiles) { //Ingresa la primera imagen $File = $this->saveFileAux($input, $loggedUserId, $organizationId, $databaseConnectionName); array_push($dataFiles, array('id' => $File->id , 'url' => $File->url)); $originalImageRoute = $input['system_route']; foreach ($sizes as $size) { // $Img = $this->makeImage($originalImageRoute); $Img = $this->Image->make($file->getPathname()); $input['width'] = $Img->width(); $input['height'] = $Img->height(); $input['name'] = $name . '_' . $size . '.' . $ext; $input['system_route'] = $route . $input['name']; $input['key'] = $this->generateFileKey($name, $organizationId, $organizationName); $input['url'] = $this->generateURL($input['key'], $input['is_public'], $input['system_route'], false); $input['url_html'] = '<a href="'. $input['url'] .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'; $Img->resize($size, null, function ($constraint) { $constraint->aspectRatio(); }); // $Img->save($input['system_route']); $this->Storage->put( $storageLocation . $input['name'], // file_get_contents($file->getPathname()) $Img->encode() ); if($this->Config->get('filesystems.default') == 'gcs' && $input['is_public']) { $this->Storage->setVisibility($input['system_route'], 'public'); $input['url'] = $this->Storage->getDriver()->getAdapter()->getUrl($input['system_route']); $input['url_html'] = '<a href="'. $input['url'] .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'; } $File = $this->saveFileAux($input , $loggedUserId , $organizationId, $databaseConnectionName); array_push($dataFiles, array('id' => $File->id , 'url' => $File->url)); } }); return json_encode(array('success' => $this->Lang->get('form.defaultSuccessSaveMessage'), 'dataFiles' => $dataFiles)); }
php
public function saveFile(array $input, $file, $openTransaction = true, $databaseConnectionName = null, $organizationId = null, $loggedUserId = null, $organizationName = null) { if(empty($organizationId)) { $organizationId = $this->AuthenticationManager->getCurrentUserOrganizationId(); } if(empty($loggedUserId)) { $loggedUserId = $this->AuthenticationManager->getLoggedUserId(); } if(empty($organizationName)) { $organizationName = $this->AuthenticationManager->getCurrentUserOrganizationName(); } //Saca la extension del archivo $ext = $file->getClientOriginalExtension(); //Solo si es Imagen $type = ''; //Recorre el arreglo en busca de coincidencias foreach ($this->Config->get('file-extensions') as $key => $value) { if(in_array(strtolower($ext), $value['extensions'])) { //Cuando lo encuentra lo asigna el icono y el color $icon = $value['icon']; $color = $value['color']; $type = $key; break; } } //El nombre del archivo sin extencion y el key que se guardara en la base $name = str_replace(' ', '_', pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)); $fileName = str_replace(' ', '_', $file->getClientOriginalName()); //Sacamos lo que nos importa de los arreglos $icon_url = $this->Config->get('file-general.url.icon'); $color_url = $this->Config->get('file-general.url.color'); $route = $storageLocation = 'organizations/'. $organizationId . '/'; //La ruta donde se guardará el archivo // if($this->Config->get('filesystems.default') == 'gcs') // { // $route = $storageLocation; // } // else // { // $route = storage_path('app/'. $storageLocation); // } $key = $this->generateFileKey($name, $organizationId, $organizationName); $url = $this->generateURL($key, $input['isPublic'], $route . $fileName, false); //Se agrega informacion importante $input = eloquent_array_filter_for_insert($input); $input = array_add($input, 'name', $fileName); $input = array_add($input, 'type', 'A'); $input = array_add($input, 'system_type', $type); $input = array_add($input, 'system_route', $route . $fileName); $input = array_add($input, 'url', $url); $input = array_add($input, 'url_html', '<a href="'. $url .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'); $input = array_add($input, 'is_public', $input['isPublic'] == '0'?false:true); $input = array_add($input, 'key', $key); $input = array_add($input, 'icon', $icon); $input = array_add($input, 'icon_html', '<i class="'. $icon .'" aria-hidden="true" style="font-size: 2em;color:'. $color .';"></i>'); $input = array_add($input, 'organization_id', $organizationId); if(!empty($input['system_reference_id'])) { $input['system_reference_type'] = $this->journalConfigurations[$input['journal_id']]['journalizedType'][0]; } //como no trae parent_file_id viene de otro form if(!empty($input['parent_folder'])) { //la informacion viene de mi form y procedo normalmente $parents = explode('/', $input['parent_folder']); $parentId = null; //Foreach invencible foreach ($parents as $folderName) { // $result = $this->File->byParentAndByOrganization($key, $organizationId); $result = $this->File->byParentByFolderNameAndByOrganization($parentId, $folderName, $organizationId, $databaseConnectionName); $count = $result->count(); if($count == 0) { //Si no existe el parent $response = json_decode($this->create(array('name' => $folderName , 'parent_file_id' => $parentId), false, $databaseConnectionName, $organizationId, $loggedUserId), true); $parentId = $response['id']; } else { //Si existe el parent $Folder = $result->first(); $parentId = $Folder->id; } } //El ultimo parentId sera donde se inserte el archivo $input['parent_file_id'] = $parentId; } $result = $this->File->byFileNameAndByOrganization($input['name'], $organizationId, $databaseConnectionName); //Verificar el nombre de los archivos if($result->count() > 0) { //Error, dos carpetas no pueden tener el mismo nombre en la misma raiz return json_encode(array('error' => $this->Lang->get('decima-file::file-management.fileAlreadyExistValidation'))); } //Quitando informacion no requerida unset($input['_token'] , $input['parent_label'] , $input['file_id'] , $input['file-uploader-file'] , $input['journal_id'], $input['parent_folder']); //Se introduce el archivo en el storage $storageLocationWithName = $storageLocation . $input['name']; $this->Storage->put( $storageLocationWithName, file_get_contents($file->getPathname()) ); if($this->Config->get('filesystems.default') == 'gcs' && $input['is_public']) { $this->Storage->setVisibility($storageLocationWithName, 'public'); $input['url'] = $this->Storage->getDriver()->getAdapter()->getUrl($storageLocationWithName); $input['url_html'] = '<a href="'. $input['url'] .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'; } //El min $minWidth = $imgWidth = ''; $sizes = array(); //El if maestro if($type == 'image') { //Instancia del driver para la redimencionar las imagenes //$this->Image->configure(array('driver' => 'imagick')); // $Img = $this->makeImage($input['system_route']); $Img = $this->Image->make($file->getPathname()); $input['width'] = $imgWidth = $Img->width(); $input['height'] = $imgHeight = $Img->height(); if(!empty($input['minWidth']) && $imgWidth < (int)$input['minWidth']) { //Desmadre para borrar el archivo $this->Storage->delete( 'organizations/'. $organizationId . '/' . $input['name']); return json_encode(array('error' => $this->Lang->get('decima-file::file-management.minWidthValidation', array('minWidth' => $input['minWidth'])))); } if(!empty($input['sameWidthAsHeight'])) { if($imgWidth != $imgHeight) { return json_encode(array('error' => $this->Lang->get('decima-file::file-management.imageNotSquareValidation'))); } } if(!empty($input['sizes'])) { //Se crea el arreglo de los sizes $sizes = explode(',' , $input['sizes']); } } //Borro el size de $input, ya que no los usare unset($input['sizes'] , $input['minWidth'], $input['isPublic'], $input['sameWidthAsHeight']); $dataFiles = array(); $this->DB->transaction(function() use ($input, $loggedUserId, $organizationId, $databaseConnectionName, $route, $sizes, $name, $ext , $organizationName , $type, $imgWidth, $icon_url, $color_url, $file, $storageLocation, &$dataFiles) { //Ingresa la primera imagen $File = $this->saveFileAux($input, $loggedUserId, $organizationId, $databaseConnectionName); array_push($dataFiles, array('id' => $File->id , 'url' => $File->url)); $originalImageRoute = $input['system_route']; foreach ($sizes as $size) { // $Img = $this->makeImage($originalImageRoute); $Img = $this->Image->make($file->getPathname()); $input['width'] = $Img->width(); $input['height'] = $Img->height(); $input['name'] = $name . '_' . $size . '.' . $ext; $input['system_route'] = $route . $input['name']; $input['key'] = $this->generateFileKey($name, $organizationId, $organizationName); $input['url'] = $this->generateURL($input['key'], $input['is_public'], $input['system_route'], false); $input['url_html'] = '<a href="'. $input['url'] .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'; $Img->resize($size, null, function ($constraint) { $constraint->aspectRatio(); }); // $Img->save($input['system_route']); $this->Storage->put( $storageLocation . $input['name'], // file_get_contents($file->getPathname()) $Img->encode() ); if($this->Config->get('filesystems.default') == 'gcs' && $input['is_public']) { $this->Storage->setVisibility($input['system_route'], 'public'); $input['url'] = $this->Storage->getDriver()->getAdapter()->getUrl($input['system_route']); $input['url_html'] = '<a href="'. $input['url'] .'" target="_blank"><i class="'. $icon_url .'" aria-hidden="true" style="font-size: 2em;color:'. $color_url .';"></i></a>'; } $File = $this->saveFileAux($input , $loggedUserId , $organizationId, $databaseConnectionName); array_push($dataFiles, array('id' => $File->id , 'url' => $File->url)); } }); return json_encode(array('success' => $this->Lang->get('form.defaultSuccessSaveMessage'), 'dataFiles' => $dataFiles)); }
[ "public", "function", "saveFile", "(", "array", "$", "input", ",", "$", "file", ",", "$", "openTransaction", "=", "true", ",", "$", "databaseConnectionName", "=", "null", ",", "$", "organizationId", "=", "null", ",", "$", "loggedUserId", "=", "null", ",", "$", "organizationName", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "organizationId", ")", ")", "{", "$", "organizationId", "=", "$", "this", "->", "AuthenticationManager", "->", "getCurrentUserOrganizationId", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "loggedUserId", ")", ")", "{", "$", "loggedUserId", "=", "$", "this", "->", "AuthenticationManager", "->", "getLoggedUserId", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "organizationName", ")", ")", "{", "$", "organizationName", "=", "$", "this", "->", "AuthenticationManager", "->", "getCurrentUserOrganizationName", "(", ")", ";", "}", "//Saca la extension del archivo", "$", "ext", "=", "$", "file", "->", "getClientOriginalExtension", "(", ")", ";", "//Solo si es Imagen", "$", "type", "=", "''", ";", "//Recorre el arreglo en busca de coincidencias", "foreach", "(", "$", "this", "->", "Config", "->", "get", "(", "'file-extensions'", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "strtolower", "(", "$", "ext", ")", ",", "$", "value", "[", "'extensions'", "]", ")", ")", "{", "//Cuando lo encuentra lo asigna el icono y el color", "$", "icon", "=", "$", "value", "[", "'icon'", "]", ";", "$", "color", "=", "$", "value", "[", "'color'", "]", ";", "$", "type", "=", "$", "key", ";", "break", ";", "}", "}", "//El nombre del archivo sin extencion y el key que se guardara en la base", "$", "name", "=", "str_replace", "(", "' '", ",", "'_'", ",", "pathinfo", "(", "$", "file", "->", "getClientOriginalName", "(", ")", ",", "PATHINFO_FILENAME", ")", ")", ";", "$", "fileName", "=", "str_replace", "(", "' '", ",", "'_'", ",", "$", "file", "->", "getClientOriginalName", "(", ")", ")", ";", "//Sacamos lo que nos importa de los arreglos", "$", "icon_url", "=", "$", "this", "->", "Config", "->", "get", "(", "'file-general.url.icon'", ")", ";", "$", "color_url", "=", "$", "this", "->", "Config", "->", "get", "(", "'file-general.url.color'", ")", ";", "$", "route", "=", "$", "storageLocation", "=", "'organizations/'", ".", "$", "organizationId", ".", "'/'", ";", "//La ruta donde se guardará el archivo", "// if($this->Config->get('filesystems.default') == 'gcs')", "// {", "// $route = $storageLocation;", "// }", "// else", "// {", "// $route = storage_path('app/'. $storageLocation);", "// }", "$", "key", "=", "$", "this", "->", "generateFileKey", "(", "$", "name", ",", "$", "organizationId", ",", "$", "organizationName", ")", ";", "$", "url", "=", "$", "this", "->", "generateURL", "(", "$", "key", ",", "$", "input", "[", "'isPublic'", "]", ",", "$", "route", ".", "$", "fileName", ",", "false", ")", ";", "//Se agrega informacion importante", "$", "input", "=", "eloquent_array_filter_for_insert", "(", "$", "input", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'name'", ",", "$", "fileName", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'type'", ",", "'A'", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'system_type'", ",", "$", "type", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'system_route'", ",", "$", "route", ".", "$", "fileName", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'url'", ",", "$", "url", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'url_html'", ",", "'<a href=\"'", ".", "$", "url", ".", "'\" target=\"_blank\"><i class=\"'", ".", "$", "icon_url", ".", "'\" aria-hidden=\"true\" style=\"font-size: 2em;color:'", ".", "$", "color_url", ".", "';\"></i></a>'", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'is_public'", ",", "$", "input", "[", "'isPublic'", "]", "==", "'0'", "?", "false", ":", "true", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'key'", ",", "$", "key", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'icon'", ",", "$", "icon", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'icon_html'", ",", "'<i class=\"'", ".", "$", "icon", ".", "'\" aria-hidden=\"true\" style=\"font-size: 2em;color:'", ".", "$", "color", ".", "';\"></i>'", ")", ";", "$", "input", "=", "array_add", "(", "$", "input", ",", "'organization_id'", ",", "$", "organizationId", ")", ";", "if", "(", "!", "empty", "(", "$", "input", "[", "'system_reference_id'", "]", ")", ")", "{", "$", "input", "[", "'system_reference_type'", "]", "=", "$", "this", "->", "journalConfigurations", "[", "$", "input", "[", "'journal_id'", "]", "]", "[", "'journalizedType'", "]", "[", "0", "]", ";", "}", "//como no trae parent_file_id viene de otro form", "if", "(", "!", "empty", "(", "$", "input", "[", "'parent_folder'", "]", ")", ")", "{", "//la informacion viene de mi form y procedo normalmente", "$", "parents", "=", "explode", "(", "'/'", ",", "$", "input", "[", "'parent_folder'", "]", ")", ";", "$", "parentId", "=", "null", ";", "//Foreach invencible", "foreach", "(", "$", "parents", "as", "$", "folderName", ")", "{", "// $result = $this->File->byParentAndByOrganization($key, $organizationId);", "$", "result", "=", "$", "this", "->", "File", "->", "byParentByFolderNameAndByOrganization", "(", "$", "parentId", ",", "$", "folderName", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ")", ";", "$", "count", "=", "$", "result", "->", "count", "(", ")", ";", "if", "(", "$", "count", "==", "0", ")", "{", "//Si no existe el parent", "$", "response", "=", "json_decode", "(", "$", "this", "->", "create", "(", "array", "(", "'name'", "=>", "$", "folderName", ",", "'parent_file_id'", "=>", "$", "parentId", ")", ",", "false", ",", "$", "databaseConnectionName", ",", "$", "organizationId", ",", "$", "loggedUserId", ")", ",", "true", ")", ";", "$", "parentId", "=", "$", "response", "[", "'id'", "]", ";", "}", "else", "{", "//Si existe el parent", "$", "Folder", "=", "$", "result", "->", "first", "(", ")", ";", "$", "parentId", "=", "$", "Folder", "->", "id", ";", "}", "}", "//El ultimo parentId sera donde se inserte el archivo", "$", "input", "[", "'parent_file_id'", "]", "=", "$", "parentId", ";", "}", "$", "result", "=", "$", "this", "->", "File", "->", "byFileNameAndByOrganization", "(", "$", "input", "[", "'name'", "]", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ")", ";", "//Verificar el nombre de los archivos", "if", "(", "$", "result", "->", "count", "(", ")", ">", "0", ")", "{", "//Error, dos carpetas no pueden tener el mismo nombre en la misma raiz", "return", "json_encode", "(", "array", "(", "'error'", "=>", "$", "this", "->", "Lang", "->", "get", "(", "'decima-file::file-management.fileAlreadyExistValidation'", ")", ")", ")", ";", "}", "//Quitando informacion no requerida", "unset", "(", "$", "input", "[", "'_token'", "]", ",", "$", "input", "[", "'parent_label'", "]", ",", "$", "input", "[", "'file_id'", "]", ",", "$", "input", "[", "'file-uploader-file'", "]", ",", "$", "input", "[", "'journal_id'", "]", ",", "$", "input", "[", "'parent_folder'", "]", ")", ";", "//Se introduce el archivo en el storage", "$", "storageLocationWithName", "=", "$", "storageLocation", ".", "$", "input", "[", "'name'", "]", ";", "$", "this", "->", "Storage", "->", "put", "(", "$", "storageLocationWithName", ",", "file_get_contents", "(", "$", "file", "->", "getPathname", "(", ")", ")", ")", ";", "if", "(", "$", "this", "->", "Config", "->", "get", "(", "'filesystems.default'", ")", "==", "'gcs'", "&&", "$", "input", "[", "'is_public'", "]", ")", "{", "$", "this", "->", "Storage", "->", "setVisibility", "(", "$", "storageLocationWithName", ",", "'public'", ")", ";", "$", "input", "[", "'url'", "]", "=", "$", "this", "->", "Storage", "->", "getDriver", "(", ")", "->", "getAdapter", "(", ")", "->", "getUrl", "(", "$", "storageLocationWithName", ")", ";", "$", "input", "[", "'url_html'", "]", "=", "'<a href=\"'", ".", "$", "input", "[", "'url'", "]", ".", "'\" target=\"_blank\"><i class=\"'", ".", "$", "icon_url", ".", "'\" aria-hidden=\"true\" style=\"font-size: 2em;color:'", ".", "$", "color_url", ".", "';\"></i></a>'", ";", "}", "//El min", "$", "minWidth", "=", "$", "imgWidth", "=", "''", ";", "$", "sizes", "=", "array", "(", ")", ";", "//El if maestro", "if", "(", "$", "type", "==", "'image'", ")", "{", "//Instancia del driver para la redimencionar las imagenes", "//$this->Image->configure(array('driver' => 'imagick'));", "// $Img = $this->makeImage($input['system_route']);", "$", "Img", "=", "$", "this", "->", "Image", "->", "make", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "$", "input", "[", "'width'", "]", "=", "$", "imgWidth", "=", "$", "Img", "->", "width", "(", ")", ";", "$", "input", "[", "'height'", "]", "=", "$", "imgHeight", "=", "$", "Img", "->", "height", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "input", "[", "'minWidth'", "]", ")", "&&", "$", "imgWidth", "<", "(", "int", ")", "$", "input", "[", "'minWidth'", "]", ")", "{", "//Desmadre para borrar el archivo", "$", "this", "->", "Storage", "->", "delete", "(", "'organizations/'", ".", "$", "organizationId", ".", "'/'", ".", "$", "input", "[", "'name'", "]", ")", ";", "return", "json_encode", "(", "array", "(", "'error'", "=>", "$", "this", "->", "Lang", "->", "get", "(", "'decima-file::file-management.minWidthValidation'", ",", "array", "(", "'minWidth'", "=>", "$", "input", "[", "'minWidth'", "]", ")", ")", ")", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "input", "[", "'sameWidthAsHeight'", "]", ")", ")", "{", "if", "(", "$", "imgWidth", "!=", "$", "imgHeight", ")", "{", "return", "json_encode", "(", "array", "(", "'error'", "=>", "$", "this", "->", "Lang", "->", "get", "(", "'decima-file::file-management.imageNotSquareValidation'", ")", ")", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "input", "[", "'sizes'", "]", ")", ")", "{", "//Se crea el arreglo de los sizes", "$", "sizes", "=", "explode", "(", "','", ",", "$", "input", "[", "'sizes'", "]", ")", ";", "}", "}", "//Borro el size de $input, ya que no los usare", "unset", "(", "$", "input", "[", "'sizes'", "]", ",", "$", "input", "[", "'minWidth'", "]", ",", "$", "input", "[", "'isPublic'", "]", ",", "$", "input", "[", "'sameWidthAsHeight'", "]", ")", ";", "$", "dataFiles", "=", "array", "(", ")", ";", "$", "this", "->", "DB", "->", "transaction", "(", "function", "(", ")", "use", "(", "$", "input", ",", "$", "loggedUserId", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ",", "$", "route", ",", "$", "sizes", ",", "$", "name", ",", "$", "ext", ",", "$", "organizationName", ",", "$", "type", ",", "$", "imgWidth", ",", "$", "icon_url", ",", "$", "color_url", ",", "$", "file", ",", "$", "storageLocation", ",", "&", "$", "dataFiles", ")", "{", "//Ingresa la primera imagen", "$", "File", "=", "$", "this", "->", "saveFileAux", "(", "$", "input", ",", "$", "loggedUserId", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ")", ";", "array_push", "(", "$", "dataFiles", ",", "array", "(", "'id'", "=>", "$", "File", "->", "id", ",", "'url'", "=>", "$", "File", "->", "url", ")", ")", ";", "$", "originalImageRoute", "=", "$", "input", "[", "'system_route'", "]", ";", "foreach", "(", "$", "sizes", "as", "$", "size", ")", "{", "// $Img = $this->makeImage($originalImageRoute);", "$", "Img", "=", "$", "this", "->", "Image", "->", "make", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "$", "input", "[", "'width'", "]", "=", "$", "Img", "->", "width", "(", ")", ";", "$", "input", "[", "'height'", "]", "=", "$", "Img", "->", "height", "(", ")", ";", "$", "input", "[", "'name'", "]", "=", "$", "name", ".", "'_'", ".", "$", "size", ".", "'.'", ".", "$", "ext", ";", "$", "input", "[", "'system_route'", "]", "=", "$", "route", ".", "$", "input", "[", "'name'", "]", ";", "$", "input", "[", "'key'", "]", "=", "$", "this", "->", "generateFileKey", "(", "$", "name", ",", "$", "organizationId", ",", "$", "organizationName", ")", ";", "$", "input", "[", "'url'", "]", "=", "$", "this", "->", "generateURL", "(", "$", "input", "[", "'key'", "]", ",", "$", "input", "[", "'is_public'", "]", ",", "$", "input", "[", "'system_route'", "]", ",", "false", ")", ";", "$", "input", "[", "'url_html'", "]", "=", "'<a href=\"'", ".", "$", "input", "[", "'url'", "]", ".", "'\" target=\"_blank\"><i class=\"'", ".", "$", "icon_url", ".", "'\" aria-hidden=\"true\" style=\"font-size: 2em;color:'", ".", "$", "color_url", ".", "';\"></i></a>'", ";", "$", "Img", "->", "resize", "(", "$", "size", ",", "null", ",", "function", "(", "$", "constraint", ")", "{", "$", "constraint", "->", "aspectRatio", "(", ")", ";", "}", ")", ";", "// $Img->save($input['system_route']);", "$", "this", "->", "Storage", "->", "put", "(", "$", "storageLocation", ".", "$", "input", "[", "'name'", "]", ",", "// file_get_contents($file->getPathname())", "$", "Img", "->", "encode", "(", ")", ")", ";", "if", "(", "$", "this", "->", "Config", "->", "get", "(", "'filesystems.default'", ")", "==", "'gcs'", "&&", "$", "input", "[", "'is_public'", "]", ")", "{", "$", "this", "->", "Storage", "->", "setVisibility", "(", "$", "input", "[", "'system_route'", "]", ",", "'public'", ")", ";", "$", "input", "[", "'url'", "]", "=", "$", "this", "->", "Storage", "->", "getDriver", "(", ")", "->", "getAdapter", "(", ")", "->", "getUrl", "(", "$", "input", "[", "'system_route'", "]", ")", ";", "$", "input", "[", "'url_html'", "]", "=", "'<a href=\"'", ".", "$", "input", "[", "'url'", "]", ".", "'\" target=\"_blank\"><i class=\"'", ".", "$", "icon_url", ".", "'\" aria-hidden=\"true\" style=\"font-size: 2em;color:'", ".", "$", "color_url", ".", "';\"></i></a>'", ";", "}", "$", "File", "=", "$", "this", "->", "saveFileAux", "(", "$", "input", ",", "$", "loggedUserId", ",", "$", "organizationId", ",", "$", "databaseConnectionName", ")", ";", "array_push", "(", "$", "dataFiles", ",", "array", "(", "'id'", "=>", "$", "File", "->", "id", ",", "'url'", "=>", "$", "File", "->", "url", ")", ")", ";", "}", "}", ")", ";", "return", "json_encode", "(", "array", "(", "'success'", "=>", "$", "this", "->", "Lang", "->", "get", "(", "'form.defaultSuccessSaveMessage'", ")", ",", "'dataFiles'", "=>", "$", "dataFiles", ")", ")", ";", "}" ]
Save ... @param array $input An array of array as follows: array(array(appId => $appId, systemReferenceId = $systemReferenceId), array(appId => $appId, systemReferenceId = $systemReferenceId)); @param .. $file @return ... An ..
[ "Save", "..." ]
train
https://github.com/mgallegos/decima-file/blob/94c26ab40f5c4dd12e913e73376c24db27588f0b/src/Mgallegos/DecimaFile/File/Services/FileManagement/FileManager.php#L454-L682