_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q240700
Joyst_Model.Save
train
function Save($id, $data = null) { if (!$id) return; $this->LoadSchema(); if (is_array($id)) { $data = $id; if (!isset($data[$this->schema['_id']['field']])) // Incomming data has no ID to address by return; $id = $data[$this->schema['_id']['field']]; } else { $data[$this->schema['_id']['field']] = $id; } if (!$data) return; if ($this->enforceTypes) foreach ($this->schema as $key => $props) if (isset($data[$key]) || $props['type'] == 'json-import') $data[$key] = $this->UnCastType($props['type'], isset($data[$key]) ? $data[$key] : null, $data); $this->ResetQuery(array( 'method' => 'save', 'table' => $this->table, 'where' => array( $this->schema['_id']['field'] => $id, ), 'data' => $data, )); $this->Trigger('access', $data); if (!$this->continue) return FALSE; $this->Trigger('push', $data); if (!$this->continue) return FALSE; unset($data[$this->schema['_id']['field']]); // Remove ID from saving data (it will only be removed during filtering anyway as PKs can never be saved) $this->trigger('save', $id, $data); if (!$this->continue) return FALSE; if (! $data = $this->FilterFields($data, 'set')) // Nothing to save return FALSE; if (!$this->continue) return FALSE; $this->db->where("{$this->table}.{$this->schema['_id']['field']}", $id); $this->db->update($this->table, $data); $this->Trigger('saved', $id, $save); $this->ClearCache('get', $id); // Wipe the cache so the next get() doesn't return cached data return $this->returnRow ? $this->Get($id) : $save; }
php
{ "resource": "" }
q240701
Joyst_Model.Delete
train
function Delete($id) { $this->LoadSchema(); $data = array($this->schema['_id']['field'] => $id); $this->ResetQuery(array( 'method' => 'delete', 'table' => $this->table, 'where' => array( $this->schema['_id']['field'] => $id, ), )); $this->Trigger('access', $data); if (!$this->continue) return FALSE; $this->Trigger('push', $data); if (!$this->continue) return FALSE; $this->Trigger('delete', $id); if (!$id) return FALSE; if (!$this->continue) return FALSE; $this->db->from($this->table); $this->db->where("{$this->table}.{$this->schema['_id']['field']}", $id); $this->db->delete(); $this->Trigger('deleted', $id); return TRUE; }
php
{ "resource": "" }
q240702
Joyst_Model.ResetQuery
train
function ResetQuery($query = null) { $this->db->ar_select = array(); $this->db->ar_distinct = FALSE; $this->db->ar_from = array(); $this->db->ar_join = array(); $this->db->ar_where = array(); $this->db->ar_like = array(); $this->db->ar_groupby = array(); $this->db->ar_having = array(); $this->db->ar_keys = array(); $this->db->ar_limit = FALSE; $this->db->ar_offset = FALSE; $this->db->ar_order = FALSE; $this->db->ar_orderby = array(); $this->db->ar_set = array(); $this->db->ar_wherein = array(); $this->db->ar_aliased_tables = array(); $this->db->ar_store_array = array(); $this->joystError = ''; $this->continue = TRUE; $this->query = $query; }
php
{ "resource": "" }
q240703
InstallProjectController.configureAction
train
public function configureAction(Request $request) { if ($this->get('tenside.status')->isTensideConfigured()) { throw new NotAcceptableHttpException('Already configured.'); } $inputData = new JsonArray($request->getContent()); $secret = bin2hex(random_bytes(40)); if ($inputData->has('credentials/secret')) { $secret = $inputData->get('credentials/secret'); } // Add tenside configuration. $tensideConfig = $this->get('tenside.config'); $tensideConfig->set('secret', $secret); if ($inputData->has('configuration')) { $this->handleConfiguration($inputData->get('configuration', true)); } $user = $this->createUser($inputData->get('credentials/username'), $inputData->get('credentials/password')); return new JsonResponse( [ 'status' => 'OK', 'token' => $this->get('tenside.jwt_authenticator')->getTokenForData($user) ], JsonResponse::HTTP_CREATED ); }
php
{ "resource": "" }
q240704
InstallProjectController.getProjectVersionsAction
train
public function getProjectVersionsAction($vendor, $project) { $this->checkUninstalled(); $url = sprintf('https://packagist.org/packages/%s/%s.json', $vendor, $project); $rfs = new RemoteFilesystem($this->getInputOutput()); $results = $rfs->getContents($url, $url); $data = new JsonArray($results); $versions = []; foreach ($data->get('package/versions') as $information) { $version = [ 'name' => $information['name'], 'version' => $information['version'], 'version_normalized' => $information['version_normalized'], ]; $normalized = $information['version']; if ('dev-' === substr($normalized, 0, 4)) { if (isset($information['extra']['branch-alias'][$normalized])) { $version['version_normalized'] = $information['extra']['branch-alias'][$normalized]; } } if (isset($information['source']['reference'])) { $version['reference'] = $information['source']['reference']; } elseif (isset($information['dist']['reference'])) { $version['reference'] = $information['dist']['reference']; } $versions[] = $version; } return new JsonResponse( [ 'status' => 'OK', 'versions' => $versions ] ); }
php
{ "resource": "" }
q240705
InstallProjectController.getInstallationStateAction
train
public function getInstallationStateAction() { $status = $this->get('tenside.status'); return new JsonResponse( [ 'state' => [ 'tenside_configured' => $status->isTensideConfigured(), 'project_created' => $status->isProjectPresent(), 'project_installed' => $status->isProjectInstalled(), ], 'status' => 'OK' ] ); }
php
{ "resource": "" }
q240706
InstallProjectController.createUser
train
private function createUser($username, $password) { $user = new UserInformation( [ 'username' => $username, 'acl' => UserInformationInterface::ROLE_ALL ] ); $user->set('password', $this->get('security.password_encoder')->encodePassword($user, $password)); $user = $this->get('tenside.user_provider')->addUser($user)->refreshUser($user); return $user; }
php
{ "resource": "" }
q240707
InstallProjectController.handleConfiguration
train
private function handleConfiguration($configuration) { $tensideConfig = $this->get('tenside.config'); if (isset($configuration['php_cli'])) { $tensideConfig->setPhpCliBinary($configuration['php_cli']); } if (isset($configuration['php_cli_arguments'])) { $tensideConfig->setPhpCliArguments($configuration['php_cli_arguments']); } if (isset($configuration['php_cli_environment'])) { $tensideConfig->setPhpCliEnvironment($configuration['php_cli_environment']); } if (isset($configuration['php_force_background'])) { $tensideConfig->setForceToBackground($configuration['php_force_background']); } if (isset($configuration['php_can_fork'])) { $tensideConfig->setForkingAvailable($configuration['php_can_fork']); } if (isset($configuration['github_oauth_token'])) { $composerAuth = new AuthJson( $this->get('tenside.home')->tensideDataDir() . DIRECTORY_SEPARATOR . 'auth.json', null ); $composerAuth->setGithubOAuthToken($configuration['github_oauth_token']); } }
php
{ "resource": "" }
q240708
FileConfig.loadFile
train
function loadFile($file, $optional=false, $varname=false, $recursive=false) { if (!is_file($file)) { if ($optional) return $this; else throw new Exception("Failed to read config file '$file'"); } $newConfig = @include($file); if(!is_array($newConfig) && $varname) $newConfig = $$varname; if(!is_array($newConfig) && !$optional) throw new Exception("Config file '$file' doesn't contain a config"); else if(is_array($newConfig)) { if ($recursive) $this->_data = array_merge_recursive($this->_data, $newConfig); else $this->_data = array_merge($this->_data, $newConfig); } return $this; }
php
{ "resource": "" }
q240709
TemplateFinderService.find
train
public function find(PageDocument $page) { $request = $this->requestStack->getCurrentRequest(); $template = $page->getDefault(AbstractPhpcrDocument::DEFAULT_TEMPLATE_KEY); if ($template === null) { $defaults = []; /** @var RouteEnhancerInterface $enhancer */ foreach ($this->dynamicRouter->getRouteEnhancers() as $enhancer) { $defaults = array_merge($defaults, $enhancer->enhance(['_content' => $page], $request)); } if (array_key_exists(AbstractPhpcrDocument::DEFAULT_TEMPLATE_KEY, $defaults)) { $template = $defaults[AbstractPhpcrDocument::DEFAULT_TEMPLATE_KEY]; } } return $template; }
php
{ "resource": "" }
q240710
Deklaracja.setPodmiot1
train
public function setPodmiot1(\KCH\PCC3\Deklaracja\Podmiot1AnonymousType $podmiot1) { $this->podmiot1 = $podmiot1; return $this; }
php
{ "resource": "" }
q240711
Deklaracja.setZalaczniki
train
public function setZalaczniki(\KCH\PCC3\Deklaracja\ZalacznikiAnonymousType $zalaczniki) { $this->zalaczniki = $zalaczniki; return $this; }
php
{ "resource": "" }
q240712
ResqueWorkerBase.restore
train
public function restore($workerInstance) { list($hostname, $pid, $queues) = explode(':', $workerInstance, 3); if (!is_array($queues)) { $queues = explode(',', $queues); } $this->queues = $queues; $this->pid = $pid; $this->id = $workerInstance; //regenerate worker $data = $this->resqueInstance->redis->get($this->workerName() . ':' . $workerInstance); if ($data !== false) { $data = json_decode($data, true); $this->currentJob = new ResqueJobBase($this->resqueInstance, $data['queue'], $data['payload'], true); } $workerPids = self::workerPids(); if (!in_array($pid, $workerPids)) { $this->unregisterWorker(); return false; } return true; }
php
{ "resource": "" }
q240713
LoggerBase.interpolateString
train
private function interpolateString($message, array $context = []) { // Build a replacement array with braces around the context keys. $replace = []; foreach ($context as $key => $value) { // Check that the value can be cast to string. if (!is_array($value) && (!is_object($value) || method_exists($value, '__toString'))) { $replace['{' . $key . '}'] = $value; } } // Interpolate replacement values into the message. $result = strtr($message, $replace); if (is_string($result)) { return $result; } /* If something went wrong, return the original message (with a * warning). */ return sprintf( '%s (WARNING: Unable to interpolate the context values into the message. %s).', $message, var_export($replace, true) ); }
php
{ "resource": "" }
q240714
Prop.file
train
public static function file( $name, & $exists = false ) { if( !defined("APP_DIR") ) { return []; } $file = APP_DIR . "config" . DIRECTORY_SEPARATOR . $name . '.php'; if( file_exists( $file ) ) { $data = Helper::includeImport($file); $exists = true; } if( ! isset( $data ) || ! is_array( $data ) ) { $data = []; } return $data; }
php
{ "resource": "" }
q240715
Prop.cache
train
public static function cache( $name ) { static $cache = []; $name = (string) $name; if( ! isset($cache[$name]) ) { $cache[$name] = new self($name); } return $cache[$name]; }
php
{ "resource": "" }
q240716
Prop.group
train
public function group( $name ) { $name = rtrim($name, '.'); $pref = $name . '.'; $len = strlen($pref); $data = []; foreach( array_keys($this->items) as $key ) { if( $key === $name ) { $data['.'] = $this->items[$key]; } else if( strlen($key) > $len && substr($key, 0, $len) === $pref ) { $data[substr($key, $len)] = $this->items[$key]; } } return new self($data); }
php
{ "resource": "" }
q240717
Prop.pathSet
train
public function pathSet( $path, $value ) { $path = $this->createPath($path); if( $path[0] == 1 ) { $this->offsetSet($path[1], $value); } else { $array = & $this->items; for( $i = 1, $len = $path[0]; $i <= $len; $i++ ) { $key = $path[$i]; if( $i == $len ) { $array[$key] = $value; } else { if( !isset($array[$key]) || !is_array($array[$key]) ) { $array[$key] = []; } $array = & $array[$key]; } } } return $this; }
php
{ "resource": "" }
q240718
Prop.pathGetIs
train
public function pathGetIs( $path, $accessible = false ) { $path = $this->createPath($path); $array = & $this->items; $key = $path[1]; if( $path[0] > 1 ) { for( $i = 1, $len = $path[0]; $i <= $len; $i++ ) { $key = $path[$i]; if( ! array_key_exists($key, $array) ) { return false; } if( $i < $len ) { if( is_array($array[$key]) ) { $array = & $array[$key]; } else { return false; } } } } else if( ! array_key_exists($key, $array) ) { return false; } if( $accessible ) { return is_array($array[$key]); } return true; }
php
{ "resource": "" }
q240719
Prop.pathGetOr
train
public function pathGetOr( $path, $default ) { $path = $this->createPath($path); if( $path[0] == 1 ) { return $this->get($path[1]); } $array = & $this->items; for( $i = 1, $len = $path[0]; $i <= $len; $i++ ) { $key = $path[$i]; if( ! array_key_exists($key, $array) ) { break; } if( $i == $len ) { return $array[$key]; } if( !isset($array[$key]) || !is_array($array[$key]) ) { break; } $array = & $array[$key]; } return $default; }
php
{ "resource": "" }
q240720
LoopSpec.it_provides_useful_information_about_iterations
train
function it_provides_useful_information_about_iterations() { $this->next('one'); $this->getIndex()->shouldBe(0); $this->getKey()->shouldBe('one'); $this->isFirst()->shouldBe(true); $this->isLast()->shouldBe(false); $this->next('two'); $this->getIndex()->shouldBe(1); $this->getKey()->shouldBe('two'); $this->isFirst()->shouldBe(false); $this->isLast()->shouldBe(false); $this->next('three'); $this->getIndex()->shouldBe(2); $this->getKey()->shouldBe('three'); $this->isFirst()->shouldBe(false); $this->isLast()->shouldBe(true); }
php
{ "resource": "" }
q240721
Fuel.init
train
public static function init($config) { if (static::$initialized) { throw new \FuelException("You can't initialize Fuel more than once."); } // BC FIX FOR APPLICATIONS <= 1.6.1, makes Redis_Db available as Redis, // like it was in versions before 1.7 class_exists('Redis', false) or class_alias('Redis_Db', 'Redis'); static::$_paths = array(APPPATH, COREPATH); // Is Fuel running on the command line? static::$is_cli = (bool) defined('STDIN'); \Config::load($config); // Disable output compression if the client doesn't support it if (static::$is_cli or ! in_array('gzip', explode(', ', \Input::headers('Accept-Encoding', '')))) { \Config::set('ob_callback', null); } // Start up output buffering ob_start(\Config::get('ob_callback')); if (\Config::get('caching', false)) { \Finder::instance()->read_cache('FuelFileFinder'); } static::$profiling = \Config::get('profiling', false); static::$profiling and \Profiler::init(); // set a default timezone if one is defined try { static::$timezone = \Config::get('default_timezone') ?: date_default_timezone_get(); date_default_timezone_set(static::$timezone); } catch (\Exception $e) { date_default_timezone_set('UTC'); throw new \PHPErrorException($e->getMessage()); } static::$encoding = \Config::get('encoding', static::$encoding); MBSTRING and mb_internal_encoding(static::$encoding); static::$locale = \Config::get('locale', static::$locale); if ( ! static::$is_cli) { if (\Config::get('base_url') === null) { \Config::set('base_url', static::generate_base_url()); } } // Run Input Filtering \Security::clean_input(); \Event::register('fuel-shutdown', 'Fuel::finish'); // Always load classes, config & language set in always_load.php config static::always_load(); // Load in the routes \Config::load('routes', true); \Router::add(\Config::get('routes')); // Set locale, log warning when it fails if (static::$locale) { setlocale(LC_ALL, static::$locale) or logger(\Fuel::L_WARNING, 'The configured locale '.static::$locale.' is not installed on your system.', __METHOD__); } static::$initialized = true; // fire any app created events \Event::instance()->has_events('app_created') and \Event::instance()->trigger('app_created', '', 'none'); if (static::$profiling) { \Profiler::mark(__METHOD__.' End'); } }
php
{ "resource": "" }
q240722
Fuel.finish
train
public static function finish() { if (\Config::get('caching', false)) { \Finder::instance()->write_cache('FuelFileFinder'); } if (static::$profiling and ! static::$is_cli and ! \Input::is_ajax()) { // Grab the output buffer and flush it, we will rebuffer later $output = ob_get_clean(); $headers = headers_list(); $show = true; foreach ($headers as $header) { if (stripos($header, 'content-type') === 0 and stripos($header, 'text/html') === false) { $show = false; } } if ($show) { \Profiler::mark('End of Fuel Execution'); if (preg_match("|</body>.*?</html>|is", $output)) { $output = preg_replace("|</body>.*?</html>|is", '', $output); $output .= \Profiler::output(); $output .= '</body></html>'; } else { $output .= \Profiler::output(); } } // Restart the output buffer and send the new output ob_start(\Config::get('ob_callback')); echo $output; } }
php
{ "resource": "" }
q240723
Fuel.generate_base_url
train
protected static function generate_base_url() { $base_url = ''; if(\Input::server('http_host')) { $base_url .= \Input::protocol().'://'.\Input::server('http_host'); } if (\Input::server('script_name')) { $common = get_common_path(array(\Input::server('request_uri'), \Input::server('script_name'))); $base_url .= $common; } // Add a slash if it is missing and return it return rtrim($base_url, '/').'/'; }
php
{ "resource": "" }
q240724
Fuel.always_load
train
public static function always_load($array = null) { is_null($array) and $array = \Config::get('always_load', array()); isset($array['packages']) and \Package::load($array['packages']); isset($array['modules']) and \Module::load($array['modules']); if (isset($array['classes'])) { foreach ($array['classes'] as $class) { if ( ! class_exists($class = \Str::ucwords($class))) { throw new \FuelException('Class '.$class.' defined in your "always_load" config could not be loaded.'); } } } /** * Config and Lang must be either just the filename, example: array(filename) * or the filename as key and the group as value, example: array(filename => some_group) */ if (isset($array['config'])) { foreach ($array['config'] as $config => $config_group) { \Config::load((is_int($config) ? $config_group : $config), (is_int($config) ? true : $config_group)); } } if (isset($array['language'])) { foreach ($array['language'] as $lang => $lang_group) { \Lang::load((is_int($lang) ? $lang_group : $lang), (is_int($lang) ? true : $lang_group)); } } }
php
{ "resource": "" }
q240725
Fuel.clean_path
train
public static function clean_path($path) { static $search = array(APPPATH, COREPATH, PKGPATH, DOCROOT, '\\'); static $replace = array('APPPATH/', 'COREPATH/', 'PKGPATH/', 'DOCROOT/', '/'); return str_ireplace($search, $replace, $path); }
php
{ "resource": "" }
q240726
Transport.send
train
public function send(Request $request) { $interface = $request->getInterface(); $service = ConfigFactory::getClient()->getService($interface); $url = $service->getUrl(); $requestRaw = Formatter::serialize($request); $responseRaw = $this->protocol->sendData($url, $requestRaw); $response = @Formatter::unserialize($responseRaw); if (!($response instanceof Response)) { LoggerProxy::getInstance()->error("illegal response", array($responseRaw)); throw new InitiallyRpcException("illegal response"); } elseif ($response->isHasException()) { $exception = $response->getException(); if (is_object($exception) && $exception instanceof Exception) { throw $exception; } else if (is_string($exception)) { if (class_exists($exception)) { throw new $exception($response->getExceptionMessage()); } else { throw new InitiallyRpcException($response->getExceptionMessage()); } } } return $response->getResult(); }
php
{ "resource": "" }
q240727
ClientBasic.send
train
protected function send($content) { $streamOptions = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => $content, ) ); $context = stream_context_create($streamOptions); $result = @file_get_contents($this->getServerUrl(), false, $context); if ($result === false) { throw new Exception('Unable to connect to server'); } return $result; }
php
{ "resource": "" }
q240728
Email.sendActivationMessage
train
public function sendActivationMessage() { $macros = new Macros($this->_data); $message = $this->_params->get('msg_account_activate_msg'); $message = $macros->text($message); $subject = $this->_params->get('msg_account_activate_subject'); return $this->send($subject, $message, $this->_data->email, null, $this->_getFromMail()); }
php
{ "resource": "" }
q240729
IntercessionClass.addAuthor
train
public function addAuthor(string $name = null, string $email = null) { is_null($name) and $name = ''; is_null($email) and $email = ''; if (empty($name) and empty($email)) { throw new AuthorNoDataException(); } if (!empty($email)) { $author = trim(sprintf(self::FORMAT_AUTHOR, $name, $email)); } else { $author = trim($name); } $this->authors[] = $author; return $this; }
php
{ "resource": "" }
q240730
IntercessionClass.addInterface
train
public function addInterface(string $interfaceName, string $alias = null) { $this->interfaces[] = $this->addUse($interfaceName, $alias); }
php
{ "resource": "" }
q240731
IntercessionClass.addTrait
train
public function addTrait(string $traitName, string $alias = null) { $this->traits[] = $this->addUse($traitName, $alias); return $this; }
php
{ "resource": "" }
q240732
IntercessionClass.extractClassNameFromUse
train
public function extractClassNameFromUse(string $use) { $matches = []; if (preg_match(self::USE_CLASS_EXTRACT_REGEXP, $use, $matches) === 0) { throw new InvalidNamespaceException($use); } $className = $matches['classname']; $namespace = array_key_exists('namespace', $matches) ? $matches['namespace'] : ''; if (substr($namespace, -1, 1) === '\\') { $namespace = substr($namespace, 0, -1); } return [ $className, $namespace ]; }
php
{ "resource": "" }
q240733
ScriptHandler.installJSDependencies
train
public static function installJSDependencies($event) { echo "Installing JS Library dependencies for the AltamiraBundle\n"; $dir = getcwd(); ScriptHandler::gitSubmodulesUpdate(); ScriptHandler::cleanPublicJSDir(); // discovered that assetic can minify all the code - all not necessary anymore. /* echo "Compiling jqplot\n"; chdir(static::getLibsDir().DIRECTORY_SEPARATOR."jqplot"); exec('ant clean min', $output, $status); if ($status) { die("Ant failed with $status (is ant installed?)\n"); } chdir($dir); echo "Compiling flot\n"; $flotLib=static::getLibsDir() .DIRECTORY_SEPARATOR."flot"; if (($files = scandir($flotLib)) ===false ) { die("failed to traverse through flot directory"); } foreach ($files as $file) { if (substr($file,-3) == ".js") { exec(static::getYUIBin(). " ".escapeshellarg($flotLib.DIRECTORY_SEPARATOR.$file)." -o " .escapeshellarg(static::getLibsDir().DIRECTORY_SEPARATOR."flot".DIRECTORY_SEPARATOR.substr($file,0,-2)."min.js")); } } echo "Compiling flot bubbles\n"; $flotBubblesLib=static::getLibsDir() .DIRECTORY_SEPARATOR."flot-bubbles"; if (($files = scandir($flotBubblesLib)) ===false ) { die("failed to traverse through flot bubbles directory"); } foreach ($files as $file) { if (substr($file,-3) == ".js") { // minification did not work out, so commented min code. // exec(static::getYUIBin(). " ".escapeshellarg($flotBubblesLib.DIRECTORY_SEPARATOR.$file) ." -o " // .escapeshellarg(static::getLibsDir().DIRECTORY_SEPARATOR."flot-bubbles".DIRECTORY_SEPARATOR.substr($file,0,-2)."min.js")); // straight copy to min.js for compatibility with min setting in altamira copy($flotBubblesLib.DIRECTORY_SEPARATOR.$file,static::getLibsDir().DIRECTORY_SEPARATOR."flot-bubbles".DIRECTORY_SEPARATOR.substr($file,0,-2)."min.js"); } }*/ echo "Installing jqplot\n"; mkdir(static::getJSDir().DIRECTORY_SEPARATOR."jqplot",0777,true); $source = static::getLibsDir().DIRECTORY_SEPARATOR."jqplot".DIRECTORY_SEPARATOR."src"; $dest= static::getJSDir().DIRECTORY_SEPARATOR."jqplot"; recursiveAssetsOnlyCopy($source,$dest); echo "Installing flot\n"; mkdir(static::getJSDir().DIRECTORY_SEPARATOR."flot",0777,true); recursiveAssetsOnlyCopy(static::getLibsDir().DIRECTORY_SEPARATOR."flot",static::getJSDir().DIRECTORY_SEPARATOR."flot"); echo "Installing flot-bubbles\n"; mkdir(static::getJSDir().DIRECTORY_SEPARATOR."flot-bubbles",0777,true); recursiveAssetsOnlyCopy(static::getLibsDir().DIRECTORY_SEPARATOR."flot-bubbles",static::getJSDir().DIRECTORY_SEPARATOR."flot-bubbles"); }
php
{ "resource": "" }
q240734
FieldFactory.getInstance
train
public static function getInstance(array $config = []) { // If element has no name if (!isset($config['name'])){ throw new \Exception("You have to set the name of the field", 1); } if(!isset($config['class'])){ $config['class'] = Text::className(); } return parent::getInstance($config); }
php
{ "resource": "" }
q240735
AtomicFileHandler.rewindFile
train
public function rewindFile() { $this->openFile(); if(!rewind($this->getFile())) { throw FileOperationException::createForFailedToRewindFile($this->getFilePath()); } return $this; }
php
{ "resource": "" }
q240736
AtomicFileHandler.isFileEmpty
train
public function isFileEmpty() { $this->openFile(); $saved_pointer = $this->getFilePointer(); $this->rewindFile()->seekFileToEnd(); $size_pointer = $this->getFilePointer(); $this->seekFile($saved_pointer); return $size_pointer === 0; }
php
{ "resource": "" }
q240737
AtomicFileHandler.checkFile
train
protected function checkFile($writable = true) { if(!$this->fileExists()) throw NonExistentFileException::createForFileDoesNotExists($this->getFilePath()); if(!is_readable($this->file_path)) throw NotReadableFileException::createForNotReadable($this->getFilePath()); if($writable) { if(!is_writable($this->file_path)) throw NotWritableFileException::createForNotWritable($this->getFilePath()); } }
php
{ "resource": "" }
q240738
AtomicFileHandler.fileExists
train
protected function fileExists() { $this->clearStatCache(true); return (file_exists($this->file_path) && is_file($this->file_path)); }
php
{ "resource": "" }
q240739
IdentityRoleProviderFactory.createService
train
public function createService(ServiceLocatorInterface $serviceLocator) { $identityRoleProvider = new IdentityRoleProvider( $serviceLocator->get('UserRbac\UserRoleLinkerMapper'), $serviceLocator->get('UserRbac\ModuleOptions') ); if ($serviceLocator->get('zfcuser_auth_service')->hasIdentity()) { $identityRoleProvider->setDefaultIdentity( $serviceLocator->get('zfcuser_auth_service')->getIdentity() ); } return $identityRoleProvider; }
php
{ "resource": "" }
q240740
Group.setValue
train
public function setValue($value) { foreach ((array)$this as $element) { if ($value == $element->getElement()->getValue()) { $element->getElement()->check(); } else { $element->getElement()->check(false); } } }
php
{ "resource": "" }
q240741
Group.getValue
train
public function getValue() : ArrayObject { foreach ((array)$this as $element) { if ($element->getElement() instanceof Radio && $element->getElement()->checked() ) { return new class([$element->getElement()->getValue()]) extends ArrayObject { public function __toString() : string { return "{$this[0]}"; } }; } } return new class([$this->value]) extends ArrayObject { public function __toString() : string { return "{$this[0]}"; } }; }
php
{ "resource": "" }
q240742
Group.isRequired
train
public function isRequired() : Group { foreach ((array)$this as $el) { if (!is_object($el)) { continue; } $el->getElement()->attribute('required', 1); } return $this->addTest('required', function ($value) { foreach ($value as $option) { if ($option->getElement() instanceof Radio && $option->getElement()->checked() ) { return true; } } return false; }); }
php
{ "resource": "" }
q240743
Permission.getSections
train
protected function getSections(): array { $sections = explode($this->getDivider(), $this->getNotation()); foreach ($sections as $index => $section) { $sections[$index] = explode($this->getSeparator(), $section); } return $sections; }
php
{ "resource": "" }
q240744
AbstractSearch.normalizeResultSet
train
protected function normalizeResultSet(array $resultSet) { $normalized = []; foreach ($resultSet as $result) { if (($normalizedResult = $this->normalizeResult($result)) === null) { continue; } $normalized[$normalizedResult] = $normalizedResult; } return array_keys($normalized); }
php
{ "resource": "" }
q240745
PageUtil.create
train
public static function create($totalPage, $pageSize = 10, $page = 1, $gets = []) { $p = new PageUtil(); if ($pageSize < 1) { $pageSize = 1; } $total = ceil($totalPage / $pageSize); if ($page < 1) { $page = 1; } else if ($page > $total) { $page = $total; } $p->page = $page; $p->gets = $gets; $p->total = $total; $p->pageSize = $pageSize; return $p; }
php
{ "resource": "" }
q240746
Container.make
train
public function make(string $alias) { if (array_key_exists($alias, $this->bindings)) { $classOrObject = $this->bindings[$alias]; if (is_object($classOrObject)) { return $classOrObject; } return $this->makeInstance($classOrObject); } if (class_exists($alias)) { return self::register($alias, $this->makeInstance($alias))->make($alias); } throw new SimplesRunTimeError("Class '{$alias}' not found"); }
php
{ "resource": "" }
q240747
Container.makeInstance
train
public function makeInstance($className) { // class reflection $reflection = new ReflectionClass($className); // get the class constructor $constructor = $reflection->getConstructor(); // if there is no constructor, just create and // return a new instance if (!$constructor) { return $reflection->newInstance(); } // created and returns the new instance passing the // resolved parameters return $reflection->newInstanceArgs($this->resolveParameters($constructor->getParameters(), [])); }
php
{ "resource": "" }
q240748
Container.exists
train
public function exists($instance, string $method) { $reflection = new ReflectionClass(get_class($instance)); return $reflection->hasMethod($method); }
php
{ "resource": "" }
q240749
Container.invoke
train
public function invoke($instance, string $method, array $data) { // get the parameters $parameters = $this->resolveMethodParameters($instance, $method, $data, true); // get the reflection of method $reflection = new ReflectionMethod(get_class($instance), $method); // allow access $reflection->setAccessible(true); // execute the method return $reflection->invokeArgs($instance, $parameters); }
php
{ "resource": "" }
q240750
Container.resolveMethodParameters
train
public function resolveMethodParameters($instance, $method, $parameters, $labels = false) { // method reflection $reflectionMethod = new ReflectionMethod($instance, $method); // resolved array of parameters return $this->resolveParameters($reflectionMethod->getParameters(), $parameters, $labels); }
php
{ "resource": "" }
q240751
Container.resolveFunctionParameters
train
public function resolveFunctionParameters($callable, $parameters, $labels = false) { // method reflection $reflectionFunction = new ReflectionFunction($callable); // resolved array of parameters return $this->resolveParameters($reflectionFunction->getParameters(), $parameters, $labels); }
php
{ "resource": "" }
q240752
Container.resolveParameters
train
private function resolveParameters($parameters, $data, $labels = false) { $resolved = []; /** @var ReflectionParameter $reflectionParameter */ foreach ($parameters as $reflectionParameter) { /** @noinspection PhpAssignmentInConditionInspection */ $parameter = $this->parseParameter($reflectionParameter, $data, $labels); if (!is_null($parameter)) { $resolved[] = $parameter; continue; } /** @noinspection PhpAssignmentInConditionInspection */ if ($parameterClassName = $this->extractClassName($reflectionParameter)) { $resolved[] = static::make($parameterClassName); continue; } $resolved[] = null; } return $resolved; }
php
{ "resource": "" }
q240753
Container.parseParameter
train
private function parseParameter(ReflectionParameter $reflectionParameter, &$data, $labels) { // get the principal properties $name = $reflectionParameter->getName(); $value = null; if ($reflectionParameter->isOptional()) { $value = $reflectionParameter->getDefaultValue(); } // parse data using labels if ($labels) { if (isset($data[$name])) { $value = off($data, $name, $value); unset($data[$name]); } return $value; } // parse data without labels if (isset($data[0])) { $value = $data[0]; array_shift($data); reset($data); } return $value; }
php
{ "resource": "" }
q240754
Container.extractClassName
train
private function extractClassName(ReflectionParameter $reflectionParameter) { if (isset($reflectionParameter->getClass()->name)) { return $reflectionParameter->getClass()->name; } return ''; }
php
{ "resource": "" }
q240755
Statement.execute
train
public function execute() { $DB = $this->getDBO(); //Run the Query; $resultId = $DB->exec(); //\Platform\Debugger::log($resultId); $this->setResultId($resultId)->setConnectionId($DB->getResourceId())->setAffectedRows($this->getAffectedRows()); $DB->resetRun(); return $this; }
php
{ "resource": "" }
q240756
Statement.listColumns
train
public function listColumns() { $fieldNames = array(); $field = NULL; while ($field = mysqli_fetch_field($this->getResultId())) { $fieldNames[] = $field->name; } return $fieldNames; }
php
{ "resource": "" }
q240757
Statement.getColumnMeta
train
public function getColumnMeta($name = '') { $retval = array(); $field = NULL; while ($field = mysqli_fetch_field($this->getResultId())) { $f = new stdClass(); $f->name = $field->name; $f->type = $field->type; $f->default = $field->def; $f->maxLength = $field->max_length; $f->primaryKey = $field->primary_key; $retval[] = $f; } return $retval; }
php
{ "resource": "" }
q240758
Statement.freeResults
train
public function freeResults() { if (is_a($this->getResultId(), "mysqli_result")) { mysqli_free_result($this->getResultId()); $this->setResultId(FALSE); } }
php
{ "resource": "" }
q240759
ApiController.createOne
train
public function createOne(\Psr\Http\Message\ServerRequestInterface $p_request) { $this->logger->debug('FreeFW.ApiController.createOne.start'); $apiParams = $p_request->getAttribute('api_params', false); // if ($apiParams->hasData()) { /** * @var \FreeFW\Core\StorageModel $data */ $data = $apiParams->getData(); if (!$data->isValid()) { $this->logger->debug('FreeFW.ApiController.createOne.end'); return $this->createResponse(409, $data); } $data->create(); $this->logger->debug('FreeFW.ApiController.createOne.end'); return $this->createResponse(201, $data); } else { return $this->createResponse(409); } }
php
{ "resource": "" }
q240760
ApiController.removeOne
train
public function removeOne(\Psr\Http\Message\ServerRequestInterface $p_request) { $this->logger->debug('FreeFW.ApiController.removeOne.start'); $apiParams = $p_request->getAttribute('api_params', false); // if ($apiParams->hasData()) { /** * @var \FreeFW\Core\StorageModel $data */ $data = $apiParams->getData(); $data->remove(); $this->logger->debug('FreeFW.ApiController.removeOne.end'); return $this->createResponse(204); } else { return $this->createResponse(409); } }
php
{ "resource": "" }
q240761
FilterComponent.filter
train
public function filter(Query $query) { if (!empty($this->filterOptions['conditions'])) { $query->where($this->filterOptions['conditions']); } if (!empty($this->filterOptions['order'])) { $query->order($this->filterOptions['order']); } return $query; }
php
{ "resource": "" }
q240762
FilterComponent.getBacklink
train
public static function getBacklink($url, ServerRequest $request) { if (!isset($url['plugin'])) { $url['plugin'] = $request->getParam('plugin'); } if (!isset($url['controller'])) { $url['controller'] = $request->getParam('controller'); } $path = join('.', [ 'FILTER_' . ($url['plugin'] ? $url['plugin'] : ''), $url['controller'], $url['action'] ]); if (($filterOptions = $request->getSession()->read($path))) { if (isset($filterOptions['slug'])) { $url['sluggedFilter'] = $filterOptions['slug']; unset($filterOptions['slug']); } if (!empty($filterOptions)) { if (!isset($url['?'])) { $url['?'] = []; } $url['?'] = array_merge($url['?'], $filterOptions); } } return $url; }
php
{ "resource": "" }
q240763
FilterComponent._initFilterOptions
train
protected function _initFilterOptions() { if (!$this->_filterEnabled && !$this->_sortEnabled) { return; } $options = [ 'conditions' => [], 'order' => [] ]; // check filter params if (!empty($this->request->getData())) { foreach ($this->request->getData() as $field => $value) { if (!isset($this->filterFields[$field]) || $value === '') { continue; } $options = $this->_createFilterFieldOption($field, $value, $options); $this->activeFilters[$field] = $value; } } if (isset($this->sortFields[$this->request->getQuery('s')])) { $d = 'asc'; if ($this->request->getQuery('d')) { $dir = strtolower($this->request->getQuery('d')); if (in_array($dir, ['asc', 'desc'])) { $d = $dir; } } $field = $this->request->getQuery('s'); $options = $this->_createSortFieldOption($field, $d, $options); $this->activeSort[$field] = $d; } elseif (!empty($this->defaultSort)) { $options = $this->_createSortFieldOption($this->defaultSort['field'], $this->defaultSort['dir'], $options); $this->activeSort[$this->defaultSort['field']] = $this->defaultSort['dir']; } if ($this->request->getQuery('p')) { $this->page = $this->request->getQuery('p'); } $this->filterOptions = $options; }
php
{ "resource": "" }
q240764
FilterComponent._isSortEnabled
train
protected function _isSortEnabled() { if (!isset($this->controller->sortFields)) { return false; } foreach ($this->controller->sortFields as $field) { if (isset($field['actions']) && is_array($field['actions']) && in_array($this->action, $field['actions']) ) { return true; } } return false; }
php
{ "resource": "" }
q240765
FilterComponent._isFilterEnabled
train
protected function _isFilterEnabled() { if (!isset($this->controller->filterFields)) { return false; } foreach ($this->controller->filterFields as $field) { if (isset($field['actions']) && is_array($field['actions']) && in_array($this->action, $field['actions']) ) { return true; } } return false; }
php
{ "resource": "" }
q240766
FilterComponent._isPaginationEnabled
train
protected function _isPaginationEnabled() { if (!isset($this->controller->limits) || !isset($this->controller->limits[$this->action]) || !isset($this->controller->limits[$this->action]['default']) || !isset($this->controller->limits[$this->action]['limits']) ) { return false; } return true; }
php
{ "resource": "" }
q240767
FilterComponent._getSortFields
train
protected function _getSortFields() { $sortFields = []; foreach ($this->controller->sortFields as $field => $options) { if (isset($options['actions']) && is_array($options['actions']) && in_array($this->action, $options['actions']) ) { $sortFields[$field] = $options; } } return $sortFields; }
php
{ "resource": "" }
q240768
FilterComponent._getFilterFields
train
protected function _getFilterFields() { $filterFields = []; foreach ($this->controller->filterFields as $field => $options) { if (isset($options['actions']) && is_array($options['actions']) && in_array($this->action, $options['actions']) ) { $filterFields[$field] = $options; } } return $filterFields; }
php
{ "resource": "" }
q240769
FilterComponent._createSortFieldOption
train
protected function _createSortFieldOption($field, $dir, $options) { $sortField = $this->sortFields[$field]; if (isset($sortField['custom'])) { if (!is_array($sortField['custom'])) { $sortField['custom'] = [$sortField['custom']]; } foreach ($sortField['custom'] as $sortEntry) { $options['order'][] = preg_replace('/:dir/', $dir, $sortEntry); } } else { $options['order'][] = $sortField['modelField'] . ' ' . $dir; } return $options; }
php
{ "resource": "" }
q240770
FilterComponent._extractPassParams
train
protected function _extractPassParams() { if (!empty($this->controller->filterPassParams[$this->action])) { foreach ($this->controller->filterPassParams[$this->action] as $key) { if (!empty($this->request->getParam($key))) { $this->_passParams[$key] = $this->request->getParam($key); } } } }
php
{ "resource": "" }
q240771
FilterComponent._getFilterData
train
protected function _getFilterData() { $rawFilterData = $this->request->getData(); $filterData = []; foreach ($this->filterFields as $filterField => $options) { if (isset($rawFilterData[$filterField]) && $rawFilterData[$filterField] !== '') { $filterData[$filterField] = $rawFilterData[$filterField]; } } return $filterData; }
php
{ "resource": "" }
q240772
FilterComponent._setupSort
train
protected function _setupSort() { if (!($this->_sortEnabled = $this->_isSortEnabled())) { return; } $this->sortFields = $this->_getSortFields(); foreach ($this->sortFields as $field => $options) { if (!isset($options['default'])) { continue; } $dir = strtolower($options['default']); if (in_array($dir, ['asc', 'desc'])) { $this->defaultSort = [ 'field' => $field, 'dir' => $dir ]; } } }
php
{ "resource": "" }
q240773
FilterComponent._setupFilters
train
protected function _setupFilters() { if (!($this->_filterEnabled = $this->_isFilterEnabled())) { return; } $this->filterFields = $this->_getFilterFields(); $sluggedFilter = $this->request->getParam('sluggedFilter', ''); if ($sluggedFilter === '') { return; } $filterData = $this->Filters->find('filterDataBySlug', ['request' => $this->request]); if (empty($filterData)) { return; } $data = array_merge($this->request->getData(), $filterData); foreach ($data as $key => $value) { $this->request = $this->request->withData($key, $value); } $this->slug = $sluggedFilter; }
php
{ "resource": "" }
q240774
FilterComponent._setupPagination
train
protected function _setupPagination() { if (!($this->_paginationEnabled = $this->_isPaginationEnabled())) { return; } $this->defaultLimit = $this->controller->limits[$this->action]['default']; $this->limits = $this->controller->limits[$this->action]['limits']; }
php
{ "resource": "" }
q240775
FilterComponent._isFilterRequest
train
protected function _isFilterRequest() { return ( $this->controller !== null && $this->request !== null && $this->action !== null && $this->_filterEnabled ); }
php
{ "resource": "" }
q240776
FilterComponent._createFilterSlug
train
protected function _createFilterSlug(array $filterData) { /** @var Filter $existingFilter */ $existingFilter = $this->Filters->find('slugForFilterData', [ 'request' => $this->request, 'filterData' => $filterData ])->first(); if ($existingFilter) { return $existingFilter->slug; } return $this->Filters->createFilterForFilterData($this->request, $filterData); }
php
{ "resource": "" }
q240777
FilterComponent._applyFilterData
train
protected function _applyFilterData($url) { $filterData = $this->_getFilterData(); if (empty($filterData)) { return $url; } return $url + [ 'sluggedFilter' => $this->_createFilterSlug($filterData), '?' => $this->request->getQuery() ]; }
php
{ "resource": "" }
q240778
FilterComponent._applyPassedParams
train
protected function _applyPassedParams($url) { if (empty($this->_passParams)) { return $url; } return array_merge($url, $this->_passParams); }
php
{ "resource": "" }
q240779
FilterComponent._applySort
train
protected function _applySort($url) { if (!$this->_sortEnabled) { return $url; } if (!empty($this->request->getQuery('s'))) { $url['?']['s'] = $this->request->getQuery('s'); } if (!empty($this->request->getQuery('d'))) { $url['?']['d'] = $this->request->getQuery('d'); } return $url; }
php
{ "resource": "" }
q240780
Response.getIsInstructable
train
public function getIsInstructable() { $isAjax = (isset(Yii::$app->request->isAjax) && Yii::$app->request->isAjax); if (isset($_GET['_instruct'])) { if (!empty($_GET['_instruct'])) { $this->forceInstructions = true; $this->disableInstructions = false; } else { $this->forceInstructions = false; $this->disableInstructions = true; } } return (is_array($this->data) || $this->forceInstructions || $isAjax) && !$this->disableInstructions; }
php
{ "resource": "" }
q240781
FindsCallableByInheritance.classInheritance
train
public static function classInheritance($object){ $class = new ReflectionClass($object); $classNames = [$class->getName()]; while($class = $class->getParentClass()){ $classNames[] = $class->getName(); } return $classNames; }
php
{ "resource": "" }
q240782
AppManager.initApps
train
public function initApps() { if (count($this->apps) > 0) { throw new AlreadyInitiatedException('The apps are already loaded!'); } foreach ($this->appList as $className) { $instance = new $className($this); $this->apps->append($instance); } // Let the apps configure itself. foreach ($this->apps as $app) { $app->load(); } // Let the apps register it parts. foreach ($this->apps as $app) { $app->registerRoutes(Router::getInstance()); } }
php
{ "resource": "" }
q240783
Base.findSection
train
public function findSection($section) { if (!isset($this->sectionMap[$section])) { throw new UnknownSection($section); } return $this->sectionMap[$section]; }
php
{ "resource": "" }
q240784
Base.parseArray
train
public function parseArray(array $ini) { $sections = []; foreach ($ini as $name => $section) { $section = $this->parseSection($name, $section); $sections[] = $section; } return $sections; }
php
{ "resource": "" }
q240785
Base.parseSection
train
public function parseSection($name, array $section) { $name = explode(':', $name, 2); $class = $this->findSection($name[0]); if (isset($name[1])) { return new $class($name[1], $section); } return new $class($section); }
php
{ "resource": "" }
q240786
Config.save
train
public static function save($file, $config) { if ( ! is_array($config)) { if ( ! isset(static::$items[$config])) { return false; } $config = static::$items[$config]; } $info = pathinfo($file); $type = 'php'; if (isset($info['extension'])) { $type = $info['extension']; // Keep extension when it's an absolute path, because the finder won't add it if ($file[0] !== '/' and $file[1] !== ':') { $file = substr($file, 0, -(strlen($type) + 1)); } } $class = '\\Config_'.ucfirst($type); if ( ! class_exists($class)) { throw new \FuelException(sprintf('Invalid config type "%s".', $type)); } $driver = new $class($file); return $driver->save($config); }
php
{ "resource": "" }
q240787
ErrorHandler.renderError
train
public static function renderError() { try { $_errorTemplate = \Kisma::get( 'app.error_template', '_error.twig' ); Render::twigView( $_errorTemplate, array( 'base_path' => \Kisma::get( 'app.base_path' ), 'app_root' => \Kisma::get( 'app.root' ), 'page_title' => 'Error', 'error' => static::$_error, 'page_header' => 'Something has gone awry...', 'page_header_small' => 'Not cool. :(', 'navbar' => array( 'brand' => 'Kisma v' . \Kisma::KismaVersion, 'items' => array( array( 'title' => 'Kisma on GitHub!', 'href' => 'http://github.com/kisma/kisma/', 'target' => '_blank', 'active' => 'active', ), ), ), ) ); return true; } catch ( \Exception $_ex ) { Log::error( 'Exception during rendering of error: ' . print_r( static::$_error, true ) ); } return false; }
php
{ "resource": "" }
q240788
ErrorHandler._cleanTrace
train
protected static function _cleanTrace( array &$trace, $skipLines = null, $basePath = null ) { $_trace = array(); $_basePath = $basePath ?: \Kisma::get( 'app.base_path' ); // Skip some lines if ( !empty( $skipLines ) && count( $trace ) > $skipLines ) { $trace = array_slice( $trace, $skipLines ); } foreach ( $trace as $_index => $_code ) { $_traceItem = array(); Scalar::sins( $trace[$_index], 'file', 'Unspecified' ); Scalar::sins( $trace[$_index], 'line', 0 ); Scalar::sins( $trace[$_index], 'function', 'Unspecified' ); $_traceItem['file_name'] = trim( str_replace( array( $_basePath, "\t", "\r", "\n", PHP_EOL, 'phar://', ), array( null, ' ', null, null, null, null, ), $trace[$_index]['file'] ) ); $_args = null; if ( isset( $_code['args'] ) && !empty( $_code['args'] ) ) { foreach ( $_code['args'] as $_arg ) { if ( is_object( $_arg ) ) { $_args .= get_class( $_arg ) . ', '; } else if ( is_array( $_arg ) ) { $_args .= '[array], '; } else if ( is_bool( $_arg ) ) { if ( $_arg ) { $_args .= 'true, '; } else { $_args .= 'false, '; } } else if ( is_numeric( $_arg ) ) { $_args .= $_arg . ', '; } else if ( is_scalar( $_arg ) ) { $_args .= '"' . $_arg . '", '; } else { $_args .= '"' . gettype( $_arg ) . '", '; } } } $_traceItem['line'] = $trace[$_index]['line']; if ( isset( $_code['type'] ) ) { $_traceItem['function'] = ( isset( $_code['class'] ) ? $_code['class'] : null ) . $_code['type'] . $_code['function']; } else { $_traceItem['function'] = $_code['function']; } $_traceItem['function'] .= '(' . ( $_args ? ' ' . trim( $_args, ', ' ) . ' ' : null ) . ')'; $_traceItem['index'] = $_index; $_trace[] = $_traceItem; } return $_trace; }
php
{ "resource": "" }
q240789
StatementAbstract.checkPreparation
train
protected function checkPreparation() { // must be prepared if (null === $this->prepared) { throw new RuntimeException( Message::get(Message::DB_STMT_NOTPREPARED), Message::DB_STMT_NOTPREPARED ); } // close any previous resultset $this->closeResult(); }
php
{ "resource": "" }
q240790
AbstractApiLoader.loadItemOrThrowException
train
private function loadItemOrThrowException( QueryBuildingEventInterface $event, string $eventName, EventDispatcherInterface $dispatcher ) { $queryResult = $this->executeItemQuery($event, $eventName, $dispatcher); if (empty($queryResult) && $this->noItemException) { $this->logger->notice( 'Item not found from loader', [ 'loader class' => static::class, 'from event' => $eventName, 'dispatched event' => $this->itemEventName ] ); throw new \RuntimeException('Item not found from loader', 404); } return $queryResult; }
php
{ "resource": "" }
q240791
Pagination.createUri
train
public function createUri($page) { $queryString = $this->query; $queryString[] = "page={$page}"; $queryString = implode('&', $queryString); return Request::pathInfo() . "?{$queryString}"; }
php
{ "resource": "" }
q240792
Pagination.createPageLinks
train
protected function createPageLinks() { $pageLinks = array(); if ($this->totalPages > 10) { $startRange = $this->page - floor($this->range/2); $endRange = $this->page + floor($this->range/2); //Start range if ($startRange <= 0) { $startRange = 1; $endRange += abs($startRange) + 1; } // End range if ($endRange > $this->totalPages) { $startRange -= $endRange - $this->totalPages; $endRange = $this->totalPages; } // Range $range = range($startRange, $endRange); // Add first page $this->pageLinks[] = array( 'page' => 1, 'uri' => $this->createUri(1) ); foreach ($range as $page) { // Skip for first and last page if ($page == 1 or $page == $this->totalPages) { continue; } $this->pageLinks[] = array( 'page' => $page, 'uri' => $this->createUri($page) ); } // Add last page $this->pageLinks[] = array( 'page' => $this->totalPages, 'uri' => $this->createUri($this->totalPages) ); } else { for ($i = 1; $i <= $this->totalPages; $i++) { $this->pageLinks[] = array( 'page' => $i, 'uri' => $this->createUri($i) ); } } }
php
{ "resource": "" }
q240793
Xml.fromObject
train
public static function fromObject( $object, $rootName = null, $nodeName = null, $addHeader = true ) { if ( !is_object( $object ) ) { throw new \InvalidArgumentException( 'The value of "$object" is not an object.' ); } return static::fromArray( get_object_vars( $object ), $rootName, $nodeName, $addHeader ); }
php
{ "resource": "" }
q240794
Xml.fromArray
train
public static function fromArray( $data, $rootName = null, $nodeName = null, $addHeader = true ) { $_xml = true === $addHeader ? '<?xml version="1.0" encoding="UTF-8" ?>' : null; if ( null !== $rootName ) { $_xml .= Markup::openTag( $rootName ); } $_string = null; if ( $data instanceof \Traversable ) { foreach ( $data as $_key => $_value ) { if ( is_numeric( $_key ) ) { $_key = $nodeName ?: 'node'; } $_string .= Markup::tag( $_key, array(), static::fromArray( $_value, $nodeName ) ); } } else { $_string = htmlspecialchars( $data, ENT_QUOTES ); } // Add the converted XML $_xml .= $_string; if ( null !== $rootName ) { $_xml .= Markup::closeTag( $rootName ); } return $_xml; }
php
{ "resource": "" }
q240795
Session.&
train
public static function &createWithName($name = null, AuraSession $session = null) : Session { $session = ! is_null($session) ? new static : new static($session); if (is_null($name)) { return $session; } $session->setSegmentName($name); return $session; }
php
{ "resource": "" }
q240796
Session.startOrResume
train
public function startOrResume() : bool { if (!$this->session->isStarted()) { return $this->session->start(); } return $this->session->resume(); }
php
{ "resource": "" }
q240797
Session.validateToken
train
public function validateToken($value) : bool { if (!is_string($value)) { return false; } return $this->getCSRFToken()->isValid($value); }
php
{ "resource": "" }
q240798
Session.exist
train
public function exist($keyName) : bool { # double check return $this->get($keyName, true) !== true && $this->get($keyName, false) !== false; }
php
{ "resource": "" }
q240799
Parameters.required
train
public function required($keys, array $params = [], array $parents = []) { if (!$params) { $params = $this->all(); } if (is_array($keys)) { foreach ($keys as $key => $value) { if (is_int($key)) { $key = $value; } if (!isset($params[$key])) { if ($parents) { $str = ''; foreach ($parents as $parent) { $str .= '[ ' . $parent . ' => '; } $str .= $key . str_repeat(' ]', count($parents)); } else { $str = $Key; } throw new ParameterMissingException(sprintf( "Missing parameter %s", $str )); } if (is_array($value)) { $params = $params[$key]; $parents[] = $key; $this->required($value, $params, $parents); } } } else { if (!isset($params[$keys])) { throw new ParameterMissingException(sprintf( "Missing parameter %s", $keys )); } } }
php
{ "resource": "" }