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
caffeinated/beverage
src/Traits/BindIlluminate.php
BindIlluminate.ensureIlluminateBase
public function ensureIlluminateBase(Container $app = null) { if (! $app->bound('events')) { $app->singleton('events', $this->illuminateClasses['events']); $app['events']->fire('booting'); } if (! $app->bound('files')) { $app->bindIf('files', $this->illuminateClasses['files']); } }
php
public function ensureIlluminateBase(Container $app = null) { if (! $app->bound('events')) { $app->singleton('events', $this->illuminateClasses['events']); $app['events']->fire('booting'); } if (! $app->bound('files')) { $app->bindIf('files', $this->illuminateClasses['files']); } }
[ "public", "function", "ensureIlluminateBase", "(", "Container", "$", "app", "=", "null", ")", "{", "if", "(", "!", "$", "app", "->", "bound", "(", "'events'", ")", ")", "{", "$", "app", "->", "singleton", "(", "'events'", ",", "$", "this", "->", "illuminateClasses", "[", "'events'", "]", ")", ";", "$", "app", "[", "'events'", "]", "->", "fire", "(", "'booting'", ")", ";", "}", "if", "(", "!", "$", "app", "->", "bound", "(", "'files'", ")", ")", "{", "$", "app", "->", "bindIf", "(", "'files'", ",", "$", "this", "->", "illuminateClasses", "[", "'files'", "]", ")", ";", "}", "}" ]
Ensure the base event and file bindings are present. Required for binding anything else. @param Container $app @return void
[ "Ensure", "the", "base", "event", "and", "file", "bindings", "are", "present", ".", "Required", "for", "binding", "anything", "else", "." ]
train
https://github.com/caffeinated/beverage/blob/c7d612a1d3bc1baddc97fec60ab17224550efaf3/src/Traits/BindIlluminate.php#L68-L78
caffeinated/beverage
src/Traits/BindIlluminate.php
BindIlluminate.bindIlluminateCore
public function bindIlluminateCore(Container $app = null) { if (! $app) { $app = new Container(); } $this->ensureIlluminateBase($app); // Core classes $app->bindIf('url', $this->illuminateClasses[ 'url' ]); // Session and request $app->bindIf('session.manager', function ($app) { return new SessionManager($app); }); $app->bindIf('session', function ($app) { return $app['session.manager']->driver('array'); }, true); $app->bindIf('request', function ($app) { $request = Request::createFromGlobals(); if (method_exists($request, 'setSessionStore')) { $request->setSessionStore($app['session']); } else { $request->setSession($app['session']); } return $request; }, true); // Config $app->bindIf('path.config', function ($app) { return $this->illuminateConfigPath; }, true); $app->bindIf('config', function ($app) { $config = new Repository; $this->loadIlluminateConfig($app, $config); return $config; }, true); // Localization $app->bindIf('translation.loader', function ($app) { return new FileLoader($app['files'], 'src/config'); }); $app->bindIf('translator', function ($app) { $loader = new FileLoader($app['files'], 'lang'); return new Translator($loader, 'en'); }); return $app; }
php
public function bindIlluminateCore(Container $app = null) { if (! $app) { $app = new Container(); } $this->ensureIlluminateBase($app); // Core classes $app->bindIf('url', $this->illuminateClasses[ 'url' ]); // Session and request $app->bindIf('session.manager', function ($app) { return new SessionManager($app); }); $app->bindIf('session', function ($app) { return $app['session.manager']->driver('array'); }, true); $app->bindIf('request', function ($app) { $request = Request::createFromGlobals(); if (method_exists($request, 'setSessionStore')) { $request->setSessionStore($app['session']); } else { $request->setSession($app['session']); } return $request; }, true); // Config $app->bindIf('path.config', function ($app) { return $this->illuminateConfigPath; }, true); $app->bindIf('config', function ($app) { $config = new Repository; $this->loadIlluminateConfig($app, $config); return $config; }, true); // Localization $app->bindIf('translation.loader', function ($app) { return new FileLoader($app['files'], 'src/config'); }); $app->bindIf('translator', function ($app) { $loader = new FileLoader($app['files'], 'lang'); return new Translator($loader, 'en'); }); return $app; }
[ "public", "function", "bindIlluminateCore", "(", "Container", "$", "app", "=", "null", ")", "{", "if", "(", "!", "$", "app", ")", "{", "$", "app", "=", "new", "Container", "(", ")", ";", "}", "$", "this", "->", "ensureIlluminateBase", "(", "$", "app", ")", ";", "// Core classes", "$", "app", "->", "bindIf", "(", "'url'", ",", "$", "this", "->", "illuminateClasses", "[", "'url'", "]", ")", ";", "// Session and request", "$", "app", "->", "bindIf", "(", "'session.manager'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "SessionManager", "(", "$", "app", ")", ";", "}", ")", ";", "$", "app", "->", "bindIf", "(", "'session'", ",", "function", "(", "$", "app", ")", "{", "return", "$", "app", "[", "'session.manager'", "]", "->", "driver", "(", "'array'", ")", ";", "}", ",", "true", ")", ";", "$", "app", "->", "bindIf", "(", "'request'", ",", "function", "(", "$", "app", ")", "{", "$", "request", "=", "Request", "::", "createFromGlobals", "(", ")", ";", "if", "(", "method_exists", "(", "$", "request", ",", "'setSessionStore'", ")", ")", "{", "$", "request", "->", "setSessionStore", "(", "$", "app", "[", "'session'", "]", ")", ";", "}", "else", "{", "$", "request", "->", "setSession", "(", "$", "app", "[", "'session'", "]", ")", ";", "}", "return", "$", "request", ";", "}", ",", "true", ")", ";", "// Config", "$", "app", "->", "bindIf", "(", "'path.config'", ",", "function", "(", "$", "app", ")", "{", "return", "$", "this", "->", "illuminateConfigPath", ";", "}", ",", "true", ")", ";", "$", "app", "->", "bindIf", "(", "'config'", ",", "function", "(", "$", "app", ")", "{", "$", "config", "=", "new", "Repository", ";", "$", "this", "->", "loadIlluminateConfig", "(", "$", "app", ",", "$", "config", ")", ";", "return", "$", "config", ";", "}", ",", "true", ")", ";", "// Localization", "$", "app", "->", "bindIf", "(", "'translation.loader'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "FileLoader", "(", "$", "app", "[", "'files'", "]", ",", "'src/config'", ")", ";", "}", ")", ";", "$", "app", "->", "bindIf", "(", "'translator'", ",", "function", "(", "$", "app", ")", "{", "$", "loader", "=", "new", "FileLoader", "(", "$", "app", "[", "'files'", "]", ",", "'lang'", ")", ";", "return", "new", "Translator", "(", "$", "loader", ",", "'en'", ")", ";", "}", ")", ";", "return", "$", "app", ";", "}" ]
Bind the core classes to the Container @param Container $app @return Container
[ "Bind", "the", "core", "classes", "to", "the", "Container" ]
train
https://github.com/caffeinated/beverage/blob/c7d612a1d3bc1baddc97fec60ab17224550efaf3/src/Traits/BindIlluminate.php#L86-L142
caffeinated/beverage
src/Traits/BindIlluminate.php
BindIlluminate.bindIlluminateView
public function bindIlluminateView(Container $app = null, array $viewPaths = array(), $cachePath) { if (! $app) { $app = new Container(); } $this->ensureIlluminateBase($app); $app->bindShared('view.engine.resolver', function (Container $app) { $resolver = new EngineResolver; $resolver->register('php', function () { return new PhpEngine; }); $app->bindShared('blade.compiler', function (Container $app) { $cache = $this->illuminateCachePath; return new BladeCompiler($app['files'], $cache); }); $resolver->register('blade', function () use ($app) { return new CompilerEngine($app['blade.compiler'], $app['files']); }); return $resolver; }); $app->bindShared('view.finder', function (Container $app) { $paths = $this->illuminateViewPaths; return new FileViewFinder($app['files'], $paths); }); $app->bindShared('view', function (Container $app) { $env = new ViewFactory($app['view.engine.resolver'], $app['view.finder'], $app['events']); $env->setContainer($app); return $env; }); return $app; }
php
public function bindIlluminateView(Container $app = null, array $viewPaths = array(), $cachePath) { if (! $app) { $app = new Container(); } $this->ensureIlluminateBase($app); $app->bindShared('view.engine.resolver', function (Container $app) { $resolver = new EngineResolver; $resolver->register('php', function () { return new PhpEngine; }); $app->bindShared('blade.compiler', function (Container $app) { $cache = $this->illuminateCachePath; return new BladeCompiler($app['files'], $cache); }); $resolver->register('blade', function () use ($app) { return new CompilerEngine($app['blade.compiler'], $app['files']); }); return $resolver; }); $app->bindShared('view.finder', function (Container $app) { $paths = $this->illuminateViewPaths; return new FileViewFinder($app['files'], $paths); }); $app->bindShared('view', function (Container $app) { $env = new ViewFactory($app['view.engine.resolver'], $app['view.finder'], $app['events']); $env->setContainer($app); return $env; }); return $app; }
[ "public", "function", "bindIlluminateView", "(", "Container", "$", "app", "=", "null", ",", "array", "$", "viewPaths", "=", "array", "(", ")", ",", "$", "cachePath", ")", "{", "if", "(", "!", "$", "app", ")", "{", "$", "app", "=", "new", "Container", "(", ")", ";", "}", "$", "this", "->", "ensureIlluminateBase", "(", "$", "app", ")", ";", "$", "app", "->", "bindShared", "(", "'view.engine.resolver'", ",", "function", "(", "Container", "$", "app", ")", "{", "$", "resolver", "=", "new", "EngineResolver", ";", "$", "resolver", "->", "register", "(", "'php'", ",", "function", "(", ")", "{", "return", "new", "PhpEngine", ";", "}", ")", ";", "$", "app", "->", "bindShared", "(", "'blade.compiler'", ",", "function", "(", "Container", "$", "app", ")", "{", "$", "cache", "=", "$", "this", "->", "illuminateCachePath", ";", "return", "new", "BladeCompiler", "(", "$", "app", "[", "'files'", "]", ",", "$", "cache", ")", ";", "}", ")", ";", "$", "resolver", "->", "register", "(", "'blade'", ",", "function", "(", ")", "use", "(", "$", "app", ")", "{", "return", "new", "CompilerEngine", "(", "$", "app", "[", "'blade.compiler'", "]", ",", "$", "app", "[", "'files'", "]", ")", ";", "}", ")", ";", "return", "$", "resolver", ";", "}", ")", ";", "$", "app", "->", "bindShared", "(", "'view.finder'", ",", "function", "(", "Container", "$", "app", ")", "{", "$", "paths", "=", "$", "this", "->", "illuminateViewPaths", ";", "return", "new", "FileViewFinder", "(", "$", "app", "[", "'files'", "]", ",", "$", "paths", ")", ";", "}", ")", ";", "$", "app", "->", "bindShared", "(", "'view'", ",", "function", "(", "Container", "$", "app", ")", "{", "$", "env", "=", "new", "ViewFactory", "(", "$", "app", "[", "'view.engine.resolver'", "]", ",", "$", "app", "[", "'view.finder'", "]", ",", "$", "app", "[", "'events'", "]", ")", ";", "$", "env", "->", "setContainer", "(", "$", "app", ")", ";", "return", "$", "env", ";", "}", ")", ";", "return", "$", "app", ";", "}" ]
bindIlluminateView @param Container $app @param array $viewPaths @param string $cachePath @return Container
[ "bindIlluminateView" ]
train
https://github.com/caffeinated/beverage/blob/c7d612a1d3bc1baddc97fec60ab17224550efaf3/src/Traits/BindIlluminate.php#L152-L195
caffeinated/beverage
src/Traits/BindIlluminate.php
BindIlluminate.loadIlluminateConfig
protected function loadIlluminateConfig(Container $app, Repository $config) { foreach ($this->getIlluminateConfig($app) as $key => $path) { $config->set($key, require $path); } }
php
protected function loadIlluminateConfig(Container $app, Repository $config) { foreach ($this->getIlluminateConfig($app) as $key => $path) { $config->set($key, require $path); } }
[ "protected", "function", "loadIlluminateConfig", "(", "Container", "$", "app", ",", "Repository", "$", "config", ")", "{", "foreach", "(", "$", "this", "->", "getIlluminateConfig", "(", "$", "app", ")", "as", "$", "key", "=>", "$", "path", ")", "{", "$", "config", "->", "set", "(", "$", "key", ",", "require", "$", "path", ")", ";", "}", "}" ]
Load the configuration items from all config files. @param Container $app @param Repository $config @return void
[ "Load", "the", "configuration", "items", "from", "all", "config", "files", "." ]
train
https://github.com/caffeinated/beverage/blob/c7d612a1d3bc1baddc97fec60ab17224550efaf3/src/Traits/BindIlluminate.php#L204-L209
caffeinated/beverage
src/Traits/BindIlluminate.php
BindIlluminate.getIlluminateConfig
protected function getIlluminateConfig(Container $app) { $files = array(); foreach (Finder::create()->files()->name('*.php')->in($app['path.config']) as $file) { $files[basename($file->getRealPath(), '.php')] = $file->getRealPath(); } return $files; }
php
protected function getIlluminateConfig(Container $app) { $files = array(); foreach (Finder::create()->files()->name('*.php')->in($app['path.config']) as $file) { $files[basename($file->getRealPath(), '.php')] = $file->getRealPath(); } return $files; }
[ "protected", "function", "getIlluminateConfig", "(", "Container", "$", "app", ")", "{", "$", "files", "=", "array", "(", ")", ";", "foreach", "(", "Finder", "::", "create", "(", ")", "->", "files", "(", ")", "->", "name", "(", "'*.php'", ")", "->", "in", "(", "$", "app", "[", "'path.config'", "]", ")", "as", "$", "file", ")", "{", "$", "files", "[", "basename", "(", "$", "file", "->", "getRealPath", "(", ")", ",", "'.php'", ")", "]", "=", "$", "file", "->", "getRealPath", "(", ")", ";", "}", "return", "$", "files", ";", "}" ]
Get all configuration files from the application. @param Container $app @return array
[ "Get", "all", "configuration", "files", "from", "the", "application", "." ]
train
https://github.com/caffeinated/beverage/blob/c7d612a1d3bc1baddc97fec60ab17224550efaf3/src/Traits/BindIlluminate.php#L217-L226
Eresus/EresusCMS
src/core/Plugin/Controller/Admin/LegacySettings.php
Eresus_Plugin_Controller_Admin_LegacySettings.call
private function call($method, array $args = array()) { if (!method_exists($this->getPlugin(), $method)) { throw new Eresus_CMS_Exception_NotFound; } return call_user_func_array(array($this->getPlugin(), $method), $args); }
php
private function call($method, array $args = array()) { if (!method_exists($this->getPlugin(), $method)) { throw new Eresus_CMS_Exception_NotFound; } return call_user_func_array(array($this->getPlugin(), $method), $args); }
[ "private", "function", "call", "(", "$", "method", ",", "array", "$", "args", "=", "array", "(", ")", ")", "{", "if", "(", "!", "method_exists", "(", "$", "this", "->", "getPlugin", "(", ")", ",", "$", "method", ")", ")", "{", "throw", "new", "Eresus_CMS_Exception_NotFound", ";", "}", "return", "call_user_func_array", "(", "array", "(", "$", "this", "->", "getPlugin", "(", ")", ",", "$", "method", ")", ",", "$", "args", ")", ";", "}" ]
Вызывает метод модуля расширения @param string $method имя метода @param array $args аргументы @return mixed @throws Eresus_CMS_Exception_NotFound @since 3.01
[ "Вызывает", "метод", "модуля", "расширения" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/Plugin/Controller/Admin/LegacySettings.php#L72-L80
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Translation/src/filters/complement_filter.php
ezcTranslationComplementEmptyFilter.runFilter
public function runFilter( array $context ) { foreach ( $context as $element ) { if ( $element->status == ezcTranslationData::UNFINISHED ) { $element->translation = $element->original; } } }
php
public function runFilter( array $context ) { foreach ( $context as $element ) { if ( $element->status == ezcTranslationData::UNFINISHED ) { $element->translation = $element->original; } } }
[ "public", "function", "runFilter", "(", "array", "$", "context", ")", "{", "foreach", "(", "$", "context", "as", "$", "element", ")", "{", "if", "(", "$", "element", "->", "status", "==", "ezcTranslationData", "::", "UNFINISHED", ")", "{", "$", "element", "->", "translation", "=", "$", "element", "->", "original", ";", "}", "}", "}" ]
Filters the context $context. Applies the fillin filter on the given context. The filter replaces a missing translated string with its original. @param array(ezcTranslationData) $context @return void
[ "Filters", "the", "context", "$context", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Translation/src/filters/complement_filter.php#L57-L66
mustardandrew/muan-laravel-acl
src/Commands/Role/RemoveCommand.php
RemoveCommand.handle
public function handle() { $roleName = $this->argument('role'); if (! $role = Role::whereName($roleName)->first()) { $this->warn("Role {$roleName} not exists."); return 1; } if ($role->delete()) { echo "Role {$roleName} removed successfully.", PHP_EOL; } else { $this->error("Role {$roleName} not removed!"); } return 0; }
php
public function handle() { $roleName = $this->argument('role'); if (! $role = Role::whereName($roleName)->first()) { $this->warn("Role {$roleName} not exists."); return 1; } if ($role->delete()) { echo "Role {$roleName} removed successfully.", PHP_EOL; } else { $this->error("Role {$roleName} not removed!"); } return 0; }
[ "public", "function", "handle", "(", ")", "{", "$", "roleName", "=", "$", "this", "->", "argument", "(", "'role'", ")", ";", "if", "(", "!", "$", "role", "=", "Role", "::", "whereName", "(", "$", "roleName", ")", "->", "first", "(", ")", ")", "{", "$", "this", "->", "warn", "(", "\"Role {$roleName} not exists.\"", ")", ";", "return", "1", ";", "}", "if", "(", "$", "role", "->", "delete", "(", ")", ")", "{", "echo", "\"Role {$roleName} removed successfully.\"", ",", "PHP_EOL", ";", "}", "else", "{", "$", "this", "->", "error", "(", "\"Role {$roleName} not removed!\"", ")", ";", "}", "return", "0", ";", "}" ]
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/mustardandrew/muan-laravel-acl/blob/b5f23340b5536babb98d9fd0d727a7a3371c97d5/src/Commands/Role/RemoveCommand.php#L34-L50
wenbinye/PhalconX
src/Php/Lint.php
Lint.enterUse
public function enterUse(Node\Stmt\Use_ $node) { foreach ($node->uses as $use) { if (isset($this->uses[$use->alias])) { $this->addError(Errors\UseConflict::class, $use); } elseif ($node->type === Node\Stmt\Use_::TYPE_NORMAL) { $this->uses[$use->alias] = $use; } } }
php
public function enterUse(Node\Stmt\Use_ $node) { foreach ($node->uses as $use) { if (isset($this->uses[$use->alias])) { $this->addError(Errors\UseConflict::class, $use); } elseif ($node->type === Node\Stmt\Use_::TYPE_NORMAL) { $this->uses[$use->alias] = $use; } } }
[ "public", "function", "enterUse", "(", "Node", "\\", "Stmt", "\\", "Use_", "$", "node", ")", "{", "foreach", "(", "$", "node", "->", "uses", "as", "$", "use", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "uses", "[", "$", "use", "->", "alias", "]", ")", ")", "{", "$", "this", "->", "addError", "(", "Errors", "\\", "UseConflict", "::", "class", ",", "$", "use", ")", ";", "}", "elseif", "(", "$", "node", "->", "type", "===", "Node", "\\", "Stmt", "\\", "Use_", "::", "TYPE_NORMAL", ")", "{", "$", "this", "->", "uses", "[", "$", "use", "->", "alias", "]", "=", "$", "use", ";", "}", "}", "}" ]
collect use
[ "collect", "use" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Php/Lint.php#L134-L143
Smile-SA/CronBundle
Command/CronStatusCommand.php
CronStatusCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { /** @var CronService $cronService */ $cronService = $this->getContainer()->get('smile.cron.service'); $crons = $cronService->listCronsStatus(); $cronRows = array(); foreach ($crons as $cron) { $cronRows[] = array( $cron->getAlias(), $cron instanceof SmileCron ? $cron->getQueued()->format('d-m-Y H:i') : false, $cron instanceof SmileCron ? $cron->getStarted()->format('d-m-Y H:i') : false, $cron instanceof SmileCron ? $cron->getEnded()->format('d-m-Y H:i') : false, $cron instanceof SmileCron ? $cron->getStatus() : false ); } $table = new Table($output); $table ->setHeaders(array('Cron Alias', 'Queued', 'Started', 'Ended', 'Status')) ->setRows($cronRows) ; $table->render(); }
php
protected function execute(InputInterface $input, OutputInterface $output) { /** @var CronService $cronService */ $cronService = $this->getContainer()->get('smile.cron.service'); $crons = $cronService->listCronsStatus(); $cronRows = array(); foreach ($crons as $cron) { $cronRows[] = array( $cron->getAlias(), $cron instanceof SmileCron ? $cron->getQueued()->format('d-m-Y H:i') : false, $cron instanceof SmileCron ? $cron->getStarted()->format('d-m-Y H:i') : false, $cron instanceof SmileCron ? $cron->getEnded()->format('d-m-Y H:i') : false, $cron instanceof SmileCron ? $cron->getStatus() : false ); } $table = new Table($output); $table ->setHeaders(array('Cron Alias', 'Queued', 'Started', 'Ended', 'Status')) ->setRows($cronRows) ; $table->render(); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "/** @var CronService $cronService */", "$", "cronService", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'smile.cron.service'", ")", ";", "$", "crons", "=", "$", "cronService", "->", "listCronsStatus", "(", ")", ";", "$", "cronRows", "=", "array", "(", ")", ";", "foreach", "(", "$", "crons", "as", "$", "cron", ")", "{", "$", "cronRows", "[", "]", "=", "array", "(", "$", "cron", "->", "getAlias", "(", ")", ",", "$", "cron", "instanceof", "SmileCron", "?", "$", "cron", "->", "getQueued", "(", ")", "->", "format", "(", "'d-m-Y H:i'", ")", ":", "false", ",", "$", "cron", "instanceof", "SmileCron", "?", "$", "cron", "->", "getStarted", "(", ")", "->", "format", "(", "'d-m-Y H:i'", ")", ":", "false", ",", "$", "cron", "instanceof", "SmileCron", "?", "$", "cron", "->", "getEnded", "(", ")", "->", "format", "(", "'d-m-Y H:i'", ")", ":", "false", ",", "$", "cron", "instanceof", "SmileCron", "?", "$", "cron", "->", "getStatus", "(", ")", ":", "false", ")", ";", "}", "$", "table", "=", "new", "Table", "(", "$", "output", ")", ";", "$", "table", "->", "setHeaders", "(", "array", "(", "'Cron Alias'", ",", "'Queued'", ",", "'Started'", ",", "'Ended'", ",", "'Status'", ")", ")", "->", "setRows", "(", "$", "cronRows", ")", ";", "$", "table", "->", "render", "(", ")", ";", "}" ]
Execute command @param InputInterface $input Input interface @param OutputInterface $output Output interface
[ "Execute", "command" ]
train
https://github.com/Smile-SA/CronBundle/blob/3e6d29112915fa957cc04386ba9c6d1fc134d31f/Command/CronStatusCommand.php#L30-L54
zhouyl/mellivora
Mellivora/Cache/RedisConnector.php
RedisConnector.getCacheAdapter
public function getCacheAdapter() { $client = RedisAdapter::createConnection( $this->config['dsn'], $this->config['options'] ); return new RedisAdapter( $client, $this->config['namespace'], $this->config['lifetime'] ); }
php
public function getCacheAdapter() { $client = RedisAdapter::createConnection( $this->config['dsn'], $this->config['options'] ); return new RedisAdapter( $client, $this->config['namespace'], $this->config['lifetime'] ); }
[ "public", "function", "getCacheAdapter", "(", ")", "{", "$", "client", "=", "RedisAdapter", "::", "createConnection", "(", "$", "this", "->", "config", "[", "'dsn'", "]", ",", "$", "this", "->", "config", "[", "'options'", "]", ")", ";", "return", "new", "RedisAdapter", "(", "$", "client", ",", "$", "this", "->", "config", "[", "'namespace'", "]", ",", "$", "this", "->", "config", "[", "'lifetime'", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Cache/RedisConnector.php#L31-L43
zhouyl/mellivora
Mellivora/Cache/RedisConnector.php
RedisConnector.getSimpleCacheAdapter
public function getSimpleCacheAdapter() { $client = RedisCache::createConnection( $this->config['dsn'], $this->config['options'] ); return new RedisCache( $client, $this->config['namespace'], $this->config['lifetime'] ); }
php
public function getSimpleCacheAdapter() { $client = RedisCache::createConnection( $this->config['dsn'], $this->config['options'] ); return new RedisCache( $client, $this->config['namespace'], $this->config['lifetime'] ); }
[ "public", "function", "getSimpleCacheAdapter", "(", ")", "{", "$", "client", "=", "RedisCache", "::", "createConnection", "(", "$", "this", "->", "config", "[", "'dsn'", "]", ",", "$", "this", "->", "config", "[", "'options'", "]", ")", ";", "return", "new", "RedisCache", "(", "$", "client", ",", "$", "this", "->", "config", "[", "'namespace'", "]", ",", "$", "this", "->", "config", "[", "'lifetime'", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Cache/RedisConnector.php#L48-L60
lokhman/silex-tools
src/Silex/Console/Provider/DoctrineServiceProvider.php
DoctrineServiceProvider.boot
public function boot(Application $app) { $commands = [ new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), new \Doctrine\DBAL\Tools\Console\Command\ReservedWordsCommand(), new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), ]; $helperSet = new HelperSet([ 'db' => new ConnectionHelper($app['db']), ]); if (isset($app['orm.em'])) { // Doctrine ORM commands and helpers $helperSet->set(new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($app['orm.em']), 'em'); $commands = array_merge($commands, [ new \Doctrine\ORM\Tools\Console\Command\ClearCache\CollectionRegionCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\EntityRegionCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryRegionCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(), new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(), new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(), new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(), new \Doctrine\ORM\Tools\Console\Command\InfoCommand(), new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand(), new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(), new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(), ]); } $this->getConsole()->setHelperSet($helperSet); $this->getConsole()->addCommands($commands); }
php
public function boot(Application $app) { $commands = [ new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), new \Doctrine\DBAL\Tools\Console\Command\ReservedWordsCommand(), new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), ]; $helperSet = new HelperSet([ 'db' => new ConnectionHelper($app['db']), ]); if (isset($app['orm.em'])) { // Doctrine ORM commands and helpers $helperSet->set(new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($app['orm.em']), 'em'); $commands = array_merge($commands, [ new \Doctrine\ORM\Tools\Console\Command\ClearCache\CollectionRegionCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\EntityRegionCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryRegionCommand(), new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(), new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(), new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(), new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(), new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(), new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(), new \Doctrine\ORM\Tools\Console\Command\InfoCommand(), new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand(), new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(), new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(), ]); } $this->getConsole()->setHelperSet($helperSet); $this->getConsole()->addCommands($commands); }
[ "public", "function", "boot", "(", "Application", "$", "app", ")", "{", "$", "commands", "=", "[", "new", "\\", "Doctrine", "\\", "DBAL", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ImportCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "DBAL", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ReservedWordsCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "DBAL", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "RunSqlCommand", "(", ")", ",", "]", ";", "$", "helperSet", "=", "new", "HelperSet", "(", "[", "'db'", "=>", "new", "ConnectionHelper", "(", "$", "app", "[", "'db'", "]", ")", ",", "]", ")", ";", "if", "(", "isset", "(", "$", "app", "[", "'orm.em'", "]", ")", ")", "{", "// Doctrine ORM commands and helpers", "$", "helperSet", "->", "set", "(", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Helper", "\\", "EntityManagerHelper", "(", "$", "app", "[", "'orm.em'", "]", ")", ",", "'em'", ")", ";", "$", "commands", "=", "array_merge", "(", "$", "commands", ",", "[", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ClearCache", "\\", "CollectionRegionCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ClearCache", "\\", "EntityRegionCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ClearCache", "\\", "MetadataCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ClearCache", "\\", "QueryCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ClearCache", "\\", "QueryRegionCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ClearCache", "\\", "ResultCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "SchemaTool", "\\", "CreateCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "SchemaTool", "\\", "DropCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "SchemaTool", "\\", "UpdateCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ConvertDoctrine1SchemaCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ConvertMappingCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "EnsureProductionSettingsCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "GenerateEntitiesCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "GenerateProxiesCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "GenerateRepositoriesCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "InfoCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "MappingDescribeCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "RunDqlCommand", "(", ")", ",", "new", "\\", "Doctrine", "\\", "ORM", "\\", "Tools", "\\", "Console", "\\", "Command", "\\", "ValidateSchemaCommand", "(", ")", ",", "]", ")", ";", "}", "$", "this", "->", "getConsole", "(", ")", "->", "setHelperSet", "(", "$", "helperSet", ")", ";", "$", "this", "->", "getConsole", "(", ")", "->", "addCommands", "(", "$", "commands", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/lokhman/silex-tools/blob/91e84099479beb4e866abc88a55ed1e457a8a9e9/src/Silex/Console/Provider/DoctrineServiceProvider.php#L58-L99
Eresus/EresusCMS
src/ext-3rd/tinymce/eresus-connector.php
TinyMCEConnector.forms_html
function forms_html($form, $field) { $value = isset($form->values[$field['name']]) ? $form->values[$field['name']] : (isset($field['value'])?$field['value']:''); $preset = isset($field['preset']) ? $field['preset'] : 'default'; $result = "\t\t" . '<tr><td colspan="2">' . $field['label'] . '<br /><textarea name="wyswyg_' . $field['name'] . '" class="tinymce_' . $preset . '" cols="80" rows="25" style="width: 100%; height: ' . $field['height'].';">'.str_replace('$(httpRoot)', Eresus_CMS::getLegacyKernel()->root, EncodeHTML($value)).'</textarea></td></tr>'."\n"; if (!self::$scriptsInstalled) { Eresus_Kernel::app()->getPage()->linkScripts($this->root.'tiny_mce.js'); Eresus_Kernel::app()->getPage()->linkScripts($this->root.'presets/'.$preset.'.js'); self::$scriptsInstalled = true; } return $result; }
php
function forms_html($form, $field) { $value = isset($form->values[$field['name']]) ? $form->values[$field['name']] : (isset($field['value'])?$field['value']:''); $preset = isset($field['preset']) ? $field['preset'] : 'default'; $result = "\t\t" . '<tr><td colspan="2">' . $field['label'] . '<br /><textarea name="wyswyg_' . $field['name'] . '" class="tinymce_' . $preset . '" cols="80" rows="25" style="width: 100%; height: ' . $field['height'].';">'.str_replace('$(httpRoot)', Eresus_CMS::getLegacyKernel()->root, EncodeHTML($value)).'</textarea></td></tr>'."\n"; if (!self::$scriptsInstalled) { Eresus_Kernel::app()->getPage()->linkScripts($this->root.'tiny_mce.js'); Eresus_Kernel::app()->getPage()->linkScripts($this->root.'presets/'.$preset.'.js'); self::$scriptsInstalled = true; } return $result; }
[ "function", "forms_html", "(", "$", "form", ",", "$", "field", ")", "{", "$", "value", "=", "isset", "(", "$", "form", "->", "values", "[", "$", "field", "[", "'name'", "]", "]", ")", "?", "$", "form", "->", "values", "[", "$", "field", "[", "'name'", "]", "]", ":", "(", "isset", "(", "$", "field", "[", "'value'", "]", ")", "?", "$", "field", "[", "'value'", "]", ":", "''", ")", ";", "$", "preset", "=", "isset", "(", "$", "field", "[", "'preset'", "]", ")", "?", "$", "field", "[", "'preset'", "]", ":", "'default'", ";", "$", "result", "=", "\"\\t\\t\"", ".", "'<tr><td colspan=\"2\">'", ".", "$", "field", "[", "'label'", "]", ".", "'<br /><textarea name=\"wyswyg_'", ".", "$", "field", "[", "'name'", "]", ".", "'\" class=\"tinymce_'", ".", "$", "preset", ".", "'\" cols=\"80\" rows=\"25\" style=\"width: 100%; height: '", ".", "$", "field", "[", "'height'", "]", ".", "';\">'", ".", "str_replace", "(", "'$(httpRoot)'", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "root", ",", "EncodeHTML", "(", "$", "value", ")", ")", ".", "'</textarea></td></tr>'", ".", "\"\\n\"", ";", "if", "(", "!", "self", "::", "$", "scriptsInstalled", ")", "{", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "linkScripts", "(", "$", "this", "->", "root", ".", "'tiny_mce.js'", ")", ";", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", "->", "linkScripts", "(", "$", "this", "->", "root", ".", "'presets/'", ".", "$", "preset", ".", "'.js'", ")", ";", "self", "::", "$", "scriptsInstalled", "=", "true", ";", "}", "return", "$", "result", ";", "}" ]
Возвращает разметку для подключения WYSIWYG-редактора @param Form $form @param array $field @return array
[ "Возвращает", "разметку", "для", "подключения", "WYSIWYG", "-", "редактора" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/eresus-connector.php#L54-L74
Eresus/EresusCMS
src/ext-3rd/tinymce/eresus-connector.php
TinyMCEConnector.getWYSIWYG
public function getWYSIWYG(array $field) { $value = isset($field['value']) ? $field['value'] : ''; $preset = isset($field['preset']) ? $field['preset'] : 'default'; $html = '<textarea name="wyswyg_' . $field['name'] . '" class="tinymce_' . $preset . '" cols="80" rows="25" style="height: ' . $field['height'] . ';">' . str_replace('$(httpRoot)', Eresus_CMS::getLegacyKernel()->root, EncodeHTML($value)) . '</textarea>'; if (!self::$scriptsInstalled) { $html .= '<script type="text/javascript" src="' . $this->root . 'tiny_mce.js"></script>' . '<script type="text/javascript" src="' . $this->root . 'presets/' . $preset . '.js"></script>'; self::$scriptsInstalled = true; } return $html; }
php
public function getWYSIWYG(array $field) { $value = isset($field['value']) ? $field['value'] : ''; $preset = isset($field['preset']) ? $field['preset'] : 'default'; $html = '<textarea name="wyswyg_' . $field['name'] . '" class="tinymce_' . $preset . '" cols="80" rows="25" style="height: ' . $field['height'] . ';">' . str_replace('$(httpRoot)', Eresus_CMS::getLegacyKernel()->root, EncodeHTML($value)) . '</textarea>'; if (!self::$scriptsInstalled) { $html .= '<script type="text/javascript" src="' . $this->root . 'tiny_mce.js"></script>' . '<script type="text/javascript" src="' . $this->root . 'presets/' . $preset . '.js"></script>'; self::$scriptsInstalled = true; } return $html; }
[ "public", "function", "getWYSIWYG", "(", "array", "$", "field", ")", "{", "$", "value", "=", "isset", "(", "$", "field", "[", "'value'", "]", ")", "?", "$", "field", "[", "'value'", "]", ":", "''", ";", "$", "preset", "=", "isset", "(", "$", "field", "[", "'preset'", "]", ")", "?", "$", "field", "[", "'preset'", "]", ":", "'default'", ";", "$", "html", "=", "'<textarea name=\"wyswyg_'", ".", "$", "field", "[", "'name'", "]", ".", "'\" class=\"tinymce_'", ".", "$", "preset", ".", "'\" cols=\"80\" rows=\"25\" style=\"height: '", ".", "$", "field", "[", "'height'", "]", ".", "';\">'", ".", "str_replace", "(", "'$(httpRoot)'", ",", "Eresus_CMS", "::", "getLegacyKernel", "(", ")", "->", "root", ",", "EncodeHTML", "(", "$", "value", ")", ")", ".", "'</textarea>'", ";", "if", "(", "!", "self", "::", "$", "scriptsInstalled", ")", "{", "$", "html", ".=", "'<script type=\"text/javascript\" src=\"'", ".", "$", "this", "->", "root", ".", "'tiny_mce.js\"></script>'", ".", "'<script type=\"text/javascript\" src=\"'", ".", "$", "this", "->", "root", ".", "'presets/'", ".", "$", "preset", ".", "'.js\"></script>'", ";", "self", "::", "$", "scriptsInstalled", "=", "true", ";", "}", "return", "$", "html", ";", "}" ]
Возвращает разметку редактора @param array $field @return string @since 2.16
[ "Возвращает", "разметку", "редактора" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/ext-3rd/tinymce/eresus-connector.php#L86-L103
o2system/email
src/Protocols/SendMailProtocol.php
SendmailProtocol.sending
protected function sending(Message $message) { $phpMailer = new PHPMailer(); $phpMailer->isSendmail(); // Set from if (false !== ($from = $message->getFrom())) { $phpMailer->setFrom($from->getEmail(), $from->getName()); } // Set recipient if (false !== ($to = $message->getTo())) { foreach ($to as $address) { if ($address instanceof Address) { $phpMailer->addAddress($address->getEmail(), $address->getName()); } } } // Set reply-to if (false !== ($replyTo = $message->getReplyTo())) { $phpMailer->addReplyTo($replyTo->getEmail(), $replyTo->getName()); } // Set content-type if ($message->getContentType() === 'html') { $phpMailer->isHTML(true); } // Set subject, body & alt-body $phpMailer->Subject = $message->getSubject(); $phpMailer->Body = $message->getBody(); $phpMailer->AltBody = $message->getAltBody(); if (false !== ($attachments = $message->getAttachments())) { foreach ($attachments as $filename => $attachment) { $phpMailer->addAttachment($attachment, $filename); } } if ( ! $phpMailer->send()) { $this->addErrors([ $phpMailer->ErrorInfo, ]); return false; } return true; }
php
protected function sending(Message $message) { $phpMailer = new PHPMailer(); $phpMailer->isSendmail(); // Set from if (false !== ($from = $message->getFrom())) { $phpMailer->setFrom($from->getEmail(), $from->getName()); } // Set recipient if (false !== ($to = $message->getTo())) { foreach ($to as $address) { if ($address instanceof Address) { $phpMailer->addAddress($address->getEmail(), $address->getName()); } } } // Set reply-to if (false !== ($replyTo = $message->getReplyTo())) { $phpMailer->addReplyTo($replyTo->getEmail(), $replyTo->getName()); } // Set content-type if ($message->getContentType() === 'html') { $phpMailer->isHTML(true); } // Set subject, body & alt-body $phpMailer->Subject = $message->getSubject(); $phpMailer->Body = $message->getBody(); $phpMailer->AltBody = $message->getAltBody(); if (false !== ($attachments = $message->getAttachments())) { foreach ($attachments as $filename => $attachment) { $phpMailer->addAttachment($attachment, $filename); } } if ( ! $phpMailer->send()) { $this->addErrors([ $phpMailer->ErrorInfo, ]); return false; } return true; }
[ "protected", "function", "sending", "(", "Message", "$", "message", ")", "{", "$", "phpMailer", "=", "new", "PHPMailer", "(", ")", ";", "$", "phpMailer", "->", "isSendmail", "(", ")", ";", "// Set from\r", "if", "(", "false", "!==", "(", "$", "from", "=", "$", "message", "->", "getFrom", "(", ")", ")", ")", "{", "$", "phpMailer", "->", "setFrom", "(", "$", "from", "->", "getEmail", "(", ")", ",", "$", "from", "->", "getName", "(", ")", ")", ";", "}", "// Set recipient\r", "if", "(", "false", "!==", "(", "$", "to", "=", "$", "message", "->", "getTo", "(", ")", ")", ")", "{", "foreach", "(", "$", "to", "as", "$", "address", ")", "{", "if", "(", "$", "address", "instanceof", "Address", ")", "{", "$", "phpMailer", "->", "addAddress", "(", "$", "address", "->", "getEmail", "(", ")", ",", "$", "address", "->", "getName", "(", ")", ")", ";", "}", "}", "}", "// Set reply-to\r", "if", "(", "false", "!==", "(", "$", "replyTo", "=", "$", "message", "->", "getReplyTo", "(", ")", ")", ")", "{", "$", "phpMailer", "->", "addReplyTo", "(", "$", "replyTo", "->", "getEmail", "(", ")", ",", "$", "replyTo", "->", "getName", "(", ")", ")", ";", "}", "// Set content-type\r", "if", "(", "$", "message", "->", "getContentType", "(", ")", "===", "'html'", ")", "{", "$", "phpMailer", "->", "isHTML", "(", "true", ")", ";", "}", "// Set subject, body & alt-body\r", "$", "phpMailer", "->", "Subject", "=", "$", "message", "->", "getSubject", "(", ")", ";", "$", "phpMailer", "->", "Body", "=", "$", "message", "->", "getBody", "(", ")", ";", "$", "phpMailer", "->", "AltBody", "=", "$", "message", "->", "getAltBody", "(", ")", ";", "if", "(", "false", "!==", "(", "$", "attachments", "=", "$", "message", "->", "getAttachments", "(", ")", ")", ")", "{", "foreach", "(", "$", "attachments", "as", "$", "filename", "=>", "$", "attachment", ")", "{", "$", "phpMailer", "->", "addAttachment", "(", "$", "attachment", ",", "$", "filename", ")", ";", "}", "}", "if", "(", "!", "$", "phpMailer", "->", "send", "(", ")", ")", "{", "$", "this", "->", "addErrors", "(", "[", "$", "phpMailer", "->", "ErrorInfo", ",", "]", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
MailProtocol::sending Protocol message sending process. @param Message $message @return bool @throws \PHPMailer\PHPMailer\Exception
[ "MailProtocol", "::", "sending" ]
train
https://github.com/o2system/email/blob/7c64b73f539cac8df4b2aaef474b29b949067898/src/Protocols/SendMailProtocol.php#L39-L88
neat-php/database
classes/Table.php
Table.findOne
public function findOne($conditions, string $orderBy = null): Result { $query = $this->query() ->where($conditions) ->limit(1); if ($orderBy) { $query->orderBy($orderBy); } return $query->query(); }
php
public function findOne($conditions, string $orderBy = null): Result { $query = $this->query() ->where($conditions) ->limit(1); if ($orderBy) { $query->orderBy($orderBy); } return $query->query(); }
[ "public", "function", "findOne", "(", "$", "conditions", ",", "string", "$", "orderBy", "=", "null", ")", ":", "Result", "{", "$", "query", "=", "$", "this", "->", "query", "(", ")", "->", "where", "(", "$", "conditions", ")", "->", "limit", "(", "1", ")", ";", "if", "(", "$", "orderBy", ")", "{", "$", "query", "->", "orderBy", "(", "$", "orderBy", ")", ";", "}", "return", "$", "query", "->", "query", "(", ")", ";", "}" ]
Builds the query for the given conditions and executes it Will return an result with 1 or 0 rows @param array|string $conditions @param string|null $orderBy @return Result
[ "Builds", "the", "query", "for", "the", "given", "conditions", "and", "executes", "it", "Will", "return", "an", "result", "with", "1", "or", "0", "rows" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Table.php#L77-L88
neat-php/database
classes/Table.php
Table.validateIdentifier
public function validateIdentifier($id) { $printed = print_r($id, true); if (count($this->keys) > 1 && !is_array($id)) { throw new \RuntimeException("Entity $this->name has a composed key, finding by id requires an array, given: $printed"); } if (count($this->keys) !== count($id)) { $keys = print_r($this->keys, true); throw new \RuntimeException("Entity $this->name requires the following keys: $keys, given: $printed"); } }
php
public function validateIdentifier($id) { $printed = print_r($id, true); if (count($this->keys) > 1 && !is_array($id)) { throw new \RuntimeException("Entity $this->name has a composed key, finding by id requires an array, given: $printed"); } if (count($this->keys) !== count($id)) { $keys = print_r($this->keys, true); throw new \RuntimeException("Entity $this->name requires the following keys: $keys, given: $printed"); } }
[ "public", "function", "validateIdentifier", "(", "$", "id", ")", "{", "$", "printed", "=", "print_r", "(", "$", "id", ",", "true", ")", ";", "if", "(", "count", "(", "$", "this", "->", "keys", ")", ">", "1", "&&", "!", "is_array", "(", "$", "id", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Entity $this->name has a composed key, finding by id requires an array, given: $printed\"", ")", ";", "}", "if", "(", "count", "(", "$", "this", "->", "keys", ")", "!==", "count", "(", "$", "id", ")", ")", "{", "$", "keys", "=", "print_r", "(", "$", "this", "->", "keys", ",", "true", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "\"Entity $this->name requires the following keys: $keys, given: $printed\"", ")", ";", "}", "}" ]
Validates the identifier to prevent unexpected behaviour @param int|string|array $id
[ "Validates", "the", "identifier", "to", "prevent", "unexpected", "behaviour" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Table.php#L148-L158
neat-php/database
classes/Table.php
Table.where
public function where($id) { $this->validateIdentifier($id); if (!is_array($id)) { $key = reset($this->keys); return [$key => $id]; } else { return $id; } }
php
public function where($id) { $this->validateIdentifier($id); if (!is_array($id)) { $key = reset($this->keys); return [$key => $id]; } else { return $id; } }
[ "public", "function", "where", "(", "$", "id", ")", "{", "$", "this", "->", "validateIdentifier", "(", "$", "id", ")", ";", "if", "(", "!", "is_array", "(", "$", "id", ")", ")", "{", "$", "key", "=", "reset", "(", "$", "this", "->", "keys", ")", ";", "return", "[", "$", "key", "=>", "$", "id", "]", ";", "}", "else", "{", "return", "$", "id", ";", "}", "}" ]
Creates the where condition for the identifier @param int|string|array $id @return array
[ "Creates", "the", "where", "condition", "for", "the", "identifier" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Table.php#L166-L176
gdbots/iam-php
src/SearchUsersRequestHandler.php
SearchUsersRequestHandler.beforeSearchNodes
protected function beforeSearchNodes(SearchNodesRequest $request, ParsedQuery $parsedQuery): void { parent::beforeSearchNodes($request, $parsedQuery); $required = BoolOperator::REQUIRED(); foreach (['is_staff', 'is_blocked'] as $trinary) { if (Trinary::UNKNOWN !== $request->get($trinary)) { $parsedQuery->addNode( new Field( $trinary, new Word(Trinary::TRUE_VAL === $request->get($trinary) ? 'true' : 'false', $required), $required ) ); } } }
php
protected function beforeSearchNodes(SearchNodesRequest $request, ParsedQuery $parsedQuery): void { parent::beforeSearchNodes($request, $parsedQuery); $required = BoolOperator::REQUIRED(); foreach (['is_staff', 'is_blocked'] as $trinary) { if (Trinary::UNKNOWN !== $request->get($trinary)) { $parsedQuery->addNode( new Field( $trinary, new Word(Trinary::TRUE_VAL === $request->get($trinary) ? 'true' : 'false', $required), $required ) ); } } }
[ "protected", "function", "beforeSearchNodes", "(", "SearchNodesRequest", "$", "request", ",", "ParsedQuery", "$", "parsedQuery", ")", ":", "void", "{", "parent", "::", "beforeSearchNodes", "(", "$", "request", ",", "$", "parsedQuery", ")", ";", "$", "required", "=", "BoolOperator", "::", "REQUIRED", "(", ")", ";", "foreach", "(", "[", "'is_staff'", ",", "'is_blocked'", "]", "as", "$", "trinary", ")", "{", "if", "(", "Trinary", "::", "UNKNOWN", "!==", "$", "request", "->", "get", "(", "$", "trinary", ")", ")", "{", "$", "parsedQuery", "->", "addNode", "(", "new", "Field", "(", "$", "trinary", ",", "new", "Word", "(", "Trinary", "::", "TRUE_VAL", "===", "$", "request", "->", "get", "(", "$", "trinary", ")", "?", "'true'", ":", "'false'", ",", "$", "required", ")", ",", "$", "required", ")", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/gdbots/iam-php/blob/3dbfa602de183a7ac5fb5140304e8cf4c4b15ab3/src/SearchUsersRequestHandler.php#L20-L36
webdevvie/pheanstalk-task-queue-bundle
Command/WorkerCommand.php
WorkerCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->initialiseWorker($input, $output); $this->keepAliveTimeout = $input->getOption('keepaliveTimeout', 60); $this->lastKeepdbalive = time(); $this->taskCommandGenerator = $this->getContainer()->get( 'webdevvie_pheanstalk_taskqueue.task_command_generator' ); $this->verboseOutput("<info>Taskworker observing tube:</info>" . $this->tube); $this->verboseOutput("<info>Keepalive for db timeout in seconds:</info>" . $this->keepAliveTimeout); while ($this->keepWorking) { $this->keepDbAlive(); try { $taskObject = $this->taskQueueService->reserveTask($this->tube); } catch (TaskQueueServiceException $exception) { $this->verboseOutput("<error>Exception from service:</error>" . $exception->getMessage()); $this->logException($exception); $taskObject = false; } if ($taskObject instanceof WorkPackage) { $this->runTask($taskObject); } elseif (is_object($taskObject)) { $this->verboseOutput("Ignoring type:" . get_class($taskObject)); } if ($this->shutdownNow || $this->shutdownGracefully) { $this->keepWorking = false; } } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->initialiseWorker($input, $output); $this->keepAliveTimeout = $input->getOption('keepaliveTimeout', 60); $this->lastKeepdbalive = time(); $this->taskCommandGenerator = $this->getContainer()->get( 'webdevvie_pheanstalk_taskqueue.task_command_generator' ); $this->verboseOutput("<info>Taskworker observing tube:</info>" . $this->tube); $this->verboseOutput("<info>Keepalive for db timeout in seconds:</info>" . $this->keepAliveTimeout); while ($this->keepWorking) { $this->keepDbAlive(); try { $taskObject = $this->taskQueueService->reserveTask($this->tube); } catch (TaskQueueServiceException $exception) { $this->verboseOutput("<error>Exception from service:</error>" . $exception->getMessage()); $this->logException($exception); $taskObject = false; } if ($taskObject instanceof WorkPackage) { $this->runTask($taskObject); } elseif (is_object($taskObject)) { $this->verboseOutput("Ignoring type:" . get_class($taskObject)); } if ($this->shutdownNow || $this->shutdownGracefully) { $this->keepWorking = false; } } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "initialiseWorker", "(", "$", "input", ",", "$", "output", ")", ";", "$", "this", "->", "keepAliveTimeout", "=", "$", "input", "->", "getOption", "(", "'keepaliveTimeout'", ",", "60", ")", ";", "$", "this", "->", "lastKeepdbalive", "=", "time", "(", ")", ";", "$", "this", "->", "taskCommandGenerator", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'webdevvie_pheanstalk_taskqueue.task_command_generator'", ")", ";", "$", "this", "->", "verboseOutput", "(", "\"<info>Taskworker observing tube:</info>\"", ".", "$", "this", "->", "tube", ")", ";", "$", "this", "->", "verboseOutput", "(", "\"<info>Keepalive for db timeout in seconds:</info>\"", ".", "$", "this", "->", "keepAliveTimeout", ")", ";", "while", "(", "$", "this", "->", "keepWorking", ")", "{", "$", "this", "->", "keepDbAlive", "(", ")", ";", "try", "{", "$", "taskObject", "=", "$", "this", "->", "taskQueueService", "->", "reserveTask", "(", "$", "this", "->", "tube", ")", ";", "}", "catch", "(", "TaskQueueServiceException", "$", "exception", ")", "{", "$", "this", "->", "verboseOutput", "(", "\"<error>Exception from service:</error>\"", ".", "$", "exception", "->", "getMessage", "(", ")", ")", ";", "$", "this", "->", "logException", "(", "$", "exception", ")", ";", "$", "taskObject", "=", "false", ";", "}", "if", "(", "$", "taskObject", "instanceof", "WorkPackage", ")", "{", "$", "this", "->", "runTask", "(", "$", "taskObject", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "taskObject", ")", ")", "{", "$", "this", "->", "verboseOutput", "(", "\"Ignoring type:\"", ".", "get_class", "(", "$", "taskObject", ")", ")", ";", "}", "if", "(", "$", "this", "->", "shutdownNow", "||", "$", "this", "->", "shutdownGracefully", ")", "{", "$", "this", "->", "keepWorking", "=", "false", ";", "}", "}", "}" ]
{@inheritDoc} @param InputInterface $input @param OutputInterface $output @return void @throws \InvalidArgumentException
[ "{", "@inheritDoc", "}" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/WorkerCommand.php#L71-L99
webdevvie/pheanstalk-task-queue-bundle
Command/WorkerCommand.php
WorkerCommand.handleRunningProcess
private function handleRunningProcess( Process $process, &$runningCommand, &$failed, &$hasReceivedSignal, &$exitCode, &$exitCodeText ) { if ($process->isRunning()) { if ($hasReceivedSignal) { return; } //force it to shut down now! if ($this->shutdownNow) { $this->output->write("[RECEIVED SIGNAL] Shutting down now!"); $process->stop(0); $hasReceivedSignal = true; $this->keepWorking = false; $runningCommand = false; } if ((!$this->keepWorking || $this->shutdownGracefully)) { //we need to keep this running until we are finished... $this->output->write("[RECEIVED SIGNAL] will shutdown after finishing task"); $hasReceivedSignal = true; } } else { $runningCommand = false; $exitCode = $process->getExitCode(); $exitCodeText = $process->getExitCode(); if ($exitCode != 0) { $failed = true; } } }
php
private function handleRunningProcess( Process $process, &$runningCommand, &$failed, &$hasReceivedSignal, &$exitCode, &$exitCodeText ) { if ($process->isRunning()) { if ($hasReceivedSignal) { return; } //force it to shut down now! if ($this->shutdownNow) { $this->output->write("[RECEIVED SIGNAL] Shutting down now!"); $process->stop(0); $hasReceivedSignal = true; $this->keepWorking = false; $runningCommand = false; } if ((!$this->keepWorking || $this->shutdownGracefully)) { //we need to keep this running until we are finished... $this->output->write("[RECEIVED SIGNAL] will shutdown after finishing task"); $hasReceivedSignal = true; } } else { $runningCommand = false; $exitCode = $process->getExitCode(); $exitCodeText = $process->getExitCode(); if ($exitCode != 0) { $failed = true; } } }
[ "private", "function", "handleRunningProcess", "(", "Process", "$", "process", ",", "&", "$", "runningCommand", ",", "&", "$", "failed", ",", "&", "$", "hasReceivedSignal", ",", "&", "$", "exitCode", ",", "&", "$", "exitCodeText", ")", "{", "if", "(", "$", "process", "->", "isRunning", "(", ")", ")", "{", "if", "(", "$", "hasReceivedSignal", ")", "{", "return", ";", "}", "//force it to shut down now!", "if", "(", "$", "this", "->", "shutdownNow", ")", "{", "$", "this", "->", "output", "->", "write", "(", "\"[RECEIVED SIGNAL] Shutting down now!\"", ")", ";", "$", "process", "->", "stop", "(", "0", ")", ";", "$", "hasReceivedSignal", "=", "true", ";", "$", "this", "->", "keepWorking", "=", "false", ";", "$", "runningCommand", "=", "false", ";", "}", "if", "(", "(", "!", "$", "this", "->", "keepWorking", "||", "$", "this", "->", "shutdownGracefully", ")", ")", "{", "//we need to keep this running until we are finished...", "$", "this", "->", "output", "->", "write", "(", "\"[RECEIVED SIGNAL] will shutdown after finishing task\"", ")", ";", "$", "hasReceivedSignal", "=", "true", ";", "}", "}", "else", "{", "$", "runningCommand", "=", "false", ";", "$", "exitCode", "=", "$", "process", "->", "getExitCode", "(", ")", ";", "$", "exitCodeText", "=", "$", "process", "->", "getExitCode", "(", ")", ";", "if", "(", "$", "exitCode", "!=", "0", ")", "{", "$", "failed", "=", "true", ";", "}", "}", "}" ]
Handles any running process waiting for signals.. @param Process $process @param boolean &$runningCommand @param boolean &$failed @param boolean &$hasReceivedSignal @param integer &$exitCode @param string &$exitCodeText @return void
[ "Handles", "any", "running", "process", "waiting", "for", "signals", ".." ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/WorkerCommand.php#L175-L208
yosymfony/ConfigServiceProvider
src/Yosymfony/Silex/ConfigServiceProvider/Loaders/JsonLoader.php
JsonLoader.load
public function load($resource, $type = null) { if(null === $type) { $resource = $this->getLocation($resource); $data = $this->loadFile($resource); } else { $data = $resource; } $parsed = $this->parseResource($data); $errorMsg = $this->getLastErrorMessage(json_last_error()); if($errorMsg) { $msg = $type ? sprintf("JSON parse error: %s", $errorMsg) : sprintf("JSON parse error: %s at %s", $errorMsg, $resource); throw new \RuntimeException($msg); } $repository = new ConfigRepository(); $repository->load($parsed ? $parsed : array()); return $repository; }
php
public function load($resource, $type = null) { if(null === $type) { $resource = $this->getLocation($resource); $data = $this->loadFile($resource); } else { $data = $resource; } $parsed = $this->parseResource($data); $errorMsg = $this->getLastErrorMessage(json_last_error()); if($errorMsg) { $msg = $type ? sprintf("JSON parse error: %s", $errorMsg) : sprintf("JSON parse error: %s at %s", $errorMsg, $resource); throw new \RuntimeException($msg); } $repository = new ConfigRepository(); $repository->load($parsed ? $parsed : array()); return $repository; }
[ "public", "function", "load", "(", "$", "resource", ",", "$", "type", "=", "null", ")", "{", "if", "(", "null", "===", "$", "type", ")", "{", "$", "resource", "=", "$", "this", "->", "getLocation", "(", "$", "resource", ")", ";", "$", "data", "=", "$", "this", "->", "loadFile", "(", "$", "resource", ")", ";", "}", "else", "{", "$", "data", "=", "$", "resource", ";", "}", "$", "parsed", "=", "$", "this", "->", "parseResource", "(", "$", "data", ")", ";", "$", "errorMsg", "=", "$", "this", "->", "getLastErrorMessage", "(", "json_last_error", "(", ")", ")", ";", "if", "(", "$", "errorMsg", ")", "{", "$", "msg", "=", "$", "type", "?", "sprintf", "(", "\"JSON parse error: %s\"", ",", "$", "errorMsg", ")", ":", "sprintf", "(", "\"JSON parse error: %s at %s\"", ",", "$", "errorMsg", ",", "$", "resource", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "$", "msg", ")", ";", "}", "$", "repository", "=", "new", "ConfigRepository", "(", ")", ";", "$", "repository", "->", "load", "(", "$", "parsed", "?", "$", "parsed", ":", "array", "(", ")", ")", ";", "return", "$", "repository", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yosymfony/ConfigServiceProvider/blob/f6cb9a9fc707b6c92e0d03201e5ecc17eaee3114/src/Yosymfony/Silex/ConfigServiceProvider/Loaders/JsonLoader.php#L27-L53
eghojansu/moe
src/tools/SMTP.php
SMTP.dialog
protected function dialog($cmd=NULL,$log=TRUE) { $socket=&$this->socket; if (!is_null($cmd)) fputs($socket,$cmd."\r\n"); $reply=''; while (!feof($socket) && ($info=stream_get_meta_data($socket)) && !$info['timed_out'] && $str=fgets($socket,4096)) { $reply.=$str; if (preg_match('/(?:^|\n)\d{3} .+?\r\n/s',$reply)) break; } if ($log) { $this->log.=$cmd."\n"; $this->log.=str_replace("\r",'',$reply); } return $reply; }
php
protected function dialog($cmd=NULL,$log=TRUE) { $socket=&$this->socket; if (!is_null($cmd)) fputs($socket,$cmd."\r\n"); $reply=''; while (!feof($socket) && ($info=stream_get_meta_data($socket)) && !$info['timed_out'] && $str=fgets($socket,4096)) { $reply.=$str; if (preg_match('/(?:^|\n)\d{3} .+?\r\n/s',$reply)) break; } if ($log) { $this->log.=$cmd."\n"; $this->log.=str_replace("\r",'',$reply); } return $reply; }
[ "protected", "function", "dialog", "(", "$", "cmd", "=", "NULL", ",", "$", "log", "=", "TRUE", ")", "{", "$", "socket", "=", "&", "$", "this", "->", "socket", ";", "if", "(", "!", "is_null", "(", "$", "cmd", ")", ")", "fputs", "(", "$", "socket", ",", "$", "cmd", ".", "\"\\r\\n\"", ")", ";", "$", "reply", "=", "''", ";", "while", "(", "!", "feof", "(", "$", "socket", ")", "&&", "(", "$", "info", "=", "stream_get_meta_data", "(", "$", "socket", ")", ")", "&&", "!", "$", "info", "[", "'timed_out'", "]", "&&", "$", "str", "=", "fgets", "(", "$", "socket", ",", "4096", ")", ")", "{", "$", "reply", ".=", "$", "str", ";", "if", "(", "preg_match", "(", "'/(?:^|\\n)\\d{3} .+?\\r\\n/s'", ",", "$", "reply", ")", ")", "break", ";", "}", "if", "(", "$", "log", ")", "{", "$", "this", "->", "log", ".=", "$", "cmd", ".", "\"\\n\"", ";", "$", "this", "->", "log", ".=", "str_replace", "(", "\"\\r\"", ",", "''", ",", "$", "reply", ")", ";", "}", "return", "$", "reply", ";", "}" ]
Send SMTP command and record server response @return string @param $cmd string @param $log bool
[ "Send", "SMTP", "command", "and", "record", "server", "response" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/SMTP.php#L106-L122
eghojansu/moe
src/tools/SMTP.php
SMTP.send
function send($message,$log=TRUE) { if ($this->scheme=='ssl' && !extension_loaded('openssl')) return FALSE; // Message should not be blank if (!$message) user_error(self::E_Blank,E_USER_ERROR); $fw=Base::instance(); // Retrieve headers $headers=$this->headers; // Connect to the server $socket=&$this->socket; $socket=@fsockopen($this->host,$this->port); if (!$socket) return FALSE; stream_set_blocking($socket,TRUE); // Get server's initial response $this->dialog(NULL,FALSE); // Announce presence $reply=$this->dialog('EHLO '.$fw->get('HOST'),$log); if (strtolower($this->scheme)=='tls') { $this->dialog('STARTTLS',$log); stream_socket_enable_crypto( $socket,TRUE,STREAM_CRYPTO_METHOD_TLS_CLIENT); $reply=$this->dialog('EHLO '.$fw->get('HOST'),$log); if (preg_match('/8BITMIME/',$reply)) $headers['Content-Transfer-Encoding']='8bit'; else { $headers['Content-Transfer-Encoding']='quoted-printable'; $message=quoted_printable_encode($message); } } if ($this->user && $this->pw && preg_match('/AUTH/',$reply)) { // Authenticate $this->dialog('AUTH LOGIN',$log); $this->dialog(base64_encode($this->user),$log); $this->dialog(base64_encode($this->pw),$log); } // Required headers $reqd=array('From','To','Subject'); foreach ($reqd as $id) if (empty($headers[$id])) user_error(sprintf(self::E_Header,$id),E_USER_ERROR); $eol="\r\n"; $str=''; // Stringify headers foreach ($headers as $key=>&$val) { if (!in_array($key,$reqd)) { $str.=$key.': '.$val.$eol; } if (in_array($key,array('From','To','Cc','Bcc')) && !preg_match('/[<>]/',$val)) $val='<'.$val.'>'; unset($val); } // Start message dialog $this->dialog('MAIL FROM: '.strstr($headers['From'],'<'),$log); foreach ($fw->split($headers['To']. (isset($headers['Cc'])?(';'.$headers['Cc']):''). (isset($headers['Bcc'])?(';'.$headers['Bcc']):'')) as $dst) $this->dialog('RCPT TO: '.strstr($dst,'<'),$log); $this->dialog('DATA',$log); if ($this->attachments) { // Replace Content-Type $hash=uniqid(NULL,TRUE); $type=$headers['Content-Type']; $headers['Content-Type']='multipart/mixed; '. 'boundary="'.$hash.'"'; // Send mail headers $out=''; foreach ($headers as $key=>$val) if ($key!='Bcc') $out.=$key.': '.$val.$eol; $out.=$eol; $out.='This is a multi-part message in MIME format'.$eol; $out.=$eol; $out.='--'.$hash.$eol; $out.='Content-Type: '.$type.$eol; $out.=$eol; $out.=$message.$eol; foreach ($this->attachments as $attachment) { if (is_array($attachment['filename'])) { list($alias,$file)=each($attachment); $filename=$alias; $attachment['filename']=$file; } else $filename=basename($attachment); $out.='--'.$hash.$eol; $out.='Content-Type: application/octet-stream'.$eol; $out.='Content-Transfer-Encoding: base64'.$eol; if ($attachment['cid']) $out.='Content-ID: '.$attachment['cid'].$eol; $out.='Content-Disposition: attachment; '. 'filename="'.$filename.'"'.$eol; $out.=$eol; $out.=chunk_split( base64_encode(file_get_contents($attachment))).$eol; } $out.=$eol; $out.='--'.$hash.'--'.$eol; $out.='.'; $this->dialog($out,FALSE); } else { // Send mail headers $out=''; foreach ($headers as $key=>$val) if ($key!='Bcc') $out.=$key.': '.$val.$eol; $out.=$eol; $out.=$message.$eol; $out.='.'; // Send message $this->dialog($out); } $this->dialog('QUIT',$log); if ($socket) fclose($socket); return TRUE; }
php
function send($message,$log=TRUE) { if ($this->scheme=='ssl' && !extension_loaded('openssl')) return FALSE; // Message should not be blank if (!$message) user_error(self::E_Blank,E_USER_ERROR); $fw=Base::instance(); // Retrieve headers $headers=$this->headers; // Connect to the server $socket=&$this->socket; $socket=@fsockopen($this->host,$this->port); if (!$socket) return FALSE; stream_set_blocking($socket,TRUE); // Get server's initial response $this->dialog(NULL,FALSE); // Announce presence $reply=$this->dialog('EHLO '.$fw->get('HOST'),$log); if (strtolower($this->scheme)=='tls') { $this->dialog('STARTTLS',$log); stream_socket_enable_crypto( $socket,TRUE,STREAM_CRYPTO_METHOD_TLS_CLIENT); $reply=$this->dialog('EHLO '.$fw->get('HOST'),$log); if (preg_match('/8BITMIME/',$reply)) $headers['Content-Transfer-Encoding']='8bit'; else { $headers['Content-Transfer-Encoding']='quoted-printable'; $message=quoted_printable_encode($message); } } if ($this->user && $this->pw && preg_match('/AUTH/',$reply)) { // Authenticate $this->dialog('AUTH LOGIN',$log); $this->dialog(base64_encode($this->user),$log); $this->dialog(base64_encode($this->pw),$log); } // Required headers $reqd=array('From','To','Subject'); foreach ($reqd as $id) if (empty($headers[$id])) user_error(sprintf(self::E_Header,$id),E_USER_ERROR); $eol="\r\n"; $str=''; // Stringify headers foreach ($headers as $key=>&$val) { if (!in_array($key,$reqd)) { $str.=$key.': '.$val.$eol; } if (in_array($key,array('From','To','Cc','Bcc')) && !preg_match('/[<>]/',$val)) $val='<'.$val.'>'; unset($val); } // Start message dialog $this->dialog('MAIL FROM: '.strstr($headers['From'],'<'),$log); foreach ($fw->split($headers['To']. (isset($headers['Cc'])?(';'.$headers['Cc']):''). (isset($headers['Bcc'])?(';'.$headers['Bcc']):'')) as $dst) $this->dialog('RCPT TO: '.strstr($dst,'<'),$log); $this->dialog('DATA',$log); if ($this->attachments) { // Replace Content-Type $hash=uniqid(NULL,TRUE); $type=$headers['Content-Type']; $headers['Content-Type']='multipart/mixed; '. 'boundary="'.$hash.'"'; // Send mail headers $out=''; foreach ($headers as $key=>$val) if ($key!='Bcc') $out.=$key.': '.$val.$eol; $out.=$eol; $out.='This is a multi-part message in MIME format'.$eol; $out.=$eol; $out.='--'.$hash.$eol; $out.='Content-Type: '.$type.$eol; $out.=$eol; $out.=$message.$eol; foreach ($this->attachments as $attachment) { if (is_array($attachment['filename'])) { list($alias,$file)=each($attachment); $filename=$alias; $attachment['filename']=$file; } else $filename=basename($attachment); $out.='--'.$hash.$eol; $out.='Content-Type: application/octet-stream'.$eol; $out.='Content-Transfer-Encoding: base64'.$eol; if ($attachment['cid']) $out.='Content-ID: '.$attachment['cid'].$eol; $out.='Content-Disposition: attachment; '. 'filename="'.$filename.'"'.$eol; $out.=$eol; $out.=chunk_split( base64_encode(file_get_contents($attachment))).$eol; } $out.=$eol; $out.='--'.$hash.'--'.$eol; $out.='.'; $this->dialog($out,FALSE); } else { // Send mail headers $out=''; foreach ($headers as $key=>$val) if ($key!='Bcc') $out.=$key.': '.$val.$eol; $out.=$eol; $out.=$message.$eol; $out.='.'; // Send message $this->dialog($out); } $this->dialog('QUIT',$log); if ($socket) fclose($socket); return TRUE; }
[ "function", "send", "(", "$", "message", ",", "$", "log", "=", "TRUE", ")", "{", "if", "(", "$", "this", "->", "scheme", "==", "'ssl'", "&&", "!", "extension_loaded", "(", "'openssl'", ")", ")", "return", "FALSE", ";", "// Message should not be blank", "if", "(", "!", "$", "message", ")", "user_error", "(", "self", "::", "E_Blank", ",", "E_USER_ERROR", ")", ";", "$", "fw", "=", "Base", "::", "instance", "(", ")", ";", "// Retrieve headers", "$", "headers", "=", "$", "this", "->", "headers", ";", "// Connect to the server", "$", "socket", "=", "&", "$", "this", "->", "socket", ";", "$", "socket", "=", "@", "fsockopen", "(", "$", "this", "->", "host", ",", "$", "this", "->", "port", ")", ";", "if", "(", "!", "$", "socket", ")", "return", "FALSE", ";", "stream_set_blocking", "(", "$", "socket", ",", "TRUE", ")", ";", "// Get server's initial response", "$", "this", "->", "dialog", "(", "NULL", ",", "FALSE", ")", ";", "// Announce presence", "$", "reply", "=", "$", "this", "->", "dialog", "(", "'EHLO '", ".", "$", "fw", "->", "get", "(", "'HOST'", ")", ",", "$", "log", ")", ";", "if", "(", "strtolower", "(", "$", "this", "->", "scheme", ")", "==", "'tls'", ")", "{", "$", "this", "->", "dialog", "(", "'STARTTLS'", ",", "$", "log", ")", ";", "stream_socket_enable_crypto", "(", "$", "socket", ",", "TRUE", ",", "STREAM_CRYPTO_METHOD_TLS_CLIENT", ")", ";", "$", "reply", "=", "$", "this", "->", "dialog", "(", "'EHLO '", ".", "$", "fw", "->", "get", "(", "'HOST'", ")", ",", "$", "log", ")", ";", "if", "(", "preg_match", "(", "'/8BITMIME/'", ",", "$", "reply", ")", ")", "$", "headers", "[", "'Content-Transfer-Encoding'", "]", "=", "'8bit'", ";", "else", "{", "$", "headers", "[", "'Content-Transfer-Encoding'", "]", "=", "'quoted-printable'", ";", "$", "message", "=", "quoted_printable_encode", "(", "$", "message", ")", ";", "}", "}", "if", "(", "$", "this", "->", "user", "&&", "$", "this", "->", "pw", "&&", "preg_match", "(", "'/AUTH/'", ",", "$", "reply", ")", ")", "{", "// Authenticate", "$", "this", "->", "dialog", "(", "'AUTH LOGIN'", ",", "$", "log", ")", ";", "$", "this", "->", "dialog", "(", "base64_encode", "(", "$", "this", "->", "user", ")", ",", "$", "log", ")", ";", "$", "this", "->", "dialog", "(", "base64_encode", "(", "$", "this", "->", "pw", ")", ",", "$", "log", ")", ";", "}", "// Required headers", "$", "reqd", "=", "array", "(", "'From'", ",", "'To'", ",", "'Subject'", ")", ";", "foreach", "(", "$", "reqd", "as", "$", "id", ")", "if", "(", "empty", "(", "$", "headers", "[", "$", "id", "]", ")", ")", "user_error", "(", "sprintf", "(", "self", "::", "E_Header", ",", "$", "id", ")", ",", "E_USER_ERROR", ")", ";", "$", "eol", "=", "\"\\r\\n\"", ";", "$", "str", "=", "''", ";", "// Stringify headers", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "&", "$", "val", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "reqd", ")", ")", "{", "$", "str", ".=", "$", "key", ".", "': '", ".", "$", "val", ".", "$", "eol", ";", "}", "if", "(", "in_array", "(", "$", "key", ",", "array", "(", "'From'", ",", "'To'", ",", "'Cc'", ",", "'Bcc'", ")", ")", "&&", "!", "preg_match", "(", "'/[<>]/'", ",", "$", "val", ")", ")", "$", "val", "=", "'<'", ".", "$", "val", ".", "'>'", ";", "unset", "(", "$", "val", ")", ";", "}", "// Start message dialog", "$", "this", "->", "dialog", "(", "'MAIL FROM: '", ".", "strstr", "(", "$", "headers", "[", "'From'", "]", ",", "'<'", ")", ",", "$", "log", ")", ";", "foreach", "(", "$", "fw", "->", "split", "(", "$", "headers", "[", "'To'", "]", ".", "(", "isset", "(", "$", "headers", "[", "'Cc'", "]", ")", "?", "(", "';'", ".", "$", "headers", "[", "'Cc'", "]", ")", ":", "''", ")", ".", "(", "isset", "(", "$", "headers", "[", "'Bcc'", "]", ")", "?", "(", "';'", ".", "$", "headers", "[", "'Bcc'", "]", ")", ":", "''", ")", ")", "as", "$", "dst", ")", "$", "this", "->", "dialog", "(", "'RCPT TO: '", ".", "strstr", "(", "$", "dst", ",", "'<'", ")", ",", "$", "log", ")", ";", "$", "this", "->", "dialog", "(", "'DATA'", ",", "$", "log", ")", ";", "if", "(", "$", "this", "->", "attachments", ")", "{", "// Replace Content-Type", "$", "hash", "=", "uniqid", "(", "NULL", ",", "TRUE", ")", ";", "$", "type", "=", "$", "headers", "[", "'Content-Type'", "]", ";", "$", "headers", "[", "'Content-Type'", "]", "=", "'multipart/mixed; '", ".", "'boundary=\"'", ".", "$", "hash", ".", "'\"'", ";", "// Send mail headers", "$", "out", "=", "''", ";", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "val", ")", "if", "(", "$", "key", "!=", "'Bcc'", ")", "$", "out", ".=", "$", "key", ".", "': '", ".", "$", "val", ".", "$", "eol", ";", "$", "out", ".=", "$", "eol", ";", "$", "out", ".=", "'This is a multi-part message in MIME format'", ".", "$", "eol", ";", "$", "out", ".=", "$", "eol", ";", "$", "out", ".=", "'--'", ".", "$", "hash", ".", "$", "eol", ";", "$", "out", ".=", "'Content-Type: '", ".", "$", "type", ".", "$", "eol", ";", "$", "out", ".=", "$", "eol", ";", "$", "out", ".=", "$", "message", ".", "$", "eol", ";", "foreach", "(", "$", "this", "->", "attachments", "as", "$", "attachment", ")", "{", "if", "(", "is_array", "(", "$", "attachment", "[", "'filename'", "]", ")", ")", "{", "list", "(", "$", "alias", ",", "$", "file", ")", "=", "each", "(", "$", "attachment", ")", ";", "$", "filename", "=", "$", "alias", ";", "$", "attachment", "[", "'filename'", "]", "=", "$", "file", ";", "}", "else", "$", "filename", "=", "basename", "(", "$", "attachment", ")", ";", "$", "out", ".=", "'--'", ".", "$", "hash", ".", "$", "eol", ";", "$", "out", ".=", "'Content-Type: application/octet-stream'", ".", "$", "eol", ";", "$", "out", ".=", "'Content-Transfer-Encoding: base64'", ".", "$", "eol", ";", "if", "(", "$", "attachment", "[", "'cid'", "]", ")", "$", "out", ".=", "'Content-ID: '", ".", "$", "attachment", "[", "'cid'", "]", ".", "$", "eol", ";", "$", "out", ".=", "'Content-Disposition: attachment; '", ".", "'filename=\"'", ".", "$", "filename", ".", "'\"'", ".", "$", "eol", ";", "$", "out", ".=", "$", "eol", ";", "$", "out", ".=", "chunk_split", "(", "base64_encode", "(", "file_get_contents", "(", "$", "attachment", ")", ")", ")", ".", "$", "eol", ";", "}", "$", "out", ".=", "$", "eol", ";", "$", "out", ".=", "'--'", ".", "$", "hash", ".", "'--'", ".", "$", "eol", ";", "$", "out", ".=", "'.'", ";", "$", "this", "->", "dialog", "(", "$", "out", ",", "FALSE", ")", ";", "}", "else", "{", "// Send mail headers", "$", "out", "=", "''", ";", "foreach", "(", "$", "headers", "as", "$", "key", "=>", "$", "val", ")", "if", "(", "$", "key", "!=", "'Bcc'", ")", "$", "out", ".=", "$", "key", ".", "': '", ".", "$", "val", ".", "$", "eol", ";", "$", "out", ".=", "$", "eol", ";", "$", "out", ".=", "$", "message", ".", "$", "eol", ";", "$", "out", ".=", "'.'", ";", "// Send message", "$", "this", "->", "dialog", "(", "$", "out", ")", ";", "}", "$", "this", "->", "dialog", "(", "'QUIT'", ",", "$", "log", ")", ";", "if", "(", "$", "socket", ")", "fclose", "(", "$", "socket", ")", ";", "return", "TRUE", ";", "}" ]
Transmit message @return bool @param $message string @param $log bool
[ "Transmit", "message" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/SMTP.php#L145-L264
mmanos/laravel-casset
src/controllers/CassetController.php
CassetController.getIndex
public function getIndex($type = null) { $container = Input::get('c'); $files = Input::get('files', ''); if (empty($type) || !in_array($type, array('style', 'script'))) { App::abort(404); } if (empty($container)) { App::abort(404); } $files = json_decode(base64_decode($files), true); if (empty($files) || !is_array($files)) { App::abort(404); } foreach ($files as $file) { Facades\Casset::container($container)->add( array_get($file, 'source'), array(), array_get($file, 'dependencies', array()) ); } $response = Response::make(Facades\Casset::container($container)->content($type)); if ('style' == $type) { $response->headers->set('Content-Type', 'text/css'); } else { $response->headers->set('Content-Type', 'application/json'); } return $response; }
php
public function getIndex($type = null) { $container = Input::get('c'); $files = Input::get('files', ''); if (empty($type) || !in_array($type, array('style', 'script'))) { App::abort(404); } if (empty($container)) { App::abort(404); } $files = json_decode(base64_decode($files), true); if (empty($files) || !is_array($files)) { App::abort(404); } foreach ($files as $file) { Facades\Casset::container($container)->add( array_get($file, 'source'), array(), array_get($file, 'dependencies', array()) ); } $response = Response::make(Facades\Casset::container($container)->content($type)); if ('style' == $type) { $response->headers->set('Content-Type', 'text/css'); } else { $response->headers->set('Content-Type', 'application/json'); } return $response; }
[ "public", "function", "getIndex", "(", "$", "type", "=", "null", ")", "{", "$", "container", "=", "Input", "::", "get", "(", "'c'", ")", ";", "$", "files", "=", "Input", "::", "get", "(", "'files'", ",", "''", ")", ";", "if", "(", "empty", "(", "$", "type", ")", "||", "!", "in_array", "(", "$", "type", ",", "array", "(", "'style'", ",", "'script'", ")", ")", ")", "{", "App", "::", "abort", "(", "404", ")", ";", "}", "if", "(", "empty", "(", "$", "container", ")", ")", "{", "App", "::", "abort", "(", "404", ")", ";", "}", "$", "files", "=", "json_decode", "(", "base64_decode", "(", "$", "files", ")", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "files", ")", "||", "!", "is_array", "(", "$", "files", ")", ")", "{", "App", "::", "abort", "(", "404", ")", ";", "}", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "Facades", "\\", "Casset", "::", "container", "(", "$", "container", ")", "->", "add", "(", "array_get", "(", "$", "file", ",", "'source'", ")", ",", "array", "(", ")", ",", "array_get", "(", "$", "file", ",", "'dependencies'", ",", "array", "(", ")", ")", ")", ";", "}", "$", "response", "=", "Response", "::", "make", "(", "Facades", "\\", "Casset", "::", "container", "(", "$", "container", ")", "->", "content", "(", "$", "type", ")", ")", ";", "if", "(", "'style'", "==", "$", "type", ")", "{", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'text/css'", ")", ";", "}", "else", "{", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "}", "return", "$", "response", ";", "}" ]
Index action. @return mixed
[ "Index", "action", "." ]
train
https://github.com/mmanos/laravel-casset/blob/0f7db71211c1daa99bde30afa41da2692a39b81c/src/controllers/CassetController.php#L20-L57
glynnforrest/active-doctrine
src/ActiveDoctrine/Fixture/FixtureLoader.php
FixtureLoader.addFixture
public function addFixture(FixtureInterface $fixture) { $this->dropTables = array_merge($this->dropTables, (array) $fixture->getTables()); $this->fixtures[] = $fixture; }
php
public function addFixture(FixtureInterface $fixture) { $this->dropTables = array_merge($this->dropTables, (array) $fixture->getTables()); $this->fixtures[] = $fixture; }
[ "public", "function", "addFixture", "(", "FixtureInterface", "$", "fixture", ")", "{", "$", "this", "->", "dropTables", "=", "array_merge", "(", "$", "this", "->", "dropTables", ",", "(", "array", ")", "$", "fixture", "->", "getTables", "(", ")", ")", ";", "$", "this", "->", "fixtures", "[", "]", "=", "$", "fixture", ";", "}" ]
Add a fixture to be loaded into the database. @param FixtureInterface $fixture
[ "Add", "a", "fixture", "to", "be", "loaded", "into", "the", "database", "." ]
train
https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Fixture/FixtureLoader.php#L22-L26
glynnforrest/active-doctrine
src/ActiveDoctrine/Fixture/FixtureLoader.php
FixtureLoader.run
public function run(Connection $connection, $append = false) { if (!$append) { //in the future, resolve key constraints here foreach (array_unique($this->dropTables) as $table) { $connection->delete($table, [1 => 1], [\PDO::PARAM_INT]); } } foreach ($this->getSortedFixtures() as $fixture) { $this->runFixture($connection, $fixture); } }
php
public function run(Connection $connection, $append = false) { if (!$append) { //in the future, resolve key constraints here foreach (array_unique($this->dropTables) as $table) { $connection->delete($table, [1 => 1], [\PDO::PARAM_INT]); } } foreach ($this->getSortedFixtures() as $fixture) { $this->runFixture($connection, $fixture); } }
[ "public", "function", "run", "(", "Connection", "$", "connection", ",", "$", "append", "=", "false", ")", "{", "if", "(", "!", "$", "append", ")", "{", "//in the future, resolve key constraints here", "foreach", "(", "array_unique", "(", "$", "this", "->", "dropTables", ")", "as", "$", "table", ")", "{", "$", "connection", "->", "delete", "(", "$", "table", ",", "[", "1", "=>", "1", "]", ",", "[", "\\", "PDO", "::", "PARAM_INT", "]", ")", ";", "}", "}", "foreach", "(", "$", "this", "->", "getSortedFixtures", "(", ")", "as", "$", "fixture", ")", "{", "$", "this", "->", "runFixture", "(", "$", "connection", ",", "$", "fixture", ")", ";", "}", "}" ]
Run all fixtures. @param Connection $connection @param bool $append Don't empty tables before loading
[ "Run", "all", "fixtures", "." ]
train
https://github.com/glynnforrest/active-doctrine/blob/fcf8c434c7df4704966107bf9a95c005a0b37168/src/ActiveDoctrine/Fixture/FixtureLoader.php#L34-L46
neat-php/database
classes/FetchedResult.php
FetchedResult.each
public function each(callable $closure) { $results = []; foreach ($this->rows as $row) { $results[] = $closure(...array_values($row)); } return $results; }
php
public function each(callable $closure) { $results = []; foreach ($this->rows as $row) { $results[] = $closure(...array_values($row)); } return $results; }
[ "public", "function", "each", "(", "callable", "$", "closure", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "rows", "as", "$", "row", ")", "{", "$", "results", "[", "]", "=", "$", "closure", "(", "...", "array_values", "(", "$", "row", ")", ")", ";", "}", "return", "$", "results", ";", "}" ]
Call a closure for each row @param callable $closure @return array
[ "Call", "a", "closure", "for", "each", "row" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/FetchedResult.php#L39-L47
neat-php/database
classes/FetchedResult.php
FetchedResult.row
public function row() { if (isset($this->rows[$this->cursor])) { return $this->rows[$this->cursor++]; } return false; }
php
public function row() { if (isset($this->rows[$this->cursor])) { return $this->rows[$this->cursor++]; } return false; }
[ "public", "function", "row", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "rows", "[", "$", "this", "->", "cursor", "]", ")", ")", "{", "return", "$", "this", "->", "rows", "[", "$", "this", "->", "cursor", "++", "]", ";", "}", "return", "false", ";", "}" ]
Get a single row as array Moves the cursor to the next row @return array|false
[ "Get", "a", "single", "row", "as", "array" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/FetchedResult.php#L68-L75
neat-php/database
classes/FetchedResult.php
FetchedResult.values
public function values($column = 0) { if (is_int($column)) { $column = $this->rows ? array_keys($this->rows[0])[$column] : ''; } return array_map(function ($row) use ($column) { return $row[$column]; }, $this->rows); }
php
public function values($column = 0) { if (is_int($column)) { $column = $this->rows ? array_keys($this->rows[0])[$column] : ''; } return array_map(function ($row) use ($column) { return $row[$column]; }, $this->rows); }
[ "public", "function", "values", "(", "$", "column", "=", "0", ")", "{", "if", "(", "is_int", "(", "$", "column", ")", ")", "{", "$", "column", "=", "$", "this", "->", "rows", "?", "array_keys", "(", "$", "this", "->", "rows", "[", "0", "]", ")", "[", "$", "column", "]", ":", "''", ";", "}", "return", "array_map", "(", "function", "(", "$", "row", ")", "use", "(", "$", "column", ")", "{", "return", "$", "row", "[", "$", "column", "]", ";", "}", ",", "$", "this", "->", "rows", ")", ";", "}" ]
Get all values from one column Moves the cursor to the end of the result @param int|string $column @return array
[ "Get", "all", "values", "from", "one", "column" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/FetchedResult.php#L85-L94
neat-php/database
classes/FetchedResult.php
FetchedResult.value
public function value($column = 0) { $row = $this->row(); if ($row) { return is_int($column) ? array_values($row)[$column] : $row[$column]; } return false; }
php
public function value($column = 0) { $row = $this->row(); if ($row) { return is_int($column) ? array_values($row)[$column] : $row[$column]; } return false; }
[ "public", "function", "value", "(", "$", "column", "=", "0", ")", "{", "$", "row", "=", "$", "this", "->", "row", "(", ")", ";", "if", "(", "$", "row", ")", "{", "return", "is_int", "(", "$", "column", ")", "?", "array_values", "(", "$", "row", ")", "[", "$", "column", "]", ":", "$", "row", "[", "$", "column", "]", ";", "}", "return", "false", ";", "}" ]
Get a single value from one column Moves the cursor to the next row @param int|string $column @return mixed|false
[ "Get", "a", "single", "value", "from", "one", "column" ]
train
https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/FetchedResult.php#L104-L112
RhubarbPHP/Module.RestApi
src/Resources/CollectionRestResource.php
CollectionRestResource.containsResourceIdentifier
public function containsResourceIdentifier($resourceIdentifier) { // This will be very slow however the base implementation can do nothing else. // Inheritors of this class should override this if they can do this faster! $items = $this->getItems(0, false); foreach ($items[0] as $item) { if ($item->_id = $resourceIdentifier) { return true; } } return false; }
php
public function containsResourceIdentifier($resourceIdentifier) { // This will be very slow however the base implementation can do nothing else. // Inheritors of this class should override this if they can do this faster! $items = $this->getItems(0, false); foreach ($items[0] as $item) { if ($item->_id = $resourceIdentifier) { return true; } } return false; }
[ "public", "function", "containsResourceIdentifier", "(", "$", "resourceIdentifier", ")", "{", "// This will be very slow however the base implementation can do nothing else.", "// Inheritors of this class should override this if they can do this faster!", "$", "items", "=", "$", "this", "->", "getItems", "(", "0", ",", "false", ")", ";", "foreach", "(", "$", "items", "[", "0", "]", "as", "$", "item", ")", "{", "if", "(", "$", "item", "->", "_id", "=", "$", "resourceIdentifier", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Test to see if the given resource identifier exists in the collection of resources. @param $resourceIdentifier @return True if it exists, false if it does not.
[ "Test", "to", "see", "if", "the", "given", "resource", "identifier", "exists", "in", "the", "collection", "of", "resources", "." ]
train
https://github.com/RhubarbPHP/Module.RestApi/blob/825d2b920caed13811971c5eb2784a94417787bd/src/Resources/CollectionRestResource.php#L64-L77
RhubarbPHP/Module.RestApi
src/Resources/CollectionRestResource.php
CollectionRestResource.createCollectionResourceForItems
protected function createCollectionResourceForItems($items, $from, $to, $count) { $resource = parent::get(); $resource->items = $items; $resource->count = $count; $resource->range = new \stdClass(); $resource->range->from = $from; $resource->range->to = $to; return $resource; }
php
protected function createCollectionResourceForItems($items, $from, $to, $count) { $resource = parent::get(); $resource->items = $items; $resource->count = $count; $resource->range = new \stdClass(); $resource->range->from = $from; $resource->range->to = $to; return $resource; }
[ "protected", "function", "createCollectionResourceForItems", "(", "$", "items", ",", "$", "from", ",", "$", "to", ",", "$", "count", ")", "{", "$", "resource", "=", "parent", "::", "get", "(", ")", ";", "$", "resource", "->", "items", "=", "$", "items", ";", "$", "resource", "->", "count", "=", "$", "count", ";", "$", "resource", "->", "range", "=", "new", "\\", "stdClass", "(", ")", ";", "$", "resource", "->", "range", "->", "from", "=", "$", "from", ";", "$", "resource", "->", "range", "->", "to", "=", "$", "to", ";", "return", "$", "resource", ";", "}" ]
Creates a valid collection response from a list of objects. @param Collection|\stdClass[] $items @param int $from @param int $to @param int $count @return \stdClass
[ "Creates", "a", "valid", "collection", "response", "from", "a", "list", "of", "objects", "." ]
train
https://github.com/RhubarbPHP/Module.RestApi/blob/825d2b920caed13811971c5eb2784a94417787bd/src/Resources/CollectionRestResource.php#L151-L161
mikebarlow/html-helper
src/Attributes.php
Attributes.attr
public function attr(array $attributes) { $result = ''; foreach ($attributes as $attribute => $value) { $result .= ' '.(is_int($attribute) ? $value : $attribute.'="'.str_replace('"', '&quot;', $value).'"'); } return $result; }
php
public function attr(array $attributes) { $result = ''; foreach ($attributes as $attribute => $value) { $result .= ' '.(is_int($attribute) ? $value : $attribute.'="'.str_replace('"', '&quot;', $value).'"'); } return $result; }
[ "public", "function", "attr", "(", "array", "$", "attributes", ")", "{", "$", "result", "=", "''", ";", "foreach", "(", "$", "attributes", "as", "$", "attribute", "=>", "$", "value", ")", "{", "$", "result", ".=", "' '", ".", "(", "is_int", "(", "$", "attribute", ")", "?", "$", "value", ":", "$", "attribute", ".", "'=\"'", ".", "str_replace", "(", "'\"'", ",", "'&quot;'", ",", "$", "value", ")", ".", "'\"'", ")", ";", "}", "return", "$", "result", ";", "}" ]
Render the attributes @param array $attributes @return string
[ "Render", "the", "attributes" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Attributes.php#L13-L22
mikebarlow/html-helper
src/Attributes.php
Attributes.mergeAttr
public function mergeAttr() { $arrays = func_get_args(); $result = array(); foreach ($arrays as $array) { $result = $this->mergeRecursive($result, $array); } return $result; }
php
public function mergeAttr() { $arrays = func_get_args(); $result = array(); foreach ($arrays as $array) { $result = $this->mergeRecursive($result, $array); } return $result; }
[ "public", "function", "mergeAttr", "(", ")", "{", "$", "arrays", "=", "func_get_args", "(", ")", ";", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "arrays", "as", "$", "array", ")", "{", "$", "result", "=", "$", "this", "->", "mergeRecursive", "(", "$", "result", ",", "$", "array", ")", ";", "}", "return", "$", "result", ";", "}" ]
It will merge multiple attributes arrays without erase values @return array
[ "It", "will", "merge", "multiple", "attributes", "arrays", "without", "erase", "values" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Attributes.php#L29-L39
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php
ezcCacheMemcacheBackend.store
public function store( $key, $var, $expire = 0 ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } // protect our data by wrapping it in an object $data = new ezcCacheMemoryVarStruct( $key, $var, $expire ); $compressed = ( $this->options->compressed === true ) ? MEMCACHE_COMPRESSED : false; return $this->memcache->set( $key, $data, $compressed, $expire ); }
php
public function store( $key, $var, $expire = 0 ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } // protect our data by wrapping it in an object $data = new ezcCacheMemoryVarStruct( $key, $var, $expire ); $compressed = ( $this->options->compressed === true ) ? MEMCACHE_COMPRESSED : false; return $this->memcache->set( $key, $data, $compressed, $expire ); }
[ "public", "function", "store", "(", "$", "key", ",", "$", "var", ",", "$", "expire", "=", "0", ")", "{", "if", "(", "strlen", "(", "$", "key", ")", ">", "self", "::", "MAX_KEY_LENGTH", ")", "{", "throw", "new", "ezcCacheInvalidKeyException", "(", "$", "key", ",", "'Length > '", ".", "self", "::", "MAX_KEY_LENGTH", ".", "'.'", ")", ";", "}", "// protect our data by wrapping it in an object", "$", "data", "=", "new", "ezcCacheMemoryVarStruct", "(", "$", "key", ",", "$", "var", ",", "$", "expire", ")", ";", "$", "compressed", "=", "(", "$", "this", "->", "options", "->", "compressed", "===", "true", ")", "?", "MEMCACHE_COMPRESSED", ":", "false", ";", "return", "$", "this", "->", "memcache", "->", "set", "(", "$", "key", ",", "$", "data", ",", "$", "compressed", ",", "$", "expire", ")", ";", "}" ]
Adds the $var data to the cache under the key $key. Returns true or false depending on the success of the operation. @param string $key @param mixed $var @param int $expire @return bool
[ "Adds", "the", "$var", "data", "to", "the", "cache", "under", "the", "key", "$key", ".", "Returns", "true", "or", "false", "depending", "on", "the", "success", "of", "the", "operation", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php#L153-L164
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php
ezcCacheMemcacheBackend.fetch
public function fetch( $key ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } $data = $this->memcache->get( $key ); return ( is_object( $data ) ) ? $data->var : false; }
php
public function fetch( $key ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } $data = $this->memcache->get( $key ); return ( is_object( $data ) ) ? $data->var : false; }
[ "public", "function", "fetch", "(", "$", "key", ")", "{", "if", "(", "strlen", "(", "$", "key", ")", ">", "self", "::", "MAX_KEY_LENGTH", ")", "{", "throw", "new", "ezcCacheInvalidKeyException", "(", "$", "key", ",", "'Length > '", ".", "self", "::", "MAX_KEY_LENGTH", ".", "'.'", ")", ";", "}", "$", "data", "=", "$", "this", "->", "memcache", "->", "get", "(", "$", "key", ")", ";", "return", "(", "is_object", "(", "$", "data", ")", ")", "?", "$", "data", "->", "var", ":", "false", ";", "}" ]
Returns the data from the cache associated with key $key. @param mixed $key @return mixed
[ "Returns", "the", "data", "from", "the", "cache", "associated", "with", "key", "$key", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php#L172-L181
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php
ezcCacheMemcacheBackend.acquireLock
public function acquireLock( $key, $waitTime, $maxTime ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } // add() does not replace and returns true on success. $maxTime is // obeyed by Memcache expiry. while ( $this->memcache->add( $key, $key, false, $maxTime ) === false ) { // Wait for next check usleep( $waitTime ); } }
php
public function acquireLock( $key, $waitTime, $maxTime ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } // add() does not replace and returns true on success. $maxTime is // obeyed by Memcache expiry. while ( $this->memcache->add( $key, $key, false, $maxTime ) === false ) { // Wait for next check usleep( $waitTime ); } }
[ "public", "function", "acquireLock", "(", "$", "key", ",", "$", "waitTime", ",", "$", "maxTime", ")", "{", "if", "(", "strlen", "(", "$", "key", ")", ">", "self", "::", "MAX_KEY_LENGTH", ")", "{", "throw", "new", "ezcCacheInvalidKeyException", "(", "$", "key", ",", "'Length > '", ".", "self", "::", "MAX_KEY_LENGTH", ".", "'.'", ")", ";", "}", "// add() does not replace and returns true on success. $maxTime is", "// obeyed by Memcache expiry.", "while", "(", "$", "this", "->", "memcache", "->", "add", "(", "$", "key", ",", "$", "key", ",", "false", ",", "$", "maxTime", ")", "===", "false", ")", "{", "// Wait for next check", "usleep", "(", "$", "waitTime", ")", ";", "}", "}" ]
Acquires a lock on the given $key. @param string $key @param int $waitTime usleep() @param int $maxTime seconds
[ "Acquires", "a", "lock", "on", "the", "given", "$key", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php#L226-L240
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php
ezcCacheMemcacheBackend.releaseLock
public function releaseLock( $key ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } $this->memcache->delete( $key ); }
php
public function releaseLock( $key ) { if ( strlen( $key ) > self::MAX_KEY_LENGTH ) { throw new ezcCacheInvalidKeyException( $key, 'Length > ' . self::MAX_KEY_LENGTH . '.' ); } $this->memcache->delete( $key ); }
[ "public", "function", "releaseLock", "(", "$", "key", ")", "{", "if", "(", "strlen", "(", "$", "key", ")", ">", "self", "::", "MAX_KEY_LENGTH", ")", "{", "throw", "new", "ezcCacheInvalidKeyException", "(", "$", "key", ",", "'Length > '", ".", "self", "::", "MAX_KEY_LENGTH", ".", "'.'", ")", ";", "}", "$", "this", "->", "memcache", "->", "delete", "(", "$", "key", ")", ";", "}" ]
Releases a lock on the given $key. @param string $key @return void
[ "Releases", "a", "lock", "on", "the", "given", "$key", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Cache/src/backends/memcache/memcache_backend.php#L248-L256
inhere/php-librarys
src/Helpers/Req.php
Req.param
public static function param($key, $default = null) { if (!$key || !\is_string($key)) { return false; } $ret = $_POST[$key] ?? $_GET[$key] ?? $default; if (\is_string($ret)) { return stripslashes(urldecode(preg_replace('/((\%5C0+)|(\%00+))/i', '', urlencode($ret)))); } return $ret; }
php
public static function param($key, $default = null) { if (!$key || !\is_string($key)) { return false; } $ret = $_POST[$key] ?? $_GET[$key] ?? $default; if (\is_string($ret)) { return stripslashes(urldecode(preg_replace('/((\%5C0+)|(\%00+))/i', '', urlencode($ret)))); } return $ret; }
[ "public", "static", "function", "param", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "$", "key", "||", "!", "\\", "is_string", "(", "$", "key", ")", ")", "{", "return", "false", ";", "}", "$", "ret", "=", "$", "_POST", "[", "$", "key", "]", "??", "$", "_GET", "[", "$", "key", "]", "??", "$", "default", ";", "if", "(", "\\", "is_string", "(", "$", "ret", ")", ")", "{", "return", "stripslashes", "(", "urldecode", "(", "preg_replace", "(", "'/((\\%5C0+)|(\\%00+))/i'", ",", "''", ",", "urlencode", "(", "$", "ret", ")", ")", ")", ")", ";", "}", "return", "$", "ret", ";", "}" ]
Get a value from $_POST / $_GET if unavailable, take a default value @param string $key Value key @param mixed $default (optional) @return mixed Value
[ "Get", "a", "value", "from", "$_POST", "/", "$_GET", "if", "unavailable", "take", "a", "default", "value" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/Req.php#L59-L72
inhere/php-librarys
src/Helpers/Req.php
Req.server
public static function server($name, $default = '') { $name = strtoupper($name); return isset($_SERVER[$name]) ? trim($_SERVER[$name]) : $default; }
php
public static function server($name, $default = '') { $name = strtoupper($name); return isset($_SERVER[$name]) ? trim($_SERVER[$name]) : $default; }
[ "public", "static", "function", "server", "(", "$", "name", ",", "$", "default", "=", "''", ")", "{", "$", "name", "=", "strtoupper", "(", "$", "name", ")", ";", "return", "isset", "(", "$", "_SERVER", "[", "$", "name", "]", ")", "?", "trim", "(", "$", "_SERVER", "[", "$", "name", "]", ")", ":", "$", "default", ";", "}" ]
get $_SERVER value @param string $name @param string $default @return mixed
[ "get", "$_SERVER", "value" ]
train
https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/Req.php#L205-L210
phootwork/lang
src/Text.php
Text.insert
public function insert($substring, $index) { if ($index <= 0) { return $this->prepend($substring); } if ($index > $this->length()) { return $this->append($substring); } $start = mb_substr($this->string, 0, $index, $this->encoding); $end = mb_substr($this->string, $index, $this->length(), $this->encoding); return new Text($start . $substring . $end); }
php
public function insert($substring, $index) { if ($index <= 0) { return $this->prepend($substring); } if ($index > $this->length()) { return $this->append($substring); } $start = mb_substr($this->string, 0, $index, $this->encoding); $end = mb_substr($this->string, $index, $this->length(), $this->encoding); return new Text($start . $substring . $end); }
[ "public", "function", "insert", "(", "$", "substring", ",", "$", "index", ")", "{", "if", "(", "$", "index", "<=", "0", ")", "{", "return", "$", "this", "->", "prepend", "(", "$", "substring", ")", ";", "}", "if", "(", "$", "index", ">", "$", "this", "->", "length", "(", ")", ")", "{", "return", "$", "this", "->", "append", "(", "$", "substring", ")", ";", "}", "$", "start", "=", "mb_substr", "(", "$", "this", "->", "string", ",", "0", ",", "$", "index", ",", "$", "this", "->", "encoding", ")", ";", "$", "end", "=", "mb_substr", "(", "$", "this", "->", "string", ",", "$", "index", ",", "$", "this", "->", "length", "(", ")", ",", "$", "this", "->", "encoding", ")", ";", "return", "new", "Text", "(", "$", "start", ".", "$", "substring", ".", "$", "end", ")", ";", "}" ]
Inserts a substring at the given index <code> $str = new Text('Hello World!');<br> $str->insert('to this ', 5); // Hello to this World! </code> @param string|Text $substring @param int $index @return Text
[ "Inserts", "a", "substring", "at", "the", "given", "index" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L115-L127
phootwork/lang
src/Text.php
Text.compare
public function compare($compare, callable $callback = null) { if ($callback === null) { $callback = 'strcmp'; } return $callback($this->string, (string) $compare); }
php
public function compare($compare, callable $callback = null) { if ($callback === null) { $callback = 'strcmp'; } return $callback($this->string, (string) $compare); }
[ "public", "function", "compare", "(", "$", "compare", ",", "callable", "$", "callback", "=", "null", ")", "{", "if", "(", "$", "callback", "===", "null", ")", "{", "$", "callback", "=", "'strcmp'", ";", "}", "return", "$", "callback", "(", "$", "this", "->", "string", ",", "(", "string", ")", "$", "compare", ")", ";", "}" ]
Compares this string to another @param string $compare string to compare to @param callable $callback @return int
[ "Compares", "this", "string", "to", "another" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L164-L169
phootwork/lang
src/Text.php
Text.slice
public function slice($offset, $length = null) { $offset = $this->prepareOffset($offset); $length = $this->prepareLength($offset, $length); if ($length === 0) { return new Text('', $this->encoding); } return new Text(mb_substr($this->string, $offset, $length, $this->encoding), $this->encoding); }
php
public function slice($offset, $length = null) { $offset = $this->prepareOffset($offset); $length = $this->prepareLength($offset, $length); if ($length === 0) { return new Text('', $this->encoding); } return new Text(mb_substr($this->string, $offset, $length, $this->encoding), $this->encoding); }
[ "public", "function", "slice", "(", "$", "offset", ",", "$", "length", "=", "null", ")", "{", "$", "offset", "=", "$", "this", "->", "prepareOffset", "(", "$", "offset", ")", ";", "$", "length", "=", "$", "this", "->", "prepareLength", "(", "$", "offset", ",", "$", "length", ")", ";", "if", "(", "$", "length", "===", "0", ")", "{", "return", "new", "Text", "(", "''", ",", "$", "this", "->", "encoding", ")", ";", "}", "return", "new", "Text", "(", "mb_substr", "(", "$", "this", "->", "string", ",", "$", "offset", ",", "$", "length", ",", "$", "this", "->", "encoding", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Slices a piece of the string from a given offset with a specified length. If no length is given, the String is sliced to its maximum length. @see #substring @param int $offset @param int $length @return Text
[ "Slices", "a", "piece", "of", "the", "string", "from", "a", "given", "offset", "with", "a", "specified", "length", ".", "If", "no", "length", "is", "given", "the", "String", "is", "sliced", "to", "its", "maximum", "length", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L206-L215
phootwork/lang
src/Text.php
Text.substring
public function substring($start, $end = null) { $length = $this->length(); if ($end < 0) { $end = $length + $end; } $end = $end !== null ? min($end, $length) : $length; $start = min($start, $end); $end = max($start, $end); $end = $end - $start; return new Text(mb_substr($this->string, $start, $end, $this->encoding), $this->encoding); }
php
public function substring($start, $end = null) { $length = $this->length(); if ($end < 0) { $end = $length + $end; } $end = $end !== null ? min($end, $length) : $length; $start = min($start, $end); $end = max($start, $end); $end = $end - $start; return new Text(mb_substr($this->string, $start, $end, $this->encoding), $this->encoding); }
[ "public", "function", "substring", "(", "$", "start", ",", "$", "end", "=", "null", ")", "{", "$", "length", "=", "$", "this", "->", "length", "(", ")", ";", "if", "(", "$", "end", "<", "0", ")", "{", "$", "end", "=", "$", "length", "+", "$", "end", ";", "}", "$", "end", "=", "$", "end", "!==", "null", "?", "min", "(", "$", "end", ",", "$", "length", ")", ":", "$", "length", ";", "$", "start", "=", "min", "(", "$", "start", ",", "$", "end", ")", ";", "$", "end", "=", "max", "(", "$", "start", ",", "$", "end", ")", ";", "$", "end", "=", "$", "end", "-", "$", "start", ";", "return", "new", "Text", "(", "mb_substr", "(", "$", "this", "->", "string", ",", "$", "start", ",", "$", "end", ",", "$", "this", "->", "encoding", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Slices a piece of the string from a given start to an end. If no length is given, the String is sliced to its maximum length. @see #slice @param int $start @param int $end @return Text
[ "Slices", "a", "piece", "of", "the", "string", "from", "a", "given", "start", "to", "an", "end", ".", "If", "no", "length", "is", "given", "the", "String", "is", "sliced", "to", "its", "maximum", "length", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L226-L237
phootwork/lang
src/Text.php
Text.countSubstring
public function countSubstring($substring, $caseSensitive = true) { $this->verifyNotEmpty($substring, '$substring'); if ($caseSensitive) { return mb_substr_count($this->string, $substring, $this->encoding); } $str = mb_strtoupper($this->string, $this->encoding); $substring = mb_strtoupper($substring, $this->encoding); return mb_substr_count($str, $substring, $this->encoding); }
php
public function countSubstring($substring, $caseSensitive = true) { $this->verifyNotEmpty($substring, '$substring'); if ($caseSensitive) { return mb_substr_count($this->string, $substring, $this->encoding); } $str = mb_strtoupper($this->string, $this->encoding); $substring = mb_strtoupper($substring, $this->encoding); return mb_substr_count($str, $substring, $this->encoding); }
[ "public", "function", "countSubstring", "(", "$", "substring", ",", "$", "caseSensitive", "=", "true", ")", "{", "$", "this", "->", "verifyNotEmpty", "(", "$", "substring", ",", "'$substring'", ")", ";", "if", "(", "$", "caseSensitive", ")", "{", "return", "mb_substr_count", "(", "$", "this", "->", "string", ",", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "}", "$", "str", "=", "mb_strtoupper", "(", "$", "this", "->", "string", ",", "$", "this", "->", "encoding", ")", ";", "$", "substring", "=", "mb_strtoupper", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "return", "mb_substr_count", "(", "$", "str", ",", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Count the number of substring occurrences. @param string|Text $substring The substring to count the occurrencies @param boolean $caseSensitive Force case-sensitivity @return int
[ "Count", "the", "number", "of", "substring", "occurrences", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L246-L254
phootwork/lang
src/Text.php
Text.replace
public function replace($search, $replace) { if ($search instanceof Text) { $search = $search->toString(); } else if ($search instanceof Arrayable) { $search = $search->toArray(); } if ($replace instanceof Text) { $replace = $replace->toString(); } else if ($replace instanceof Arrayable) { $replace = $replace->toArray(); } return new Text(str_replace($search, $replace, $this->string), $this->encoding); }
php
public function replace($search, $replace) { if ($search instanceof Text) { $search = $search->toString(); } else if ($search instanceof Arrayable) { $search = $search->toArray(); } if ($replace instanceof Text) { $replace = $replace->toString(); } else if ($replace instanceof Arrayable) { $replace = $replace->toArray(); } return new Text(str_replace($search, $replace, $this->string), $this->encoding); }
[ "public", "function", "replace", "(", "$", "search", ",", "$", "replace", ")", "{", "if", "(", "$", "search", "instanceof", "Text", ")", "{", "$", "search", "=", "$", "search", "->", "toString", "(", ")", ";", "}", "else", "if", "(", "$", "search", "instanceof", "Arrayable", ")", "{", "$", "search", "=", "$", "search", "->", "toArray", "(", ")", ";", "}", "if", "(", "$", "replace", "instanceof", "Text", ")", "{", "$", "replace", "=", "$", "replace", "->", "toString", "(", ")", ";", "}", "else", "if", "(", "$", "replace", "instanceof", "Arrayable", ")", "{", "$", "replace", "=", "$", "replace", "->", "toArray", "(", ")", ";", "}", "return", "new", "Text", "(", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "this", "->", "string", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Replace all occurrences of the search string with the replacement string @see #supplant @param Arrayable|Text|array|string $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles. @param Arrayable|Text|array|string $replace The replacement value that replaces found search values. An array may be used to designate multiple replacements. @return Text
[ "Replace", "all", "occurrences", "of", "the", "search", "string", "with", "the", "replacement", "string" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L275-L289
phootwork/lang
src/Text.php
Text.supplant
public function supplant(array $map) { return new Text(str_replace(array_keys($map), array_values($map), $this->string), $this->encoding); }
php
public function supplant(array $map) { return new Text(str_replace(array_keys($map), array_values($map), $this->string), $this->encoding); }
[ "public", "function", "supplant", "(", "array", "$", "map", ")", "{", "return", "new", "Text", "(", "str_replace", "(", "array_keys", "(", "$", "map", ")", ",", "array_values", "(", "$", "map", ")", ",", "$", "this", "->", "string", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Replaces all occurences of given replacement map. Keys will be replaced with its values. @param array $map the replacements. Keys will be replaced with its value. @return Text
[ "Replaces", "all", "occurences", "of", "given", "replacement", "map", ".", "Keys", "will", "be", "replaced", "with", "its", "values", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L297-L299
phootwork/lang
src/Text.php
Text.splice
public function splice($replacement, $offset, $length = null) { $offset = $this->prepareOffset($offset); $length = $this->prepareLength($offset, $length); $start = $this->substring(0, $offset); $end = $this->substring($offset + $length); return new Text($start . $replacement . $end); }
php
public function splice($replacement, $offset, $length = null) { $offset = $this->prepareOffset($offset); $length = $this->prepareLength($offset, $length); $start = $this->substring(0, $offset); $end = $this->substring($offset + $length); return new Text($start . $replacement . $end); }
[ "public", "function", "splice", "(", "$", "replacement", ",", "$", "offset", ",", "$", "length", "=", "null", ")", "{", "$", "offset", "=", "$", "this", "->", "prepareOffset", "(", "$", "offset", ")", ";", "$", "length", "=", "$", "this", "->", "prepareLength", "(", "$", "offset", ",", "$", "length", ")", ";", "$", "start", "=", "$", "this", "->", "substring", "(", "0", ",", "$", "offset", ")", ";", "$", "end", "=", "$", "this", "->", "substring", "(", "$", "offset", "+", "$", "length", ")", ";", "return", "new", "Text", "(", "$", "start", ".", "$", "replacement", ".", "$", "end", ")", ";", "}" ]
Replace text within a portion of a string. @param string|Text $replacement @param int $offset @param int|null $length @return Text @throws \InvalidArgumentException If $offset is greater then the string length or $length is too small.
[ "Replace", "text", "within", "a", "portion", "of", "a", "string", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L310-L318
phootwork/lang
src/Text.php
Text.chars
public function chars() { $chars = new ArrayObject(); for ($i = 0, $l = $this->length(); $i < $l; $i++) { $chars->push($this->at($i)); } return $chars; }
php
public function chars() { $chars = new ArrayObject(); for ($i = 0, $l = $this->length(); $i < $l; $i++) { $chars->push($this->at($i)); } return $chars; }
[ "public", "function", "chars", "(", ")", "{", "$", "chars", "=", "new", "ArrayObject", "(", ")", ";", "for", "(", "$", "i", "=", "0", ",", "$", "l", "=", "$", "this", "->", "length", "(", ")", ";", "$", "i", "<", "$", "l", ";", "$", "i", "++", ")", "{", "$", "chars", "->", "push", "(", "$", "this", "->", "at", "(", "$", "i", ")", ")", ";", "}", "return", "$", "chars", ";", "}" ]
Returns an ArrayObject consisting of the characters in the string. @return ArrayObject An ArrayObject of all chars
[ "Returns", "an", "ArrayObject", "consisting", "of", "the", "characters", "in", "the", "string", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L349-L355
phootwork/lang
src/Text.php
Text.indexOf
public function indexOf($string, $offset = 0) { $offset = $this->prepareOffset($offset); if ($string == '') { return $offset; } return mb_strpos($this->string, (string) $string, $offset, $this->encoding); }
php
public function indexOf($string, $offset = 0) { $offset = $this->prepareOffset($offset); if ($string == '') { return $offset; } return mb_strpos($this->string, (string) $string, $offset, $this->encoding); }
[ "public", "function", "indexOf", "(", "$", "string", ",", "$", "offset", "=", "0", ")", "{", "$", "offset", "=", "$", "this", "->", "prepareOffset", "(", "$", "offset", ")", ";", "if", "(", "$", "string", "==", "''", ")", "{", "return", "$", "offset", ";", "}", "return", "mb_strpos", "(", "$", "this", "->", "string", ",", "(", "string", ")", "$", "string", ",", "$", "offset", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Returns the index of a given string, starting at the optional zero-related offset @param string $string @param int $offset zero-related offset @return int|boolean int for the index or false if the given string doesn't occur
[ "Returns", "the", "index", "of", "a", "given", "string", "starting", "at", "the", "optional", "zero", "-", "related", "offset" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L364-L372
phootwork/lang
src/Text.php
Text.lastIndexOf
public function lastIndexOf($string, $offset = null) { if (null === $offset) { $offset = $this->length(); } else { $offset = $this->prepareOffset($offset); } if ($string === '') { return $offset; } /* Converts $offset to a negative offset as strrpos has a different * behavior for positive offsets. */ return mb_strrpos($this, (string) $string, $offset - $this->length(), $this->encoding); }
php
public function lastIndexOf($string, $offset = null) { if (null === $offset) { $offset = $this->length(); } else { $offset = $this->prepareOffset($offset); } if ($string === '') { return $offset; } /* Converts $offset to a negative offset as strrpos has a different * behavior for positive offsets. */ return mb_strrpos($this, (string) $string, $offset - $this->length(), $this->encoding); }
[ "public", "function", "lastIndexOf", "(", "$", "string", ",", "$", "offset", "=", "null", ")", "{", "if", "(", "null", "===", "$", "offset", ")", "{", "$", "offset", "=", "$", "this", "->", "length", "(", ")", ";", "}", "else", "{", "$", "offset", "=", "$", "this", "->", "prepareOffset", "(", "$", "offset", ")", ";", "}", "if", "(", "$", "string", "===", "''", ")", "{", "return", "$", "offset", ";", "}", "/* Converts $offset to a negative offset as strrpos has a different\n\t\t * behavior for positive offsets. */", "return", "mb_strrpos", "(", "$", "this", ",", "(", "string", ")", "$", "string", ",", "$", "offset", "-", "$", "this", "->", "length", "(", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Returns the last index of a given string, starting at the optional offset @param string $string @param int $offset @return int|boolean int for the index or false if the given string doesn't occur
[ "Returns", "the", "last", "index", "of", "a", "given", "string", "starting", "at", "the", "optional", "offset" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L381-L395
phootwork/lang
src/Text.php
Text.startsWith
public function startsWith($substring) { $substringLength = mb_strlen($substring, $this->encoding); $startOfStr = mb_substr($this->string, 0, $substringLength, $this->encoding); return (string) $substring === $startOfStr; }
php
public function startsWith($substring) { $substringLength = mb_strlen($substring, $this->encoding); $startOfStr = mb_substr($this->string, 0, $substringLength, $this->encoding); return (string) $substring === $startOfStr; }
[ "public", "function", "startsWith", "(", "$", "substring", ")", "{", "$", "substringLength", "=", "mb_strlen", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "$", "startOfStr", "=", "mb_substr", "(", "$", "this", "->", "string", ",", "0", ",", "$", "substringLength", ",", "$", "this", "->", "encoding", ")", ";", "return", "(", "string", ")", "$", "substring", "===", "$", "startOfStr", ";", "}" ]
Checks whether the string starts with the given string. Case sensitive! @see Text::startsWithIgnoreCase() @param string|Text $substring The substring to look for @return boolean
[ "Checks", "whether", "the", "string", "starts", "with", "the", "given", "string", ".", "Case", "sensitive!" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L404-L409
phootwork/lang
src/Text.php
Text.startsWithIgnoreCase
public function startsWithIgnoreCase($substring) { $substring = mb_strtolower($substring, $this->encoding); $substringLength = mb_strlen($substring, $this->encoding); $startOfStr = mb_strtolower(mb_substr($this->string, 0, $substringLength, $this->encoding)); return (string) $substring === $startOfStr; }
php
public function startsWithIgnoreCase($substring) { $substring = mb_strtolower($substring, $this->encoding); $substringLength = mb_strlen($substring, $this->encoding); $startOfStr = mb_strtolower(mb_substr($this->string, 0, $substringLength, $this->encoding)); return (string) $substring === $startOfStr; }
[ "public", "function", "startsWithIgnoreCase", "(", "$", "substring", ")", "{", "$", "substring", "=", "mb_strtolower", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "$", "substringLength", "=", "mb_strlen", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "$", "startOfStr", "=", "mb_strtolower", "(", "mb_substr", "(", "$", "this", "->", "string", ",", "0", ",", "$", "substringLength", ",", "$", "this", "->", "encoding", ")", ")", ";", "return", "(", "string", ")", "$", "substring", "===", "$", "startOfStr", ";", "}" ]
Checks whether the string starts with the given string. Ignores case. @see Text::startsWith() @param string|Text $substring The substring to look for @return boolean
[ "Checks", "whether", "the", "string", "starts", "with", "the", "given", "string", ".", "Ignores", "case", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L418-L424
phootwork/lang
src/Text.php
Text.endsWith
public function endsWith($substring) { $substringLength = mb_strlen($substring, $this->encoding); $endOfStr = mb_substr($this->string, $this->length() - $substringLength, $substringLength, $this->encoding); return (string) $substring === $endOfStr; }
php
public function endsWith($substring) { $substringLength = mb_strlen($substring, $this->encoding); $endOfStr = mb_substr($this->string, $this->length() - $substringLength, $substringLength, $this->encoding); return (string) $substring === $endOfStr; }
[ "public", "function", "endsWith", "(", "$", "substring", ")", "{", "$", "substringLength", "=", "mb_strlen", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "$", "endOfStr", "=", "mb_substr", "(", "$", "this", "->", "string", ",", "$", "this", "->", "length", "(", ")", "-", "$", "substringLength", ",", "$", "substringLength", ",", "$", "this", "->", "encoding", ")", ";", "return", "(", "string", ")", "$", "substring", "===", "$", "endOfStr", ";", "}" ]
Checks whether the string ends with the given string. Case sensitive! @see Text::endsWithIgnoreCase() @param string|Text $substring The substring to look for @return boolean
[ "Checks", "whether", "the", "string", "ends", "with", "the", "given", "string", ".", "Case", "sensitive!" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L433-L438
phootwork/lang
src/Text.php
Text.endsWithIgnoreCase
public function endsWithIgnoreCase($substring) { $substring = mb_strtolower($substring, $this->encoding); $substringLength = mb_strlen($substring, $this->encoding); $endOfStr = mb_strtolower(mb_substr($this->string, $this->length() - $substringLength, $substringLength, $this->encoding)); return (string) $substring === $endOfStr; }
php
public function endsWithIgnoreCase($substring) { $substring = mb_strtolower($substring, $this->encoding); $substringLength = mb_strlen($substring, $this->encoding); $endOfStr = mb_strtolower(mb_substr($this->string, $this->length() - $substringLength, $substringLength, $this->encoding)); return (string) $substring === $endOfStr; }
[ "public", "function", "endsWithIgnoreCase", "(", "$", "substring", ")", "{", "$", "substring", "=", "mb_strtolower", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "$", "substringLength", "=", "mb_strlen", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "$", "endOfStr", "=", "mb_strtolower", "(", "mb_substr", "(", "$", "this", "->", "string", ",", "$", "this", "->", "length", "(", ")", "-", "$", "substringLength", ",", "$", "substringLength", ",", "$", "this", "->", "encoding", ")", ")", ";", "return", "(", "string", ")", "$", "substring", "===", "$", "endOfStr", ";", "}" ]
Checks whether the string ends with the given string. Ingores case. @see Text::endsWith() @param string|Text $substring The substring to look for @return boolean
[ "Checks", "whether", "the", "string", "ends", "with", "the", "given", "string", ".", "Ingores", "case", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L447-L453
phootwork/lang
src/Text.php
Text.trim
public function trim($characters = " \t\n\r\v\0") { return new Text(trim($this->string, (string) $characters), $this->encoding); }
php
public function trim($characters = " \t\n\r\v\0") { return new Text(trim($this->string, (string) $characters), $this->encoding); }
[ "public", "function", "trim", "(", "$", "characters", "=", "\" \\t\\n\\r\\v\\0\"", ")", "{", "return", "new", "Text", "(", "trim", "(", "$", "this", "->", "string", ",", "(", "string", ")", "$", "characters", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Strip whitespace (or other characters) from the beginning and end of the string @param string $characters Optionally, the stripped characters can also be specified using the mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. @return Text
[ "Strip", "whitespace", "(", "or", "other", "characters", ")", "from", "the", "beginning", "and", "end", "of", "the", "string" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L491-L493
phootwork/lang
src/Text.php
Text.trimStart
public function trimStart($characters = " \t\n\r\v\0") { return new Text(ltrim($this->string, (string) $characters), $this->encoding); }
php
public function trimStart($characters = " \t\n\r\v\0") { return new Text(ltrim($this->string, (string) $characters), $this->encoding); }
[ "public", "function", "trimStart", "(", "$", "characters", "=", "\" \\t\\n\\r\\v\\0\"", ")", "{", "return", "new", "Text", "(", "ltrim", "(", "$", "this", "->", "string", ",", "(", "string", ")", "$", "characters", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Strip whitespace (or other characters) from the beginning of the string @param string $characters Optionally, the stripped characters can also be specified using the mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. @return Text
[ "Strip", "whitespace", "(", "or", "other", "characters", ")", "from", "the", "beginning", "of", "the", "string" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L505-L507
phootwork/lang
src/Text.php
Text.trimEnd
public function trimEnd($characters = " \t\n\r\v\0") { return new Text(rtrim($this->string, (string) $characters), $this->encoding); }
php
public function trimEnd($characters = " \t\n\r\v\0") { return new Text(rtrim($this->string, (string) $characters), $this->encoding); }
[ "public", "function", "trimEnd", "(", "$", "characters", "=", "\" \\t\\n\\r\\v\\0\"", ")", "{", "return", "new", "Text", "(", "rtrim", "(", "$", "this", "->", "string", ",", "(", "string", ")", "$", "characters", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Strip whitespace (or other characters) from the end of the string @param string $characters Optionally, the stripped characters can also be specified using the mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters. @return Text
[ "Strip", "whitespace", "(", "or", "other", "characters", ")", "from", "the", "end", "of", "the", "string" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L519-L521
phootwork/lang
src/Text.php
Text.pad
public function pad($length, $padding = ' ') { $len = $length - $this->length(); return $this->applyPadding(floor($len / 2), ceil($len / 2), $padding); }
php
public function pad($length, $padding = ' ') { $len = $length - $this->length(); return $this->applyPadding(floor($len / 2), ceil($len / 2), $padding); }
[ "public", "function", "pad", "(", "$", "length", ",", "$", "padding", "=", "' '", ")", "{", "$", "len", "=", "$", "length", "-", "$", "this", "->", "length", "(", ")", ";", "return", "$", "this", "->", "applyPadding", "(", "floor", "(", "$", "len", "/", "2", ")", ",", "ceil", "(", "$", "len", "/", "2", ")", ",", "$", "padding", ")", ";", "}" ]
Adds padding to the start and end @param int $length @param string $padding @return Text
[ "Adds", "padding", "to", "the", "start", "and", "end" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L530-L533
phootwork/lang
src/Text.php
Text.applyPadding
protected function applyPadding($left = 0, $right = 0, $padStr = ' ') { $length = mb_strlen($padStr, $this->encoding); $strLength = $this->length(); $paddedLength = $strLength + $left + $right; if (!$length || $paddedLength <= $strLength) { return $this; } $leftPadding = mb_substr(str_repeat($padStr, ceil($left / $length)), 0, $left, $this->encoding); $rightPadding = mb_substr(str_repeat($padStr, ceil($right / $length)), 0, $right, $this->encoding); return new Text($leftPadding . $this->string . $rightPadding); }
php
protected function applyPadding($left = 0, $right = 0, $padStr = ' ') { $length = mb_strlen($padStr, $this->encoding); $strLength = $this->length(); $paddedLength = $strLength + $left + $right; if (!$length || $paddedLength <= $strLength) { return $this; } $leftPadding = mb_substr(str_repeat($padStr, ceil($left / $length)), 0, $left, $this->encoding); $rightPadding = mb_substr(str_repeat($padStr, ceil($right / $length)), 0, $right, $this->encoding); return new Text($leftPadding . $this->string . $rightPadding); }
[ "protected", "function", "applyPadding", "(", "$", "left", "=", "0", ",", "$", "right", "=", "0", ",", "$", "padStr", "=", "' '", ")", "{", "$", "length", "=", "mb_strlen", "(", "$", "padStr", ",", "$", "this", "->", "encoding", ")", ";", "$", "strLength", "=", "$", "this", "->", "length", "(", ")", ";", "$", "paddedLength", "=", "$", "strLength", "+", "$", "left", "+", "$", "right", ";", "if", "(", "!", "$", "length", "||", "$", "paddedLength", "<=", "$", "strLength", ")", "{", "return", "$", "this", ";", "}", "$", "leftPadding", "=", "mb_substr", "(", "str_repeat", "(", "$", "padStr", ",", "ceil", "(", "$", "left", "/", "$", "length", ")", ")", ",", "0", ",", "$", "left", ",", "$", "this", "->", "encoding", ")", ";", "$", "rightPadding", "=", "mb_substr", "(", "str_repeat", "(", "$", "padStr", ",", "ceil", "(", "$", "right", "/", "$", "length", ")", ")", ",", "0", ",", "$", "right", ",", "$", "this", "->", "encoding", ")", ";", "return", "new", "Text", "(", "$", "leftPadding", ".", "$", "this", "->", "string", ".", "$", "rightPadding", ")", ";", "}" ]
Adds the specified amount of left and right padding to the given string. The default character used is a space. @see https://github.com/danielstjules/Stringy/blob/master/src/Stringy.php @param int $left Length of left padding @param int $right Length of right padding @param string $padStr String used to pad @return Text the padded string
[ "Adds", "the", "specified", "amount", "of", "left", "and", "right", "padding", "to", "the", "given", "string", ".", "The", "default", "character", "used", "is", "a", "space", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L567-L578
phootwork/lang
src/Text.php
Text.wrapWords
public function wrapWords($width = 75, $break = "\n", $cut = false) { return new Text(wordwrap($this->string, $width, $break, $cut), $this->encoding); }
php
public function wrapWords($width = 75, $break = "\n", $cut = false) { return new Text(wordwrap($this->string, $width, $break, $cut), $this->encoding); }
[ "public", "function", "wrapWords", "(", "$", "width", "=", "75", ",", "$", "break", "=", "\"\\n\"", ",", "$", "cut", "=", "false", ")", "{", "return", "new", "Text", "(", "wordwrap", "(", "$", "this", "->", "string", ",", "$", "width", ",", "$", "break", ",", "$", "cut", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Returns a copy of the string wrapped at a given number of characters @param int $width The number of characters at which the string will be wrapped. @param string $break The line is broken using the optional break parameter. @param bool $cut If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. @return Text Returns the string wrapped at the specified length.
[ "Returns", "a", "copy", "of", "the", "string", "wrapped", "at", "a", "given", "number", "of", "characters" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L616-L618
phootwork/lang
src/Text.php
Text.repeat
public function repeat($multiplier) { $this->verifyNotNegative($multiplier, 'Number of repetitions'); return new Text(str_repeat($this->string, $multiplier), $this->encoding); }
php
public function repeat($multiplier) { $this->verifyNotNegative($multiplier, 'Number of repetitions'); return new Text(str_repeat($this->string, $multiplier), $this->encoding); }
[ "public", "function", "repeat", "(", "$", "multiplier", ")", "{", "$", "this", "->", "verifyNotNegative", "(", "$", "multiplier", ",", "'Number of repetitions'", ")", ";", "return", "new", "Text", "(", "str_repeat", "(", "$", "this", "->", "string", ",", "$", "multiplier", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Repeat the string $times times. If $times is 0, it returns ''. @param int $multiplier @return Text @throws \InvalidArgumentException If $times is negative.
[ "Repeat", "the", "string", "$times", "times", ".", "If", "$times", "is", "0", "it", "returns", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L627-L630
phootwork/lang
src/Text.php
Text.truncate
public function truncate($length, $substring = '') { if ($this->length() <= $length) { return new Text($this->string, $this->encoding); } $substrLen = mb_strlen($substring, $this->encoding); if ($this->length() + $substrLen > $length) { $length -= $substrLen; } return $this->substring(0, $length)->append($substring); }
php
public function truncate($length, $substring = '') { if ($this->length() <= $length) { return new Text($this->string, $this->encoding); } $substrLen = mb_strlen($substring, $this->encoding); if ($this->length() + $substrLen > $length) { $length -= $substrLen; } return $this->substring(0, $length)->append($substring); }
[ "public", "function", "truncate", "(", "$", "length", ",", "$", "substring", "=", "''", ")", "{", "if", "(", "$", "this", "->", "length", "(", ")", "<=", "$", "length", ")", "{", "return", "new", "Text", "(", "$", "this", "->", "string", ",", "$", "this", "->", "encoding", ")", ";", "}", "$", "substrLen", "=", "mb_strlen", "(", "$", "substring", ",", "$", "this", "->", "encoding", ")", ";", "if", "(", "$", "this", "->", "length", "(", ")", "+", "$", "substrLen", ">", "$", "length", ")", "{", "$", "length", "-=", "$", "substrLen", ";", "}", "return", "$", "this", "->", "substring", "(", "0", ",", "$", "length", ")", "->", "append", "(", "$", "substring", ")", ";", "}" ]
Truncates the string with a substring and ensures it doesn't exceed the given length @param int $length @param string $substring @return Text
[ "Truncates", "the", "string", "with", "a", "substring", "and", "ensures", "it", "doesn", "t", "exceed", "the", "given", "length" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L648-L660
phootwork/lang
src/Text.php
Text.split
public function split($delimiter, $limit = PHP_INT_MAX) { return new ArrayObject(explode($delimiter, $this->string, $limit)); }
php
public function split($delimiter, $limit = PHP_INT_MAX) { return new ArrayObject(explode($delimiter, $this->string, $limit)); }
[ "public", "function", "split", "(", "$", "delimiter", ",", "$", "limit", "=", "PHP_INT_MAX", ")", "{", "return", "new", "ArrayObject", "(", "explode", "(", "$", "delimiter", ",", "$", "this", "->", "string", ",", "$", "limit", ")", ")", ";", "}" ]
Splits the string by string @param string $delimiter The boundary string. @param integer $limit If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last -limit are returned. If the limit parameter is zero, then this is treated as 1. @return ArrayObject Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter. If delimiter is an empty string (""), split() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. @TODO: Maybe throw an exception or something on those odd delimiters?
[ "Splits", "the", "string", "by", "string" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L692-L694
phootwork/lang
src/Text.php
Text.join
public static function join(array $pieces, $glue = '', $encoding = null) { return new Text(implode($pieces, $glue), $encoding); }
php
public static function join(array $pieces, $glue = '', $encoding = null) { return new Text(implode($pieces, $glue), $encoding); }
[ "public", "static", "function", "join", "(", "array", "$", "pieces", ",", "$", "glue", "=", "''", ",", "$", "encoding", "=", "null", ")", "{", "return", "new", "Text", "(", "implode", "(", "$", "pieces", ",", "$", "glue", ")", ",", "$", "encoding", ")", ";", "}" ]
Join array elements with a string @param array $pieces The array of strings to join. @param string $glue Defaults to an empty string. @param string $encoding the desired encoding @return Text Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
[ "Join", "array", "elements", "with", "a", "string" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L706-L708
phootwork/lang
src/Text.php
Text.chunk
public function chunk($splitLength = 1) { $this->verifyPositive($splitLength, 'The chunk length'); return new ArrayObject(str_split($this->string, $splitLength)); }
php
public function chunk($splitLength = 1) { $this->verifyPositive($splitLength, 'The chunk length'); return new ArrayObject(str_split($this->string, $splitLength)); }
[ "public", "function", "chunk", "(", "$", "splitLength", "=", "1", ")", "{", "$", "this", "->", "verifyPositive", "(", "$", "splitLength", ",", "'The chunk length'", ")", ";", "return", "new", "ArrayObject", "(", "str_split", "(", "$", "this", "->", "string", ",", "$", "splitLength", ")", ")", ";", "}" ]
Convert the string to an array @param int $splitLength Maximum length of the chunk. @return ArrayObject If the optional splitLength parameter is specified, the returned array will be broken down into chunks with each being splitLength in length, otherwise each chunk will be one character in length. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element. @throws \InvalidArgumentException If splitLength is less than 1.
[ "Convert", "the", "string", "to", "an", "array" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L723-L727
phootwork/lang
src/Text.php
Text.toLowerCaseFirst
public function toLowerCaseFirst() { $first = $this->substring(0, 1); $rest = $this->substring(1); return new Text(mb_strtolower($first, $this->encoding) . $rest, $this->encoding); }
php
public function toLowerCaseFirst() { $first = $this->substring(0, 1); $rest = $this->substring(1); return new Text(mb_strtolower($first, $this->encoding) . $rest, $this->encoding); }
[ "public", "function", "toLowerCaseFirst", "(", ")", "{", "$", "first", "=", "$", "this", "->", "substring", "(", "0", ",", "1", ")", ";", "$", "rest", "=", "$", "this", "->", "substring", "(", "1", ")", ";", "return", "new", "Text", "(", "mb_strtolower", "(", "$", "first", ",", "$", "this", "->", "encoding", ")", ".", "$", "rest", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Transforms the string to first character lowercased @return Text
[ "Transforms", "the", "string", "to", "first", "character", "lowercased" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L750-L755
phootwork/lang
src/Text.php
Text.toUpperCaseFirst
public function toUpperCaseFirst() { $first = $this->substring(0, 1); $rest = $this->substring(1); return new Text(mb_strtoupper($first, $this->encoding) . $rest, $this->encoding); }
php
public function toUpperCaseFirst() { $first = $this->substring(0, 1); $rest = $this->substring(1); return new Text(mb_strtoupper($first, $this->encoding) . $rest, $this->encoding); }
[ "public", "function", "toUpperCaseFirst", "(", ")", "{", "$", "first", "=", "$", "this", "->", "substring", "(", "0", ",", "1", ")", ";", "$", "rest", "=", "$", "this", "->", "substring", "(", "1", ")", ";", "return", "new", "Text", "(", "mb_strtoupper", "(", "$", "first", ",", "$", "this", "->", "encoding", ")", ".", "$", "rest", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Transforms the string to first character uppercased @return Text
[ "Transforms", "the", "string", "to", "first", "character", "uppercased" ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L771-L776
phootwork/lang
src/Text.php
Text.toCapitalCaseWords
public function toCapitalCaseWords() { $encoding = $this->encoding; return $this->split(' ')->map(function ($str) use ($encoding) { return Text::create($str, $encoding)->toCapitalCase(); })->join(' '); }
php
public function toCapitalCaseWords() { $encoding = $this->encoding; return $this->split(' ')->map(function ($str) use ($encoding) { return Text::create($str, $encoding)->toCapitalCase(); })->join(' '); }
[ "public", "function", "toCapitalCaseWords", "(", ")", "{", "$", "encoding", "=", "$", "this", "->", "encoding", ";", "return", "$", "this", "->", "split", "(", "' '", ")", "->", "map", "(", "function", "(", "$", "str", ")", "use", "(", "$", "encoding", ")", "{", "return", "Text", "::", "create", "(", "$", "str", ",", "$", "encoding", ")", "->", "toCapitalCase", "(", ")", ";", "}", ")", "->", "join", "(", "' '", ")", ";", "}" ]
Transforms the string with the words capitalized. @return Text
[ "Transforms", "the", "string", "with", "the", "words", "capitalized", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L792-L797
phootwork/lang
src/Text.php
Text.toStudlyCase
public function toStudlyCase() { $input = $this->trim('-_'); if ($input->isEmpty()) { return $input; } $encoding = $this->encoding; return Text::create(preg_replace_callback('/([A-Z-_][a-z0-9]+)/', function ($matches) use ($encoding) { return Text::create($matches[0], $encoding)->replace(['-', '_'], '')->toUpperCaseFirst(); }, $input), $this->encoding)->toUpperCaseFirst(); }
php
public function toStudlyCase() { $input = $this->trim('-_'); if ($input->isEmpty()) { return $input; } $encoding = $this->encoding; return Text::create(preg_replace_callback('/([A-Z-_][a-z0-9]+)/', function ($matches) use ($encoding) { return Text::create($matches[0], $encoding)->replace(['-', '_'], '')->toUpperCaseFirst(); }, $input), $this->encoding)->toUpperCaseFirst(); }
[ "public", "function", "toStudlyCase", "(", ")", "{", "$", "input", "=", "$", "this", "->", "trim", "(", "'-_'", ")", ";", "if", "(", "$", "input", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "input", ";", "}", "$", "encoding", "=", "$", "this", "->", "encoding", ";", "return", "Text", "::", "create", "(", "preg_replace_callback", "(", "'/([A-Z-_][a-z0-9]+)/'", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "encoding", ")", "{", "return", "Text", "::", "create", "(", "$", "matches", "[", "0", "]", ",", "$", "encoding", ")", "->", "replace", "(", "[", "'-'", ",", "'_'", "]", ",", "''", ")", "->", "toUpperCaseFirst", "(", ")", ";", "}", ",", "$", "input", ")", ",", "$", "this", "->", "encoding", ")", "->", "toUpperCaseFirst", "(", ")", ";", "}" ]
Converts this string into StudlyCase. Numbers are considered as part of its previous piece. <code> $var = new Text('my_own_variable');<br> $var->toStudlyCase(); // MyOwnVariable $var = new Text('my_test3_variable');<br> $var->toStudlyCase(); // MyTest3Variable </code> @return Text
[ "Converts", "this", "string", "into", "StudlyCase", ".", "Numbers", "are", "considered", "as", "part", "of", "its", "previous", "piece", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L846-L855
phootwork/lang
src/Text.php
Text.toKebabCase
public function toKebabCase() { if ($this->contains('_')) { return $this->replace('_', '-'); } return new Text(mb_strtolower(preg_replace('/([a-z0-9])([A-Z])/', '$1-$2', $this->string)), $this->encoding); }
php
public function toKebabCase() { if ($this->contains('_')) { return $this->replace('_', '-'); } return new Text(mb_strtolower(preg_replace('/([a-z0-9])([A-Z])/', '$1-$2', $this->string)), $this->encoding); }
[ "public", "function", "toKebabCase", "(", ")", "{", "if", "(", "$", "this", "->", "contains", "(", "'_'", ")", ")", "{", "return", "$", "this", "->", "replace", "(", "'_'", ",", "'-'", ")", ";", "}", "return", "new", "Text", "(", "mb_strtolower", "(", "preg_replace", "(", "'/([a-z0-9])([A-Z])/'", ",", "'$1-$2'", ",", "$", "this", "->", "string", ")", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Convert this string into kebab-case. Numbers are considered as part of its previous piece. <code> $var = new Text('myOwnVariable');<br> $var->toKebapCase(); // my-own-variable $var = new Text('myTest3Variable');<br> $var->toKebapCase(); // my-test3-variable </code> @return Text
[ "Convert", "this", "string", "into", "kebab", "-", "case", ".", "Numbers", "are", "considered", "as", "part", "of", "its", "previous", "piece", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L870-L876
phootwork/lang
src/Text.php
Text.toPlural
public function toPlural(Pluralizer $pluralizer = null) { $pluralizer = $pluralizer ?: new EnglishPluralizer(); return new Text($pluralizer->getPluralForm($this->string), $this->encoding); }
php
public function toPlural(Pluralizer $pluralizer = null) { $pluralizer = $pluralizer ?: new EnglishPluralizer(); return new Text($pluralizer->getPluralForm($this->string), $this->encoding); }
[ "public", "function", "toPlural", "(", "Pluralizer", "$", "pluralizer", "=", "null", ")", "{", "$", "pluralizer", "=", "$", "pluralizer", "?", ":", "new", "EnglishPluralizer", "(", ")", ";", "return", "new", "Text", "(", "$", "pluralizer", "->", "getPluralForm", "(", "$", "this", "->", "string", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Get the plural form of the Text object. @return Text
[ "Get", "the", "plural", "form", "of", "the", "Text", "object", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L883-L887
phootwork/lang
src/Text.php
Text.toSingular
public function toSingular(Pluralizer $pluralizer = null) { $pluralizer = $pluralizer ?: new EnglishPluralizer(); return new Text($pluralizer->getSingularForm($this->string), $this->encoding); }
php
public function toSingular(Pluralizer $pluralizer = null) { $pluralizer = $pluralizer ?: new EnglishPluralizer(); return new Text($pluralizer->getSingularForm($this->string), $this->encoding); }
[ "public", "function", "toSingular", "(", "Pluralizer", "$", "pluralizer", "=", "null", ")", "{", "$", "pluralizer", "=", "$", "pluralizer", "?", ":", "new", "EnglishPluralizer", "(", ")", ";", "return", "new", "Text", "(", "$", "pluralizer", "->", "getSingularForm", "(", "$", "this", "->", "string", ")", ",", "$", "this", "->", "encoding", ")", ";", "}" ]
Get the singular form of the Text object. @return Text
[ "Get", "the", "singular", "form", "of", "the", "Text", "object", "." ]
train
https://github.com/phootwork/lang/blob/2e5dc084d9102bf6b4c60f3ec2acc2ef49861588/src/Text.php#L894-L898
rhosocial/yii2-user
security/PasswordHistory.php
PasswordHistory.validatePassword
public function validatePassword($password) { if (static::judgePasswordHash($password)) { return $this->{$this->passwordHashAttribute} == $password; } return Yii::$app->security->validatePassword($password, $this->{$this->passwordHashAttribute}); }
php
public function validatePassword($password) { if (static::judgePasswordHash($password)) { return $this->{$this->passwordHashAttribute} == $password; } return Yii::$app->security->validatePassword($password, $this->{$this->passwordHashAttribute}); }
[ "public", "function", "validatePassword", "(", "$", "password", ")", "{", "if", "(", "static", "::", "judgePasswordHash", "(", "$", "password", ")", ")", "{", "return", "$", "this", "->", "{", "$", "this", "->", "passwordHashAttribute", "}", "==", "$", "password", ";", "}", "return", "Yii", "::", "$", "app", "->", "security", "->", "validatePassword", "(", "$", "password", ",", "$", "this", "->", "{", "$", "this", "->", "passwordHashAttribute", "}", ")", ";", "}" ]
Validate password. @param string $password Password or Password Hash. @return boolean
[ "Validate", "password", "." ]
train
https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/security/PasswordHistory.php#L48-L54
rhosocial/yii2-user
security/PasswordHistory.php
PasswordHistory.isUsed
public static function isUsed($password, $user = null) { if (!User::isValid($user)) { throw new InvalidParamException('User Invalid.'); } $passwords = static::find()->createdBy($user)->all(); foreach ($passwords as $p) { /* @var $p static */ if ($p->validatePassword($password)) { return $p; } } return false; }
php
public static function isUsed($password, $user = null) { if (!User::isValid($user)) { throw new InvalidParamException('User Invalid.'); } $passwords = static::find()->createdBy($user)->all(); foreach ($passwords as $p) { /* @var $p static */ if ($p->validatePassword($password)) { return $p; } } return false; }
[ "public", "static", "function", "isUsed", "(", "$", "password", ",", "$", "user", "=", "null", ")", "{", "if", "(", "!", "User", "::", "isValid", "(", "$", "user", ")", ")", "{", "throw", "new", "InvalidParamException", "(", "'User Invalid.'", ")", ";", "}", "$", "passwords", "=", "static", "::", "find", "(", ")", "->", "createdBy", "(", "$", "user", ")", "->", "all", "(", ")", ";", "foreach", "(", "$", "passwords", "as", "$", "p", ")", "{", "/* @var $p static */", "if", "(", "$", "p", "->", "validatePassword", "(", "$", "password", ")", ")", "{", "return", "$", "p", ";", "}", "}", "return", "false", ";", "}" ]
Check whether the password has been used. @param string $password Password or Password Hash. @param User $user @return false|static The first validated password model, or false if not validated.
[ "Check", "whether", "the", "password", "has", "been", "used", "." ]
train
https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/security/PasswordHistory.php#L62-L75
rhosocial/yii2-user
security/PasswordHistory.php
PasswordHistory.setPassword
public function setPassword($password) { $this->{$this->passwordHashAttribute} = Yii::$app->security->generatePasswordHash($password); }
php
public function setPassword($password) { $this->{$this->passwordHashAttribute} = Yii::$app->security->generatePasswordHash($password); }
[ "public", "function", "setPassword", "(", "$", "password", ")", "{", "$", "this", "->", "{", "$", "this", "->", "passwordHashAttribute", "}", "=", "Yii", "::", "$", "app", "->", "security", "->", "generatePasswordHash", "(", "$", "password", ")", ";", "}" ]
Set password. @param string $password
[ "Set", "password", "." ]
train
https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/security/PasswordHistory.php#L81-L84
rhosocial/yii2-user
security/PasswordHistory.php
PasswordHistory.add
public static function add($password, $user = null) { if (static::isUsed($password, $user) && !$user->allowUsedPassword) { throw new InvalidParamException('Password existed.'); } if (static::judgePasswordHash($password)) { $passwordHistory = $user->create(static::class); $passwordHistory->{$passwordHistory->passwordHashAttribute} = $password; } else { $passwordHistory = $user->create(static::class, ['password' => $password]); } /* @var $passwordHistory static */ return $passwordHistory->save(); }
php
public static function add($password, $user = null) { if (static::isUsed($password, $user) && !$user->allowUsedPassword) { throw new InvalidParamException('Password existed.'); } if (static::judgePasswordHash($password)) { $passwordHistory = $user->create(static::class); $passwordHistory->{$passwordHistory->passwordHashAttribute} = $password; } else { $passwordHistory = $user->create(static::class, ['password' => $password]); } /* @var $passwordHistory static */ return $passwordHistory->save(); }
[ "public", "static", "function", "add", "(", "$", "password", ",", "$", "user", "=", "null", ")", "{", "if", "(", "static", "::", "isUsed", "(", "$", "password", ",", "$", "user", ")", "&&", "!", "$", "user", "->", "allowUsedPassword", ")", "{", "throw", "new", "InvalidParamException", "(", "'Password existed.'", ")", ";", "}", "if", "(", "static", "::", "judgePasswordHash", "(", "$", "password", ")", ")", "{", "$", "passwordHistory", "=", "$", "user", "->", "create", "(", "static", "::", "class", ")", ";", "$", "passwordHistory", "->", "{", "$", "passwordHistory", "->", "passwordHashAttribute", "}", "=", "$", "password", ";", "}", "else", "{", "$", "passwordHistory", "=", "$", "user", "->", "create", "(", "static", "::", "class", ",", "[", "'password'", "=>", "$", "password", "]", ")", ";", "}", "/* @var $passwordHistory static */", "return", "$", "passwordHistory", "->", "save", "(", ")", ";", "}" ]
Add password to history. @param string $password Password or Password Hash. @param User $user @return boolean @throws InvalidParamException throw if password existed.
[ "Add", "password", "to", "history", "." ]
train
https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/security/PasswordHistory.php#L99-L112
rhosocial/yii2-user
security/PasswordHistory.php
PasswordHistory.first
public static function first($user = null) { if (!User::isValid($user)) { throw new InvalidParamException('User Invalid.'); } return static::find()->createdBy($user)->orderByCreatedAt()->one(); }
php
public static function first($user = null) { if (!User::isValid($user)) { throw new InvalidParamException('User Invalid.'); } return static::find()->createdBy($user)->orderByCreatedAt()->one(); }
[ "public", "static", "function", "first", "(", "$", "user", "=", "null", ")", "{", "if", "(", "!", "User", "::", "isValid", "(", "$", "user", ")", ")", "{", "throw", "new", "InvalidParamException", "(", "'User Invalid.'", ")", ";", "}", "return", "static", "::", "find", "(", ")", "->", "createdBy", "(", "$", "user", ")", "->", "orderByCreatedAt", "(", ")", "->", "one", "(", ")", ";", "}" ]
Get first password hash. @param User $user @return static @throws InvalidParamException throw if user invalid.
[ "Get", "first", "password", "hash", "." ]
train
https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/security/PasswordHistory.php#L146-L152
rhosocial/yii2-user
security/PasswordHistory.php
PasswordHistory.last
public static function last($user = null) { if (!User::isValid($user)) { throw new InvalidParamException('User Invalid.'); } return static::find()->createdBy($user)->orderByCreatedAt(SORT_DESC)->one(); }
php
public static function last($user = null) { if (!User::isValid($user)) { throw new InvalidParamException('User Invalid.'); } return static::find()->createdBy($user)->orderByCreatedAt(SORT_DESC)->one(); }
[ "public", "static", "function", "last", "(", "$", "user", "=", "null", ")", "{", "if", "(", "!", "User", "::", "isValid", "(", "$", "user", ")", ")", "{", "throw", "new", "InvalidParamException", "(", "'User Invalid.'", ")", ";", "}", "return", "static", "::", "find", "(", ")", "->", "createdBy", "(", "$", "user", ")", "->", "orderByCreatedAt", "(", "SORT_DESC", ")", "->", "one", "(", ")", ";", "}" ]
Get last password hash. @param User $user @return static @throws InvalidParamException throw if user invalid.
[ "Get", "last", "password", "hash", "." ]
train
https://github.com/rhosocial/yii2-user/blob/96737a9d8ca7e9c42cd2b7736d6c0a90ede6e5bc/security/PasswordHistory.php#L161-L167
highday/glitter
src/Http/Controllers/Office/Customer/SearchController.php
SearchController.search
public function search( string $preset = null, Request $request, SearchService $service, CustomerFinderGroup $finderGroup ) { // キーワードセット $keyword = $request->input('keyword', null); $service->setKeyword($keyword); $finder = ($preset) ? $finderGroup->getFinder($preset) : null; if (!$finder) { $default_finder = $finderGroup->getDefault(); if (!$default_finder) { throw new NotFoundHttpException(); } return redirect()->route('glitter.office.customer.search', ['preset' => $default_finder->getName()]); } $customers = $service->search($finder); return view('glitter.office::customer.search', compact('keyword', 'customers', 'preset', 'finder', 'finderGroup')); }
php
public function search( string $preset = null, Request $request, SearchService $service, CustomerFinderGroup $finderGroup ) { // キーワードセット $keyword = $request->input('keyword', null); $service->setKeyword($keyword); $finder = ($preset) ? $finderGroup->getFinder($preset) : null; if (!$finder) { $default_finder = $finderGroup->getDefault(); if (!$default_finder) { throw new NotFoundHttpException(); } return redirect()->route('glitter.office.customer.search', ['preset' => $default_finder->getName()]); } $customers = $service->search($finder); return view('glitter.office::customer.search', compact('keyword', 'customers', 'preset', 'finder', 'finderGroup')); }
[ "public", "function", "search", "(", "string", "$", "preset", "=", "null", ",", "Request", "$", "request", ",", "SearchService", "$", "service", ",", "CustomerFinderGroup", "$", "finderGroup", ")", "{", "// キーワードセット", "$", "keyword", "=", "$", "request", "->", "input", "(", "'keyword'", ",", "null", ")", ";", "$", "service", "->", "setKeyword", "(", "$", "keyword", ")", ";", "$", "finder", "=", "(", "$", "preset", ")", "?", "$", "finderGroup", "->", "getFinder", "(", "$", "preset", ")", ":", "null", ";", "if", "(", "!", "$", "finder", ")", "{", "$", "default_finder", "=", "$", "finderGroup", "->", "getDefault", "(", ")", ";", "if", "(", "!", "$", "default_finder", ")", "{", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}", "return", "redirect", "(", ")", "->", "route", "(", "'glitter.office.customer.search'", ",", "[", "'preset'", "=>", "$", "default_finder", "->", "getName", "(", ")", "]", ")", ";", "}", "$", "customers", "=", "$", "service", "->", "search", "(", "$", "finder", ")", ";", "return", "view", "(", "'glitter.office::customer.search'", ",", "compact", "(", "'keyword'", ",", "'customers'", ",", "'preset'", ",", "'finder'", ",", "'finderGroup'", ")", ")", ";", "}" ]
@param string|null $preset ファインダー名 @param Request $request @param SearchService $service @param CustomerFinderGroup $finderGroup @return Factory|View|RedirectResponse
[ "@param", "string|null", "$preset", "ファインダー名", "@param", "Request", "$request", "@param", "SearchService", "$service", "@param", "CustomerFinderGroup", "$finderGroup" ]
train
https://github.com/highday/glitter/blob/d1c7a227fd2343806bd3ec0314e621ced57dfe66/src/Http/Controllers/Office/Customer/SearchController.php#L27-L54
jaxon-php/jaxon-jquery
src/Dom/Action.php
Action.getScript
public function getScript() { $this->useSingleQuotes(); foreach($this->aArguments as $xArgument) { if($xArgument instanceof Element) { $this->addParameter(Jaxon::JS_VALUE, $xArgument->getScript()); } else if($xArgument instanceof Parameter) { $this->addParameter($xArgument->getType(), $xArgument->getValue()); } else if($xArgument instanceof Request) { $this->addParameter(Jaxon::JS_VALUE, 'function(){' . $xArgument->getScript() . ';}'); } else if(is_numeric($xArgument)) { $this->addParameter(Jaxon::NUMERIC_VALUE, $xArgument); } else if(is_string($xArgument)) { $this->addParameter(Jaxon::QUOTED_VALUE, $xArgument); } else if(is_bool($xArgument)) { $this->addParameter(Jaxon::BOOL_VALUE, $xArgument); } else if(is_array($xArgument) || is_object($xArgument)) { $this->addParameter(Jaxon::JS_VALUE, $xArgument); } } return $this->sMethod . '(' . implode(', ', $this->aParameters) . ')'; }
php
public function getScript() { $this->useSingleQuotes(); foreach($this->aArguments as $xArgument) { if($xArgument instanceof Element) { $this->addParameter(Jaxon::JS_VALUE, $xArgument->getScript()); } else if($xArgument instanceof Parameter) { $this->addParameter($xArgument->getType(), $xArgument->getValue()); } else if($xArgument instanceof Request) { $this->addParameter(Jaxon::JS_VALUE, 'function(){' . $xArgument->getScript() . ';}'); } else if(is_numeric($xArgument)) { $this->addParameter(Jaxon::NUMERIC_VALUE, $xArgument); } else if(is_string($xArgument)) { $this->addParameter(Jaxon::QUOTED_VALUE, $xArgument); } else if(is_bool($xArgument)) { $this->addParameter(Jaxon::BOOL_VALUE, $xArgument); } else if(is_array($xArgument) || is_object($xArgument)) { $this->addParameter(Jaxon::JS_VALUE, $xArgument); } } return $this->sMethod . '(' . implode(', ', $this->aParameters) . ')'; }
[ "public", "function", "getScript", "(", ")", "{", "$", "this", "->", "useSingleQuotes", "(", ")", ";", "foreach", "(", "$", "this", "->", "aArguments", "as", "$", "xArgument", ")", "{", "if", "(", "$", "xArgument", "instanceof", "Element", ")", "{", "$", "this", "->", "addParameter", "(", "Jaxon", "::", "JS_VALUE", ",", "$", "xArgument", "->", "getScript", "(", ")", ")", ";", "}", "else", "if", "(", "$", "xArgument", "instanceof", "Parameter", ")", "{", "$", "this", "->", "addParameter", "(", "$", "xArgument", "->", "getType", "(", ")", ",", "$", "xArgument", "->", "getValue", "(", ")", ")", ";", "}", "else", "if", "(", "$", "xArgument", "instanceof", "Request", ")", "{", "$", "this", "->", "addParameter", "(", "Jaxon", "::", "JS_VALUE", ",", "'function(){'", ".", "$", "xArgument", "->", "getScript", "(", ")", ".", "';}'", ")", ";", "}", "else", "if", "(", "is_numeric", "(", "$", "xArgument", ")", ")", "{", "$", "this", "->", "addParameter", "(", "Jaxon", "::", "NUMERIC_VALUE", ",", "$", "xArgument", ")", ";", "}", "else", "if", "(", "is_string", "(", "$", "xArgument", ")", ")", "{", "$", "this", "->", "addParameter", "(", "Jaxon", "::", "QUOTED_VALUE", ",", "$", "xArgument", ")", ";", "}", "else", "if", "(", "is_bool", "(", "$", "xArgument", ")", ")", "{", "$", "this", "->", "addParameter", "(", "Jaxon", "::", "BOOL_VALUE", ",", "$", "xArgument", ")", ";", "}", "else", "if", "(", "is_array", "(", "$", "xArgument", ")", "||", "is_object", "(", "$", "xArgument", ")", ")", "{", "$", "this", "->", "addParameter", "(", "Jaxon", "::", "JS_VALUE", ",", "$", "xArgument", ")", ";", "}", "}", "return", "$", "this", "->", "sMethod", ".", "'('", ".", "implode", "(", "', '", ",", "$", "this", "->", "aParameters", ")", ".", "')'", ";", "}" ]
Return a string representation of the call to this jQuery function @return string
[ "Return", "a", "string", "representation", "of", "the", "call", "to", "this", "jQuery", "function" ]
train
https://github.com/jaxon-php/jaxon-jquery/blob/90766a8ea8a4124a3f110e96b316370f71762380/src/Dom/Action.php#L41-L76
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/parts/rfc822_parser.php
ezcMailRfc822Parser.parseBody
public function parseBody( $origLine ) { $line = rtrim( $origLine, "\r\n" ); if ( $this->parserState == self::PARSE_STATE_HEADERS && $line == '' ) { $this->parserState = self::PARSE_STATE_BODY; // clean up headers for the part // the rest of the headers should be set on the mail object. $headers = new ezcMailHeadersHolder(); $headers['Content-Type'] = $this->headers['Content-Type']; if ( isset( $this->headers['Content-Transfer-Encoding'] ) ) { $headers['Content-Transfer-Encoding'] = $this->headers['Content-Transfer-Encoding']; } if ( isset( $this->headers['Content-Disposition'] ) ) { $headers['Content-Disposition'] = $this->headers['Content-Disposition']; } // get the correct body type $this->bodyParser = self::createPartParserForHeaders( $headers ); } else if ( $this->parserState == self::PARSE_STATE_HEADERS ) { $this->parseHeader( $line, $this->headers ); } else // we are parsing headers { $this->bodyParser->parseBody( $origLine ); } }
php
public function parseBody( $origLine ) { $line = rtrim( $origLine, "\r\n" ); if ( $this->parserState == self::PARSE_STATE_HEADERS && $line == '' ) { $this->parserState = self::PARSE_STATE_BODY; // clean up headers for the part // the rest of the headers should be set on the mail object. $headers = new ezcMailHeadersHolder(); $headers['Content-Type'] = $this->headers['Content-Type']; if ( isset( $this->headers['Content-Transfer-Encoding'] ) ) { $headers['Content-Transfer-Encoding'] = $this->headers['Content-Transfer-Encoding']; } if ( isset( $this->headers['Content-Disposition'] ) ) { $headers['Content-Disposition'] = $this->headers['Content-Disposition']; } // get the correct body type $this->bodyParser = self::createPartParserForHeaders( $headers ); } else if ( $this->parserState == self::PARSE_STATE_HEADERS ) { $this->parseHeader( $line, $this->headers ); } else // we are parsing headers { $this->bodyParser->parseBody( $origLine ); } }
[ "public", "function", "parseBody", "(", "$", "origLine", ")", "{", "$", "line", "=", "rtrim", "(", "$", "origLine", ",", "\"\\r\\n\"", ")", ";", "if", "(", "$", "this", "->", "parserState", "==", "self", "::", "PARSE_STATE_HEADERS", "&&", "$", "line", "==", "''", ")", "{", "$", "this", "->", "parserState", "=", "self", "::", "PARSE_STATE_BODY", ";", "// clean up headers for the part", "// the rest of the headers should be set on the mail object.", "$", "headers", "=", "new", "ezcMailHeadersHolder", "(", ")", ";", "$", "headers", "[", "'Content-Type'", "]", "=", "$", "this", "->", "headers", "[", "'Content-Type'", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Content-Transfer-Encoding'", "]", ")", ")", "{", "$", "headers", "[", "'Content-Transfer-Encoding'", "]", "=", "$", "this", "->", "headers", "[", "'Content-Transfer-Encoding'", "]", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Content-Disposition'", "]", ")", ")", "{", "$", "headers", "[", "'Content-Disposition'", "]", "=", "$", "this", "->", "headers", "[", "'Content-Disposition'", "]", ";", "}", "// get the correct body type", "$", "this", "->", "bodyParser", "=", "self", "::", "createPartParserForHeaders", "(", "$", "headers", ")", ";", "}", "else", "if", "(", "$", "this", "->", "parserState", "==", "self", "::", "PARSE_STATE_HEADERS", ")", "{", "$", "this", "->", "parseHeader", "(", "$", "line", ",", "$", "this", "->", "headers", ")", ";", "}", "else", "// we are parsing headers", "{", "$", "this", "->", "bodyParser", "->", "parseBody", "(", "$", "origLine", ")", ";", "}", "}" ]
Parses the body of an rfc 2822 message. @throws ezcBaseFileNotFoundException if a neccessary temporary file could not be openened. @param string $origLine
[ "Parses", "the", "body", "of", "an", "rfc", "2822", "message", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/parts/rfc822_parser.php#L71-L104
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/parts/rfc822_parser.php
ezcMailRfc822Parser.finish
public function finish( $class = "ezcMail" ) { $mail = new $class(); $mail->setHeaders( $this->headers->getCaseSensitiveArray() ); ezcMailPartParser::parsePartHeaders( $this->headers, $mail ); // from if ( isset( $this->headers['From'] ) ) { $mail->from = ezcMailTools::parseEmailAddress( $this->headers['From'] ); } // to if ( isset( $this->headers['To'] ) ) { $mail->to = ezcMailTools::parseEmailAddresses( $this->headers['To'] ); } // cc if ( isset( $this->headers['Cc'] ) ) { $mail->cc = ezcMailTools::parseEmailAddresses( $this->headers['Cc'] ); } // bcc if ( isset( $this->headers['Bcc'] ) ) { $mail->bcc = ezcMailTools::parseEmailAddresses( $this->headers['Bcc'] ); } // subject if ( isset( $this->headers['Subject'] ) ) { $mail->subject = ezcMailTools::mimeDecode( $this->headers['Subject'] ); $mail->subjectCharset = 'utf-8'; } // message ID if ( isset( $this->headers['Message-Id'] ) ) { $mail->messageID = $this->headers['Message-Id']; } // Return-Path if ( isset( $this->headers['Return-Path'] ) ) { $mail->returnPath = ezcMailTools::parseEmailAddress( $this->headers['Return-Path'] ); } if ( $this->bodyParser !== null ) { $mail->body = $this->bodyParser->finish(); } return $mail; }
php
public function finish( $class = "ezcMail" ) { $mail = new $class(); $mail->setHeaders( $this->headers->getCaseSensitiveArray() ); ezcMailPartParser::parsePartHeaders( $this->headers, $mail ); // from if ( isset( $this->headers['From'] ) ) { $mail->from = ezcMailTools::parseEmailAddress( $this->headers['From'] ); } // to if ( isset( $this->headers['To'] ) ) { $mail->to = ezcMailTools::parseEmailAddresses( $this->headers['To'] ); } // cc if ( isset( $this->headers['Cc'] ) ) { $mail->cc = ezcMailTools::parseEmailAddresses( $this->headers['Cc'] ); } // bcc if ( isset( $this->headers['Bcc'] ) ) { $mail->bcc = ezcMailTools::parseEmailAddresses( $this->headers['Bcc'] ); } // subject if ( isset( $this->headers['Subject'] ) ) { $mail->subject = ezcMailTools::mimeDecode( $this->headers['Subject'] ); $mail->subjectCharset = 'utf-8'; } // message ID if ( isset( $this->headers['Message-Id'] ) ) { $mail->messageID = $this->headers['Message-Id']; } // Return-Path if ( isset( $this->headers['Return-Path'] ) ) { $mail->returnPath = ezcMailTools::parseEmailAddress( $this->headers['Return-Path'] ); } if ( $this->bodyParser !== null ) { $mail->body = $this->bodyParser->finish(); } return $mail; }
[ "public", "function", "finish", "(", "$", "class", "=", "\"ezcMail\"", ")", "{", "$", "mail", "=", "new", "$", "class", "(", ")", ";", "$", "mail", "->", "setHeaders", "(", "$", "this", "->", "headers", "->", "getCaseSensitiveArray", "(", ")", ")", ";", "ezcMailPartParser", "::", "parsePartHeaders", "(", "$", "this", "->", "headers", ",", "$", "mail", ")", ";", "// from", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'From'", "]", ")", ")", "{", "$", "mail", "->", "from", "=", "ezcMailTools", "::", "parseEmailAddress", "(", "$", "this", "->", "headers", "[", "'From'", "]", ")", ";", "}", "// to", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'To'", "]", ")", ")", "{", "$", "mail", "->", "to", "=", "ezcMailTools", "::", "parseEmailAddresses", "(", "$", "this", "->", "headers", "[", "'To'", "]", ")", ";", "}", "// cc", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Cc'", "]", ")", ")", "{", "$", "mail", "->", "cc", "=", "ezcMailTools", "::", "parseEmailAddresses", "(", "$", "this", "->", "headers", "[", "'Cc'", "]", ")", ";", "}", "// bcc", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Bcc'", "]", ")", ")", "{", "$", "mail", "->", "bcc", "=", "ezcMailTools", "::", "parseEmailAddresses", "(", "$", "this", "->", "headers", "[", "'Bcc'", "]", ")", ";", "}", "// subject", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Subject'", "]", ")", ")", "{", "$", "mail", "->", "subject", "=", "ezcMailTools", "::", "mimeDecode", "(", "$", "this", "->", "headers", "[", "'Subject'", "]", ")", ";", "$", "mail", "->", "subjectCharset", "=", "'utf-8'", ";", "}", "// message ID", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Message-Id'", "]", ")", ")", "{", "$", "mail", "->", "messageID", "=", "$", "this", "->", "headers", "[", "'Message-Id'", "]", ";", "}", "// Return-Path", "if", "(", "isset", "(", "$", "this", "->", "headers", "[", "'Return-Path'", "]", ")", ")", "{", "$", "mail", "->", "returnPath", "=", "ezcMailTools", "::", "parseEmailAddress", "(", "$", "this", "->", "headers", "[", "'Return-Path'", "]", ")", ";", "}", "if", "(", "$", "this", "->", "bodyParser", "!==", "null", ")", "{", "$", "mail", "->", "body", "=", "$", "this", "->", "bodyParser", "->", "finish", "(", ")", ";", "}", "return", "$", "mail", ";", "}" ]
Returns an ezcMail corresponding to the parsed message. You can specify an alternate class using the $class parameter, if you extended ezcMail. @param string $class Class to instanciate instead of ezcMail. @return ezcMail
[ "Returns", "an", "ezcMail", "corresponding", "to", "the", "parsed", "message", ".", "You", "can", "specify", "an", "alternate", "class", "using", "the", "$class", "parameter", "if", "you", "extended", "ezcMail", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/parser/parts/rfc822_parser.php#L114-L163
spiderling-php/spiderling
src/CrawlerSession.php
CrawlerSession.saveHtml
public function saveHtml($filename, $base = null) { $this->ensureWritableDirectory(dirname($filename)); $html = new Html($this->getHtml()); if (null !== $base) { $html->resolveLinks(\GuzzleHttp\Psr7\uri_for($base)); } file_put_contents($filename, $html->get()); return $this; }
php
public function saveHtml($filename, $base = null) { $this->ensureWritableDirectory(dirname($filename)); $html = new Html($this->getHtml()); if (null !== $base) { $html->resolveLinks(\GuzzleHttp\Psr7\uri_for($base)); } file_put_contents($filename, $html->get()); return $this; }
[ "public", "function", "saveHtml", "(", "$", "filename", ",", "$", "base", "=", "null", ")", "{", "$", "this", "->", "ensureWritableDirectory", "(", "dirname", "(", "$", "filename", ")", ")", ";", "$", "html", "=", "new", "Html", "(", "$", "this", "->", "getHtml", "(", ")", ")", ";", "if", "(", "null", "!==", "$", "base", ")", "{", "$", "html", "->", "resolveLinks", "(", "\\", "GuzzleHttp", "\\", "Psr7", "\\", "uri_for", "(", "$", "base", ")", ")", ";", "}", "file_put_contents", "(", "$", "filename", ",", "$", "html", "->", "get", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Save the HTML of the session into a file Optionally resolve all the links with a base uri @param string $filename @throws InvalidArgumentException if directory doesnt exist or is not writable @param UriInterface|string $base
[ "Save", "the", "HTML", "of", "the", "session", "into", "a", "file", "Optionally", "resolve", "all", "the", "links", "with", "a", "base", "uri" ]
train
https://github.com/spiderling-php/spiderling/blob/030d70fb71c89256e3b256dda7fa4c47751d9c53/src/CrawlerSession.php#L85-L98
fccn/oai-pmh-core
src/libs/phprop.php
Phprop.parse
public static function parse($filename, $del=".") { if (is_null(self::$_instance)) { self::$_instance = new self($filename, $del); } return self::$_instance->getObj(); //return self::$_instance; }
php
public static function parse($filename, $del=".") { if (is_null(self::$_instance)) { self::$_instance = new self($filename, $del); } return self::$_instance->getObj(); //return self::$_instance; }
[ "public", "static", "function", "parse", "(", "$", "filename", ",", "$", "del", "=", "\".\"", ")", "{", "if", "(", "is_null", "(", "self", "::", "$", "_instance", ")", ")", "{", "self", "::", "$", "_instance", "=", "new", "self", "(", "$", "filename", ",", "$", "del", ")", ";", "}", "return", "self", "::", "$", "_instance", "->", "getObj", "(", ")", ";", "//return self::$_instance;", "}" ]
Singleton pattern constructor @param string ini filename @param string delimiter, it is '.' by default but can be changed @return object : object containing ini data
[ "Singleton", "pattern", "constructor" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/libs/phprop.php#L91-L98
fccn/oai-pmh-core
src/libs/phprop.php
Phprop._parseIni
private function _parseIni($iniFile) { $aParsedIni = parse_ini_file($iniFile, true, INI_SCANNER_RAW); $tmpArray = array(); foreach ($aParsedIni as $key=>$value) { if (strpos($key, ':') !== false) { $sections = explode(':', $key); if (count($sections) != 2) { throw new Exception('Malformed section header!'); } $currentSection = trim($sections[0]); $parentSection = trim($sections[1]); $value = array_merge_recursive( $aParsedIni[$parentSection], $aParsedIni[$key] ); $aParsedIni[$currentSection] = $value; unset($aParsedIni[$key]); $key = $currentSection; } if (is_array($value)) { foreach ($value as $vk=>$vv) { $newKey = $key.".".$vk; $tmpArray[$newKey] = $vv; if ( is_string($vv) && preg_match_all('/\${([a-zA-Z0-9\.]+)}/', $vv, $match) ) { if (!isset($match[1])) { continue; } $variableKey = $match[1]; foreach ($variableKey as &$var) { if (strpos($var, '.') === false) { $var = $key . '.' . $var; } } $this->_varDeps[$newKey] = $variableKey; } } } } if (!empty($tmpArray)) { $aParsedIni = $tmpArray; } foreach ($aParsedIni as $key=>$value) { //extract parsed array keys if (array_key_exists($key, $this->_varDeps)) { $deps = &$this->_varDeps; $value = preg_replace_callback( '/\${([a-zA-Z0-9\.]+)}/', function ($match) use ($key, $aParsedIni, &$deps) { return $aParsedIni[array_shift($deps[$key])]; }, $value ); $aParsedIni[$key] = $value; } $this->_tmpValue = $value;//set temporay value to current ini value $aXKey = explode($this->_delimiter, $key); //get ini key segments //set object properties recursively based on parsed ini $this->_recursiveInit($this->_obj, $aXKey); } }
php
private function _parseIni($iniFile) { $aParsedIni = parse_ini_file($iniFile, true, INI_SCANNER_RAW); $tmpArray = array(); foreach ($aParsedIni as $key=>$value) { if (strpos($key, ':') !== false) { $sections = explode(':', $key); if (count($sections) != 2) { throw new Exception('Malformed section header!'); } $currentSection = trim($sections[0]); $parentSection = trim($sections[1]); $value = array_merge_recursive( $aParsedIni[$parentSection], $aParsedIni[$key] ); $aParsedIni[$currentSection] = $value; unset($aParsedIni[$key]); $key = $currentSection; } if (is_array($value)) { foreach ($value as $vk=>$vv) { $newKey = $key.".".$vk; $tmpArray[$newKey] = $vv; if ( is_string($vv) && preg_match_all('/\${([a-zA-Z0-9\.]+)}/', $vv, $match) ) { if (!isset($match[1])) { continue; } $variableKey = $match[1]; foreach ($variableKey as &$var) { if (strpos($var, '.') === false) { $var = $key . '.' . $var; } } $this->_varDeps[$newKey] = $variableKey; } } } } if (!empty($tmpArray)) { $aParsedIni = $tmpArray; } foreach ($aParsedIni as $key=>$value) { //extract parsed array keys if (array_key_exists($key, $this->_varDeps)) { $deps = &$this->_varDeps; $value = preg_replace_callback( '/\${([a-zA-Z0-9\.]+)}/', function ($match) use ($key, $aParsedIni, &$deps) { return $aParsedIni[array_shift($deps[$key])]; }, $value ); $aParsedIni[$key] = $value; } $this->_tmpValue = $value;//set temporay value to current ini value $aXKey = explode($this->_delimiter, $key); //get ini key segments //set object properties recursively based on parsed ini $this->_recursiveInit($this->_obj, $aXKey); } }
[ "private", "function", "_parseIni", "(", "$", "iniFile", ")", "{", "$", "aParsedIni", "=", "parse_ini_file", "(", "$", "iniFile", ",", "true", ",", "INI_SCANNER_RAW", ")", ";", "$", "tmpArray", "=", "array", "(", ")", ";", "foreach", "(", "$", "aParsedIni", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "strpos", "(", "$", "key", ",", "':'", ")", "!==", "false", ")", "{", "$", "sections", "=", "explode", "(", "':'", ",", "$", "key", ")", ";", "if", "(", "count", "(", "$", "sections", ")", "!=", "2", ")", "{", "throw", "new", "Exception", "(", "'Malformed section header!'", ")", ";", "}", "$", "currentSection", "=", "trim", "(", "$", "sections", "[", "0", "]", ")", ";", "$", "parentSection", "=", "trim", "(", "$", "sections", "[", "1", "]", ")", ";", "$", "value", "=", "array_merge_recursive", "(", "$", "aParsedIni", "[", "$", "parentSection", "]", ",", "$", "aParsedIni", "[", "$", "key", "]", ")", ";", "$", "aParsedIni", "[", "$", "currentSection", "]", "=", "$", "value", ";", "unset", "(", "$", "aParsedIni", "[", "$", "key", "]", ")", ";", "$", "key", "=", "$", "currentSection", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "vk", "=>", "$", "vv", ")", "{", "$", "newKey", "=", "$", "key", ".", "\".\"", ".", "$", "vk", ";", "$", "tmpArray", "[", "$", "newKey", "]", "=", "$", "vv", ";", "if", "(", "is_string", "(", "$", "vv", ")", "&&", "preg_match_all", "(", "'/\\${([a-zA-Z0-9\\.]+)}/'", ",", "$", "vv", ",", "$", "match", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "match", "[", "1", "]", ")", ")", "{", "continue", ";", "}", "$", "variableKey", "=", "$", "match", "[", "1", "]", ";", "foreach", "(", "$", "variableKey", "as", "&", "$", "var", ")", "{", "if", "(", "strpos", "(", "$", "var", ",", "'.'", ")", "===", "false", ")", "{", "$", "var", "=", "$", "key", ".", "'.'", ".", "$", "var", ";", "}", "}", "$", "this", "->", "_varDeps", "[", "$", "newKey", "]", "=", "$", "variableKey", ";", "}", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "tmpArray", ")", ")", "{", "$", "aParsedIni", "=", "$", "tmpArray", ";", "}", "foreach", "(", "$", "aParsedIni", "as", "$", "key", "=>", "$", "value", ")", "{", "//extract parsed array keys", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "_varDeps", ")", ")", "{", "$", "deps", "=", "&", "$", "this", "->", "_varDeps", ";", "$", "value", "=", "preg_replace_callback", "(", "'/\\${([a-zA-Z0-9\\.]+)}/'", ",", "function", "(", "$", "match", ")", "use", "(", "$", "key", ",", "$", "aParsedIni", ",", "&", "$", "deps", ")", "{", "return", "$", "aParsedIni", "[", "array_shift", "(", "$", "deps", "[", "$", "key", "]", ")", "]", ";", "}", ",", "$", "value", ")", ";", "$", "aParsedIni", "[", "$", "key", "]", "=", "$", "value", ";", "}", "$", "this", "->", "_tmpValue", "=", "$", "value", ";", "//set temporay value to current ini value", "$", "aXKey", "=", "explode", "(", "$", "this", "->", "_delimiter", ",", "$", "key", ")", ";", "//get ini key segments", "//set object properties recursively based on parsed ini", "$", "this", "->", "_recursiveInit", "(", "$", "this", "->", "_obj", ",", "$", "aXKey", ")", ";", "}", "}" ]
Parses ini file and extract its keys and prepare it for object creation
[ "Parses", "ini", "file", "and", "extract", "its", "keys", "and", "prepare", "it", "for", "object", "creation" ]
train
https://github.com/fccn/oai-pmh-core/blob/a9c6852482c7bd7c48911a2165120325ecc27ea2/src/libs/phprop.php#L103-L165
hametuha/wpametu
src/WPametu/File/Image.php
Image.trim
public function trim( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ){ $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) return $editor; $editor->set_quality( $jpeg_quality ); $resized = $editor->resize( $max_w, $max_h, $crop ); if ( is_wp_error( $resized ) ) return $resized; $dest_file = $editor->generate_filename( $suffix, $dest_path ); $saved = $editor->save( $dest_file ); if ( is_wp_error( $saved ) ) return $saved; return $dest_file; }
php
public function trim( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ){ $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) return $editor; $editor->set_quality( $jpeg_quality ); $resized = $editor->resize( $max_w, $max_h, $crop ); if ( is_wp_error( $resized ) ) return $resized; $dest_file = $editor->generate_filename( $suffix, $dest_path ); $saved = $editor->save( $dest_file ); if ( is_wp_error( $saved ) ) return $saved; return $dest_file; }
[ "public", "function", "trim", "(", "$", "file", ",", "$", "max_w", ",", "$", "max_h", ",", "$", "crop", "=", "false", ",", "$", "suffix", "=", "null", ",", "$", "dest_path", "=", "null", ",", "$", "jpeg_quality", "=", "90", ")", "{", "$", "editor", "=", "wp_get_image_editor", "(", "$", "file", ")", ";", "if", "(", "is_wp_error", "(", "$", "editor", ")", ")", "return", "$", "editor", ";", "$", "editor", "->", "set_quality", "(", "$", "jpeg_quality", ")", ";", "$", "resized", "=", "$", "editor", "->", "resize", "(", "$", "max_w", ",", "$", "max_h", ",", "$", "crop", ")", ";", "if", "(", "is_wp_error", "(", "$", "resized", ")", ")", "return", "$", "resized", ";", "$", "dest_file", "=", "$", "editor", "->", "generate_filename", "(", "$", "suffix", ",", "$", "dest_path", ")", ";", "$", "saved", "=", "$", "editor", "->", "save", "(", "$", "dest_file", ")", ";", "if", "(", "is_wp_error", "(", "$", "saved", ")", ")", "return", "$", "saved", ";", "return", "$", "dest_file", ";", "}" ]
Clone of image resize @see image_resize @param string $file Image file path. @param int $max_w Maximum width to resize to. @param int $max_h Maximum height to resize to. @param bool $crop Optional. Whether to crop image or resize. @param string $suffix Optional. File suffix. @param string $dest_path Optional. New image file path. @param int $jpeg_quality Optional, default is 90. Image quality percentage. @return mixed WP_Error on failure. String with new destination path.
[ "Clone", "of", "image", "resize" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/File/Image.php#L39-L56
hametuha/wpametu
src/WPametu/File/Image.php
Image.fit
public function fit($src, $dest, $width, $height){ // Calculate $size = getimagesize($src); $ratio = max($width / $size[0], $height / $size[1]); $old_width = $size[0]; $old_height = $size[1]; $new_width = intval($old_width * $ratio); $new_height = intval($old_height * $ratio); // Resize @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) ); $image = imagecreatefromstring( file_get_contents( $src ) ); $new_image = wp_imagecreatetruecolor( $new_width, $new_height ); imagecopyresampled( $new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); if ( IMAGETYPE_PNG == $size[2] && function_exists('imageistruecolor') && !imageistruecolor( $image ) ){ imagetruecolortopalette( $new_image, false, imagecolorstotal( $image ) ); } // Destroy old image imagedestroy( $image ); // Save switch($size[2]){ case IMAGETYPE_GIF: $result = imagegif($new_image, $dest); break; case IMAGETYPE_PNG: $result = imagepng($new_image, $dest); break; default: $result = imagejpeg($new_image, $dest); break; } imagedestroy($new_image); return $result; }
php
public function fit($src, $dest, $width, $height){ // Calculate $size = getimagesize($src); $ratio = max($width / $size[0], $height / $size[1]); $old_width = $size[0]; $old_height = $size[1]; $new_width = intval($old_width * $ratio); $new_height = intval($old_height * $ratio); // Resize @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) ); $image = imagecreatefromstring( file_get_contents( $src ) ); $new_image = wp_imagecreatetruecolor( $new_width, $new_height ); imagecopyresampled( $new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); if ( IMAGETYPE_PNG == $size[2] && function_exists('imageistruecolor') && !imageistruecolor( $image ) ){ imagetruecolortopalette( $new_image, false, imagecolorstotal( $image ) ); } // Destroy old image imagedestroy( $image ); // Save switch($size[2]){ case IMAGETYPE_GIF: $result = imagegif($new_image, $dest); break; case IMAGETYPE_PNG: $result = imagepng($new_image, $dest); break; default: $result = imagejpeg($new_image, $dest); break; } imagedestroy($new_image); return $result; }
[ "public", "function", "fit", "(", "$", "src", ",", "$", "dest", ",", "$", "width", ",", "$", "height", ")", "{", "// Calculate", "$", "size", "=", "getimagesize", "(", "$", "src", ")", ";", "$", "ratio", "=", "max", "(", "$", "width", "/", "$", "size", "[", "0", "]", ",", "$", "height", "/", "$", "size", "[", "1", "]", ")", ";", "$", "old_width", "=", "$", "size", "[", "0", "]", ";", "$", "old_height", "=", "$", "size", "[", "1", "]", ";", "$", "new_width", "=", "intval", "(", "$", "old_width", "*", "$", "ratio", ")", ";", "$", "new_height", "=", "intval", "(", "$", "old_height", "*", "$", "ratio", ")", ";", "// Resize", "@", "ini_set", "(", "'memory_limit'", ",", "apply_filters", "(", "'image_memory_limit'", ",", "WP_MAX_MEMORY_LIMIT", ")", ")", ";", "$", "image", "=", "imagecreatefromstring", "(", "file_get_contents", "(", "$", "src", ")", ")", ";", "$", "new_image", "=", "wp_imagecreatetruecolor", "(", "$", "new_width", ",", "$", "new_height", ")", ";", "imagecopyresampled", "(", "$", "new_image", ",", "$", "image", ",", "0", ",", "0", ",", "0", ",", "0", ",", "$", "new_width", ",", "$", "new_height", ",", "$", "old_width", ",", "$", "old_height", ")", ";", "if", "(", "IMAGETYPE_PNG", "==", "$", "size", "[", "2", "]", "&&", "function_exists", "(", "'imageistruecolor'", ")", "&&", "!", "imageistruecolor", "(", "$", "image", ")", ")", "{", "imagetruecolortopalette", "(", "$", "new_image", ",", "false", ",", "imagecolorstotal", "(", "$", "image", ")", ")", ";", "}", "// Destroy old image", "imagedestroy", "(", "$", "image", ")", ";", "// Save", "switch", "(", "$", "size", "[", "2", "]", ")", "{", "case", "IMAGETYPE_GIF", ":", "$", "result", "=", "imagegif", "(", "$", "new_image", ",", "$", "dest", ")", ";", "break", ";", "case", "IMAGETYPE_PNG", ":", "$", "result", "=", "imagepng", "(", "$", "new_image", ",", "$", "dest", ")", ";", "break", ";", "default", ":", "$", "result", "=", "imagejpeg", "(", "$", "new_image", ",", "$", "dest", ")", ";", "break", ";", "}", "imagedestroy", "(", "$", "new_image", ")", ";", "return", "$", "result", ";", "}" ]
Fit small image to specified bound @param string $src @param string $dest @param int $width @param int $height @return bool
[ "Fit", "small", "image", "to", "specified", "bound" ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/File/Image.php#L67-L99
blast-project/BaseEntitiesBundle
src/Controller/SearchController.php
SearchController.retrieveAutocompleteItemsAction
public function retrieveAutocompleteItemsAction(Request $request) { // $$pool = $this->container->get('sonata.admin.pool')->getInstance($request->get('admin_code')); $admin = $this->container->get('sonata.admin.pool')->getInstance($request->get('admin_code')); $admin->setRequest($request); $context = $request->get('_context', ''); if ($context === 'filter' && false === $admin->isGranted('LIST')) { throw new AccessDeniedException(); } if ($context !== 'filter' && false === $admin->isGranted('CREATE') && false === $admin->isGranted('EDIT') ) { throw new AccessDeniedException(); } // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast $admin->setSubject($admin->getNewInstance()); if ($context === 'filter') { // filter $fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field')); $filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName()); $property = $filterAutocomplete->getFieldOption('property'); $callback = $filterAutocomplete->getFieldOption('callback'); // not used $minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3); $itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10); $reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', '_page'); // not used (TODO) $toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback'); } else { // create/edit form $fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field')); $formAutocomplete = $admin->getForm()->get($fieldDescription->getName()); if ($formAutocomplete->getConfig()->getAttribute('disabled')) { throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.'); } $property = $formAutocomplete->getConfig()->getAttribute('property'); $callback = $formAutocomplete->getConfig()->getAttribute('callback'); // not used $minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length'); $itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page'); $reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number'); // not used (TODO) $toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback'); } $searchText = $request->get('q'); $targetAdmin = $fieldDescription->getAssociationAdmin(); // check user permission if (false === $targetAdmin->isGranted('LIST')) { throw new AccessDeniedException(); } if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) { return new JsonResponse(array('status' => 'KO', 'message' => 'Too short search string.'), 403); } $class = $targetAdmin->getClass(); $em = $this->getDoctrine()->getManager(); $classMetadata = $em->getClassMetadata($class); $searchHandler = $this->getContainer()->get('blast_base_entities.search_handler'); $searchHandler->handleEntity($classMetadata); $results = $searchHandler->indexSearch($searchText, $itemsPerPage); $items = []; foreach ($results as $entity) { if ($toStringCallback !== null) { if (!is_callable($toStringCallback)) { throw new \RuntimeException('Option "to_string_callback" does not contain callable function.'); } $label = call_user_func($toStringCallback, $entity, $property); } else { $resultMetadata = $targetAdmin->getObjectMetadata($entity); $label = $resultMetadata->getTitle(); } $items[] = array( 'id' => $admin->id($entity), 'label' => $label, ); } return new JsonResponse(array( 'status' => 'OK', 'more' => false, // TODO ! 'items' => $items, )); }
php
public function retrieveAutocompleteItemsAction(Request $request) { // $$pool = $this->container->get('sonata.admin.pool')->getInstance($request->get('admin_code')); $admin = $this->container->get('sonata.admin.pool')->getInstance($request->get('admin_code')); $admin->setRequest($request); $context = $request->get('_context', ''); if ($context === 'filter' && false === $admin->isGranted('LIST')) { throw new AccessDeniedException(); } if ($context !== 'filter' && false === $admin->isGranted('CREATE') && false === $admin->isGranted('EDIT') ) { throw new AccessDeniedException(); } // subject will be empty to avoid unnecessary database requests and keep autocomplete function fast $admin->setSubject($admin->getNewInstance()); if ($context === 'filter') { // filter $fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field')); $filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName()); $property = $filterAutocomplete->getFieldOption('property'); $callback = $filterAutocomplete->getFieldOption('callback'); // not used $minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3); $itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10); $reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', '_page'); // not used (TODO) $toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback'); } else { // create/edit form $fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field')); $formAutocomplete = $admin->getForm()->get($fieldDescription->getName()); if ($formAutocomplete->getConfig()->getAttribute('disabled')) { throw new AccessDeniedException('Autocomplete list can`t be retrieved because the form element is disabled or read_only.'); } $property = $formAutocomplete->getConfig()->getAttribute('property'); $callback = $formAutocomplete->getConfig()->getAttribute('callback'); // not used $minimumInputLength = $formAutocomplete->getConfig()->getAttribute('minimum_input_length'); $itemsPerPage = $formAutocomplete->getConfig()->getAttribute('items_per_page'); $reqParamPageNumber = $formAutocomplete->getConfig()->getAttribute('req_param_name_page_number'); // not used (TODO) $toStringCallback = $formAutocomplete->getConfig()->getAttribute('to_string_callback'); } $searchText = $request->get('q'); $targetAdmin = $fieldDescription->getAssociationAdmin(); // check user permission if (false === $targetAdmin->isGranted('LIST')) { throw new AccessDeniedException(); } if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) { return new JsonResponse(array('status' => 'KO', 'message' => 'Too short search string.'), 403); } $class = $targetAdmin->getClass(); $em = $this->getDoctrine()->getManager(); $classMetadata = $em->getClassMetadata($class); $searchHandler = $this->getContainer()->get('blast_base_entities.search_handler'); $searchHandler->handleEntity($classMetadata); $results = $searchHandler->indexSearch($searchText, $itemsPerPage); $items = []; foreach ($results as $entity) { if ($toStringCallback !== null) { if (!is_callable($toStringCallback)) { throw new \RuntimeException('Option "to_string_callback" does not contain callable function.'); } $label = call_user_func($toStringCallback, $entity, $property); } else { $resultMetadata = $targetAdmin->getObjectMetadata($entity); $label = $resultMetadata->getTitle(); } $items[] = array( 'id' => $admin->id($entity), 'label' => $label, ); } return new JsonResponse(array( 'status' => 'OK', 'more' => false, // TODO ! 'items' => $items, )); }
[ "public", "function", "retrieveAutocompleteItemsAction", "(", "Request", "$", "request", ")", "{", "// $$pool = $this->container->get('sonata.admin.pool')->getInstance($request->get('admin_code'));", "$", "admin", "=", "$", "this", "->", "container", "->", "get", "(", "'sonata.admin.pool'", ")", "->", "getInstance", "(", "$", "request", "->", "get", "(", "'admin_code'", ")", ")", ";", "$", "admin", "->", "setRequest", "(", "$", "request", ")", ";", "$", "context", "=", "$", "request", "->", "get", "(", "'_context'", ",", "''", ")", ";", "if", "(", "$", "context", "===", "'filter'", "&&", "false", "===", "$", "admin", "->", "isGranted", "(", "'LIST'", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "if", "(", "$", "context", "!==", "'filter'", "&&", "false", "===", "$", "admin", "->", "isGranted", "(", "'CREATE'", ")", "&&", "false", "===", "$", "admin", "->", "isGranted", "(", "'EDIT'", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "// subject will be empty to avoid unnecessary database requests and keep autocomplete function fast", "$", "admin", "->", "setSubject", "(", "$", "admin", "->", "getNewInstance", "(", ")", ")", ";", "if", "(", "$", "context", "===", "'filter'", ")", "{", "// filter", "$", "fieldDescription", "=", "$", "this", "->", "retrieveFilterFieldDescription", "(", "$", "admin", ",", "$", "request", "->", "get", "(", "'field'", ")", ")", ";", "$", "filterAutocomplete", "=", "$", "admin", "->", "getDatagrid", "(", ")", "->", "getFilter", "(", "$", "fieldDescription", "->", "getName", "(", ")", ")", ";", "$", "property", "=", "$", "filterAutocomplete", "->", "getFieldOption", "(", "'property'", ")", ";", "$", "callback", "=", "$", "filterAutocomplete", "->", "getFieldOption", "(", "'callback'", ")", ";", "// not used", "$", "minimumInputLength", "=", "$", "filterAutocomplete", "->", "getFieldOption", "(", "'minimum_input_length'", ",", "3", ")", ";", "$", "itemsPerPage", "=", "$", "filterAutocomplete", "->", "getFieldOption", "(", "'items_per_page'", ",", "10", ")", ";", "$", "reqParamPageNumber", "=", "$", "filterAutocomplete", "->", "getFieldOption", "(", "'req_param_name_page_number'", ",", "'_page'", ")", ";", "// not used (TODO)", "$", "toStringCallback", "=", "$", "filterAutocomplete", "->", "getFieldOption", "(", "'to_string_callback'", ")", ";", "}", "else", "{", "// create/edit form", "$", "fieldDescription", "=", "$", "this", "->", "retrieveFormFieldDescription", "(", "$", "admin", ",", "$", "request", "->", "get", "(", "'field'", ")", ")", ";", "$", "formAutocomplete", "=", "$", "admin", "->", "getForm", "(", ")", "->", "get", "(", "$", "fieldDescription", "->", "getName", "(", ")", ")", ";", "if", "(", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'disabled'", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", "'Autocomplete list can`t be retrieved because the form element is disabled or read_only.'", ")", ";", "}", "$", "property", "=", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'property'", ")", ";", "$", "callback", "=", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'callback'", ")", ";", "// not used", "$", "minimumInputLength", "=", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'minimum_input_length'", ")", ";", "$", "itemsPerPage", "=", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'items_per_page'", ")", ";", "$", "reqParamPageNumber", "=", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'req_param_name_page_number'", ")", ";", "// not used (TODO)", "$", "toStringCallback", "=", "$", "formAutocomplete", "->", "getConfig", "(", ")", "->", "getAttribute", "(", "'to_string_callback'", ")", ";", "}", "$", "searchText", "=", "$", "request", "->", "get", "(", "'q'", ")", ";", "$", "targetAdmin", "=", "$", "fieldDescription", "->", "getAssociationAdmin", "(", ")", ";", "// check user permission", "if", "(", "false", "===", "$", "targetAdmin", "->", "isGranted", "(", "'LIST'", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "if", "(", "mb_strlen", "(", "$", "searchText", ",", "'UTF-8'", ")", "<", "$", "minimumInputLength", ")", "{", "return", "new", "JsonResponse", "(", "array", "(", "'status'", "=>", "'KO'", ",", "'message'", "=>", "'Too short search string.'", ")", ",", "403", ")", ";", "}", "$", "class", "=", "$", "targetAdmin", "->", "getClass", "(", ")", ";", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "$", "classMetadata", "=", "$", "em", "->", "getClassMetadata", "(", "$", "class", ")", ";", "$", "searchHandler", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'blast_base_entities.search_handler'", ")", ";", "$", "searchHandler", "->", "handleEntity", "(", "$", "classMetadata", ")", ";", "$", "results", "=", "$", "searchHandler", "->", "indexSearch", "(", "$", "searchText", ",", "$", "itemsPerPage", ")", ";", "$", "items", "=", "[", "]", ";", "foreach", "(", "$", "results", "as", "$", "entity", ")", "{", "if", "(", "$", "toStringCallback", "!==", "null", ")", "{", "if", "(", "!", "is_callable", "(", "$", "toStringCallback", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Option \"to_string_callback\" does not contain callable function.'", ")", ";", "}", "$", "label", "=", "call_user_func", "(", "$", "toStringCallback", ",", "$", "entity", ",", "$", "property", ")", ";", "}", "else", "{", "$", "resultMetadata", "=", "$", "targetAdmin", "->", "getObjectMetadata", "(", "$", "entity", ")", ";", "$", "label", "=", "$", "resultMetadata", "->", "getTitle", "(", ")", ";", "}", "$", "items", "[", "]", "=", "array", "(", "'id'", "=>", "$", "admin", "->", "id", "(", "$", "entity", ")", ",", "'label'", "=>", "$", "label", ",", ")", ";", "}", "return", "new", "JsonResponse", "(", "array", "(", "'status'", "=>", "'OK'", ",", "'more'", "=>", "false", ",", "// TODO !", "'items'", "=>", "$", "items", ",", ")", ")", ";", "}" ]
Retrieve list of items for autocomplete form field with search indexes Based on Sonata\AdminBundle\Controller\HelperController#retrieveAutocompleteItemsAction. @param Request $request @return JsonResponse @throws \RuntimeException @throws AccessDeniedException @todo refactor this to avoid dependency to BaseEntitiesBundle
[ "Retrieve", "list", "of", "items", "for", "autocomplete", "form", "field", "with", "search", "indexes", "Based", "on", "Sonata", "\\", "AdminBundle", "\\", "Controller", "\\", "HelperController#retrieveAutocompleteItemsAction", "." ]
train
https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/Controller/SearchController.php#L37-L130
blast-project/BaseEntitiesBundle
src/Controller/SearchController.php
SearchController.retrieveFormFieldDescription
private function retrieveFormFieldDescription(AdminInterface $admin, $field) { $admin->getFormFieldDescriptions(); $fieldDescription = $admin->getFormFieldDescription($field); if (!$fieldDescription) { throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field)); } if (null === $fieldDescription->getTargetEntity()) { throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field)); } return $fieldDescription; }
php
private function retrieveFormFieldDescription(AdminInterface $admin, $field) { $admin->getFormFieldDescriptions(); $fieldDescription = $admin->getFormFieldDescription($field); if (!$fieldDescription) { throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field)); } if (null === $fieldDescription->getTargetEntity()) { throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field)); } return $fieldDescription; }
[ "private", "function", "retrieveFormFieldDescription", "(", "AdminInterface", "$", "admin", ",", "$", "field", ")", "{", "$", "admin", "->", "getFormFieldDescriptions", "(", ")", ";", "$", "fieldDescription", "=", "$", "admin", "->", "getFormFieldDescription", "(", "$", "field", ")", ";", "if", "(", "!", "$", "fieldDescription", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'The field \"%s\" does not exist.'", ",", "$", "field", ")", ")", ";", "}", "if", "(", "null", "===", "$", "fieldDescription", "->", "getTargetEntity", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'No associated entity with field \"%s\".'", ",", "$", "field", ")", ")", ";", "}", "return", "$", "fieldDescription", ";", "}" ]
Retrieve the form field description given by field name. Copied from Sonata\AdminBundle\Controller\HelperController. @param AdminInterface $admin @param string $field @return FormInterface @throws \RuntimeException
[ "Retrieve", "the", "form", "field", "description", "given", "by", "field", "name", ".", "Copied", "from", "Sonata", "\\", "AdminBundle", "\\", "Controller", "\\", "HelperController", "." ]
train
https://github.com/blast-project/BaseEntitiesBundle/blob/abd06891fc38922225ab7e4fcb437a286ba2c0c4/src/Controller/SearchController.php#L143-L158
webdevvie/pheanstalk-task-queue-bundle
Command/Example/AddExampleTaskCommand.php
AddExampleTaskCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $this->initialiseWorker($input, $output); $totalTasks = $input->getOption('total-tasks'); for ($counter = 0; $counter < $totalTasks; $counter++) { $task = new ExampleTaskDescription(); $task->message = 'hello world'; $task->wait = 1; $this->taskQueueService->queueTask($task, $this->tube); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $this->initialiseWorker($input, $output); $totalTasks = $input->getOption('total-tasks'); for ($counter = 0; $counter < $totalTasks; $counter++) { $task = new ExampleTaskDescription(); $task->message = 'hello world'; $task->wait = 1; $this->taskQueueService->queueTask($task, $this->tube); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "this", "->", "initialiseWorker", "(", "$", "input", ",", "$", "output", ")", ";", "$", "totalTasks", "=", "$", "input", "->", "getOption", "(", "'total-tasks'", ")", ";", "for", "(", "$", "counter", "=", "0", ";", "$", "counter", "<", "$", "totalTasks", ";", "$", "counter", "++", ")", "{", "$", "task", "=", "new", "ExampleTaskDescription", "(", ")", ";", "$", "task", "->", "message", "=", "'hello world'", ";", "$", "task", "->", "wait", "=", "1", ";", "$", "this", "->", "taskQueueService", "->", "queueTask", "(", "$", "task", ",", "$", "this", "->", "tube", ")", ";", "}", "}" ]
Adds an example task to the task queue using the ExampleTask.php @param InputInterface $input @param OutputInterface $output @return void @throws \InvalidArgumentException
[ "Adds", "an", "example", "task", "to", "the", "task", "queue", "using", "the", "ExampleTask", ".", "php" ]
train
https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Example/AddExampleTaskCommand.php#L43-L53
Visithor/visithor
src/Visithor/Reader/YamlConfigurationReader.php
YamlConfigurationReader.read
public function read($path) { $config = $this ->readByFilename( $path, Visithor::CONFIG_FILE_NAME_DISTR ); if (false === $config) { $config = $this ->readByFilename( $path, Visithor::CONFIG_FILE_NAME ); } return $config; }
php
public function read($path) { $config = $this ->readByFilename( $path, Visithor::CONFIG_FILE_NAME_DISTR ); if (false === $config) { $config = $this ->readByFilename( $path, Visithor::CONFIG_FILE_NAME ); } return $config; }
[ "public", "function", "read", "(", "$", "path", ")", "{", "$", "config", "=", "$", "this", "->", "readByFilename", "(", "$", "path", ",", "Visithor", "::", "CONFIG_FILE_NAME_DISTR", ")", ";", "if", "(", "false", "===", "$", "config", ")", "{", "$", "config", "=", "$", "this", "->", "readByFilename", "(", "$", "path", ",", "Visithor", "::", "CONFIG_FILE_NAME", ")", ";", "}", "return", "$", "config", ";", "}" ]
Read all the configuration given a path @param string $path Path @return array|false Configuration loaded or false if file not exists
[ "Read", "all", "the", "configuration", "given", "a", "path" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Reader/YamlConfigurationReader.php#L32-L49
Visithor/visithor
src/Visithor/Reader/YamlConfigurationReader.php
YamlConfigurationReader.readByFilename
public function readByFilename($path, $filename) { $config = false; $configFilePath = rtrim($path, '/') . '/' . $filename; if (is_file($configFilePath)) { $yamlParser = new YamlParser(); $config = $yamlParser->parse(file_get_contents($configFilePath)); } return $config; }
php
public function readByFilename($path, $filename) { $config = false; $configFilePath = rtrim($path, '/') . '/' . $filename; if (is_file($configFilePath)) { $yamlParser = new YamlParser(); $config = $yamlParser->parse(file_get_contents($configFilePath)); } return $config; }
[ "public", "function", "readByFilename", "(", "$", "path", ",", "$", "filename", ")", "{", "$", "config", "=", "false", ";", "$", "configFilePath", "=", "rtrim", "(", "$", "path", ",", "'/'", ")", ".", "'/'", ".", "$", "filename", ";", "if", "(", "is_file", "(", "$", "configFilePath", ")", ")", "{", "$", "yamlParser", "=", "new", "YamlParser", "(", ")", ";", "$", "config", "=", "$", "yamlParser", "->", "parse", "(", "file_get_contents", "(", "$", "configFilePath", ")", ")", ";", "}", "return", "$", "config", ";", "}" ]
Read all the configuration given a path and a filename @param string $path Path @param string $filename File name @return array Configuration
[ "Read", "all", "the", "configuration", "given", "a", "path", "and", "a", "filename" ]
train
https://github.com/Visithor/visithor/blob/201ba2cfc536a0875983c79226947aa20b9f4dca/src/Visithor/Reader/YamlConfigurationReader.php#L60-L71
syzygypl/page-media-set-bundle
DependencyInjection/PageMediaSetExtension.php
PageMediaSetExtension.load
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $configs = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); if ($configs['indexer']) { $loader->load('indexer.yml'); } $container->setParameter('page_media_set.types', $configs['types']); $repository = $container->getDefinition('page_media_set.format_repository'); foreach ($configs['formats'] as $name => $format) { $id = 'page_media_set.format.' . $name; $container->setDefinition($id, (new Definition(MediaFormat::class, [ $name, $format['min_width'], $format['min_height'], $format['max_width'], $format['max_height'] ]))->setPublic(false)); $repository->addMethodCall('add', [new Reference($id)]); } }
php
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $configs = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); if ($configs['indexer']) { $loader->load('indexer.yml'); } $container->setParameter('page_media_set.types', $configs['types']); $repository = $container->getDefinition('page_media_set.format_repository'); foreach ($configs['formats'] as $name => $format) { $id = 'page_media_set.format.' . $name; $container->setDefinition($id, (new Definition(MediaFormat::class, [ $name, $format['min_width'], $format['min_height'], $format['max_width'], $format['max_height'] ]))->setPublic(false)); $repository->addMethodCall('add', [new Reference($id)]); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "configs", "=", "$", "this", "->", "processConfiguration", "(", "$", "configuration", ",", "$", "configs", ")", ";", "$", "loader", "=", "new", "Loader", "\\", "YamlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "loader", "->", "load", "(", "'services.yml'", ")", ";", "if", "(", "$", "configs", "[", "'indexer'", "]", ")", "{", "$", "loader", "->", "load", "(", "'indexer.yml'", ")", ";", "}", "$", "container", "->", "setParameter", "(", "'page_media_set.types'", ",", "$", "configs", "[", "'types'", "]", ")", ";", "$", "repository", "=", "$", "container", "->", "getDefinition", "(", "'page_media_set.format_repository'", ")", ";", "foreach", "(", "$", "configs", "[", "'formats'", "]", "as", "$", "name", "=>", "$", "format", ")", "{", "$", "id", "=", "'page_media_set.format.'", ".", "$", "name", ";", "$", "container", "->", "setDefinition", "(", "$", "id", ",", "(", "new", "Definition", "(", "MediaFormat", "::", "class", ",", "[", "$", "name", ",", "$", "format", "[", "'min_width'", "]", ",", "$", "format", "[", "'min_height'", "]", ",", "$", "format", "[", "'max_width'", "]", ",", "$", "format", "[", "'max_height'", "]", "]", ")", ")", "->", "setPublic", "(", "false", ")", ")", ";", "$", "repository", "->", "addMethodCall", "(", "'add'", ",", "[", "new", "Reference", "(", "$", "id", ")", "]", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/syzygypl/page-media-set-bundle/blob/013d5321518755b07d292d63d5b3f1ddeb635107/DependencyInjection/PageMediaSetExtension.php#L23-L49
wenbinye/PhalconX
src/Php/ClassHierarchy.php
ClassHierarchy.addClass
public function addClass($class, $extends = null, $implements = []) { $classId = $this->registerClass($class); if ($extends) { $parentClassId = $this->registerClass($extends); $this->extends[$classId] = [$parentClassId]; } if (!empty($implements)) { $interfaceIds = []; foreach ($implements as $interface) { $interfaceIds[] = $this->registerInterface($interface); } $this->implements[$classId] = $interfaceIds; } }
php
public function addClass($class, $extends = null, $implements = []) { $classId = $this->registerClass($class); if ($extends) { $parentClassId = $this->registerClass($extends); $this->extends[$classId] = [$parentClassId]; } if (!empty($implements)) { $interfaceIds = []; foreach ($implements as $interface) { $interfaceIds[] = $this->registerInterface($interface); } $this->implements[$classId] = $interfaceIds; } }
[ "public", "function", "addClass", "(", "$", "class", ",", "$", "extends", "=", "null", ",", "$", "implements", "=", "[", "]", ")", "{", "$", "classId", "=", "$", "this", "->", "registerClass", "(", "$", "class", ")", ";", "if", "(", "$", "extends", ")", "{", "$", "parentClassId", "=", "$", "this", "->", "registerClass", "(", "$", "extends", ")", ";", "$", "this", "->", "extends", "[", "$", "classId", "]", "=", "[", "$", "parentClassId", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "implements", ")", ")", "{", "$", "interfaceIds", "=", "[", "]", ";", "foreach", "(", "$", "implements", "as", "$", "interface", ")", "{", "$", "interfaceIds", "[", "]", "=", "$", "this", "->", "registerInterface", "(", "$", "interface", ")", ";", "}", "$", "this", "->", "implements", "[", "$", "classId", "]", "=", "$", "interfaceIds", ";", "}", "}" ]
add class to hierarchy tree @param string $class @param string $extends parent class @param array $implements interfaces that implements @return self
[ "add", "class", "to", "hierarchy", "tree" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Php/ClassHierarchy.php#L74-L88
wenbinye/PhalconX
src/Php/ClassHierarchy.php
ClassHierarchy.addInterface
public function addInterface($interface, $extends = []) { $interfaceId = $this->registerInterface($interface); if (!empty($extends)) { $interfaceIds = []; foreach ($extends as $name) { $interfaceIds[] = $this->registerInterface($name); } $this->interfaceExtends[$interfaceId] = $interfaceIds; } }
php
public function addInterface($interface, $extends = []) { $interfaceId = $this->registerInterface($interface); if (!empty($extends)) { $interfaceIds = []; foreach ($extends as $name) { $interfaceIds[] = $this->registerInterface($name); } $this->interfaceExtends[$interfaceId] = $interfaceIds; } }
[ "public", "function", "addInterface", "(", "$", "interface", ",", "$", "extends", "=", "[", "]", ")", "{", "$", "interfaceId", "=", "$", "this", "->", "registerInterface", "(", "$", "interface", ")", ";", "if", "(", "!", "empty", "(", "$", "extends", ")", ")", "{", "$", "interfaceIds", "=", "[", "]", ";", "foreach", "(", "$", "extends", "as", "$", "name", ")", "{", "$", "interfaceIds", "[", "]", "=", "$", "this", "->", "registerInterface", "(", "$", "name", ")", ";", "}", "$", "this", "->", "interfaceExtends", "[", "$", "interfaceId", "]", "=", "$", "interfaceIds", ";", "}", "}" ]
add interface to hierarchy tree @param string $interface @param array $extends @return self
[ "add", "interface", "to", "hierarchy", "tree" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Php/ClassHierarchy.php#L97-L107
wenbinye/PhalconX
src/Php/ClassHierarchy.php
ClassHierarchy.getParent
public function getParent($class) { $classId = $this->getClassId($class); if (!isset($classId)) { return false; } $parentClassId = $this->extends[$classId]; return isset($parentClassId) ? $this->classes[$parentClassId[0]] : null; }
php
public function getParent($class) { $classId = $this->getClassId($class); if (!isset($classId)) { return false; } $parentClassId = $this->extends[$classId]; return isset($parentClassId) ? $this->classes[$parentClassId[0]] : null; }
[ "public", "function", "getParent", "(", "$", "class", ")", "{", "$", "classId", "=", "$", "this", "->", "getClassId", "(", "$", "class", ")", ";", "if", "(", "!", "isset", "(", "$", "classId", ")", ")", "{", "return", "false", ";", "}", "$", "parentClassId", "=", "$", "this", "->", "extends", "[", "$", "classId", "]", ";", "return", "isset", "(", "$", "parentClassId", ")", "?", "$", "this", "->", "classes", "[", "$", "parentClassId", "[", "0", "]", "]", ":", "null", ";", "}" ]
gets parent class @param string $class @retutn string|null|false
[ "gets", "parent", "class" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Php/ClassHierarchy.php#L115-L123
wenbinye/PhalconX
src/Php/ClassHierarchy.php
ClassHierarchy.getAncestors
public function getAncestors($class) { $ancestors = []; while (true) { $parent = $this->getParent($class); if ($parent) { $ancestors[] = $parent; $class = $parent; } else { break; } } return $ancestors; }
php
public function getAncestors($class) { $ancestors = []; while (true) { $parent = $this->getParent($class); if ($parent) { $ancestors[] = $parent; $class = $parent; } else { break; } } return $ancestors; }
[ "public", "function", "getAncestors", "(", "$", "class", ")", "{", "$", "ancestors", "=", "[", "]", ";", "while", "(", "true", ")", "{", "$", "parent", "=", "$", "this", "->", "getParent", "(", "$", "class", ")", ";", "if", "(", "$", "parent", ")", "{", "$", "ancestors", "[", "]", "=", "$", "parent", ";", "$", "class", "=", "$", "parent", ";", "}", "else", "{", "break", ";", "}", "}", "return", "$", "ancestors", ";", "}" ]
gets all parent classes @param string $class @return array
[ "gets", "all", "parent", "classes" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Php/ClassHierarchy.php#L131-L144