_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q239900
TabHelper.createTab
train
public function createTab($name, $label, $options = array()) { $options = array_replace( $options, array( 'label' => $label, 'inherit_data' => true, )); $tab = $this->formBuilder->create($name, TabsTabType::class, $options); $this->formBuilder->get('tabs')->add($tab); return $tab; }
php
{ "resource": "" }
q239901
BaseController.render
train
public function render($content, Response $response) { $response->setStatusCode(Response::HTTP_OK); $response->headers->set('Content-Type', 'application/json'); $response->setContent(json_encode($content)); return $response; }
php
{ "resource": "" }
q239902
Session.Start
train
public static function Start($sName, $sSessionDiretory = null){ $oThis = self::CreateInstanceIfNotExists(); if(!empty($sName)){ $sName = md5($sName); if(!is_null($sSessionDiretory)){ @session_save_path($sSessionDiretory); Storage::Set("session.path", $sSessionDiretory); } @session_name($sName); $sSessionName = session_name(); if($sSessionName != $sName) $oThis->sName = $sSessionName; else $oThis->sName = $sName; $bSession = session_start(); if($bSession){ Storage::Set("session.name", $oThis->sName); Storage::Set("session.id", session_id()); switch($_SERVER["SERVER_ADDR"]){ case "127.0.0.1"://Setting to developer mode case "::1": $iTimeout = time()+3600; session_cache_expire(60); //Increases the cache time of the session to 60 minutes session_cache_limiter("nocache"); //Sets the cache limiter to 'nocache' Storage::Set("session.timeout", $iTimeout); //Setting the timeout session ends break; default: $iTimeout = time()+900; session_cache_expire(15); //Shortens the session cache for 15 minutes session_cache_limiter("private"); //Sets the cache limiter to 'private' Storage::Set("session.timeout", $iTimeout); //Setting the timeout session ends break; } //Recording session information Storage::Set("session.cache.limiter", session_cache_limiter()); Storage::Set("session.cache.expire", session_cache_expire()); Storage::Set("session.cookie.enable", array_key_exists($sName, $_COOKIE)); //Verifying authentication information if(array_key_exists($oThis->sName, $_SESSION)){ if(array_key_exists("authentication", $_SESSION[$oThis->sName])) $oThis->aAuth = $_SESSION[$oThis->sName]["authentication"]; if(!empty($oThis->aAuth)){ Storage::Set("user.id", $oThis->aAuth["id"]); Storage::Set("user.name", $oThis->aAuth["name"]); Storage::Set("user.username", $oThis->aAuth["username"]); Storage::Set("user.root", $oThis->aAuth["root"]); Storage::Set("session.timeout.login", $oThis->aAuth["timeout"]); } } Storage::Set("session.enabled", true); $oThis->bStarted = true; return true; } else{ Storage::Set("session.enabled", false); return false; } } else{ Storage::Set("session.enabled", false); return false; } }
php
{ "resource": "" }
q239903
Session.Login
train
public static function Login($mId, $sUsername, $sName, $iTimeout = 3600, $bRoot = false){ $oThis = self::CreateInstanceIfNotExists(); if($oThis->bStarted){ $iTimeout = time()+$iTimeout; $oThis->aAuth = array("id" => $mId, "name" => $sName, "username" => $sUsername, "timeout" => $iTimeout, "root" => $bRoot); $_SESSION[$oThis->sName]["authentication"] = $oThis->aAuth; if(!empty($oThis->aAuth)){ Storage::Set("user.id", $oThis->aAuth["id"]); Storage::Set("user.name", $oThis->aAuth["name"]); Storage::Set("user.username", $oThis->aAuth["username"]); Storage::Set("user.root", $oThis->aAuth["root"]); Storage::Set("session.timeout.login", $iTimeout); } } }
php
{ "resource": "" }
q239904
Session.Logout
train
public static function Logout(){ $oThis = self::CreateInstanceIfNotExists(); if($oThis->bStarted){ session_unset(); unset($_SESSION[$oThis->sName]["authentication"]); unset($oThis->aAuth); } }
php
{ "resource": "" }
q239905
Session.CheckAuthentication
train
public static function CheckAuthentication(){ $oThis = self::CreateInstanceIfNotExists(); $bReturn = ($oThis->bStarted) ? (!empty($oThis->aAuth["id"]) && !empty($oThis->aAuth["username"]) && ((intval($oThis->aAuth["timeout"]) > time()) || (intval($oThis->aAuth["timeout"]) <= 0))) : false; return $bReturn; }
php
{ "resource": "" }
q239906
Session.Has
train
public static function Has($sKey){ $oThis = self::CreateInstanceIfNotExists(); if($oThis->bStarted) return array_key_exists($sKey, $_SESSION[$oThis->sName]); else return false; }
php
{ "resource": "" }
q239907
Session.Set
train
public static function Set($sKey, $mValue){ $oThis = self::CreateInstanceIfNotExists(); if($oThis->bStarted){ if($sKey != "name" && $sKey != "id" && $sKey != "authentication"){ $_SESSION[$oThis->sName][$sKey] = $mValue; return true; } else{ return false; } } else{ return false; } }
php
{ "resource": "" }
q239908
Session.Get
train
public static function Get($sKey){ $oThis = self::CreateInstanceIfNotExists(); if($oThis->bStarted) return (!empty($_SESSION[$oThis->sName][$sKey])) ? $_SESSION[$oThis->sName][$sKey] : false; else return null; }
php
{ "resource": "" }
q239909
Cache.forge
train
public static function forge($identifier, $config = array()) { // load the default config $defaults = \Config::get('cache', array()); // $config can be either an array of config settings or the name of the storage driver if ( ! empty($config) and ! is_array($config) and ! is_null($config)) { $config = array('driver' => $config); } // Overwrite default values with given config $config = array_merge($defaults, (array) $config); if (empty($config['driver'])) { throw new \FuelException('No cache driver given or no default cache driver set.'); } $class = '\\Cache_Storage_'.ucfirst($config['driver']); // Convert the name to a string when necessary $identifier = call_user_func($class.'::stringify_identifier', $identifier); // Return instance of the requested cache object return new $class($identifier, $config); }
php
{ "resource": "" }
q239910
Router.route
train
public function route() { $this->routes->rewind(); while ($this->routes->valid()) { $route = $this->routes->current(); if ($route->run()) { return; } $this->routes->next(); } throw new \RuntimeException("FlexPress router: No route found - please make sure you have setup routes."); }
php
{ "resource": "" }
q239911
Router.replaceFilterFunctions
train
protected function replaceFilterFunctions(array $conditions) { foreach ($conditions as $key => $condition) { if (is_string($condition)) { $conditions[$key] = $this->filters[$condition]; } } return $conditions; }
php
{ "resource": "" }
q239912
Theme.resolveList
train
public static function resolveList($renderKey, $stopClass = null, $type = null) { $viewListList = static::resolve($renderKey, $stopClass, $type); $finalList = []; foreach($viewListList as $theme => $viewList) { foreach($viewList as $view) { if(is_array($view)) { $finalList = array_merge($finalList, $view); } else { $finalList[] = $view; } } } return array_unique($finalList); }
php
{ "resource": "" }
q239913
Theme.resolveFirst
train
public static function resolveFirst($renderKey, $stopClass = null, $type = null) { $viewListList = static::resolve($renderKey, $stopClass, $type); $viewList = current($viewListList); if(!$viewList) { return; } $view = current($viewList); return $view; }
php
{ "resource": "" }
q239914
Theme.render
train
public static function render($object, array $vars = [], $type = null) { if($view = static::resolveFirst($object, null, $type)) { return new $view(['object' => $object] + $vars); } }
php
{ "resource": "" }
q239915
Theme.wrap
train
public static function wrap($body, $vars = []) { if(isset(static::$wrap)) { if($body instanceof \SeanMorris\Theme\View) { $body = $body->render(); } foreach(static::$wrap as $wrapper) { $body = new $wrapper(['body' => $body] + $vars); } } return $body; }
php
{ "resource": "" }
q239916
Theme.selectType
train
protected static function selectType($views, $type) { if(!is_array($views)) { return $views; } if($type === FALSE) { return $views; } if(!$type) { return current($views); } if(!isset($views[$type])) { return null; } return $views[$type]; }
php
{ "resource": "" }
q239917
Statement.supportFilter
train
protected function supportFilter( array $list = [], bool $enable = true ) { foreach( $list as $type ) { if( !$enable ) unset( $this->_filter[ $type ] ); else if( !isset( $this->_filter[ $type ] ) ) $this->_filter[ $type ] = []; } return $this; }
php
{ "resource": "" }
q239918
Statement.supportCustom
train
protected function supportCustom( array $list = [], bool $enable = true ) { foreach( $list as $name ) { if( !$enable ) unset( $this->_custom[ $name ] ); else if( !isset( $this->_custom[ $name ] ) ) $this->_custom[ $name ] = []; } return $this; }
php
{ "resource": "" }
q239919
Conversion.setAdapter
train
public function setAdapter($adapter) { if (!is_string($adapter) && !$adapter instanceof ConversionAlgorithmInterface) { throw new Exception\InvalidArgumentException(sprintf( '"%s" expects a string or an instance of ConversionAlgorithmInterface; received "%s"', __METHOD__, is_object($adapter) ? get_class($adapter) : gettype($adapter) )); } if (is_string($adapter)) { if (!class_exists($adapter)) { throw new Exception\RuntimeException(sprintf( '"%s" unable to load adapter; class "%s" not found', __METHOD__, $adapter )); } $adapter = new $adapter(); if (!$adapter instanceof ConversionAlgorithmInterface) { throw new Exception\InvalidArgumentException(sprintf( '"%s" expects a string representing an instance of ConversionAlgorithmInterface; received "%s"', __METHOD__, is_object($adapter) ? get_class($adapter) : gettype($adapter) )); } } $this->adapter = $adapter; return $this; }
php
{ "resource": "" }
q239920
Conversion.getAdapter
train
public function getAdapter() { if (!$this->adapter) { throw new Exception\RuntimeException(sprintf( '"%s" unable to load adapter; adapter not found', __METHOD__ )); } if (method_exists($this->adapter, 'setOptions')) { $this->adapter->setOptions($this->getAdapterOptions()); } return $this->adapter; }
php
{ "resource": "" }
q239921
Conversion.setAdapterOptions
train
public function setAdapterOptions($options) { if (!is_array($options) && !$options instanceof AbstractOptions) { throw new Exception\InvalidArgumentException(sprintf( '"%s" expects an array or a valid instance of "%s"; received "%s"', __METHOD__, 'Zend\Stdlib\AbstractOptions', is_object($options) ? get_class($options) : gettype($options) )); } $this->adapterOptions = $options; $this->options = $options; return $this; }
php
{ "resource": "" }
q239922
Conversion.getAbstractOptions
train
protected function getAbstractOptions() { $optClass = self::getOptionsFullQualifiedClassName($this->adapter); // Does the option class exist? if (!class_exists($optClass)) { throw new Exception\DomainException( sprintf( '"%s" expects that an options class ("%s") for the current adapter exists', __METHOD__, $optClass ) ); } $opts = new $optClass(); if (!$opts instanceof AbstractOptions) { throw new Exception\DomainException(sprintf( '"%s" expects the options class to resolve to a valid "%s" instance; received "%s"', __METHOD__, 'Zend\Stdlib\AbstractOptions', $optClass )); } return $opts; }
php
{ "resource": "" }
q239923
Conversion.getOptions
train
public function getOptions($option = null) { $this->getAdapterOptions(); if ($option !== null) { if (!isset($this->options[$option])) { throw new Exception\RuntimeException(sprintf( 'Options "%s" not found', $option )); } return $this->options[$option]; } return $this->options; }
php
{ "resource": "" }
q239924
Conversion.getOptionsFullQualifiedClassName
train
public static function getOptionsFullQualifiedClassName($adapter) { if (!$adapter) { throw new Exception\InvalidArgumentException(sprintf( '"%s" unable to load adapter; adapter not found', __METHOD__ )); } if (!$adapter instanceof ConversionAlgorithmInterface) { throw new Exception\InvalidArgumentException(sprintf( '"%s" expects an instance of ConversionAlgorithmInterface; received "%s"', __METHOD__, is_object($adapter) ? get_class($adapter) : gettype($adapter) )); } $adapterClass = get_class($adapter); $namespace = substr($adapterClass, 0, strrpos($adapterClass, '\\')); return $namespace . '\\Options\\' . $adapter->getName() . 'Options'; }
php
{ "resource": "" }
q239925
FormCompletenessChecker.isComplete
train
public static function isComplete(Form $form) { //Set the return value to true by default $ret = true; //Foreach child of the form foreach($form->all() as $child) { //If the child is required, check that its set if ($child->isRequired()) { if ($child->isEmpty()) { $ret = false; break; } } } //Return return $ret; }
php
{ "resource": "" }
q239926
KoineString.at
train
public function at($start = null, $length = null) { return new self(mb_substr((string) $this, $start, $length, 'UTF-8')); }
php
{ "resource": "" }
q239927
Zend_Http_Response_Stream.fromStream
train
public static function fromStream($response_str, $stream) { $code = self::extractCode($response_str); $headers = self::extractHeaders($response_str); $version = self::extractVersion($response_str); $message = self::extractMessage($response_str); return new self($code, $headers, $stream, $version, $message); }
php
{ "resource": "" }
q239928
Zend_Http_Response_Stream.readStream
train
protected function readStream() { if(!is_resource($this->stream)) { return ''; } if(isset($headers['content-length'])) { $this->body = stream_get_contents($this->stream, $headers['content-length']); } else { $this->body = stream_get_contents($this->stream); } fclose($this->stream); $this->stream = null; }
php
{ "resource": "" }
q239929
RolesController.listAction
train
public function listAction() { $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles'); $roles = []; foreach (array_keys($roleHierarchy) as $role) { $roles[] = ['id' => $role, 'name' => $role]; } return new JsonResponse($roles); }
php
{ "resource": "" }
q239930
Ini.loadFile
train
public function loadFile($pFile, $pParseKeys = false) { $this->_content = parse_ini_file($pFile, true); if ($pParseKeys) { $this->_parseKeys($this->_content); } return $this; }
php
{ "resource": "" }
q239931
SDK.create
train
public static function create( AuthInterface $authentication, bool $throwsExceptions = false, string $baseUrl = 'https://api.idos.io/1.0/' ) : self { return new static( $authentication, new Client(), $throwsExceptions, $baseUrl ); }
php
{ "resource": "" }
q239932
SDK.getEndpointClassName
train
protected function getEndpointClassName(string $name) : string { $className = sprintf( '%s\\%s\\%s', 'idOS', 'Endpoint', ucfirst($name) ); if (! class_exists($className)) { throw new \RuntimeException( sprintf( 'Invalid endpoint name "%s" (%s)', $name, $className ) ); } return $className; }
php
{ "resource": "" }
q239933
AdminConfigurationBuilder.addSection
train
public function addSection($name, $label, $position=0) { $sectionManager = $this->container->get('admin.configuration.configsection_manager'); $section = $sectionManager->getRepository()->findOneByName($name); if (!$section) { $section = new ConfigSection(); $section->setName($name); $section->setSLabel($label); $section->setPosition($position); $sectionManager->create($section); return true; } return false; }
php
{ "resource": "" }
q239934
AdminConfigurationBuilder.addGroup
train
public function addGroup($sectionName, $name, $label, $position=0) { $groupManager = $this->container->get('admin.configuration.configgroup_manager'); $sectionManager = $this->container->get('admin.configuration.configsection_manager'); $group = $groupManager->getRepository()->findOneBySectionAndGroupName($sectionName, $name); $section = $sectionManager->getRepository()->findOneByName($sectionName); if (!$section) { throw new AdminConfigurationBuilderException(sprintf('The section "%s" does not exist.', $sectionName)); } if (!$group && $section) { $group = new ConfigGroup(); $group->setConfigSection($section); $group->setName($name); $group->setGLabel($label); $group->setPosition($position); $groupManager->create($group); return true; } return false; }
php
{ "resource": "" }
q239935
AdminConfigurationBuilder.addType
train
public function addType($identifier, $label, $formType, $options = array()) { $typeManager = $this->container->get('admin.configuration.configtype_manager'); $type = $typeManager->getRepository()->findOneByIdentifier($identifier); if (!$type) { $type = new ConfigType(); $type->setIdentifier($identifier); $type->setTLabel($label); $type->setFormType($formType); if ( is_array($options) && count($options) ) { $type->setOptions(json_encode($options)); } $typeManager->create($type); return true; } return false; }
php
{ "resource": "" }
q239936
Store.getUploadProgress
train
final public static function getUploadProgress($formName) { $key = ini_get("session.upload_progress.prefix") . $formName; if (!empty($_SESSION[$key])) { $current = $_SESSION[$key]["bytes_processed"]; $total = $_SESSION[$key]["content_length"]; return $current < $total ? ceil($current / $total * 100) : 100; } else { return 100; } }
php
{ "resource": "" }
q239937
Store.start
train
final public function start($killPrevious = FALSE) { //starts this session if not creates a new one //$self = (!isset($this) || !is_a($this, "Library\Session")) ? self::getInstance() : $this; //@TODO Check if there is an existing session! //If there is any previous and killprevious is false, //simply do a garbage collection and return; //if we can't read the session if (($session = $this->read()) !== FALSE) { $this->update($session); } else { $this->create(); } //Carbage collection $this->gc(); }
php
{ "resource": "" }
q239938
Store.getSplash
train
final public function getSplash() { $userIp = md5($this->input->serialize($this->input->getVar('REMOTE_ADDR', \IS\STRING, '', 'server'))); $userAgent = md5($this->input->serialize($this->input->getVar('HTTP_USER_AGENT', \IS\STRING, '', 'server'))); $userDomain = md5($this->input->serialize((string)$this->uri->getHost())); //throw in a token for specific id of browser, $token = (string)$this->generateToken(); $splash = array( "ip" => $userIp, "agent" => $userAgent, "domain" => $userDomain, "token" => $token ); return $splash; }
php
{ "resource": "" }
q239939
Store.create
train
final public function create() { $self = $this; $splash = $self->getSplash(); $sessId = $this->generateId($splash); session_id($sessId); //Must be called before the sesion start to generate the Id session_cache_limiter('none'); session_name(md5($self->cookie . $splash['agent'] . $splash['ip'] . $splash['domain'])); session_start(); //Create the default namespace; affix to splash; //The default namespace will contain vars such as -request count, - last session start time, -last session response time, etc //The dfault namespace will also contain, instantiated objects? // $defaultReg = new Registry("default"); $self->registry['default'] = $defaultReg; //update the cookie with the expiry time //Create the authenticated namespace and lock it! $self->set("handler", $this->authenticator, "auth"); $this->write($sessId, $splash); }
php
{ "resource": "" }
q239940
Store.getAuthority
train
final public function getAuthority() { $self = $this; $auth = $self->get("handler", "auth"); //$authority = \Platform\Authorize::getInstance(); if (is_a($auth, Authenticate::class)) { if (isset($auth->authenticated)) { //Read Rights if we have a userId //$self->authority = $authority->getPermissions($auth); } } //return $self->authority; }
php
{ "resource": "" }
q239941
Store.isAuthenticated
train
final public function isAuthenticated() { $self = $this; $auth = $self->get("handler", "auth"); if (is_a($auth, Authenticate::class)) { if (isset($auth->authenticated)) { return (bool)$auth->authenticated; } } return false; }
php
{ "resource": "" }
q239942
Store.generateId
train
final public function generateId($splash) { $encryptor = $this->encryptor; $input = $this->input; $sessId = md5($encryptor->getKey() . $input->serialize($splash)); return $sessId; }
php
{ "resource": "" }
q239943
Store.read
train
final public function read($id = Null) { $self = $this; $input = $this->input; $uri = $this->uri; //$dbo = Database::getInstance(); $splash = $self->getSplash(); //Do we have a cookie? $sessCookie = md5($self->cookie . $splash['agent'] . $splash['ip'] . $splash['domain']); $sessId = $input->getCookie($sessCookie); if (empty($sessId) || !$sessId) { //we will have to create a new session return false; } $userIp = md5($input->serialize($input->getVar('REMOTE_ADDR', \IS\STRING, '', 'server'))); $userAgent = md5($input->serialize($input->getVar('HTTP_USER_AGENT', \IS\STRING, '', 'server'))); $userDomain = md5($input->serialize((string)$uri->getHost())); //Read the session //$_handler = ucfirst($self->store); $handler = $this->handler; $object = $handler->read($splash, $self, $sessId); //If this is not an object then we have a problem if (!is_object($object)) return false; //Redecorate $splash = array( "ip" => $userIp, "agent" => $userAgent, "domain" => $userDomain, "token" => $object->session_token ); $testId = $self->generateId($splash); if ($testId <> $sessId) { $this->destroy($sessId); return false; //will lead to re-creation } //check if expired $now = time(); if ($object->session_expires < $now) { $this->destroy($sessId); return false; //Will lead to re-creation of a new one } $self->ip = $object->session_ip; $self->agent = $object->session_agent; $self->token = $object->session_token; $self->id = $sessId; //@TODO Restore the registry //which hopefully should contain auth and other serialized info in namespsaces $registry = new Registry("default"); //Validate? if (!empty($object->session_registry)) { //First get an instance of the registry, just to be sure its loaded $registry = $input->unserialize($object->session_registry); $self->registry = $registry; $_SESSION = $self->getNamespace("default")->getAllData(); } else { //just re-create a default registry $_SESSION = array(); //Session is array; //Because we can't restore $self->registry['default'] = $registry; } //Update total requests in the default namespace; $reqCount = $self->get("totalRequests"); $newCount = $reqCount + 1; //Set a total Requests Count $self->set("totalRequests", $newCount); //Return the session Id, to pass to self::update return $sessId; }
php
{ "resource": "" }
q239944
Store.update
train
final public function update($sessId, $userdata = array()) { if (empty($sessId)) { return false; } $self = $this; //updates a started session for exp time //stores data for the registry $now = time(); $newExpires = $now + $self->life; $update = array( "session_lastactive" => $now, "session_expires" => $newExpires ); $self->id = $sessId; //If isset registry and is not empty, store userdata; if (isset($self->registry) && is_array($self->registry)) { $userdata = $this->input->serialize($self->registry); $update["session_registry"] = $userdata; } //Read the session $handler = $this->handler; //Must be called before the sesion start to generate the Id session_id($sessId); //session_start(); if (!$handler->update($update, $self, $self->id)) { return false; } return true; }
php
{ "resource": "" }
q239945
Store.restart
train
final public function restart() { $id = $this->getId(); $this->destroy($id); $this->create(); $this->gc(); }
php
{ "resource": "" }
q239946
Store.destroy
train
final public function destroy($id = "") { $id = !empty($id) ? $id : $this->getId(); $now = time(); if (empty($id)) { return false; } setcookie(session_name(), '', $now - 42000, '/'); if (session_id()) { @session_unset(); @session_destroy(); } //Delete from db; //Do a garbage collection $this->gc($id); }
php
{ "resource": "" }
q239947
Store.write
train
final public function write($sessId, $data = array()) { //Writes user data to the db; $self = $this; //expires $expires = time() + $self->life; //Sets the cookie //$output->setCookie($self->cookie, $sessId."0".$data['token'], $expires); //$output->setCookie($sessId, $data['token'], $expires); $cookie = session_get_cookie_params(); //Cookie parameters session_set_cookie_params($expires, $cookie['path'], $cookie['domain'], true); $self->id = session_id(); $userdata = $this->input->serialize($self->registry); //last modified = now; //expires = now + life ; $handler = $this->handler; if (!$handler->write($userdata, $data, $self, $sessId, $expires)) { return false; } return true; }
php
{ "resource": "" }
q239948
Store.lock
train
final public function lock($namespace) { //locks a namespace in this session to prevent editing if (empty($namespace)) { //@TODO throw an exception, //we don't know what namespace this is return false; } $session = $this; //unlocks a namespace if (isset($session->registry[$namespace]) && !$session->isLocked($namespace)) { $session->registry[$namespace]->lock(); return true; } return false; }
php
{ "resource": "" }
q239949
Store.isLocked
train
final public function isLocked($namespace) { if (empty($namespace)) { return true; //just say its locked } //checks if a namespace in this session is locked $session = $this; //unlocks a namespace if (isset($session->registry[$namespace])) { return $session->registry[$namespace]->isLocked(); } return false; }
php
{ "resource": "" }
q239950
Store.get
train
final public function get($varname, $namespace = 'default') { //gets a registry var, stored in a namespace of this session id $session = $this; if (!isset($namespace) || empty($namespace)) { //@TODO Throw an exception, we need a name or use the default; return false; } //@TODO, check if the regitry is not locked before adding $registry = $session->getNamespace($namespace); return $registry->get($varname); }
php
{ "resource": "" }
q239951
Store.set
train
final public function set($varname, $value = NULL, $namespace = 'default') { //stores a value to a varname in a namespace of this session $session = $this; if (!isset($namespace) || empty($namespace)) { //@TODO Throw an exception, we need a name or use the default; throw new Exception("Cannot set new Session variable to unknown '{$namespace}' namespace"); return false; } //If we don't have a registry to that namespace; if (!isset($session->registry[$namespace])) { //Create it; $registry = new Registry($namespace); $session->registry[$namespace] = $registry; } //echo $namespace; //@TODO, check if the regitry is not locked before adding if (!$session->isLocked($namespace)) { $registry = $session->getNamespace($namespace); $registry->set($varname, $value); } //If auth is locked return $session; }
php
{ "resource": "" }
q239952
Store.remove
train
final public function remove($varname = '', $namespace = 'default') { //if the registry is empty and the namespace is not default //delete the registry; //stores a value to a varname in a namespace of this session $session = $this; //echo $namespace; //@TODO, check if the regitry is not locked before adding if (!$session->isLocked($namespace)) { $registry = $session->getNamespace($namespace); $registry->delete($varname); } //If auth is locked return $session; }
php
{ "resource": "" }
q239953
LanguagesController.copyFallbackTranslations
train
private function copyFallbackTranslations($newLocale) { \DB::transaction(function () use ($newLocale) { $existingTranslations = Translation::get(); $fallbackLanguage = Language::whereIsFallback(1)->first(); if ($fallbackLanguage) { $fallbackIsoCode = $fallbackLanguage->iso_code; $fallbackTranslations = Translation::whereLocale($fallbackIsoCode)->get(); if ($fallbackTranslations) { $copiedTranslationsWithNewLocale = $fallbackTranslations->map(function ($translation) use ( $newLocale ) { unset($translation->id); $translation->locale = mb_strtolower($newLocale); return $translation; })->toArray(); $translationsToCreate = []; foreach ($copiedTranslationsWithNewLocale as $translation) { // Safety feature - dont create entry if it already exists // This might happen if administrator creates new language, deletes it, and then creates again $exists = $existingTranslations ->where('group', $translation['group']) ->where('key', $translation['key']) ->where('locale', $translation['locale']) ->first(); if (!$exists) { $translationsToCreate[] = $translation; } } foreach (array_chunk($translationsToCreate, 300) as $chunk) { Translation::insert($chunk); } } } }); }
php
{ "resource": "" }
q239954
UrlResolver.getContentTypePageUrl
train
public function getContentTypePageUrl(ContentTypePage $page, ContentInterface $document) { return $this->router->generate( $this->getRouteName($page), $this->getRoutingParamaters($page, $document) ); }
php
{ "resource": "" }
q239955
Client.slReseplanerare2Trip
train
public function slReseplanerare2Trip($originId, $destId, array $options = []) { $params = [ 'key' => $this->slReseplanerare2key, 'originId' => $originId, 'destId' => $destId ]; $params = array_merge($params, $options); $url = $this->SlReseplanerare2URL.'/trip.json'; $request = $this->client->request('GET', $url, [ 'query' => $params ]); $json = json_decode($request->getBody(), true); return $json; }
php
{ "resource": "" }
q239956
Client.slReseplanerare2Geometry
train
public function slReseplanerare2Geometry($ref) { $url = $this->SlReseplanerare2URL.'/geometry.json'; $params = [ 'key' => $this->slReseplanerare2key, 'ref' => $ref ]; $request = $this->client->request('GET', $url, [ 'query' => $params ]); $json = json_decode($request->getBody(), true); return $json; }
php
{ "resource": "" }
q239957
Client.slReseplanerare2JourneyDetail
train
public function slReseplanerare2JourneyDetail($ref) { $url = $this->SlReseplanerare2URL.'/journeydetail.json'; $params = [ 'key' => $this->slReseplanerare2key, 'ref' => $ref ]; $request = $this->client->request('GET', $url, [ 'query' => $params ]); $resp = $this->client->send($request); $json = json_decode($resp->getBody(), true); return $json; }
php
{ "resource": "" }
q239958
BHTML.out_head
train
public function out_head(){ $this->frameworks_process(); if($this->lazyload){ $this->lazyload_prepare(); } //Outputing $tab=' '; echo($tab.'<title>'.$this->title.'</title>'.PHP_EOL); if(!empty($this->link_canonical)){ echo($tab.'<link rel="canonical" href="'.$this->link_canonical.'" />'.PHP_EOL); } //Add meta info... foreach($this->meta as $mi){ echo($tab.'<meta'); if(!empty($mi['name'])){ echo(' name="'.$mi['name'].'"'); } if(!empty($mi['http_equiv'])){ echo(' http-equiv="'.$mi['http_equiv'].'"'); } echo(' content="'.htmlspecialchars($mi['content']).'"'); echo('>'.PHP_EOL); } //Add CSS, author, etc. foreach($this->link as $lnk){ echo($tab.'<link'); foreach($lnk as $key=>$value){ echo(' '.$key.'="'.htmlspecialchars($value).'"'); } echo(' />'.PHP_EOL); } //sort js with priority $this->js_sort(); //Outputing style declaration... foreach($this->style as $style){ echo($tab.'<style>'); echo($style); echo($tab.'</style>'.PHP_EOL); } //Add javascript... foreach($this->js as $js){ echo($tab.'<script type="text/javascript"'); if(!empty($js['src'])){ echo(' src="'.$js['src'].'"'); } echo('>'.$js['val'].'</script>'.PHP_EOL); } }
php
{ "resource": "" }
q239959
Psr3ErrorHandler.getLevel
train
private function getLevel(\Throwable $t, array $context): string { // Check if the severity matches a PSR-3 log level if ( false === $this->ignoreSeverity && isset($context[Context::SEVERITY]) && is_string($context[Context::SEVERITY]) && $this->validateLevel($context[Context::SEVERITY]) ) { return $context[Context::SEVERITY]; } // Find the log level based on the error in the level map (avoid looping through the whole array) // Note: this ignores the order defined in the map. $class = get_class($t); if (isset($this->levelMap[$class]) && $this->validateLevel($this->levelMap[$class])) { return $this->levelMap[$class]; } // Find the log level based on the error in the level map foreach ($this->levelMap as $className => $candidate) { if ($t instanceof $className && $this->validateLevel($candidate)) { return $candidate; } } // Return the default log level return self::DEFAULT_LOG_LEVEL; }
php
{ "resource": "" }
q239960
Database.buildQuery
train
public function buildQuery( $table_name, $type, $params = null ) { if ( $type == "find" ) { $sub_sql = isset($params["sub_sql"]) ? $params["sub_sql"] : null; $sql = "SELECT * FROM $table_name"; if ( isset($sub_sql) ) { $sql .= " " . $sub_sql; } $sql .= ";"; } else if ( $type == "update" ) { $columns = isset($params["columns"]) ? $params["columns"] : null; $sql = "UPDATE $table_name SET "; foreach ( $columns as $column ) { $sql .= $column["name"] . "=:" . $column["name"] . ","; } $sql = rtrim( $sql, ", " ); $sql .= " WHERE "; foreach ( $columns as $column ) { $sql .= $column["name"] . "=:snap_" . $column["name"] . " AND "; } $sql = rtrim( $sql, " AND " ); $sql .= ";"; } else if ( $type == "insert" ) { $columns = isset($params["columns"]) ? $params["columns"] : null; $sql = "INSERT INTO $table_name ("; foreach ( $columns as $column ) { $sql .= $column["name"] . ", ";; } $sql = rtrim( $sql, ", " ); $sql .= ") VALUES ("; foreach ( $columns as $column ) { $sql .= ":" . $column["name"] . ", "; } $sql = rtrim( $sql, ", " ); $sql .= ");"; } return $this->prepare( $sql ); }
php
{ "resource": "" }
q239961
ParametersTrait.getParam
train
public function getParam($key, $default = null) { if (isset($this->parameters[$key])) { return $this->parameters[$key]; } return $default; }
php
{ "resource": "" }
q239962
LinkController.recurseLinkNodes
train
private function recurseLinkNodes(array $nodes, $language, $mode, TreeNodeInterface $targetNode = null) { $elementService = $this->get('phlexible_element.element_service'); $iconResolver = $this->get('phlexible_element.icon_resolver'); $data = []; foreach ($nodes as $node) { /* @var $node \Phlexible\Bundle\TreeBundle\Model\TreeNodeInterface */ $element = $elementService->findElement($node->getTypeId()); $elementVersion = $elementService->findLatestElementVersion($element); $elementtype = $elementService->findElementtype($element); $tid = $node->getId(); $tree = $node->getTree(); $children = $tree->getChildren($node); $dataNode = [ 'id' => $node->getId(), 'eid' => $node->getTypeId(), 'text' => $elementVersion->getBackendTitle($language, $element->getMasterLanguage()).' ['.$tid.']', 'icon' => $iconResolver->resolveTreeNode($node, $language), 'children' => !$tree->hasChildren($node) ? [] : $mode === self::MODE_NOET_TARGET && $tree->isParentOf($node, $targetNode) ? $this->recurseLinkNodes($children, $language, $mode, $targetNode) : false, 'leaf' => !$tree->hasChildren($node), 'expanded' => false, ]; /* $leafCount = 0; if (is_array($dataNode['children'])) { foreach($dataNode['children'] as $child) { $leafCount += $child['leafCount']; if (!isset($child['disabled']) || !$child['disabled']) { ++$leafCount; } } } $dataNode['leafCount'] = $leafCount; */ $data[] = $dataNode; } return $data; }
php
{ "resource": "" }
q239963
LinkController.recursiveTreeStrip
train
private function recursiveTreeStrip(array $data) { if (count($data) === 1 && !empty($data[0]['children'])) { return $this->recursiveTreeStrip($data[0]['children']); } return $data; }
php
{ "resource": "" }
q239964
CategoriesControllerCategories.getModel
train
public function getModel($name = 'Category', $prefix = 'CategoriesModel', $config = array('ignore_request' => true)) { return parent::getModel($name, $prefix, $config); }
php
{ "resource": "" }
q239965
CategoriesControllerCategories.rebuild
train
public function rebuild() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); $extension = $this->input->get('extension'); $this->setRedirect(JRoute::_('index.php?option=com_categories&view=categories&extension=' . $extension, false)); /** @var CategoriesModelCategory $model */ $model = $this->getModel(); if ($model->rebuild()) { // Rebuild succeeded. $this->setMessage(JText::_('COM_CATEGORIES_REBUILD_SUCCESS')); return true; } // Rebuild failed. $this->setMessage(JText::_('COM_CATEGORIES_REBUILD_FAILURE')); return false; }
php
{ "resource": "" }
q239966
CategoriesControllerCategories.saveorder
train
public function saveorder() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); JLog::add('CategoriesControllerCategories::saveorder() is deprecated. Function will be removed in 4.0', JLog::WARNING, 'deprecated'); // Get the arrays from the Request $order = $this->input->post->get('order', null, 'array'); $originalOrder = explode(',', $this->input->getString('original_order_values')); // Make sure something has changed if (!($order === $originalOrder)) { parent::saveorder(); } else { // Nothing to reorder $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list, false)); return true; } }
php
{ "resource": "" }
q239967
CategoriesControllerCategories.delete
train
public function delete() { JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN')); // Get items to remove from the request. $cid = $this->input->get('cid', array(), 'array'); $extension = $this->input->getCmd('extension', null); if (!is_array($cid) || count($cid) < 1) { JError::raiseWarning(500, JText::_($this->text_prefix . '_NO_ITEM_SELECTED')); } else { // Get the model. /** @var CategoriesModelCategory $model */ $model = $this->getModel(); // Make sure the item ids are integers $cid = ArrayHelper::toInteger($cid); // Remove the items. if ($model->delete($cid)) { $this->setMessage(JText::plural($this->text_prefix . '_N_ITEMS_DELETED', count($cid))); } else { $this->setMessage($model->getError()); } } $this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&extension=' . $extension, false)); }
php
{ "resource": "" }
q239968
CategoriesControllerCategories.checkin
train
public function checkin() { // Process parent checkin method. $result = parent::checkin(); // Overrride the redirect Uri. $redirectUri = 'index.php?option=' . $this->option . '&view=' . $this->view_list . '&extension=' . $this->input->get('extension', '', 'CMD'); $this->setRedirect(JRoute::_($redirectUri, false), $this->message, $this->messageType); return $result; }
php
{ "resource": "" }
q239969
Plugin.parsePropertyFile
train
public function parsePropertyFile(BuildInterface $build, $fileName) { $activeProperty = false; $trimNextLine = false; $arr = array(); $fh = fopen($fileName, 'r'); if (is_resource($fh)) { while ($line = fgets($fh)) { if (preg_match('/^[!#].*/', $line)) { // comment } elseif (preg_match("/^.*?([\._-\w]+?)\s*[=:]+\s*(.*)$/", $line, $matches)) { // we have a key definition $activeProperty = true; $key = $matches[1]; $valuePart = $matches[2]; $arr[$key] = trim($valuePart); if ($arr[$key]{strlen($arr[$key]) - 1} == '\\') { $arr[$key] = substr($arr[$key], 0, -1); $trimNextLine = true; } else { $trimNextLine = false; } } elseif ($activeProperty) { $trimmed = trim($line); if (empty($trimmed)) { $activeProperty = false; continue; } elseif ($trimNextLine) { $line = $trimmed; } else { $line = rtrim($line); } $arr[$key] .= "\n".$line; if ($arr[$key]{strlen($arr[$key]) - 1} == '\\') { $arr[$key] = substr($arr[$key], 0, -1); $trimNextLine = true; } else { $trimNextLine = false; } } } foreach ($arr as $key => $value) { $build->debug('Setting property "${'.$key.'}" to "'.$value.'"'); $build->setProperty($key, stripcslashes($value)); } } else { $build->error('Cannot read from property file: '.$fileName); } }
php
{ "resource": "" }
q239970
Restful._customRequest
train
protected function _customRequest($url, $data, $type) { $response = $this->curl->init($this->url ?? $url) ->option('returntransfer', true) ->option('customrequest', strtoupper($type)) ->option('ssl_verifypeer', $this->sslVerifyPeer) ->option('postfields', $data) ->exec(); return $this->_result($response); }
php
{ "resource": "" }
q239971
DbTableGateway.gc
train
public function gc($maxlifetime) { $platform = $this->tableGateway->getAdapter()->getPlatform(); $where = new Where(); $where->lessThan( $this->options->getModifiedColumn(), new Expression('(' . time() . ' - ' . $platform->quoteIdentifier($this->options->getLifetimeColumn()) . ')') ); $rows = $this->tableGateway->select($where); $ids = []; /* @var \UthandoSessionManager\Model\SessionModel $row */ foreach ($rows as $row) { $ids[] = $row->{$this->options->getIdColumn()}; } if (count($ids) > 0) { $where = new Where(); $result = (bool) $this->tableGateway->delete( $where->in($this->options->getIdColumn(), $ids) ); } else { $result = false; } return $result; }
php
{ "resource": "" }
q239972
UserRepository.save
train
public function save(User $user) : bool { if (!$user->save()) { throw new \RuntimeException($this->i18n->t('setrun/user', 'Saving error')); } return true; }
php
{ "resource": "" }
q239973
UserRepository.remove
train
public function remove(User $user) : bool { if (!$user->delete()) { throw new \RuntimeException($this->i18n->t('setrun/user', 'Removing error')); } return true; }
php
{ "resource": "" }
q239974
UserRepository.getBy
train
public function getBy(array $condition) : User { if (!$user = User::find()->andWhere($condition)->limit(1)->one()) { throw new NotFoundException($this->i18n->t('setrun/user', 'User not found')); } return $user; }
php
{ "resource": "" }
q239975
View.load
train
private static function load($path) { $path = str_replace('.', '/', $path); $path = FULL_PATH . $path; if(substr($path, -4) != '.php') { $path = $path . '.php'; } return $path; }
php
{ "resource": "" }
q239976
View.get
train
public static function get($file, $data = []) { $path = self::load('views.' . $file); extract($data, EXTR_SKIP); include $path; }
php
{ "resource": "" }
q239977
View.parse
train
private static function parse($file, $data) { $file = file_get_contents($file, FILE_USE_INCLUDE_PATH); // Go through each variable and replace the values foreach($data as $key => $value) { $pattern = '{{{' . $key . '}}}'; $file = preg_replace($pattern, $value, $file); } if(!!$file) { return $file; } return false; }
php
{ "resource": "" }
q239978
BufferOverflowException.setOverflowMagnitude
train
public function setOverflowMagnitude($magnitude) { if ($magnitude < 0) { throw new \LogicException('Overflow magnitude cannot be negative.'); } if (!is_numeric($magnitude)) { throw new \InvalidArgumentException('Overflow magnitude should be a number.'); } $this->overflowMagnitude = $magnitude; }
php
{ "resource": "" }
q239979
AbstractConfig.getFilepath
train
public function getFilepath() { if (isset($this->dirPath)) { $filepath = $this->dirPath .'/'.$this->filename; } else { $fileSystem = $this->createNew(FileSystem::class); $filepath = $fileSystem->getCurrentWorkingDirectory() .'/'.$this->filename; } return $filepath; }
php
{ "resource": "" }
q239980
AbstractConfig.validateConfig
train
public function validateConfig(array $rules, array $configData) { $validator = $this->createNew(Validator::class); if ($validator->isValid($rules, $configData) == false) { throw new DataValidationException('The config is invalid: ' . print_r($validator->getErrors(), 1)); } }
php
{ "resource": "" }
q239981
AbstractConfig.open
train
public function open() { $fileSystem = $this->createNew(FileSystem::class); $filepath = $this->getFilepath(); $contents = $fileSystem->fileGetContents($filepath); $this->configData = json_decode($contents, true); if (isset($this->configData) == false) { throw new MalformedDataException('The contents of the file "'.$filepath.'" are not valid json'); } $this->validateConfig($this->rules, $this->configData); }
php
{ "resource": "" }
q239982
AbstractConfig.save
train
public function save() { $filepath = $this->getFilepath(); $this->validateConfig($this->rules, $this->configData); $fileSystem = $this->createNew(FileSystem::class); $fileSystem->filePutContents($filepath, json_encode($this->configData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); }
php
{ "resource": "" }
q239983
YouTubeStreamsLoader.getStreams
train
public function getStreams($channelId = null) { if (!$channelId) { $channelId = $this->channelId; } if (!$channelId) { throw new MissingChannelIdException("You must specify the channel id"); } if ($this->cache) { $data = $this->cache->fetch($this->getCacheKey($channelId)); if ($data !== false) { return $data; } } $searchResponse = $this->client->get( 'search', [ 'query' => [ 'part' => 'id', 'channelId' => $channelId, 'eventType' => 'live', 'type' => 'video', 'maxResults' => 50 ] ] ); $searchData = json_decode($searchResponse->getBody()->getContents(), true); $videosResponse = $this->client->get( 'videos', [ 'query' => [ 'part' => 'id,snippet,liveStreamingDetails', 'id' => implode( ',', array_map( function ($video) { return $video['id']['videoId']; }, $searchData['items'] ) ) ] ] ); $videosData = json_decode($videosResponse->getBody()->getContents(), true); $streams = array_map( function ($video) { return [ 'name' => $video['snippet']['title'], 'thumb' => $video['snippet']['thumbnails']['high']['url'], 'videoId' => $video['id'] ]; }, array_values( array_filter( $videosData['items'], function ($video) { return !isset($video['liveStreamingDetails']['actualEndTime']); } ) ) ); if ($this->cache && $this->cacheTimeout > 0) { $this->cache->save($this->getCacheKey($channelId), $streams, $this->cacheTimeout); } return $streams; }
php
{ "resource": "" }
q239984
Config.get
train
public static function get($file, $key = false, $force = false) { $item = self::read($file, $force); if($item === false) { return false; } if($key != false && isset($item[$key])) { return $item[$key]; } return $item; }
php
{ "resource": "" }
q239985
JoinFacade.inner
train
public function inner($table, array $optionalTables = array()) { $preparedTablesArray = $this->_getPreparedTableObjects($table, $optionalTables); $this->join->inner($preparedTablesArray['table'], $preparedTablesArray['optionalTables']); return $this; }
php
{ "resource": "" }
q239986
JoinFacade.left
train
public function left($table, array $optionalTables = array()) { $preparedTablesArray = $this->_getPreparedTableObjects($table, $optionalTables); $this->join->left($preparedTablesArray['table'], $preparedTablesArray['optionalTables']); return $this; }
php
{ "resource": "" }
q239987
JoinFacade.right
train
public function right($table, array $optionalTables = array()) { $preparedTablesArray = $this->_getPreparedTableObjects($table, $optionalTables); $this->join->right($preparedTablesArray['table'], $preparedTablesArray['optionalTables']); return $this; }
php
{ "resource": "" }
q239988
JoinFacade.leftOuter
train
public function leftOuter($table, array $optionalTables = array()) { $preparedTablesArray = $this->_getPreparedTableObjects($table, $optionalTables); $this->join->leftOuter($preparedTablesArray['table'], $preparedTablesArray['optionalTables']); return $this; }
php
{ "resource": "" }
q239989
JoinFacade.rightOuter
train
public function rightOuter($table, array $optionalTables = array()) { $preparedTablesArray = $this->_getPreparedTableObjects($table, $optionalTables); $this->join->rightOuter($preparedTablesArray['table'], $preparedTablesArray['optionalTables']); return $this; }
php
{ "resource": "" }
q239990
JoinFacade._getPreparedTableObjects
train
private function _getPreparedTableObjects($table, array $optionalTables) { $tableObj = $this->factory->references('Table', $table); $optionalTablesObj = array(); foreach($optionalTables as $tbl) { $optionalTablesObj[] = $this->factory->references('Table', $tbl); } return array('table' => $tableObj, 'optionalTables' => $optionalTablesObj); }
php
{ "resource": "" }
q239991
JoinFacade._checkOnArguments
train
private function _checkOnArguments(array $firstColumn, array $secondColumn) { if(!array_key_exists('column', $firstColumn) || !array_key_exists('table', $firstColumn) || !array_key_exists('column', $secondColumn) || !array_key_exists('table', $secondColumn) ) { throw new \InvalidArgumentException('Both arguments of on method require "column" and "table" as key'); } }
php
{ "resource": "" }
q239992
Kernel.createEach
train
protected function createEach() { foreach ($this->providers as $class => &$data) { if ( ! array_get($data, 'instance')) { $instance = $this->getProviderInvoker() ->create($class, $this->getSharedArguments()); array_set($data, 'instance', $instance); $this->create(); break; } } }
php
{ "resource": "" }
q239993
Kernel.configureEach
train
protected function configureEach() { foreach ($this->providers as $class => &$data) { if ( ! array_contains(array_get($data, 'tags'), ProviderTag::CONFIGURED)) { $this->create(); array_add($data, 'tags', ProviderTag::CONFIGURED); $instance = array_get($data, 'instance'); if (method_exists($instance, 'configure')) { $this->getProviderInvoker() ->configure($instance, $this->getSharedArguments()); } $this->configureEach(); break; } } }
php
{ "resource": "" }
q239994
Kernel.initializeEach
train
protected function initializeEach() { foreach ($this->providers as $class => &$data) { if ( ! array_contains(array_get($data, 'tags'), ProviderTag::INITIALIZED)) { $this->configure(); array_add($data, 'tags', ProviderTag::INITIALIZED); $instance = array_get($data, 'instance'); if (method_exists($instance, 'initialize')) { $this->getProviderInvoker() ->initialize($instance, $this->getSharedArguments()); } $this->initializeEach(); break; } } }
php
{ "resource": "" }
q239995
Kernel.bootEach
train
protected function bootEach() { foreach ($this->providers as $class => &$data) { if ( ! array_contains(array_get($data, 'tags'), ProviderTag::BOOTED)) { $this->initialize(); array_add($data, 'tags', ProviderTag::BOOTED); $instance = array_get($data, 'instance'); if (method_exists($instance, 'boot')) { $this->getProviderInvoker() ->boot($instance, $this->getSharedArguments()); } $this->bootEach(); break; } } }
php
{ "resource": "" }
q239996
Kernel.shutdownEach
train
protected function shutdownEach() { foreach ($this->providers as $class => &$data) { if ( ! array_contains(array_get($data, 'tags'), ProviderTag::SHUTDOWN)) { $this->boot(); array_add($data, 'tags', ProviderTag::SHUTDOWN); $instance = array_get($data, 'instance'); if (method_exists($instance, 'shutdown')) { $this->getProviderInvoker() ->boot($instance, $this->getSharedArguments()); } $this->shutdownEach(); break; } } }
php
{ "resource": "" }
q239997
MessageAdapter.add
train
public function add($message, $code, $type) { $default = ['message' => $message, 'code' => $code, 'type' => $type]; if ($type == 'error' && is_numeric($code) && $code >= 0) { $default['descriptor'] = array_search($code, $this->codes['codes']); } if ($this->domain !== self::DEFAULT_DOMAIN) { $default['domain'] = $this->domain; } array_push($this->messages, $default); return $this; }
php
{ "resource": "" }
q239998
DbManagementTable.populate
train
public function populate(DbManagement $db, DbManagementObject $DbManagementObject, $query) { $keys = array_values($DbManagementObject->getKeys()); $db->add($query, $keys); $array = array_values($DbManagementObject->getValues()); $db->query($query, $array); return $db->lastInsertId(); }
php
{ "resource": "" }
q239999
DbManagementTable.getData
train
public function getData(DbManagement $db, $query, $params, DbManagementObject $DbManagementObject) { $keys = $DbManagementObject->getKeys(); //parse params to check their validity and //use the conventions to sort and filter results $parsed = $this->parseParams($params, $keys, $DbManagementObject->getTypes()); $array=[]; //if valid params have been detected //query is filled in with arguments if(isset($parsed)){ foreach ($parsed as $type => $values) { switch($type){ case "min": foreach ($values as $key => $val) { $min = $keys[$key]."-min"; $db->sortMin($query,$keys[$key],$min); $array[]=$val; } break; case "max": foreach ($values as $key => $val) { $max = $keys[$key]."-max"; $db->sortMax($query,$keys[$key],$max); $array[]=$val; } break; case "up": foreach ($values as $val) { $db->orderUp($query,$keys[$val]); } break; case "down": foreach ($values as $val) { $db->orderDown($query,$keys[$val]); } break; case "equals": foreach ($values as $key => $val) { $db->sort($query,$keys[$key], $keys[$key]); $array[]=$val; } break; } } } //close query $db->closeQuery($query); $answer = $db->query($query, $array); $args=[]; while ($row = $answer->fetch(\PDO::FETCH_ASSOC)) { foreach ($keys as $key => $val) { $argsDbManagementObject[$val]=$row[$val]; } $args[] = $argsDbManagementObject; } return $args; }
php
{ "resource": "" }