_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q266700
TransactionAbstract.setType
test
public function setType($type) { $type = (string) $type; if ($this->exists() && $this->type !== $type) { $this->updated['type'] = true; } $this->type = $type; return $this; }
php
{ "resource": "" }
q266701
TransactionAbstract.setComment
test
public function setComment($comment) { $comment = ($comment === null ? $comment : (string) $comment); if ($this->exists() && $this->comment !== $comment) { $this->updated['comment'] = true; } $this->comment = $comment; return $this; }
php
{ "resource": "" }
q266702
TransactionAbstract.setCategoryId
test
public function setCategoryId($categoryId) { $categoryId = (int) $categoryId; if ($this->categoryId < 0) { throw new \UnderflowException('Value of "categoryId" must be greater than 0'); } if ($this->exists() && $this->categoryId !== $categoryId) { $this->updated['categoryId'] = true; } $this->categoryId = $categoryId; return $this; }
php
{ "resource": "" }
q266703
TransactionAbstract.setAccountIdVirtual
test
public function setAccountIdVirtual($accountIdVirtual) { $accountIdVirtual = (int) $accountIdVirtual; if ($this->accountIdVirtual < 0) { throw new \UnderflowException('Value of "accountIdVirtual" must be greater than 0'); } if ($this->exists() && $this->accountIdVirtual !== $accountIdVirtual) { $this->updated['accountIdVirtual'] = true; } $this->accountIdVirtual = $accountIdVirtual; return $this; }
php
{ "resource": "" }
q266704
TimeInterval.fromString
test
public static function fromString($startTime, $endTime): self { return new static(TimeBuilder::fromString($startTime), TimeBuilder::fromString($endTime)); }
php
{ "resource": "" }
q266705
Database.fromArray
test
public static function fromArray(array $config) { if (!isset($config['engine'])) { throw new \InvalidArgumentException("Missing engine: must be either 'mysql' or 'sqlite'"); } if (!in_array(strtolower($config['engine']), ['sqlite', 'mysql'])) { throw new \InvalidArgumentException("Unsupported engine {$config['engine']}"); } if ($config['engine'] === 'sqlite') { return static::sqlite( $config['file'], $config['options'] ?? [] ); } if ($config['engine'] === 'mysql') { return static::mysql( $config['host'], $config['name'], $config['user'] ?? null, $config['pass'] ?? null, $config['options'] ?? [] ); } return null; }
php
{ "resource": "" }
q266706
Database.sqlite
test
public static function sqlite(string $file, array $options = []) { $options = array_replace(static::$defaultOptions, $options); $instance = new static("sqlite:{$file}", null, null, $options); $instance->databaseType = 'sqlite'; $instance->isWritable = ($file === ':memory:') || (is_writable(dirname($file)) && is_writable($file)); return $instance; }
php
{ "resource": "" }
q266707
Database.mysql
test
public static function mysql(string $host, string $dbname, string $user = null, string $password = null, array $options = []) { $options = array_replace(static::$defaultOptions, $options); $instance = new static("mysql:host={$host};dbname=${dbname}", $user, $password, $options); $instance->databaseType = 'mysql'; return $instance; }
php
{ "resource": "" }
q266708
Database.run
test
public function run($sql, array $params = [], bool $returnStatement = false, int $fetchMode = PDO::FETCH_ASSOC) { if ($sql instanceof Query) { $params = $sql->getParams(); $sql = $sql->getSql(); } $stm = $this->prepare($sql); $stm->execute($params); $this->logQuery($sql, $params); if ($returnStatement) { return $stm; } elseif (substr(trim($sql), 0, 6) === 'SELECT') { return $stm->fetchAll($fetchMode); } else { return $stm->rowCount(); } }
php
{ "resource": "" }
q266709
Database.tableNames
test
public function tableNames() { if ($this->databaseType === 'mysql') { $sql = "SHOW TABLES"; } elseif ($this->databaseType === 'sqlite') { $sql = "SELECT name FROM sqlite_master WHERE type='table'"; } else { throw new \RuntimeException("Unsupported database type: '{$this->databaseType}'"); } $stm = $this->query($sql); $r = $stm->fetchAll(); $tables = array_map(function ($t) { return reset($t); }, $r); $this->logQuery($sql); return $tables; }
php
{ "resource": "" }
q266710
Database.row
test
public function row($sql, array $params = [], $rowNumber = 0) { $result = $this->run($sql, $params, false, PDO::FETCH_ASSOC); return $result[$rowNumber] ?? null; }
php
{ "resource": "" }
q266711
Database.cell
test
public function cell($sql, array $params = [], $columnName = 0) { $result = $this->run($sql, $params, false, PDO::FETCH_BOTH); return $result[0][$columnName] ?? null; }
php
{ "resource": "" }
q266712
Database.tableExists
test
public function tableExists(string $tableName) { try { $sql = "SELECT 1 FROM {$tableName} LIMIT 1"; $this->prepare($sql); $this->logQuery("[PREPARE ONLY] $sql"); return true; } catch (PDOException $e) {} return false; }
php
{ "resource": "" }
q266713
Database.columnExists
test
public function columnExists(string $tableName, string $columnName) { if ($this->tableExists($tableName)) { $names = array_flip($this->getColumnNames($tableName)); return array_key_exists($columnName, $names); } return false; }
php
{ "resource": "" }
q266714
Database.getPrimaryKeys
test
public function getPrimaryKeys(string $table, bool $asArray = false) { $pk = []; if ($this->databaseType === 'mysql') { $sql = "SHOW COLUMNS FROM {$table}"; $primaryKeyIndex = 'Key'; $primaryKeyValue = 'PRI'; $tableNameIndex = 'Field'; } elseif ($this->databaseType === 'sqlite') { $sql = "PRAGMA table_info({$table})"; $primaryKeyIndex = 'pk'; $primaryKeyValue = 1; $tableNameIndex = 'name'; } else { throw new \RuntimeException("Unsupported database type: '{$this->databaseType}'"); } $stm = $this->query($sql); $r = $stm->fetchAll(); $this->logQuery($sql); # Search all columns for the Primary Key flag foreach ($r as $col) { if ($col[$primaryKeyIndex] == $primaryKeyValue) { # Add this column to the primary keys list $pk[] = $col[$tableNameIndex]; } } # if the return value is preferred as string if (!$asArray) { $pk = join(',', $pk); } return $pk; }
php
{ "resource": "" }
q266715
Database.getColumnNames
test
public function getColumnNames(string $table, bool $withTableName = false, bool $aliased = false) { $cols = []; if ($this->databaseType === 'mysql') { $sql = "SHOW COLUMNS FROM {$table}"; $tableNameIndex = 'Field'; } elseif ($this->databaseType === 'sqlite') { $sql = "PRAGMA table_info({$table})"; $tableNameIndex = 'name'; } else { throw new \RuntimeException("Unsupported database type: '{$this->databaseType}'"); } # Get all columns from a selected table $r = $this->query($sql)->fetchAll(); $this->logQuery($sql); # Add column names to $cols array foreach ($r as $i => $col) { $colName = $col[$tableNameIndex]; if ($aliased) { $i = "{$table}_{$colName}"; } if ($withTableName) { $colName = "{$table}.${colName}"; } $cols[$i] = $colName; } return $cols; }
php
{ "resource": "" }
q266716
Database.logQuery
test
public function logQuery(string $sql, array $params = []) { if ($this->logger instanceof LoggerInterface) { $message = $sql . ' => ' . json_encode($params); $this->logger->info($message); } }
php
{ "resource": "" }
q266717
Module.onBootstrap
test
public function onBootstrap(EventInterface $e) { /* @var $sm \Zend\ServiceManager\ServiceLocatorInterface */ $sm = $e->getApplication()->getServiceManager(); /* @var $em \Doctrine\ORM\EntityManager */ $em = $sm->get('Doctrine\ORM\EntityManager'); $em->getEventManager()->addEventSubscriber(new ServiceAwareEntityListener($sm)); }
php
{ "resource": "" }
q266718
OptimizeCommand.run
test
public function run(): int { // If the cache file already exists, delete it if (file_exists(config()['cacheFilePath'])) { unlink(config()['cacheFilePath']); } app()->setup( [ 'app' => [ 'debug' => false, 'env' => 'production', ], ], true ); $containerCache = container()->getCacheable(); $consoleCache = console()->getCacheable(); $eventsCache = events()->getCacheable(); $routesCache = router()->getCacheable(); $configCache = config(); $configCache['cache']['container'] = $containerCache; $configCache['cache']['console'] = $consoleCache; $configCache['cache']['events'] = $eventsCache; $configCache['cache']['routing'] = $routesCache; $configCache['container']['useCache'] = true; $configCache['console']['useCache'] = true; $configCache['events']['useCache'] = true; $configCache['routing']['useCache'] = true; // Get the results of the cache attempt $result = file_put_contents( config()['cacheFilePath'], '<?php return ' . var_export($configCache, true) . ';', LOCK_EX ); if ($result === false) { output()->writeMessage( 'An error occurred while optimizing the application.', true ); return 1; } output()->writeMessage('Application optimized successfully', true); return 0; }
php
{ "resource": "" }
q266719
Zend_Filter_Encrypt_Openssl._setKeys
test
protected function _setKeys($keys) { if (!is_array($keys)) { throw new Zend_Filter_Exception('Invalid options argument provided to filter'); } foreach ($keys as $type => $key) { if (is_file($key) and is_readable($key)) { $file = fopen($key, 'r'); $cert = fread($file, 8192); fclose($file); } else { $cert = $key; $key = count($this->_keys[$type]); } switch ($type) { case 'public': $test = openssl_pkey_get_public($cert); if ($test === false) { throw new Zend_Filter_Exception("Public key '{$cert}' not valid"); } openssl_free_key($test); $this->_keys['public'][$key] = $cert; break; case 'private': $test = openssl_pkey_get_private($cert, $this->_passphrase); if ($test === false) { throw new Zend_Filter_Exception("Private key '{$cert}' not valid"); } openssl_free_key($test); $this->_keys['private'][$key] = $cert; break; case 'envelope': $this->_keys['envelope'][$key] = $cert; break; default: break; } } return $this; }
php
{ "resource": "" }
q266720
Zend_Filter_Encrypt_Openssl.setPrivateKey
test
public function setPrivateKey($key, $passphrase = null) { if (is_array($key)) { foreach($key as $type => $option) { if ($type !== 'private') { $key['private'] = $option; unset($key[$type]); } } } else { $key = array('private' => $key); } if ($passphrase !== null) { $this->setPassphrase($passphrase); } return $this->_setKeys($key); }
php
{ "resource": "" }
q266721
Zend_Filter_Encrypt_Openssl.setEnvelopeKey
test
public function setEnvelopeKey($key) { if (is_array($key)) { foreach($key as $type => $option) { if ($type !== 'envelope') { $key['envelope'] = $option; unset($key[$type]); } } } else { $key = array('envelope' => $key); } return $this->_setKeys($key); }
php
{ "resource": "" }
q266722
Zend_Filter_Encrypt_Openssl.setCompression
test
public function setCompression($compression) { if (is_string($this->_compression)) { $compression = array('adapter' => $compression); } $this->_compression = $compression; return $this; }
php
{ "resource": "" }
q266723
Base.tsGetFormatted
test
public function tsGetFormatted(\DateTime $tsProperty = null, $format = self::DEFAULT_DATE_FORMAT, $timezone = null) { if ($tsProperty === null) { return ''; } $shiftedTs = clone $tsProperty; return $this->setDtTz($shiftedTs, $timezone)->format($format); }
php
{ "resource": "" }
q266724
Users.supprimerUtilisateur
test
public function supprimerUtilisateur($idUser) { $oDateNow = new \DateTime('now'); $iReturn = $this->_oParamUsersRepository->supprimerUtilisateur($idUser, $oDateNow); if($iReturn != 1) { $aVarReturn = array( 'error' => true, 'reasons' => array( 'msg'=>'Une erreur s\'est produite durant la suppression' ), ); } else { $aVarReturn = array( 'error' => false, 'reasons' => null, 'nbMaj' => $iReturn, ); } return $aVarReturn; }
php
{ "resource": "" }
q266725
ReturnArgumentPromise.execute
test
public function execute(array $args, FunctionProphecy $function) { return count($args) > $this->index ? $args[$this->index] : null; }
php
{ "resource": "" }
q266726
MigrateController.createMigrationHistoryTable
test
protected function createMigrationHistoryTable() { $tableName = $this->db->getSchema()->getRawTableName($this->migrationTable); $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW); $promises = []; $promises[] = $this->db->createCommand()->createTable($this->migrationTable, [ 'version' => 'varchar(' . static::MAX_NAME_LENGTH . ') NOT NULL PRIMARY KEY', 'apply_time' => 'integer', ])->execute(); $promises[] = $this->db->createCommand()->insert($this->migrationTable, [ 'version' => self::BASE_MIGRATION, 'apply_time' => time(), ])->execute(); return allInOrder($promises)->then(function() { $this->stdout("Done.\n", Console::FG_GREEN); return true; }); }
php
{ "resource": "" }
q266727
Zend_Filter.addFilter
test
public function addFilter(Zend_Filter_Interface $filter, $placement = self::CHAIN_APPEND) { if ($placement == self::CHAIN_PREPEND) { array_unshift($this->_filters, $filter); } else { $this->_filters[] = $filter; } return $this; }
php
{ "resource": "" }
q266728
Zend_Filter.filterStatic
test
public static function filterStatic($value, $classBaseName, array $args = array(), $namespaces = array()) { $namespaces = array_merge((array) $namespaces, self::$_defaultNamespaces, array('Zend_Filter')); foreach ($namespaces as $namespace) { $className = $namespace . '_' . ucfirst($classBaseName); if (!class_exists($className, false)) { try { $file = str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; if (Zend_Loader::isReadable($file)) { Zend_Loader::loadClass($className); } else { continue; } } catch (Zend_Exception $ze) { continue; } } $class = new ReflectionClass($className); if ($class->implementsInterface('Zend_Filter_Interface')) { if ($class->hasMethod('__construct')) { $object = $class->newInstanceArgs($args); } else { $object = $class->newInstance(); } return $object->filter($value); } } throw new Zend_Filter_Exception("Filter class not found from basename '$classBaseName'"); }
php
{ "resource": "" }
q266729
ActiveRelationTrait.addInverseRelations
test
protected function addInverseRelations(&$result) { if ($this->inverseOf === null) { return; } foreach ($result as $i => $relatedModel) { if ($relatedModel instanceof ActiveRecordInterface) { if (!isset($inverseRelation)) { $inverseRelation = $relatedModel->getRelation($this->inverseOf); } $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel); } else { if (!isset($inverseRelation)) { /* @var $modelClass ActiveRecordInterface */ $modelClass = $this->modelClass; $inverseRelation = $modelClass::instance()->getRelation($this->inverseOf); } $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel; } } }
php
{ "resource": "" }
q266730
ActiveRelationTrait.populateRelation
test
public function populateRelation($name, &$primaryModels) { if (!is_array($this->link)) { throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.'); } $viaQuery = null; $viaModels = null; $viaModelsUsed = true; if ($this->via instanceof self) { // via junction table /* @var $viaQuery ActiveRelationTrait */ $viaQuery = $this->via; $filterPr = $viaQuery->findJunctionRows($primaryModels)->otherwise( function() { return []; } ); } elseif (is_array($this->via)) { // via relation /* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */ list($viaName, $viaQuery) = $this->via; if ($viaQuery->asArray === null) { // inherit asArray from primary query $viaQuery->asArray($this->asArray); } $viaQuery->primaryModel = null; $filterPr = $viaQuery->populateRelation($viaName, $primaryModels)->otherwise( function() { return []; } ); } else { $viaModelsUsed = false; $filterPr = resolve($primaryModels); } $filterPr->then(function($filterModels) use (&$viaModelsUsed, &$viaModels) { if ($viaModelsUsed) { $viaModels = $filterModels; } $this->filterByModels($filterModels); return true; })->then(function() use ($name, &$primaryModels, &$viaModels, &$viaQuery) { if (!$this->multiple && count($primaryModels) === 1) { return $this->populateRelationAsyncSingle($name, $primaryModels); } else { return $this->populateRelationAsyncMultiple($name, $primaryModels, $viaModels, $viaQuery); } }); return $filterPr; }
php
{ "resource": "" }
q266731
ActiveRelationTrait.populateRelationAsyncSingle
test
protected function populateRelationAsyncSingle($name, &$primaryModels) { return $this->one()->otherwise(function() { return null; })->then( function($model) use ($name, &$primaryModels) { $primaryModel = reset($primaryModels); if ($primaryModel instanceof ActiveRecordInterface) { $primaryModel->populateRelation($name, $model); } else { $primaryModels[key($primaryModels)][$name] = $model; } if ($this->inverseOf !== null) { $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf); } return [$model]; } ); }
php
{ "resource": "" }
q266732
ActiveRelationTrait.populateRelationAsyncMultiple
test
protected function populateRelationAsyncMultiple($name, &$primaryModels, $viaModels = null, $viaQuery = null) { // https://github.com/yiisoft/yii2/issues/3197 // delay indexing related models after buckets are built $indexBy = $this->indexBy; $this->indexBy = null; return $this->all()->otherwise(function() { return []; })->then( function($models) use (&$primaryModels, $name, $viaModels, $viaQuery, $indexBy) { if (isset($viaModels, $viaQuery)) { $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery->link); } else { $buckets = $this->buildBuckets($models, $this->link); } $this->indexBy = $indexBy; if ($this->indexBy !== null && $this->multiple) { $buckets = $this->indexBuckets($buckets, $this->indexBy); } $link = array_values(isset($viaQuery) ? $viaQuery->link : $this->link); foreach ($primaryModels as $i => $primaryModel) { if ($this->multiple && count($link) === 1 && is_array($keys = $primaryModel[reset($link)])) { $value = []; foreach ($keys as $key) { $key = $this->normalizeModelKey($key); if (isset($buckets[$key])) { if ($this->indexBy !== null) { // if indexBy is set, array_merge will cause renumbering of numeric array foreach ($buckets[$key] as $bucketKey => $bucketValue) { $value[$bucketKey] = $bucketValue; } } else { $value = array_merge($value, $buckets[$key]); } } } } else { $key = $this->getModelKey($primaryModel, $link); $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null); } if ($primaryModel instanceof ActiveRecordInterface) { $primaryModel->populateRelation($name, $value); } else { $primaryModels[$i][$name] = $value; } } if ($this->inverseOf !== null) { $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf); } return $models; } ); }
php
{ "resource": "" }
q266733
Message.listInvalidProperties
test
public function listInvalidProperties() { $invalid_properties = []; if ($this->container['source'] === null) { $invalid_properties[] = "'source' can't be null"; } if ($this->container['destinations'] === null) { $invalid_properties[] = "'destinations' can't be null"; } return $invalid_properties; }
php
{ "resource": "" }
q266734
Flatten.process
test
private function process(array $array, $prefix = '') { $result = []; foreach ($array as $key => $value) { // Subarrray handling needed? if (is_array($value)) { // __preserve key set tha signals us to store the array as it is? if ($this->preserve_flagged_arrays && array_key_exists('__preserve', $value)) { $result[$prefix . $key . $this->glue . 'array'] = $value; unset($value['__preserve']); } // Flatten the array $result = $result + $this->process($value, $prefix . $key . $this->glue, $this->glue, $this->preserve_flagged_arrays); } else { $result[$prefix . $key] = $value; } } return $result; }
php
{ "resource": "" }
q266735
Entity.of
test
public static function of($class) { $reflector = new \ReflectionClass($class); $name = Annotation::ofClass($class, 'entity') ?: strtolower($reflector->getShortName()); $entity = new static($name, $class); $defaults = $reflector->getDefaultProperties(); foreach ($defaults as $property => $default) { $annotations = Annotation::ofProperty($class, $property); $type = !empty($annotations['var']) ? $annotations['var'] : 'string'; $field = new Entity\Field($property, $type); $field->nullable = $default !== null; $field->default = $default; $field->primary = isset($annotations['id']) ?: ($property === 'id'); $entity->fields[$property] = $field; } return $entity; }
php
{ "resource": "" }
q266736
Text.equals
test
public function equals(?Text $other = null): bool { if($other === null) { return false; } return $this->raw === (string)$other; }
php
{ "resource": "" }
q266737
Text.endsWith
test
public function endsWith(Text $other): bool { return strrpos($this->raw, (string)$other, -$other->length) === ($this->length - $other->length); }
php
{ "resource": "" }
q266738
Text.contains
test
public function contains(Text $other): bool { return strpos($this->raw, (string)$other) !== false; }
php
{ "resource": "" }
q266739
Text.substring
test
public function substring(int $start, ?int $length = null): Text { if($length === null) { return new static(substr($this->raw, $start)); } return new static(substr($this->raw, $start, $length)); }
php
{ "resource": "" }
q266740
Text.replace
test
public function replace(Text $search, Text $replace): Text { return new static(str_replace((string)$search, (string)$replace, $this->raw)); }
php
{ "resource": "" }
q266741
Text.replaceByRegex
test
public function replaceByRegex(Regex $search, Text $replace): Text { return $search->replace($this, $replace); }
php
{ "resource": "" }
q266742
BaseActiveRecord.beforeSave
test
public function beforeSave($insert) { $eventName = $insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE; $isValid = true; $this->emit($eventName, [&$this, &$isValid]); return $isValid; }
php
{ "resource": "" }
q266743
BaseActiveRecord.beforeDelete
test
public function beforeDelete() { $isValid = true; $this->emit(self::EVENT_BEFORE_DELETE, [&$this, &$isValid]); return $isValid; }
php
{ "resource": "" }
q266744
BaseActiveRecord.refresh
test
public function refresh() { return static::findOne($this->getPrimaryKey(true))->then( function($record) { /* @var $record BaseActiveRecord */ $result = $this->refreshInternal($record); return $result ? true : reject(false); } ); }
php
{ "resource": "" }
q266745
ActiveRecord.updateAll
test
public static function updateAll($attributes, $condition = '', $params = [], $connection = null) { $command = static::getDb()->createCommand(); $command->update(static::tableName(), $attributes, $condition, $params); if (isset($connection)) { $command->setConnection($connection); } return $command->execute(); }
php
{ "resource": "" }
q266746
ActiveRecord.deleteAll
test
public static function deleteAll($condition = null, $params = [], $connection = null) { $command = static::getDb()->createCommand(); $command->delete(static::tableName(), $condition, $params); if (isset($connection)) { $command->setConnection($connection); } return $command->execute(); }
php
{ "resource": "" }
q266747
ActiveRecord.insert
test
public function insert($runValidation = true, $attributes = null) { $validationPromise = $runValidation ? new LazyPromise(function() use ($attributes) { return $this->validate($attributes); }) : Reaction\Promise\resolveLazy(true); return $validationPromise ->otherwiseLazy(function() { Reaction::info('Model not inserted due to validation error in {method}.', ['method' => __METHOD__]); return reject(new ValidationError("Model validation error")); })->thenLazy(function() use ($attributes) { if (!$this->isTransactional(self::OP_INSERT)) { return new LazyPromise(function() use ($attributes) { return $this->insertInternal($attributes); }); } $transaction = static::getDb()->createTransaction(); return $transaction->begin()->then( function(ConnectionInterface $connection) use ($attributes) { return $this->insertInternal($attributes, $connection); } )->then( function($result) use ($transaction) { return $transaction->commit()->then(function() use ($result) { return $result; }); }, function($exception) use ($transaction) { return $transaction->rollBack()->then( function() use ($exception) { throw $exception; }, function($e) use ($exception) { throw $exception; } ); } ); }); }
php
{ "resource": "" }
q266748
ActiveRecord.insertInternal
test
protected function insertInternal($attributes = null, $connection = null) { if (!$this->beforeSave(true)) { return reject(false); } $values = $this->getDirtyAttributes($attributes); return static::getDb()->getSchema()->insert(static::tableName(), $values, $connection)->then( function($primaryKeys) use ($values) { if ($primaryKeys === false) { return reject(false); } foreach ($primaryKeys as $name => $value) { $id = static::getTableSchema()->columns[$name]->phpTypecast($value); $this->setAttribute($name, $id); $values[$name] = $id; } $changedAttributes = array_fill_keys(array_keys($values), null); $this->setOldAttributes($values); $this->afterSave(true, $changedAttributes); return true; } ); }
php
{ "resource": "" }
q266749
ActiveRecord.deleteInternal
test
protected function deleteInternal($connection = null) { if (!$this->beforeDelete()) { return Reaction\Promise\rejectLazy(false); } // we do not check the return value of deleteAll() because it's possible // the record is already deleted in the database and thus the method will return 0 $condition = $this->getOldPrimaryKey(true); $lock = $this->optimisticLock(); if ($lock !== null) { $condition[$lock] = $this->$lock; } return static::deleteAll($condition, [], $connection)->thenLazy( function($result) use ($lock) { if ($lock !== null && !$result) { throw new StaleObjectException('The object being deleted is outdated.'); } $this->setOldAttributes(null); $this->afterDelete(); return $result; } ); }
php
{ "resource": "" }
q266750
AbstractEntryProvider.getMethods
test
public function getMethods(): array { $methods = []; $reflection = new \ReflectionClass($this); foreach ($reflection->getMethods() as $method) { $identifier = $this->getMethodIdentifier($method); if (!\is_null($identifier)) { $methods[$identifier] = $method->getName(); } } return $methods; }
php
{ "resource": "" }
q266751
AbstractEntryProvider.getMethodIdentifier
test
private function getMethodIdentifier(\ReflectionMethod $method): ?string { if (!$method->isPublic() || $method->isStatic()) { return null; } if (preg_match('/^__[^_]/', $method->getName())) { return null; } $type = $method->getReturnType(); if (!$type instanceof \ReflectionType || $type->isBuiltin()) { return null; } return $type->getName(); }
php
{ "resource": "" }
q266752
ResponseItemData.callbackCustomData
test
public function callbackCustomData($value, $raw) { $defaultKeys = ['id','slugs','data','type','href','tags','lang','alternate_languages','linked_documents','first_publication_date','last_publication_date']; foreach($raw as $key => $value) { if(in_array($key, $defaultKeys)) { unset($raw[$key]); } } return $raw; }
php
{ "resource": "" }
q266753
HelpController.getCommands
test
public function getCommands($withInternal = false) {$commands = []; $namespaces = Reaction::$app->router->controllerNamespaces; $controllers = Reaction\Helpers\ClassFinderHelper::findClassesPsr4($namespaces, true); foreach ($controllers as $controllerClass) { if (!$withInternal && Reaction\Helpers\ReflectionHelper::isImplements($controllerClass, 'Reaction\Routes\ControllerInternalInterface')) { continue; } if ($this->validateControllerClass($controllerClass)) { $relativePath = Reaction::$app->router->getRelativeControllerNamespace($controllerClass); $pathArray = explode('\\', $relativePath); $classBasename = array_pop($pathArray); $command = Inflector::camel2id(substr($classBasename, 0, -10), '-', true); if (!empty($pathArray)) { $classPath = ltrim(implode('/', $pathArray), DIRECTORY_SEPARATOR); $command = $classPath . DIRECTORY_SEPARATOR . $command; } $commands[] = $command; } } sort($commands); return array_unique($commands); }
php
{ "resource": "" }
q266754
HelpController.getCommandHelp
test
protected function getCommandHelp($controller) { $controller->color = $this->color; $this->stdout("\nDESCRIPTION\n", Console::BOLD); $comment = $controller->getHelp(); if ($comment !== '') { $this->stdout("\n$comment\n\n"); } $actions = $this->getActions($controller); if (!empty($actions)) { $this->stdout("\nSUB-COMMANDS\n\n", Console::BOLD); $prefix = $controller->getUniqueId(); $maxlen = 5; foreach ($actions as $action) { $len = strlen($prefix . '/' . $action) + 2 + ($action === $controller->defaultAction ? 10 : 0); if ($maxlen < $len) { $maxlen = $len; } } foreach ($actions as $action) { $this->stdout('- ' . $this->ansiFormat($prefix . '/' . $action, Console::FG_YELLOW)); $len = strlen($prefix . '/' . $action) + 2; if ($action === $controller->defaultAction) { $this->stdout(' (default)', Console::FG_GREEN); $len += 10; } $summary = $controller->getActionHelpSummary($action); if ($summary !== '') { $this->stdout(str_repeat(' ', $maxlen - $len + 2) . Console::wrapText($summary, $maxlen + 2)); } $this->stdout("\n"); } $scriptName = $this->getScriptName(); $this->stdout("\nTo see the detailed information about individual sub-commands, enter:\n"); $this->stdout("\n $scriptName " . $this->ansiFormat('help', Console::FG_YELLOW) . ' ' . $this->ansiFormat('<sub-command>', Console::FG_CYAN) . "\n\n"); } }
php
{ "resource": "" }
q266755
HelpController.createController
test
protected function createController($command, $config = [], $defaultOnFault = true) { $config['app'] = $this->app; return Reaction::$app->router->createController($command, $config, $defaultOnFault); }
php
{ "resource": "" }
q266756
ErrorHandler.handleException
test
public function handleException($exception) { $this->exception = $exception; try { $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } return $this->renderException($exception); } catch (\Exception $e) { // an other exception could be thrown while displaying the exception $this->handleFallbackExceptionMessage($e, $exception); } catch (\Throwable $e) { // additional check for \Throwable introduced in PHP 7 $this->handleFallbackExceptionMessage($e, $exception); } $this->exception = null; return new Reaction\Web\Response(500, [], 'Server error'); }
php
{ "resource": "" }
q266757
ErrorHandler.handleFatalError
test
public function handleFatalError() { unset($this->_memoryReserve); static::loadErrorExceptionClass(); $error = error_get_last(); if (ErrorException::isFatalError($error)) { $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']); $this->exception = $exception; $this->logException($exception); if ($this->discardExistingOutput) { $this->clearOutput(); } $this->renderException($exception); } }
php
{ "resource": "" }
q266758
ErrorHandler.logException
test
public function logException($exception) { $category = get_class($exception); if ($exception instanceof HttpException) { $category = 'Reaction\\Exceptions\\HttpException:' . $exception->statusCode; } elseif ($exception instanceof \ErrorException) { $category .= ':' . $exception->getSeverity(); } $message = $exception->getMessage(); $fileLine = ''; if ($exception->getFile() && $exception->getLine()) { $fileLine = "\n" . $exception->getFile() . ':' . $exception->getLine(); } $logMessage = $category . "\n" . $message . $fileLine; if (Console::streamSupportsAnsiColors(STDOUT)) { $logMessage = Console::ansiFormat($logMessage, [Console::FG_RED]); } Reaction::$app->logger->logRaw($logMessage); }
php
{ "resource": "" }
q266759
ErrorHandler.getExceptionTrace
test
public static function getExceptionTrace(\Throwable $exception, $asString = true) { $trace = $exception->getTrace(); $trace = static::reduceStackTrace($exception, $trace); return $asString ? static::getExceptionTraceAsString($trace) : $trace; }
php
{ "resource": "" }
q266760
ErrorHandler.reduceStackTrace
test
public static function reduceStackTrace(\Throwable $exception, $trace) { $exclude = [ 'Reaction\Promise\Promise' => ['settle'], 'React\Promise\Promise' => ['settle'], 'Rx\Observer\AbstractObserver' => [], 'Rx\Observer\AutoDetachObserver' => [], 'Rx\Observer\CallbackObserver' => [], ]; $file = $exception->getFile(); $traceNew = []; foreach ($trace as $num => $row) { $rowFile = isset($row['file']) ? $row['file'] : null; $rowClass = isset($row['class']) ? $row['class'] : null; $rowFunction = isset($row['function']) ? $row['function'] : '{closure}'; if ( isset($exclude[$rowClass]) && (empty($exclude[$rowClass]) || in_array($rowFunction, $exclude[$rowClass])) && $rowFile !== $file ) { continue; } $traceNew[] = $row; } return $traceNew; }
php
{ "resource": "" }
q266761
RequestAppHelperProxy.proxyWithAppProperty
test
private function proxyWithAppProperty($method, $arguments = [], $position = -1, $propertyName = 'charset') { $this->injectVariableToArguments($this->app->{$propertyName}, $arguments, $position); return $this->proxy($method, $arguments); }
php
{ "resource": "" }
q266762
RequestAppHelperProxy.proxyWithApp
test
protected function proxyWithApp($method, $arguments = [], $position = -1) { $this->injectVariableToArguments($this->app, $arguments, $position); return $this->proxy($method, $arguments); }
php
{ "resource": "" }
q266763
RequestAppHelperProxy.injectVariableToArguments
test
protected function injectVariableToArguments($variable, &$arguments, $position = -1) { $argsCount = count($arguments); //Negative value handle (from end) if ($position < 0) { $position = $argsCount - $position; } if (!isset($arguments[$position]) && $position >= 0 && $position <= $argsCount) { $arguments[$position] = $variable; } }
php
{ "resource": "" }
q266764
RequestAppHelperProxy.ensureTranslated
test
protected function ensureTranslated(&$string) { if (is_object($string) && $string instanceof TranslationPromise) { $string = $string->translate($this->app->language); } }
php
{ "resource": "" }
q266765
CreateGithubRepo.create
test
public function create(string $repoName) { $this->getGithubAuthentication()->authenticate(); $this->getRepositoryApi()->create($repoName, '', '', true, $this->getOrganization(), true, true, true); }
php
{ "resource": "" }
q266766
Notification.startup
test
protected function startup($notification) { $reflect = new ReflectionClass($notification); $this->configBase = 'notifications.' . $reflect->getShortName(); if (empty(config("{$this->configBase}.notification.name"))) { $this->failed("Required notification.name is missing in notification configuration"); } Log::info( get_class($this) . ': ' . 'A notification module has been called: ' . config("{$this->configBase}.notification.name") ); }
php
{ "resource": "" }
q266767
SecurityKeyGenerator.random
test
public function random($prefix = ''){ $key = $prefix.$this->create().strval(rand(strlen($_SERVER['REMOTE_ADDR']), rand(111,2222))); $uniqid = uniqid($key); return md5($uniqid); }
php
{ "resource": "" }
q266768
Entity.forDataStore
test
public function forDataStore(): array { $properties = []; // Otherwise iterate through the properties array foreach (static::$properties as $property) { $value = $this->{$property}; // Check if a type was set for this attribute $type = static::$propertyTypes[$property] ?? null; // If the type is object and the property isn't already an object if ($type === PropertyType::OBJECT && \is_object($value)) { // Unserialize the object $value = serialize($value); } // If the type is array and the property isn't already an array elseif ($type === PropertyType::ARRAY && \is_array($value)) { $value = \json_encode($value); } // And set each property to its value $properties[$property] = $value; } return $properties; }
php
{ "resource": "" }
q266769
Assert.registerClass
test
public static function registerClass( /*int*/ $customType, /*string*/ $customClassName ) { $customType = @intval($customType); if(0x1000 > $customType) { self::raise([ 'message' => 'Unique id for a custom error starts from 0x1000', 'type' => Exceptions\Error::TYPE_ARGUMENT, 'magic' => 0xf181 ]); } // One custom class for each unique id. if(isset(self::$customErrors[$customType])) { self::raise([ 'message' => sprintf( 'Unique id (%d) has already been assigned a custom error', $customType ), 'type' => Exceptions\Error::TYPE_ARGUMENT, 'magic' => 0xf182 ]); } // Remove any white spaces from the class name. $customClassName = @trim($customClassName); // Allow forward slash to be specified as the namespace separator. $customClassName = @str_replace('/', '\\', $customClassName); // Adding a leading back-slash to it, if not present. if('\\' !== $customClassName{0}) { $customClassName = '\\' . $customClassName; } // Make sure this class exists and extends our own Error class. if(!class_exists($customClassName)) { self::raise([ 'message' => sprintf( 'Custom error class is erroneous: %s', $customClassName ), 'type' => Exceptions\Error::TYPE_ARGUMENT, 'magic' => 0xf183 ]); } // Make sure this custom error class is a descendant of our own Error class. if(!is_subclass_of($customClassName, '\\Fine47\\Exceptions\\Error')) { self::raise([ 'message' => 'Custom error class is not sub class of Error.', 'type' => Exceptions\Error::TYPE_ARGUMENT, 'magic' => 0xf184 ]); } // Register the error class. self::$customErrors[$customType] = $customClassName; }
php
{ "resource": "" }
q266770
AssignmentController.actionAssign
test
public function actionAssign($id) { $model = Yii::createObject([ 'class' => Assignment::className(), 'user_id' => $id, ]); if ($model->load(\Yii::$app->request->post()) && $model->updateAssignments()) { } return \jarrus90\User\widgets\Assignments::widget([ 'model' => $model, ]); }
php
{ "resource": "" }
q266771
Search.requestForCountries
test
public function requestForCountries($countries = array()) { if (empty($countries)) { $countries = self::$countryList; } $results = array(); foreach ($countries as $country) { $this->setCountry($country); $results[$country] = $this->request(); } return $results; }
php
{ "resource": "" }
q266772
StringTools.htmlEncode
test
public static function htmlEncode($string, $specialChars = true) { if ($specialChars) { $string = htmlspecialchars($string); } return htmlentities($string); }
php
{ "resource": "" }
q266773
HTTP_Request2_Response.getDefaultReasonPhrase
test
public static function getDefaultReasonPhrase($code = null) { if (null === $code) { return self::$phrases; } else { return isset(self::$phrases[$code]) ? self::$phrases[$code] : null; } }
php
{ "resource": "" }
q266774
HTTP_Request2_Response.getHeader
test
public function getHeader($headerName = null) { if (null === $headerName) { return $this->headers; } else { $headerName = strtolower($headerName); return isset($this->headers[$headerName])? $this->headers[$headerName]: null; } }
php
{ "resource": "" }
q266775
HTTP_Request2_Response.getBody
test
public function getBody() { if (0 == strlen($this->body) || !$this->bodyEncoded || !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate')) ) { return $this->body; } else { if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) { $oldEncoding = mb_internal_encoding(); mb_internal_encoding('8bit'); } try { switch (strtolower($this->getHeader('content-encoding'))) { case 'gzip': $decoded = self::decodeGzip($this->body); break; case 'deflate': $decoded = self::decodeDeflate($this->body); } } catch (Exception $e) { } if (!empty($oldEncoding)) { mb_internal_encoding($oldEncoding); } if (!empty($e)) { throw $e; } return $decoded; } }
php
{ "resource": "" }
q266776
HTTP_Request2_Response.decodeDeflate
test
public static function decodeDeflate($data) { if (!function_exists('gzuncompress')) { throw new HTTP_Request2_LogicException( 'Unable to decode body: gzip extension not available', HTTP_Request2_Exception::MISCONFIGURATION ); } // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950, // while many applications send raw deflate stream from RFC 1951. // We should check for presence of zlib header and use gzuncompress() or // gzinflate() as needed. See bug #15305 $header = unpack('n', substr($data, 0, 2)); return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data); }
php
{ "resource": "" }
q266777
Builder.exists
test
public function exists() { try { $sql = SQL::tableExists($this->entity->name); return $this->execute($sql); } catch(\PDOException $e) { return false; } }
php
{ "resource": "" }
q266778
Builder.clear
test
public function clear() { $sql = SQL::truncateTable($this->entity->name); return $this->execute($sql); }
php
{ "resource": "" }
q266779
Connections.checking
test
private function checking() : void { $cleared = ! ($this->cIdleCount() + $this->cBusyCount()); if ($this->exiting) { if ($this->pool && ($closed = $this->pool->closed())->pended() && $cleared) { $closed->resolve(); } return; } $cleared && $this->resizing( max( 1, $this->options->initial, min($this->getWaitQ->count(), $this->options->maxIdle) ), 'minimum-scaling' ); }
php
{ "resource": "" }
q266780
Server.getHeaders
test
public function getHeaders(): array { $headers = []; $specialHeaders = self::SPECIAL_HEADERS; foreach ($this->collection as $key => $value) { if ( \in_array($key, $specialHeaders, true) || 0 === strpos($key, 'HTTP_') ) { $headers[$this->getHeaderName($key)] = $value; } } return $headers; }
php
{ "resource": "" }
q266781
Server.getHeaderName
test
protected function getHeaderName($header): string { if (0 === strpos($header, 'HTTP_')) { $header = substr($header, 5); } $header = str_replace( ' ', '-', ucwords(str_replace('_', ' ', strtolower($header))) ); return $header; }
php
{ "resource": "" }
q266782
NativeOutput.write
test
public function write(array $messages, bool $newLine = null, OutputStyle $outputStyle = null): void { foreach ($messages as $message) { $this->writeMessage($message, $newLine, $outputStyle); } }
php
{ "resource": "" }
q266783
NativeOutput.writeMessage
test
public function writeMessage(string $message, bool $newLine = null, OutputStyle $outputStyle = null): void { $newLine = $newLine ?? false; $outputStyleType = $outputStyle ? $outputStyle->getValue() : OutputStyle::NORMAL; switch ($outputStyleType) { case OutputStyle::NORMAL: $message = $this->formatter->format($message); break; case OutputStyle::RAW: break; case OutputStyle::PLAIN: $message = strip_tags($this->formatter->format($message)); break; } $this->writeOut($message, $newLine); }
php
{ "resource": "" }
q266784
Zend_Filter_Null.setType
test
public function setType($type = null) { if (is_array($type)) { $detected = 0; foreach($type as $value) { if (is_int($value)) { $detected += $value; } else if (in_array($value, $this->_constants)) { $detected += array_search($value, $this->_constants); } } $type = $detected; } else if (is_string($type)) { if (in_array($type, $this->_constants)) { $type = array_search($type, $this->_constants); } } if (!is_int($type) || ($type < 0) || ($type > self::ALL)) { throw new Zend_Filter_Exception('Unknown type'); } $this->_type = $type; return $this; }
php
{ "resource": "" }
q266785
FileFinder.findInPaths
test
protected function findInPaths($name, array $paths) { foreach ($paths as $path) { foreach ($this->getPossibleFiles($name) as $file) { if ($this->fs->exists($viewPath = $path.'/'.$file)) { return $viewPath; } } } throw new InvalidArgumentException("Resource '$name' not found."); }
php
{ "resource": "" }
q266786
FileFinder.getPossibleFiles
test
protected function getPossibleFiles($name) { return array_map(function($extension) use ($name) { return str_replace('.', '/', $name).'.'.$extension; }, $this->extensions); }
php
{ "resource": "" }
q266787
NativeSession.start
test
public function start(): void { // If the session is already active if ($this->isActive() || headers_sent()) { // No need to reactivate return; } // If the session failed to start if (! session_start()) { // Throw a new exception throw new SessionStartFailure('The session failed to start!'); } // Set the data $this->data = &$_SESSION; }
php
{ "resource": "" }
q266788
NativeSession.get
test
public function get(string $id) { return $this->has($id) ? $this->data[$id] : null; }
php
{ "resource": "" }
q266789
NativeSession.set
test
public function set(string $id, string $value): void { $this->data[$id] = $value; }
php
{ "resource": "" }
q266790
NativeSession.remove
test
public function remove(string $id): bool { if (! $this->has($id)) { return false; } unset($this->data[$id]); return true; }
php
{ "resource": "" }
q266791
NativeSession.csrf
test
public function csrf(string $id): string { $token = bin2hex(random_bytes(64)); $this->set($id, $token); return $token; }
php
{ "resource": "" }
q266792
NativeSession.validateCsrf
test
public function validateCsrf(string $id, string $token): bool { if (! $this->has($id)) { return false; } $sessionToken = $this->get($id); if (! \is_string($sessionToken)) { return false; } $this->remove($id); return hash_equals($token, $sessionToken); }
php
{ "resource": "" }
q266793
Inflector.humanize
test
public static function humanize($name) { if (empty($name)) { return ''; } $word = static::tableize(static::classify($name), ' '); $word = strtoupper($word[0]) . substr($word, 1); return $word; }
php
{ "resource": "" }
q266794
File.delete
test
public function delete($clean_only = false): bool { $path = $this->replaceDirectorySeperator($this->filename); if (!file_exists($path)) { return true; } if (!is_dir($path)) { return unlink($path); } $files = scandir($path); foreach ($files as $item) { $file = $path . DIRECTORY_SEPARATOR . $item; if (is_dir($file)) { $this->delete($file); } else { unlink($file); } } return $clean_only == false ? rmdir($path) : true; }
php
{ "resource": "" }
q266795
File.move
test
public function move($destination) { if (copy($this->filename, $destination)) { unlink($this->filename); $this->filename = $destination; return $destination; } else { return false; } }
php
{ "resource": "" }
q266796
File.clean
test
public function clean($delimiter = '-') { // The fileextension should not be normalized. if (strrpos($this->filename, '.') !== false) { list ($name, $extension) = explode('.', $this->filename); } $normalize = new Normalize($name); $name = $normalize->normalize(); $name = preg_replace('/[^[:alnum:]\-]+/', $delimiter, $name); $name = preg_replace('/' . $delimiter . '+/', $delimiter, $name); $name = rtrim($name, $delimiter); $cleaned = isset($extension) ? $name . '.' . $extension : $name; return $cleaned; }
php
{ "resource": "" }
q266797
DispatcherAwareTrait.dispatch
test
final public function dispatch($name, EventInterface $event) { if ($this->hasDispatcher()) { $this->getDispatcher()->dispatch($name, $event); return true; } return false; }
php
{ "resource": "" }
q266798
Error.handle
test
public function handle($level, $message, $file, $line, $context) { if ( $this->level === 0 ) return true; if ( $level & (E_USER_DEPRECATED | E_DEPRECATED) ) { if (self::$logger !== null) { if ( version_compare(PHP_VERSION, '5.4', '<') ) { $stack = array_slice(debug_backtrace(false), 0, 10); } else { $stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10); } self::$logger->warning($message, array( 'type' => self::TYPE_DEPRECATION, 'stack' => $stack )); } return true; } if ( error_reporting() & $level && $this->level & $level ) { $this->generateErrorException($level, $message, $file, $line, false); } return true; }
php
{ "resource": "" }
q266799
Error.handleFatal
test
public function handleFatal() { $error = $this->getLastError(); if ($error === null) return; unset($this->reservedMemory); $type = $error['type']; if ( $this->level === 0 || !in_array($type, array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) { return; } // get current exception handler $exceptionHandler = set_exception_handler(function() {}); restore_exception_handler(); if ( is_array($exceptionHandler) && $exceptionHandler[0] instanceof Error ) { $this->generateErrorException($type, $error['message'], $error['file'], $error['line']); } }
php
{ "resource": "" }