_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q266500
BaseMigrateController.actionDown
test
public function actionDown(RequestApplicationInterface $app, $limit = 1) { if ($limit === 'all') { $limit = null; } else { $limit = (int)$limit; if ($limit < 1) { throw new Exception('The step argument must be greater than 0.'); } } return $this->getMigrationHistory($limit)->then( function($migrations) { if (empty($migrations)) { $this->stdout("No migration has been done before.\n", Console::FG_YELLOW); return true; } $migrations = array_keys($migrations); $n = count($migrations); $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW); foreach ($migrations as $migration) { $this->stdout("\t$migration\n"); } $this->stdout("\n"); $reverted = 0; return $this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')->then( function() use ($migrations, $n, &$reverted) { $promises = []; foreach ($migrations as $migration) { $promises[] = $this->migrateDown($migration)->thenLazy( function() use (&$reverted) { $reverted++; return true; }, function($error = null) use ($reverted, $n) { $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return reject($error); } ); } return allInOrder($promises)->then( function() use ($n) { $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN); $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN); } ); } ); } ); }
php
{ "resource": "" }
q266501
BaseMigrateController.actionFresh
test
public function actionFresh(RequestApplicationInterface $app) { if (\Reaction::isProd()) { $this->stdout("App env is set to 'production'.\nRefreshing migrations is not possible on production systems.\n"); return resolve(true); } $confirmMessage = "Are you sure you want to reset the database and start the migration from the beginning?\nAll data will be lost irreversibly!"; return $this->confirm($confirmMessage)->then( function() { return $this->truncateDatabase(); }, function() { $this->stdout('Action was cancelled by user. Nothing has been performed.'); return resolve(true); } )->then( function() use ($app) { return $this->actionUp($app); } ); }
php
{ "resource": "" }
q266502
BaseMigrateController.actionHistory
test
public function actionHistory(RequestApplicationInterface $app, $limit = 10) { if ($limit === 'all') { $limit = null; } else { $limit = (int)$limit; if ($limit < 1) { throw new Exception('The limit must be greater than 0.'); } } return $this->getMigrationHistory($limit)->then( function($migrations) use ($limit) { if (empty($migrations)) { $this->stdout("No migration has been done before.\n", Console::FG_YELLOW); } else { $n = count($migrations); if ($limit > 0) { $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW); } else { $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW); } foreach ($migrations as $version => $time) { $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n"); } } return true; } ); }
php
{ "resource": "" }
q266503
BaseMigrateController.actionNew
test
public function actionNew(RequestApplicationInterface $app, $limit = 10) { if ($limit === 'all') { $limit = null; } else { $limit = (int)$limit; if ($limit < 1) { throw new Exception('The limit must be greater than 0.'); } } return $this->getNewMigrations()->then( function($migrations) use ($limit) { if (empty($migrations)) { $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN); } else { $n = count($migrations); if ($limit && $n > $limit) { $migrations = array_slice($migrations, 0, $limit); $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW); } else { $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW); } foreach ($migrations as $migration) { $this->stdout("\t" . $migration . "\n"); } } return true; } ); }
php
{ "resource": "" }
q266504
BaseMigrateController.actionCreate
test
public function actionCreate(RequestApplicationInterface $app, $name) { if (!preg_match('/^[\w\\\\]+$/', $name)) { throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.'); } list($namespace, $className) = $this->generateClassName($name); // Abort if name is too long $nameLimit = $this->getMigrationNameLimit(); if ($nameLimit !== null && strlen($className) > $nameLimit) { throw new Exception('The migration name is too long.'); } $migrationPath = $this->findMigrationPath($namespace); $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php'; return $this->confirm("Create new migration '$file'?")->then( function() use ($app, $name, $className, $namespace, $migrationPath, $file) { $content = $this->generateMigrationSourceCode([ 'name' => $name, 'className' => $className, 'namespace' => $namespace, ], $app); FileHelper::createDirectory($migrationPath); file_put_contents($file, $content, LOCK_EX); $this->stdout("New migration created successfully.\n", Console::FG_GREEN); return true; } ); }
php
{ "resource": "" }
q266505
BaseMigrateController.migrateDown
test
protected function migrateDown($class) { if ($class === self::BASE_MIGRATION) { return resolveLazy(true); } $this->stdout("*** reverting $class\n", Console::FG_YELLOW); $start = microtime(true); $promise = new LazyPromise(function() use (&$migration, $class, $start) { return $this->createMigration($class) ->then(function($migration) { /** @var MigrationInterface $migration */ return $migration->down(); })->then(function() use ($class, $start) { $time = microtime(true) - $start; $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN); return $this->removeMigrationHistory($class); }, function($error = null) use ($class, $start) { $time = microtime(true) - $start; $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED); $prevException = $error instanceof \Throwable ? $error : null; $exception = new Exception("Failed to revert $class (time: " . sprintf('%.3f', $time) . "s)", 0, $prevException); throw new $exception; }); }); return $promise; }
php
{ "resource": "" }
q266506
BaseMigrateController.migrateToTime
test
protected function migrateToTime(RequestApplicationInterface $app, $time) { return $this->getMigrationHistory(null)->then( function($migrations) use ($app, $time) { $migrations = array_values($migrations); $count = 0; while ($count < count($migrations) && $migrations[$count] > $time) { ++$count; } if ($count === 0) { $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN); } else { return $this->actionDown($app, $count); } return reject(new Exception("Nothing needs to be done")); } ); }
php
{ "resource": "" }
q266507
BaseMigrateController.migrateToVersion
test
protected function migrateToVersion(RequestApplicationInterface $app, $version) { $originalVersion = $version; return $this->getNewMigrations()->then( function($migrations) use ($app, $version) { foreach ($migrations as $i => $migration) { if (strpos($migration, $version) === 0) { return $this->actionUp($app, $i + 1); } } return reject(null); } )->then(null, function() use ($app, $version, $originalVersion) { return $this->getMigrationHistory(null) ->then(function($migrations) use ($app, $version, $originalVersion) { $migrations = array_keys($migrations); foreach ($migrations as $i => $migration) { if (strpos($migration, $version, $originalVersion) === 0) { if ($i === 0) { $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW); } else { $this->actionDown($app, $i); } return resolve(true); } } throw new Exception("Unable to find the version '$originalVersion'."); }); }); }
php
{ "resource": "" }
q266508
Database._loadAdapter
test
protected function _loadAdapter($autoconnect = true) { $factory = \Library\Factory::create() ->factoryName(__CLASS__) ->mustImplementAndExtend(array( Kernel::DATABASE_ADAPTER_ABSTRACT, Kernel::DATABASE_ADAPTER_INTERFACE )) ->defaultNamespace(Kernel::DATABASE_ADAPTER_DEFAULT_NAMESPACE) ->classNameMask(array('%s', '%s'.Kernel::DATABASE_ADAPTER_SUFFIX)) ; $params = array( $this, $this->__db_name, $this->__adapter_options ); $this->__adapter = $factory->build($this->__adapter_type, $params); /* $_adapter_class = '\Lib\DatabaseAdapter\\'.ucfirst($this->__adapter_type); if (!\CarteBlanche\App\Loader::classExists($_adapter_class)) { $_adapter_class .= 'Adapter'; } if (\CarteBlanche\App\Loader::classExists($_adapter_class)) { try { $this->__adapter = new $_adapter_class( $this, CarteBlanche::getPath('db_path').$this->__db_name, $this->__adapter_options ); } catch ( \Exception $e ) { throw new \RuntimeException( sprintf('An error occurred while trying to load Database Adapter "%s"!', $_adapter_class) ); } if (!($this->__adapter instanceof \Lib\DatabaseAdapter\AbstractDatabaseAdapter)) { throw new \DomainException( sprintf('A Database Adapter must extend the "\Lib\DatabaseAdapter\AbstractDatabaseAdapter" class (got "%s")!', $_adapter_class) ); } if (!($this->__adapter instanceof \Lib\DatabaseAdapter\DatabaseAdapterInterface)) { throw new \DomainException( sprintf('A Database Adapter must implements the "\Lib\DatabaseAdapter\DatabaseAdapterInterface" interface (got "%s")!', $_adapter_class) ); } } else { throw new \RuntimeException( sprintf('Database adapter for type "%s" doesn\'t exist!', $this->__adapter_type) ); } */ if (true===$autoconnect) $this->connect(); return $this; }
php
{ "resource": "" }
q266509
Database.connect
test
protected function connect() { if (empty($this->__adapter)) self::_loadAdapter(); $this->db = $this->__adapter->connect(); return $this; }
php
{ "resource": "" }
q266510
Database.addCachedQuery
test
public function addCachedQuery($query, $results = null) { $this->queries[] = $query; if (!is_null($results)) $this->queries_results[$query] = $results; return $this; }
php
{ "resource": "" }
q266511
Database.getCachedResults
test
public function getCachedResults( $query ) { return isset($this->queries_results[$query]) ? $this->queries_results[$query] : false; }
php
{ "resource": "" }
q266512
Database.arrayQuery
test
public function arrayQuery($query = null, $method = 'arrayQuery', $cached = true) { if (empty($this->__adapter)) self::_loadAdapter(); return $this->__adapter->arrayQuery( $query, $method, $cached ); }
php
{ "resource": "" }
q266513
Database.add_table
test
public function add_table($tablename = null, $table_structure = null) { if (empty($tablename) || empty($table_structure)) return false; if (!is_string($table_structure)) $table_structure_str = join(',', self::build_fields_array( $table_structure ) ); else $table_structure_str = $table_structure; if (!self::table_exists($tablename)) { $query = "CREATE TABLE $tablename ($table_structure_str);"; /* $results = $this->db->queryExec($query, $err); if ($err) trigger_error( "Can not create table '$tablename' [$err]!", E_USER_ERROR ); */ $results = $this->query($query, null, 'queryExec'); $this->addCachedQuery( $query, $results ); } return self::table_exists($tablename); }
php
{ "resource": "" }
q266514
Database.add_fields
test
public function add_fields($tablename = null, $table_structure = null) { if (empty($tablename) || empty($table_structure)) return false; if (!is_string($table_structure)) $table_structure_ar = self::build_fields_array( $table_structure ); else $table_structure_ar = array($table_structure); if (self::table_exists($tablename)) { $query = "ALTER TABLE $tablename ADD COLUMN ( ".join(',', $table_structure_ar)." );"; /* $this->queries[] = $query; $results = $this->db->queryExec($query, $err); if ($err) trigger_error( "Can not alter table '$tablename' [$err]!", E_USER_ERROR ); */ $results = $this->query($query, null, 'queryExec'); $this->addCachedQuery( $query ); } return true; }
php
{ "resource": "" }
q266515
Database.table_infos
test
public function table_infos($tablename = null) { if (!empty($tablename)) { if (isset($this->tables[$tablename]) && is_array($this->tables[$tablename])) return $this->tables[$tablename]; $query = "PRAGMA table_info ('{$tablename}')"; $results = $this->arrayQuery($query); $this->tables[$tablename] = $results; return $results; } return false; }
php
{ "resource": "" }
q266516
Database.table_exists
test
public function table_exists($tablename = null) { if (!empty($tablename)) { if (isset($this->tables[$tablename])) return true; $query = "SELECT name FROM sqlite_master WHERE name='{$tablename}'"; $results = $this->query($query); if ($results && $results->numRows()) { $this->tables[$tablename] = true; return true; } } return false; }
php
{ "resource": "" }
q266517
Database.build_fields_array
test
public function build_fields_array($table_structure = null) { if (empty($table_structure) || !is_array($table_structure)) return; $table_structure_ar=array(); foreach($table_structure as $index=>$form) { if (is_string($form)) $table_structure_ar[] = $index.' '.$form; else $table_structure_ar[] = $index.' '.$form['type'].' ' .( (!empty($form['null']) && $form['null']==true) ? 'null' : 'not null').' ' .(!empty($form['default']) ? 'default \''.$form['default'].'\'' : '').' ' .(!empty($form['index']) ? $form['index'] : ''); } return $table_structure_ar; }
php
{ "resource": "" }
q266518
Database.escape
test
public function escape($str = null, $double_quotes = false) { if (empty($this->__adapter)) self::_loadAdapter(); return $this->__adapter->escape($str); }
php
{ "resource": "" }
q266519
Database.clear
test
public function clear() { $this->query_type='SELECT'; $this->fields=null; $this->from=null; $this->where=''; $this->limit=null; $this->offset=null; $this->order_by=null; $this->order_way=null; }
php
{ "resource": "" }
q266520
Database.where
test
public function where($arg = null, $val = null, $sign = '=', $operator = 'OR') { $this->where .= (strlen($this->where) ? " {$operator} " : '') .$arg .( !empty($val) ? " {$sign} ".self::escape($val) : '' ); return $this; }
php
{ "resource": "" }
q266521
Database.where_str
test
public function where_str($str = null, $operator = 'OR') { $this->where .= (strlen($this->where) ? " {$operator} " : '') .$str; return $this; }
php
{ "resource": "" }
q266522
Database.where_in
test
public function where_in($arg = null, $val = null, $operator = 'OR') { $this->where .= (strlen($this->where) ? " {$operator} " : '') .$arg .( !empty($val) && is_array($val) ? " IN (".self::escape( implode(',',$val) ).")" : '' ); return $this; }
php
{ "resource": "" }
q266523
Database.or_where
test
public function or_where($arg = null, $val = null, $sign = '=') { return self::where($arg, $val, $sign, 'OR'); }
php
{ "resource": "" }
q266524
Database.and_where
test
public function and_where($arg = null, $val = null, $sign = '=') { return self::where($arg, $val, $sign, 'AND'); }
php
{ "resource": "" }
q266525
Database.order_by
test
public function order_by($order_by = null, $order_way = 'asc') { $this->order_by = $order_by; $this->order_way = $order_way; return $this; }
php
{ "resource": "" }
q266526
Database.get_query
test
public function get_query() { $query = strtoupper($this->query_type) .' '.$this->fields .' FROM '.$this->from .( !empty($this->where) ? ' WHERE '.$this->where : '' ) .( !empty($this->order_by) ? ' ORDER BY '.$this->order_by.' '.$this->order_way : '' ) .( !empty($this->limit) ? ' LIMIT '.$this->limit // .( !empty($this->offset) ? ','.$this->offset : '' ) : '' ) .( !empty($this->offset) ? ' OFFSET '.$this->offset : '' ) .';'; return $query; }
php
{ "resource": "" }
q266527
Database.get
test
public function get() { $query = $this->get_query(); $results = $this->query($query); return $results->fetchAll(); }
php
{ "resource": "" }
q266528
Database.get_single
test
public function get_single() { $query = $this->get_query(); $results = $this->singleQuery($query); return isset($results[0]) ? $results[0] : null; }
php
{ "resource": "" }
q266529
SmarTwigExtension.getAllExtensions
test
public static function getAllExtensions() { $coreExt = new UICoreExtension(); $coreExt->setBuilders(array( "ui.html" => "YsHTML", "ui.jqueryCore" => "YsJQuery", "ui.dialog" => "YsUIDialog", "ui.tabs" => "YsUITabs", "ui.accordion" => "YsUIAccordion", "ui.progressbar" => "YsUIProgressbar", "ui.slider" => "YsUISlider", "ui.autocomplete" => "YsUIAutocomplete", "ui.datepicker" => "YsUIDatepicker", "ui.datetimepicker" => "YsUIDateTimepicker", "ui.button" => "YsUIButton", "ui.multiselect" => "YsUIMultiSelect", "ui.picklist" => "YsUIPickList", "ui.popup" => "YsUIPopUp", "ui.selectmenu" => "YsUISelectMenu", "ui.expander" => "YsUIExpander", "ui.splitter" => "YsUISplitter", "ui.dynaselect" => "YsUIDynamicSelect", "ui.menu" => "YsUIMenu", "ui.panel" => "YsUIPanel", "ui.tooltip" => "YsUITooltip", "ui.draggable" => "YsUIDraggable", "ui.droppable" => "YsUIDroppable", "ui.sortable" => "YsUISortable", "ui.selectable" => "YsUISelectable", "ui.resizable" => "YsUIResizable", "ui.effect" => "YsUIEffect", "ui.video" => "YsUIVideo" )); $uiAddonsExt = new UIAddonsExtension(); $uiAddonsExt->setBuilders(array( "ui.block" => "YsBlockUI", "ui.box" => "YsJQBox", "ui.colorpicker" => "YsJQColorPicker", "ui.notify" => "YsPNotify", "ui.hotkey" => "YsKeys", "ui.monitor" => "YsJQMonitor", "ui.keypad" => "YsJQKeypad", "ui.calculator" => "YsJQCalculator", "ui.layout" => "YsJLayout", "ui.mask" => "YsJQMask", "ui.formWizard" => "YsFormWizard", "ui.ajaxForm" => "YsJQForm", "ui.validation" => "YsJQValidate", "ui.booklet" => "YsJQBooklet", "ui.cycle" => "YsJQCycle", "ui.ring" => "YsJQRing", "ui.upload" => "YsUpload", )); return array( new HTMLExtension(), new JsSintaxExtension(), new JQueryCoreExtension(), new UIWidgetExtension(), $coreExt, $uiAddonsExt ); }
php
{ "resource": "" }
q266530
ModelOperator.getInstance
test
static public function getInstance($storagePath = null) { if (!self::$_instance) { if (empty($storagePath)) { throw new \Exception("Storage path need to be specified on the first instance call for ModelOperator"); } self::$_instance = new ModelOperator($storagePath); self::$_instance->loadStructureFiles(); } return self::$_instance; }
php
{ "resource": "" }
q266531
ModelOperator.setStoragePath
test
public function setStoragePath($path) { FSService::makeWritable($path); $this->_storagePath = $path; $this->_structuresPath = $this->_storagePath . 'structure/'; $this->_modelsPath = $this->_storagePath . 'classes/'; FSService::makeWritable($this->_structuresPath); FSService::makeWritable($this->_modelsPath); $this->loadStructureFiles($this->_structuresPath); return $this; }
php
{ "resource": "" }
q266532
ModelOperator.loadStructureFiles
test
public function loadStructureFiles($path = null) { if (empty($path)) $path = $this->_structuresPath; $files = FSService::getInstance()->in($path, true)->find('*.yml', FSService::TYPE_FILE, FSService::HYDRATE_NAMES_PATH); $data = array(); //if (isset($files['structure.yml'])) { // $data = Yaml::parse(file_get_contents($files['structure.yml'])); // if (is_null($data)) $data = array(); // unset($files['structure.yml']); //} foreach ($files as $file) { $modelData = Yaml::parse(file_get_contents($file)); $modelName = !empty($modelData['model']) ? $modelData['model'] : substr($file, strrpos($file, '/') + 1, -4); $modelNamespace = "Entities"; $data = array_merge($data, array($modelNamespace . "\\" . ucfirst($modelName) => $modelData)); } $data = self::fixYamlStructures($data); $this->_structures = $data; return $this; }
php
{ "resource": "" }
q266533
ModelOperator.getModelStructure
test
public function getModelStructure($modelName) { if (empty($this->_structures)) { $this->loadStructureFiles($this->_structuresPath); } $modelName = ucfirst($modelName); if (empty($this->_structures[$modelName])) { return array(); } return $this->_structures[$modelName]; }
php
{ "resource": "" }
q266534
ModelOperator.saveModelStructure
test
public function saveModelStructure($modelName) { $info = $this->getStructurePathForModel($modelName); $filePath = $info['path'] . '/' . $info['fileName'] . '.yml'; $modelName = ucfirst($modelName); FSService::makeWritable($info['path']); if (is_file($filePath)) { unlink($filePath); } $structure = self::fixYamlStructures($this->_structures[$modelName], true); file_put_contents($filePath, Yaml::dump($structure, 6, 2)); $this->_structures[$modelName] = $structure; return true; }
php
{ "resource": "" }
q266535
ModelOperator.dataDump
test
public function dataDump($models = null) { if (!empty($models)) { if (!is_array($models)) $models = array($models); } else { $models = array_keys($this->_structures); } $data_dir = $this->_storagePath . 'data/'; FSService::makeWritable($data_dir); foreach ($models as $model) { $model = ucfirst($model); $file_name = $data_dir . strtolower($model) . '.yml'; if (!isset($this->_structures[$model])) continue; if (is_file($file_name)) { unlink($file_name); } $data = QC::create($this->_structures[$model]['table'])->execute(); file_put_contents($file_name, Yaml::dump($data, 6, 2)); } }
php
{ "resource": "" }
q266536
ModelOperator.dataLoad
test
public function dataLoad($models = null) { if (!empty($models)) { if (!is_array($models)) $models = array($models); } else { $models = array_keys($this->_structures); } $data_dir = $this->_storagePath . 'data/'; foreach ($models as $model) { $model = ucfirst($model); $file_name = $data_dir . strtolower($model) . '.yml'; if (!isset($this->_structures[$model]) || !is_file($file_name)) continue; $data = Yaml::parse(file_get_contents($file_name)); if (!is_array($data)) continue; QC::executeSQL('SET FOREIGN_KEY_CHECKS=0'); QC::executeSQL('TRUNCATE `' . $this->_structures[$model]['table'] . '`'); QC::create($this->_structures[$model]['table'])->insert($data)->execute(); } }
php
{ "resource": "" }
q266537
TransactionMapper.findAllForAccount
test
public function findAllForAccount(Account $account, \DateTimeImmutable $dateStart, \DateTimeImmutable $dateEnd) { $this->addWhere('account_id', $account->getId()); $this->addWhere('transaction_date', $dateStart->format('Y-m-d'), '>='); $this->addWhere('transaction_date', $dateEnd->format('Y-m-d'), '<='); $this->addOrder('transaction_date'); return $this->select(); }
php
{ "resource": "" }
q266538
PgConnection.setState
test
protected function setState($state) { $this->queryState = $state; $map = [ static::STATE_BUSY => static::CLIENT_POOL_STATE_BUSY, static::STATE_READY => static::CLIENT_POOL_STATE_READY, ]; $statePool = isset($map[$state]) ? $map[$state] : static::CLIENT_POOL_STATE_NOT_READY; $this->changeState($statePool); }
php
{ "resource": "" }
q266539
PgConnection.getBacklogLength
test
public function getBacklogLength() : int { return array_reduce( $this->commandQueue, function ($a, CommandInterface $command) { if ($command instanceof Query || $command instanceof Sync) { $a++; } return $a; }, 0); }
php
{ "resource": "" }
q266540
PgConnection.processQueue
test
public function processQueue() { if (count($this->commandQueue) === 0 && $this->queryState === static::STATE_READY && $this->autoDisconnect) { $this->commandQueue[] = new Terminate(); } if (count($this->commandQueue) === 0) { return; } if ($this->connStatus === $this::CONNECTION_BAD) { $this->failAllCommandsWith(new \Exception('Bad connection: ' . $this->lastError)); if ($this->stream) { $this->stream->end(); $this->stream = null; } return; } while (count($this->commandQueue) > 0 && $this->queryState === static::STATE_READY) { /** @var CommandInterface $c */ $c = array_shift($this->commandQueue); if (!$c->isActive()) { continue; } $this->debug('Sending ' . get_class($c)); if ($c instanceof Query) { $this->debug('Sending simple query: ' . $c->getQueryString()); } $this->stream->write($c->encodedMessage()); if ($c instanceof Terminate) { $this->stream->end(); } if ($c->shouldWaitForComplete()) { $this->setState($this::STATE_BUSY); if ($c instanceof Query) { $this->queryType = $this::QUERY_SIMPLE; } elseif ($c instanceof Sync) { $this->queryType = $this::QUERY_EXTENDED; } $this->currentCommand = $c; return; } } }
php
{ "resource": "" }
q266541
PgConnection.query
test
public function query($query): Observable { return new AnonymousObservable( function (ObserverInterface $observer, SchedulerInterface $scheduler = null) use ($query) { if ($this->connStatus === $this::CONNECTION_NEEDED) { $this->start(); } if ($this->connStatus === $this::CONNECTION_BAD) { $observer->onError(new \Exception('Connection failed')); return new EmptyDisposable(); } $q = new Query($query, $observer); $this->commandQueue[] = $q; $this->changeQueueCountInc(); $this->processQueue(); return new CallbackDisposable(function() use ($q) { $this->changeQueueCountDec(); if ($this->currentCommand === $q && $q->isActive()) { $this->cancelRequest(); } $q->cancel(); }); } ); }
php
{ "resource": "" }
q266542
PgConnection.setConnStatus
test
protected function setConnStatus($status) { $this->connStatus = $status; $map = [ static::CONNECTION_BAD => static::CLIENT_POOL_STATE_CLOSING, static::CONNECTION_CLOSED => static::CLIENT_POOL_STATE_CLOSING, static::CONNECTION_OK => static::CLIENT_POOL_STATE_READY, ]; if (isset($map[$status])) { $this->changeState($map[$status]); } }
php
{ "resource": "" }
q266543
PgConnection.handleMessage
test
protected function handleMessage(ParserInterface $message) { $this->debug('Handling ' . get_class($message)); if ($message instanceof DataRow) { $this->handleDataRow($message); } elseif ($message instanceof Authentication) { $this->handleAuthentication($message); } elseif ($message instanceof BackendKeyData) { $this->handleBackendKeyData($message); } elseif ($message instanceof CommandComplete) { $this->handleCommandComplete($message); } elseif ($message instanceof CopyInResponse) { $this->handleCopyInResponse($message); } elseif ($message instanceof CopyOutResponse) { $this->handleCopyOutResponse($message); } elseif ($message instanceof EmptyQueryResponse) { $this->handleEmptyQueryResponse($message); } elseif ($message instanceof ErrorResponse) { $this->handleErrorResponse($message); } elseif ($message instanceof NoticeResponse) { $this->handleNoticeResponse($message); } elseif ($message instanceof ParameterStatus) { $this->handleParameterStatus($message); } elseif ($message instanceof ParseComplete) { $this->handleParseComplete($message); } elseif ($message instanceof ReadyForQuery) { $this->handleReadyForQuery($message); } elseif ($message instanceof RowDescription) { $this->handleRowDescription($message); } }
php
{ "resource": "" }
q266544
PgConnection.processData
test
private function processData($data) { if ($this->currentMessage) { $overflow = $this->currentMessage->parseData($data); // json_encode can slow things down here //$this->debug("onData: " . json_encode($overflow) . ""); if ($overflow === false) { // there was not enough data to complete the message // leave this as the currentParser return ''; } $this->handleMessage($this->currentMessage); $this->currentMessage = null; return $overflow; } if (strlen($data) == 0) { return ''; } $type = $data[0]; $message = Message::createMessageFromIdentifier($type); if ($message !== false) { $this->currentMessage = $message; return $data; } // if (in_array($type, ['R', 'S', 'D', 'K', '2', '3', 'C', 'd', 'c', 'G', 'H', 'W', 'D', 'I', 'E', 'V', 'n', 'N', 'A', 't', '1', 's', 'Z', 'T'])) { // $this->currentParser = [$this, 'parse1PlusLenMessage']; // call_user_func($this->currentParser, $data); // } else { // echo "Unhandled message \"".$type."\""; // } }
php
{ "resource": "" }
q266545
PgConnection.cancelRequest
test
private function cancelRequest() { if ($this->currentCommand !== null) { $this->socket->connect($this->uri)->then(function (DuplexStreamInterface $conn) { $cancelRequest = new CancelRequest($this->backendKeyData->getPid(), $this->backendKeyData->getKey()); $conn->end($cancelRequest->encodedMessage()); }, function (\Throwable $e) { $this->debug("Error connecting for cancellation... " . $e->getMessage() . "\n"); }); } }
php
{ "resource": "" }
q266546
SocialController.provider
test
public function provider($provider) { $this->checkDisabled(); $this->checkProvider($provider); $this->setConfig($provider); return Socialite::driver($provider)->redirect(); }
php
{ "resource": "" }
q266547
SocialController.callback
test
public function callback(Request $request, $provider) { $this->checkDisabled(); $this->checkProvider($provider); $this->setConfig($provider); $user = User::find(Auth::id()); $redirectAfter = url('/'); if ($user) { $redirectAfter = !($user->hasPermission('laralum::access') || $user->superAdmin()) ?: route('laralum::social.integrations'); } $user = Socialite::driver($provider)->user(); if ($user->getEmail() && $user->getName()) { if (Auth::check()) { if (!Social::where(['user_id' => Auth::id(), 'provider' => $provider])->first()) { $this->registerSocial($provider, $user); return redirect($redirectAfter)->with('success', __('laralum_social::general.provider_linked', ['provider' => $provider])); } return redirect($redirectAfter)->with('error', __('laralum_social::general.provider_already_linked', ['provider' => $provider])); } $sa = Social::where(['email' => $user->getEmail(), 'provider' => $provider])->first(); if ($sa) { Auth::login($sa->user); return redirect($redirectAfter)->with('success', __('laralum_social::general.logged_in', ['provider' => $provider])); } abort(403, 'Registrations are not allowed using the social feature'); } abort(403, 'The provider did not return a valid email or name to register the user'); }
php
{ "resource": "" }
q266548
SocialController.unlink
test
public function unlink($provider) { $this->checkDisabled(); $user = User::findOrFail(Auth::id()); $redirectAfter = $user->hasPermission('laralum::access') || $user->superAdmin() ? route('laralum::social.integrations') : url('/'); $link = Social::where(['user_id' => Auth::id(), 'provider' => $provider])->first(); if (!$link) { return redirect($redirectAfter)->with('success', __('laralum_social::general.link_not_found', ['provider' => $provider])); } $link->delete(); return redirect($redirectAfter)->with('success', __('laralum_social::general.unlinked', ['provider' => $provider])); }
php
{ "resource": "" }
q266549
SocialController.settings
test
public function settings(Request $request) { $this->authorize('update', Settings::class); $this->settings->update([ 'enabled' => $request->enabled ? true : false, 'allow_register' => $request->allow_register ? false : false, // Not enabled yet 'facebook_client_id' => $request->facebook_client_id ? encrypt($request->facebook_client_id) : null, 'facebook_client_secret' => $request->facebook_client_secret ? encrypt($request->facebook_client_secret) : null, 'twitter_client_id' => $request->twitter_client_id ? encrypt($request->twitter_client_id) : null, 'twitter_client_secret' => $request->twitter_client_secret ? encrypt($request->twitter_client_secret) : null, 'linkedin_client_id' => $request->linkedin_client_id ? encrypt($request->linkedin_client_id) : null, 'linkedin_client_secret' => $request->linkedin_client_secret ? encrypt($request->linkedin_client_secret) : null, 'google_client_id' => $request->google_client_id ? encrypt($request->google_client_id) : null, 'google_client_secret' => $request->google_client_secret ? encrypt($request->google_client_secret) : null, 'github_client_id' => $request->github_client_id ? encrypt($request->github_client_id) : null, 'github_client_secret' => $request->github_client_secret ? encrypt($request->github_client_secret) : null, 'bitbucket_client_id' => $request->bitbucket_client_id ? encrypt($request->bitbucket_client_id) : null, 'bitbucket_client_secret' => $request->bitbucket_client_secret ? encrypt($request->bitbucket_client_secret) : null, ]); $this->settings->touch(); return redirect()->route('laralum::settings.index', ['p' => 'Social'])->with('success', __('laralum_social::general.updated_settings')); }
php
{ "resource": "" }
q266550
SocialController.checkProvider
test
private function checkProvider($provider) { $ci = $provider.'_client_id'; $cs = $provider.'_client_secret'; if (!$this->settings->$ci || !$this->settings->$cs) { abort(404, __('laralum_social::general.provider_not_found', ['provider' => $provider])); } }
php
{ "resource": "" }
q266551
SocialController.setConfig
test
private function setConfig($provider) { $ci = $provider.'_client_id'; $cs = $provider.'_client_secret'; config(['services.'.$provider => [ 'client_id' => decrypt($this->settings->$ci), 'client_secret' => decrypt($this->settings->$cs), 'redirect' => route('laralum_public::social.callback', ['provider' => $provider]), ]]); }
php
{ "resource": "" }
q266552
SocialController.registerSocial
test
private function registerSocial($provider, $user, $dbuser = null) { return Social::create([ 'user_id' => $dbuser ? $dbuser->id : Auth::user()->id, 'provider' => $provider, 'token' => $user->token, 'secret_token' => isset($user->tokenSecret) ? $user->tokenSecret : null, 'email' => $user->getEmail(), ]); }
php
{ "resource": "" }
q266553
ExpiringCache.cleanupTimerCallback
test
public function cleanupTimerCallback() { $now = time(); $keys = []; foreach ($this->_timestamps as $key => $timestamp) { if ($timestamp < $now) { $keys[] = $key; } } if (!empty($keys)) { $this->deleteMultiple($keys); } }
php
{ "resource": "" }
q266554
ExpiringCache.packRecord
test
protected function packRecord($record = []) { $tsKey = $this->timestampKey; $dtKey = $this->dataKey; $data = $record; $record = []; $record[$dtKey] = $data; $record[$tsKey] = time(); return $record; }
php
{ "resource": "" }
q266555
ExpiringCache.unpackRecord
test
protected function unpackRecord($record = []) { $tsKey = $this->timestampKey; $dtKey = $this->dataKey; if (!is_array($record) || !isset($record[$tsKey]) || !ArrayHelper::keyExists($dtKey, $record)) { return $record; } return $record[$dtKey]; }
php
{ "resource": "" }
q266556
ExpiringCache.createCleanupTimer
test
protected function createCleanupTimer() { if (isset($this->_timer)) { $this->loop->cancelTimer($this->_timer); } $this->_timer = $this->loop->addPeriodicTimer($this->timerInterval, [$this, 'cleanupTimerCallback']); }
php
{ "resource": "" }
q266557
ParseMenu.hasSubMenu
test
protected function hasSubMenu($menu_item_id) { // Submenu always available with a path > 1 if (count($this->meta['path']) > 1) return true; // Decide if the first level menu has any visible submenu items foreach ($this->menu as $item) { // Find the desired menu item in the first level if ($item['menu_item_id'] == $menu_item_id) { // Loop through each submenu item foreach ($item['submenu'] as $sub_item) { // If there is at least one active item if ($sub_item['is_active'] == true) { // There is a submenu to display return true; } } } } return false; }
php
{ "resource": "" }
q266558
AccountUserAbstract.setAccountId
test
public function setAccountId($accountId) { $accountId = (int) $accountId; if ($this->accountId < 0) { throw new \UnderflowException('Value of "accountId" must be greater than 0'); } if ($this->exists() && $this->accountId !== $accountId) { $this->updated['accountId'] = true; } $this->accountId = $accountId; return $this; }
php
{ "resource": "" }
q266559
AccountUserAbstract.setUserId
test
public function setUserId($userId) { $userId = (int) $userId; if ($this->userId < 0) { throw new \UnderflowException('Value of "userId" must be greater than 0'); } if ($this->exists() && $this->userId !== $userId) { $this->updated['userId'] = true; } $this->userId = $userId; return $this; }
php
{ "resource": "" }
q266560
AccountUserAbstract.getAccount
test
public function getAccount($isForceReload = false) { if ($isForceReload || null === $this->joinOneCacheAccount) { $mapper = new AccountMapper($this->dependencyContainer->getDatabase('money')); $this->joinOneCacheAccount = $mapper->findByKeys(array( 'account_id' => $this->getAccountId(), )); } return $this->joinOneCacheAccount; }
php
{ "resource": "" }
q266561
AccountUserAbstract.getUser
test
public function getUser($isForceReload = false) { if ($isForceReload || null === $this->joinOneCacheUser) { $mapper = new UserMapper($this->dependencyContainer->getDatabase('user')); $this->joinOneCacheUser = $mapper->findByKeys(array( 'user_id' => $this->getUserId(), )); } return $this->joinOneCacheUser; }
php
{ "resource": "" }
q266562
ExceptionGenerator.next
test
public function next(OrdercloudRequest $request, OrdercloudHttpException $exception) { return $this->successor->generateException($request, $exception); }
php
{ "resource": "" }
q266563
StripTags.filter
test
public function filter($str) { if (is_array($str)) { foreach ($str as $k => $v) { $str[$k] = strip_tags($v); } return $str; } return strip_tags($str); }
php
{ "resource": "" }
q266564
PEAR_Installer_Role.initializeConfig
test
function initializeConfig(&$config) { if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) { PEAR_Installer_Role::registerRoles(); } foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $class => $info) { if (!$info['config_vars']) { continue; } $config->_addConfigVars($class, $info['config_vars']); } }
php
{ "resource": "" }
q266565
PEAR_Installer_Role.getValidRoles
test
function getValidRoles($release, $clear = false) { if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) { PEAR_Installer_Role::registerRoles(); } static $ret = array(); if ($clear) { $ret = array(); } if (isset($ret[$release])) { return $ret[$release]; } $ret[$release] = array(); foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) { if (in_array($release, $okreleases['releasetypes'])) { $ret[$release][] = strtolower(str_replace('PEAR_Installer_Role_', '', $role)); } } return $ret[$release]; }
php
{ "resource": "" }
q266566
PEAR_Installer_Role.getBaseinstallRoles
test
function getBaseinstallRoles($clear = false) { if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) { PEAR_Installer_Role::registerRoles(); } static $ret; if ($clear) { unset($ret); } if (isset($ret)) { return $ret; } $ret = array(); foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) { if ($okreleases['honorsbaseinstall']) { $ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role)); } } return $ret; }
php
{ "resource": "" }
q266567
Shorten.shorten
test
public function shorten(): string { // Shorten only what is longer than the length if (strlen($this->string) < $this->length) { return $this->string; } // Shorten string by length $this->result = substr($this->string, 0, $this->length); // Shorten further until last occurence of a ' ' $string = substr($this->result, 0, strrpos($this->result, $this->endstring)); if (!empty($this->wrap_url)) { $addition = '<a href="' . $this->wrap_url . '">' . $this->addition . '</a>'; } // Add addition $this->result .= $addition; // Done. return $this->result; }
php
{ "resource": "" }
q266568
Zend_Filter_Compress_Bz2.setBlocksize
test
public function setBlocksize($blocksize) { if (($blocksize < 0) || ($blocksize > 9)) { throw new Zend_Filter_Exception('Blocksize must be between 0 and 9'); } $this->_options['blocksize'] = (int) $blocksize; return $this; }
php
{ "resource": "" }
q266569
ConfigReader.get
test
public function get($key, $defaultValue = null) { return ArrayHelper::getValue($this->data, $key, $defaultValue); }
php
{ "resource": "" }
q266570
ConfigReader.generateNames
test
protected function generateNames() { $env = getenv('APP_ENV'); $env = strtolower((!empty($env) ? $env : \Reaction::APP_ENV_PROD)); $suffixes = ['', $env, 'local']; $templates = ['main', $this->appType]; $configFiles = []; foreach ($templates as $tpl) { foreach ($suffixes as $sfx) { $tplSuffix = $sfx ? '.' . $sfx : ''; foreach ($this->extensions as $ext) { $configFiles[] = $tpl . $tplSuffix . '.' . $ext; } } } return $configFiles; }
php
{ "resource": "" }
q266571
ConfigReader.merge
test
public function merge($data = [], $key = null) { if (!isset($key)) { $this->data = ArrayHelper::merge($this->data, $data); } else { if (!isset($this->data[$key])) { $this->data[$key] = $data; } else { if (is_array($this->data[$key])) { $this->data[$key] = ArrayHelper::merge($this->data[$key], $data); } else { $this->data[$key] = $data; } } } }
php
{ "resource": "" }
q266572
ConfigReader.readData
test
public function readData() { if (empty($this->names)) { $this->names = $this->generateNames(); } //Add default configs $defaultPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . $this->configPathDefault; $paths = [$defaultPath, $this->path]; $confData = []; foreach ($paths as $basePath) { foreach ($this->names as $_name_) { $_fileName_ = $this->normalizeConfigPath($_name_, $basePath); if (($fileConfig = $this->readFileData($_fileName_)) !== null) { $confData[] = $fileConfig; } } } if (empty($confData)) { return []; } elseif (count($confData) === 1) { return reset($confData); } return static::mergeConfigs(...$confData); }
php
{ "resource": "" }
q266573
ConfigReader.readFileData
test
protected function readFileData($_fileName_ = null) { if (!file_exists($_fileName_)) { return null; } /** @noinspection PhpIncludeInspection */ $_conf_data_ = include $_fileName_; return is_array($_conf_data_) ? $_conf_data_ : []; }
php
{ "resource": "" }
q266574
ConfigReader.normalizeConfigPath
test
protected function normalizeConfigPath($filePath, $basePath = null) { if (null === $basePath) { $basePath = $this->path; } $fullPath = strpos($filePath, '/') === 0 ? $filePath : $basePath . DIRECTORY_SEPARATOR . $filePath; return $fullPath; }
php
{ "resource": "" }
q266575
EventSourcedAggregate.apply
test
protected function apply(DomainEventMessageInterface $domainEventMessage): EventSourcedAggregate { $this->getMethod($domainEventMessage, 'on')($domainEventMessage->getPayload()); return $this; }
php
{ "resource": "" }
q266576
EventSourcedAggregate.record
test
protected function record(PayloadInterface $payload, array $metaData = null): void { $domainEventMessage = new DomainEventMessage( $payload, new PayloadType($payload), new DateTime(), $this->getIdentifier(), $this->getNextVersion(), array_replace_recursive( $this ->getCommandMessage() ->getMetaData(), $metaData ) ); $this ->apply($domainEventMessage) ->addDomainEventMessage($domainEventMessage); }
php
{ "resource": "" }
q266577
AbstractCrud.setRelated
test
public function setRelated($model = null, $data = null, $id = null) { if (!empty($model) && !empty($data)) { if (!empty($id)) { if (!isset($this->data[$model])) $this->data[$model] = array(); if (!is_array($this->data[$model])) $this->data[$model] = array_filter( array( $this->data[$model] ) ); $this->data[$model][$id] = $data; } else $this->data[$model] = $data; } }
php
{ "resource": "" }
q266578
TControlAjax.attached
test
public function attached($presenter) { parent::attached($presenter); if($this->ajaxEnabled && $this->autoAjax && $presenter instanceof Nette\Application\UI\Presenter && $presenter->isAjax()) { $this->redrawControl(); } }
php
{ "resource": "" }
q266579
TControlAjax.redrawNothing
test
protected function redrawNothing() { foreach($this->getPresenter()->getComponents(TRUE, 'Nette\Application\UI\IRenderable') as $component) { $component->redrawControl(NULL, FALSE); } }
php
{ "resource": "" }
q266580
TControlAjax.go
test
final public function go($destination, $args = [], $snippets = [], $presenterForward = FALSE) { if($this->ajaxEnabled && $this->presenter->isAjax()) { foreach($snippets as $snippet) { $this->redrawControl($snippet); } if($presenterForward) { $this->presenterForward($destination, $args); } else { $this->forward($destination, $args); } } else { $this->redirect($destination, $args); } }
php
{ "resource": "" }
q266581
TwigTemplating.initPlugins
test
protected function initPlugins($plugins = '') { if (is_dir(dirname(__FILE__).'/TwigPlugins')) { $this->loadPluginsFromDirectory(dirname(__FILE__).'/TwigPlugins'); } if (isset($plugins)) { if (is_array($plugins)) { foreach ($plugins as $path) { $this->loadPluginsFromDirectory($path); } } elseif ($plugins != '') { $this->loadPluginsFromDirectory($plugins); } } }
php
{ "resource": "" }
q266582
TwigTemplating.setVars
test
public function setVars($list) { foreach ($list as $k=>$v) { $this->setVar($k,$v); } }
php
{ "resource": "" }
q266583
TwigTemplating.fetchFromString
test
protected function fetchFromString() { // loader is created each time as value of index can be changed // maybe there is way to do this without creating new loader each time $loader = new \Twig_Loader_Array(array('index' => $this->template_data)); $this->setLoader($loader); return $this->render('index', $this->template_vars); }
php
{ "resource": "" }
q266584
TwigTemplating.loadPluginsFromDirectory
test
protected function loadPluginsFromDirectory($dirpath) { if (!is_dir($dirpath)) { return false; } $contents = @scandir($dirpath); if (is_array($contents)) { foreach ($contents as $file) { if (substr($file,-4) == '.php') { $class = '\\' . substr($file,0,-4); if($class != '') { // is this secure enough? // we don't use autoloader as we don't know how taht plugins are stored require_once($dirpath.'/'.$file); try { $twig_object = new $class(); if ($twig_object instanceof \Twig_Extension) { $this->addExtension($twig_object); } } catch (\Extension $e) { } } } } } }
php
{ "resource": "" }
q266585
BusinessHoursBuilder.fromAssociativeArray
test
public static function fromAssociativeArray(array $data): BusinessHours { if (!isset($data['days'], $data['timezone']) || !\is_array($data['days'])) { throw new \InvalidArgumentException('Array is not valid.'); } $days = []; foreach ($data['days'] as $day) { $days[] = DayBuilder::fromAssociativeArray($day); } return new BusinessHours($days, new \DateTimeZone($data['timezone'])); }
php
{ "resource": "" }
q266586
BusinessHoursBuilder.shiftToTimezone
test
public static function shiftToTimezone(BusinessHours $businessHours, \DateTimeZone $newTimezone): BusinessHours { $now = new \DateTime('now'); $oldTimezone = $businessHours->getTimezone(); $offset = $newTimezone->getOffset($now) - $oldTimezone->getOffset($now); if ($offset === 0) { return clone $businessHours; } $tmpDays = \array_fill_keys(Day::getDaysOfWeek(), []); foreach ($businessHours->getDays() as $day) { foreach ($day->getOpeningHoursIntervals() as $interval) { $start = $interval->getStart()->toSeconds() + $offset; $end = $interval->getEnd()->toSeconds() + $offset; // Current day. if ($start < 86400 && $end > 0) { $startForCurrentDay = \max($start, 0); $endForCurrentDay = \min($end, 86400); $dayOfWeek = $day->getDayOfWeek(); $interval = new TimeInterval( TimeBuilder::fromSeconds($startForCurrentDay), TimeBuilder::fromSeconds($endForCurrentDay) ); $tmpDays[$dayOfWeek][] = $interval; } // Previous day. if ($start < 0) { $startForPreviousDay = 86400 + $start; $endForPreviousDay = \min(86400, 86400 + $end); $dayOfWeek = self::getPreviousDayOfWeek($day->getDayOfWeek()); $interval = new TimeInterval( TimeBuilder::fromSeconds($startForPreviousDay), TimeBuilder::fromSeconds($endForPreviousDay) ); $tmpDays[$dayOfWeek][] = $interval; } // Next day. if ($end > 86400) { $startForNextDay = \max(0, $start - 86400); $endForNextDay = $end - 86400; $dayOfWeek = self::getNextDayOfWeek($day->getDayOfWeek()); $interval = new TimeInterval( TimeBuilder::fromSeconds($startForNextDay), TimeBuilder::fromSeconds($endForNextDay) ); $tmpDays[$dayOfWeek][] = $interval; } } } $tmpDays = \array_filter($tmpDays); $days = self::flattenDaysIntervals($tmpDays); return new BusinessHours($days, $newTimezone); }
php
{ "resource": "" }
q266587
BusinessHoursBuilder.flattenDaysIntervals
test
private static function flattenDaysIntervals(array $days): array { \ksort($days); $flattenDays = []; foreach ($days as $dayOfWeek => $intervals) { $flattenDays[] = DayBuilder::fromArray($dayOfWeek, $intervals); } return $flattenDays; }
php
{ "resource": "" }
q266588
PEAR_PackageFile_v1._validateWarning
test
function _validateWarning($code, $params = array()) { $this->_stack->push($code, 'warning', $params, false, false, debug_backtrace()); }
php
{ "resource": "" }
q266589
PEAR_PackageFile_v1.getFileContents
test
function getFileContents($file) { if ($this->_archiveFile == $this->_packageFile) { // unpacked $dir = dirname($this->_packageFile); $file = $dir . DIRECTORY_SEPARATOR . $file; $file = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $file); if (file_exists($file) && is_readable($file)) { return implode('', file($file)); } } else { // tgz if (!class_exists('Archive_Tar')) { require_once 'Archive/Tar.php'; } $tar = &new Archive_Tar($this->_archiveFile); $tar->pushErrorHandling(PEAR_ERROR_RETURN); if ($file != 'package.xml' && $file != 'package2.xml') { $file = $this->getPackage() . '-' . $this->getVersion() . '/' . $file; } $file = $tar->extractInString($file); $tar->popErrorHandling(); if (PEAR::isError($file)) { return PEAR::raiseError("Cannot locate file '$file' in archive"); } return $file; } }
php
{ "resource": "" }
q266590
YamlConfigServiceProvider.parseImports
test
protected function parseImports(array $imports, $configPath) { foreach ($imports as $import) { $config = $this->parse(dirname($configPath) . '/' .$import['resource']); if ($config !== null) { $this->_configSettings = $this->mergeConfigurations( $this->_configSettings, $config ); } } }
php
{ "resource": "" }
q266591
YamlConfigServiceProvider.parse
test
protected function parse($input, $exceptionOnInvalidType = false, $objectSupport = false ) { // if input is a file, process it $file = ''; if (strpos($input, "\n") === false && is_file($input)) { if (false === is_readable($input)) { throw new ParseException( sprintf( 'Unable to parse "%s" as the file is not readable.', $input ) ); } $file = $input; $input = file_get_contents($file); } $input = str_replace( array_keys($this->_vars), array_values($this->_vars), $input ); $yaml = new Parser(); try { return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport); } catch (ParseException $e) { if ($file) { $e->setParsedFile($file); } throw $e; } }
php
{ "resource": "" }
q266592
YamlConfigServiceProvider.setYamlPatameters
test
protected function setYamlPatameters() { foreach ($this->_configSettings['parameters'] as $key => $value) { $this->_vars['%'.$key.'%'] = $value; } }
php
{ "resource": "" }
q266593
HTTP_Request2_Adapter.calculateRequestLength
test
protected function calculateRequestLength(&$headers) { $this->requestBody = $this->request->getBody(); if (is_string($this->requestBody)) { $this->contentLength = strlen($this->requestBody); } elseif (is_resource($this->requestBody)) { $stat = fstat($this->requestBody); $this->contentLength = $stat['size']; rewind($this->requestBody); } else { $this->contentLength = $this->requestBody->getLength(); $headers['content-type'] = 'multipart/form-data; boundary=' . $this->requestBody->getBoundary(); $this->requestBody->rewind(); } if (in_array($this->request->getMethod(), self::$bodyDisallowed) || 0 == $this->contentLength ) { // No body: send a Content-Length header nonetheless (request #12900), // but do that only for methods that require a body (bug #14740) if (in_array($this->request->getMethod(), self::$bodyRequired)) { $headers['content-length'] = 0; } else { unset($headers['content-length']); // if the method doesn't require a body and doesn't have a // body, don't send a Content-Type header. (request #16799) unset($headers['content-type']); } } else { if (empty($headers['content-type'])) { $headers['content-type'] = 'application/x-www-form-urlencoded'; } // Content-Length should not be sent for chunked Transfer-Encoding (bug #20125) if (!isset($headers['transfer-encoding'])) { $headers['content-length'] = $this->contentLength; } } }
php
{ "resource": "" }
q266594
CommanderConsole.executeCommand
test
public function executeCommand($command, array $input, $decorators = []) { $command = $this->mapInputToCommand($command, $input); $bus = $this->getCommandBus(); // If any decorators are passed, we'll // filter through and register them // with the CommandBus, so that they // are executed first. foreach ($decorators as $decorator) { $bus->decorate($decorator); } return $bus->execute($command); }
php
{ "resource": "" }
q266595
PEAR_PackageFile_Generator_v2._serializeValue
test
function _serializeValue($value, $tagName = null, $attributes = array()) { if (is_array($value)) { $xml = $this->_serializeArray($value, $tagName, $attributes); } elseif (is_object($value)) { $xml = $this->_serializeObject($value, $tagName); } else { $tag = array( 'qname' => $tagName, 'attributes' => $attributes, 'content' => $value ); $xml = $this->_createXMLTag($tag); } return $xml; }
php
{ "resource": "" }
q266596
Publishes.unpublishOthers
test
protected function unpublishOthers($entity) { if(!$entity->isHead()) { $head = $entity->getHead(); if($head->isPublished()) { $head->unpublish(); $this->persist($head, false); } } foreach($entity->getVersions() as $version) { if($version !== $entity && $version->isPublished()) { $version->unpublish(); $this->persist($version, false); } } }
php
{ "resource": "" }
q266597
DatabaseOptions.setClassName
test
public function setClassName($className) { $className = (string) $className; /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($className)) { throw new Exception\InvalidArgumentException('Class Name must be a non-empty string.'); } $this->className = $className; return $this; }
php
{ "resource": "" }
q266598
DatabaseOptions.setIdColumn
test
public function setIdColumn($idColumn) { $idColumn = (string) $idColumn; /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($idColumn)) { throw new Exception\InvalidArgumentException('ID column must be a non-empty string.'); } $this->idColumn = $idColumn; return $this; }
php
{ "resource": "" }
q266599
DatabaseOptions.setNameColumn
test
public function setNameColumn($nameColumn) { $nameColumn = (string) $nameColumn; /** @noinspection IsEmptyFunctionUsageInspection */ if (empty($nameColumn)) { throw new Exception\InvalidArgumentException('Name column must be a non-empty string.'); } $this->nameColumn = $nameColumn; return $this; }
php
{ "resource": "" }