_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q260500
Reflexion.get
test
public static function get($object, $property) { $property = self::getReflectionProperty($object, $property); if (is_string($object) || $property->isStatic()) { if (($declaringClass = $property->getDeclaringClass()->getName()) !== self::toClassName($object)) { return self::getReflectionProperty($declaringClass, $property->getName())->getValue(null); } return $property->getValue(null); } return $property->getValue($object); }
php
{ "resource": "" }
q260501
Reflexion.invoke
test
public static function invoke($object, $method, ...$params) { $method = self::getReflectionMethod($object, $method); if (is_string($object) || $method->isStatic()) { if (($declaringClass = $method->getDeclaringClass()->getName()) !== self::toClassName($object)) { return self::getReflectionMethod($declaringClass, $method->getName())->invokeArgs(null, $params); } return $method->invokeArgs(null, $params); } return $method->invokeArgs($object, $params); }
php
{ "resource": "" }
q260502
CacheStrategy.save
test
public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true) { return $this->uses()->save($keyName, $content, $lifetime, $stopBuffer); }
php
{ "resource": "" }
q260503
CacheStrategy.exists
test
public function exists($keyName = null, $lifetime = null) { return $this->uses()->exists($keyName, $lifetime); }
php
{ "resource": "" }
q260504
CurrencyMiddleware.getUserCurrency
test
protected function getUserCurrency(Request $request) { // Check request for currency $currency = $request->get('currency'); if ($currency && currency()->isActive($currency) === TRUE) { return $currency; } // Get currency from session $currency = $request->getSession()->get('igniter.currency'); if ($currency && currency()->isActive($currency) === TRUE) { return $currency; } return null; }
php
{ "resource": "" }
q260505
Coordinates.isEqual
test
public function isEqual(CoordinatesInterface $coordinate) { return bccomp($this->latitude, $coordinate->getLatitude(), $this->getPrecision()) === 0 AND bccomp($this->longitude, $coordinate->getLongitude(), $this->getPrecision()) === 0; }
php
{ "resource": "" }
q260506
EloquentBlock.render
test
public function render($name = null) { $args = func_get_args(); $args[] = config('app.locale'); return $this->executeCallback(static::class, __FUNCTION__, $args, function () use ($name) { $block = $this->prepareQuery($this->createModel()) ->where('name', $name) ->published() ->first(); return $block ? $block->present()->body : ''; }); }
php
{ "resource": "" }
q260507
EventEmitter.bindEvent
test
public function bindEvent($event, $callback, $priority = 0) { $this->emitterEvents[$event][$priority][] = $callback; unset($this->emitterEventSorted[$event]); return $this; }
php
{ "resource": "" }
q260508
EventEmitter.emitterEventSortEvents
test
protected function emitterEventSortEvents($eventName) { $this->emitterEventSorted[$eventName] = []; if (isset($this->emitterEvents[$eventName])) { krsort($this->emitterEvents[$eventName]); $this->emitterEventSorted[$eventName] = call_user_func_array('array_merge', $this->emitterEvents[$eventName]); } }
php
{ "resource": "" }
q260509
EventEmitter.unbindEvent
test
public function unbindEvent($event = null) { // Multiple events if (is_array($event)) { foreach ($event as $_event) { $this->unbindEvent($_event); } return; } if ($event === null) { unset($this->emitterSingleEvents); unset($this->emitterEvents); unset($this->emitterEventSorted); return $this; } if (isset($this->emitterSingleEvents[$event])) unset($this->emitterSingleEvents[$event]); if (isset($this->emitterEvents[$event])) unset($this->emitterEvents[$event]); if (isset($this->emitterEventSorted[$event])) unset($this->emitterEventSorted[$event]); return $this; }
php
{ "resource": "" }
q260510
EventEmitter.fireEvent
test
public function fireEvent($event, $params = [], $halt = FALSE) { if (!is_array($params)) $params = [$params]; $result = []; // Single events if (isset($this->emitterSingleEvents[$event])) { foreach ($this->emitterSingleEvents[$event] as $callback) { $response = call_user_func_array($callback, $params); if (is_null($response)) continue; if ($halt) return $response; $result[] = $response; } unset($this->emitterSingleEvents[$event]); } // Recurring events, with priority if (isset($this->emitterEvents[$event])) { if (!isset($this->emitterEventSorted[$event])) $this->emitterEventSortEvents($event); foreach ($this->emitterEventSorted[$event] as $callback) { $response = call_user_func_array($callback, $params); if (is_null($response)) continue; if ($halt) return $response; $result[] = $response; } } return $halt ? null : $result; }
php
{ "resource": "" }
q260511
InjectionAwareTrait.getDI
test
public function getDI() { if (!isset($this->_di)) { $this->setDI(Di::getDefault()); } return $this->_di; }
php
{ "resource": "" }
q260512
Header.has
test
public function has($name) { return isset($this->headers[$name]) || array_key_exists($name, $this->headers); }
php
{ "resource": "" }
q260513
Header.setHeaders
test
public function setHeaders(array $fields, $merge = false) { if ($merge) { $this->headers = array_merge($this->headers, $fields); } else { $this->headers = $fields; } return $this; }
php
{ "resource": "" }
q260514
Header.build
test
public function build() { $headers = []; foreach ($this->headers as $name => $value) { $headers[] = $name . ': ' . $value; } return $headers; }
php
{ "resource": "" }
q260515
Ellipsoid.checkCoordinatesEllipsoid
test
public static function checkCoordinatesEllipsoid(CoordinatesInterface $a, CoordinatesInterface $b) { if ($a->getEllipsoid() != $b->getEllipsoid()) { throw new GeoliteException('The ellipsoids for both coordinates must match !'); } }
php
{ "resource": "" }
q260516
ErrorHandler.getDetailedMessage
test
public static function getDetailedMessage($exception) { $message = $exception->getMessage(); if (!($exception instanceof ApplicationException) && Config::get('app.debug', FALSE)) { $message = sprintf('"%s" on line %s of %s', $exception->getMessage(), $exception->getLine(), $exception->getFile() ); $message .= $exception->getTraceAsString(); } return $message; }
php
{ "resource": "" }
q260517
ServerTask.mainAction
test
public function mainAction() { try { $host = $this->getHost(); $port = $this->getPort($host); $this->run($host, $port); } catch (\Exception $e) { $this->block([$e->getMessage()], 'error'); return; } }
php
{ "resource": "" }
q260518
Session.registering
test
public function registering() { $di = $this->getDI(); $di->set(Services::SESSION_BAG, Bag::class); $di->setShared(Services::SESSION, function () { /** @var \Phalcon\DiInterface $this */ $sessionConfig = $this->getShared(Services::CONFIG)->session; if (!isset($sessionConfig->adapter)) { if (!isset($sessionConfig->stores[$sessionConfig->default])) { throw new \RuntimeException("Session store {$sessionConfig->default} not found in stores"); } $sessionConfig = $sessionConfig->stores[$sessionConfig->default]; } $adapter = $sessionConfig->adapter; switch ($adapter){ case 'Aerospike': case 'Database': case 'HandlerSocket': case 'Mongo': case 'Files': case 'Libmemcached': case 'Memcache': case 'Redis': $class = 'Phalcon\Session\Adapter\\' . $adapter; break; case FilesAdapter::class: case LibmemcachedAdapter::class: case MemcacheAdapter::class: case RedisAdapter::class: $class = $adapter; break; default: $class = $adapter; if(!class_exists($adapter)){ throw new \RuntimeException("Session Adapter $class not found."); } } try { $options = []; if (!empty($sessionConfig->options)) { $options = $sessionConfig->options->toArray(); } /** @var \Phalcon\Session\Adapter|\Phalcon\Session\AdapterInterface $session */ $session = new $class($options); } catch (\Throwable $e) { throw new \RuntimeException("Session Adapter $class construction fail.", $e); } $session->start(); return $session; }); }
php
{ "resource": "" }
q260519
WorkingTime.toDateTime
test
public function toDateTime(DateTime $date = null): DateTime { if (!$date) { $date = new DateTime('1970-01-01 00:00:00'); } elseif (!($date instanceof DateTimeImmutable)) { $date = clone $date; } return $date->setTime($this->hours, $this->minutes); }
php
{ "resource": "" }
q260520
Preloader.prepareOutput
test
public function prepareOutput($file, $strict = false) { if ($strict && PHP_VERSION_ID < 70000) { throw new RuntimeException('Strict mode requires PHP 7 or greater.'); } $dir = dirname($file); if (!is_dir($dir) && !mkdir($dir, 0777, true)) { throw new RuntimeException("Unable to create directory $dir."); } $r = fopen($file, 'w'); if (!$r) { throw new RuntimeException("Unable to open $file for writing."); } if ($strict) { fwrite($r, "<?php declare(strict_types=1);\n"); } else { fwrite($r, "<?php\n"); } return $r; }
php
{ "resource": "" }
q260521
Preloader.getCode
test
public function getCode($file) { $stmts = $this->parse($file); $stmts = $this->traverse($stmts); $content = $this->prettyPrint($stmts); return $content; }
php
{ "resource": "" }
q260522
Preloader.parse
test
public function parse($file) { if (!is_string($file) || empty($file)) { throw new RuntimeException('Invalid filename provided.'); } if (!is_readable($file)) { throw new RuntimeException("Cannot open $file for reading."); } $content = php_strip_whitespace($file); return $this->parser->parse($content); }
php
{ "resource": "" }
q260523
Database.registering
test
public function registering() { $di = $this->getDI(); $database = (array)$di->getShared(Services::CONFIG)->database; $connections = (array)$database['connections']; if (count($connections) > 1) { $di->setShared(Services::DB, DatabaseStrategy::class); foreach ($connections as $name => $connection) { $di->setShared(Services::DB . '.' . $name, function () use ($connection) { return new $connection['adapter']((array)$connection['config']); }); } } else { $connection = array_shift($connections); $serviceName = Services::DB . '.' . $database['default']; $service = new Service($serviceName, function () use ($connection) { return new $connection['adapter']((array)$connection['config']); }, true); $di->setRaw($serviceName, $service); $di->setRaw(Services::DB, $service); } }
php
{ "resource": "" }
q260524
Builder.getNodeData
test
public function getNodeData($id, $required = FALSE) { $query = $this->toBase(); $query->where($this->model->getKeyName(), '=', $id); $data = $query->first([$this->model->getLftName(), $this->model->getRgtName()]); if (!$data && $required) { throw new ModelNotFoundException; } return (array)$data; }
php
{ "resource": "" }
q260525
Builder.whereAncestorOf
test
public function whereAncestorOf($id, $andSelf = FALSE, $boolean = 'and') { $keyName = $this->model->getKeyName(); if (NestedSet::isNode($id)) { $value = '?'; $this->query->addBinding($id->getRgt()); $id = $id->getKey(); } else { $valueQuery = $this->model ->newQuery() ->toBase() ->select("_.".$this->model->getRgtName()) ->from($this->model->getTable().' as _') ->where($keyName, '=', $id) ->limit(1); $this->query->mergeBindings($valueQuery); $value = '('.$valueQuery->toSql().')'; } $this->query->whereNested(function ($inner) use ($value, $andSelf, $id) { list($lft, $rgt) = $this->wrappedColumns(); $inner->whereRaw("{$value} between {$lft} and {$rgt}"); if (!$andSelf) { $inner->where($this->model->getKeyName(), '<>', $id); } }, $boolean); return $this; }
php
{ "resource": "" }
q260526
Builder.whereNodeBetween
test
public function whereNodeBetween($values, $boolean = 'and', $not = FALSE) { $this->query->whereBetween($this->model->getLftName(), $values, $boolean, $not); return $this; }
php
{ "resource": "" }
q260527
Builder.whereDescendantOf
test
public function whereDescendantOf($id, $boolean = 'and', $not = FALSE, $andSelf = FALSE ) { if (NestedSet::isNode($id)) { $data = $id->getBounds(); } else { $data = $this->model->newNestedSetQuery() ->getPlainNodeData($id, TRUE); } // Don't include the node if (!$andSelf) { ++$data[0]; } return $this->whereNodeBetween($data, $boolean, $not); }
php
{ "resource": "" }
q260528
Builder.descendantsOf
test
public function descendantsOf($id, array $columns = ['*'], $andSelf = FALSE) { try { return $this->whereDescendantOf($id, 'and', FALSE, $andSelf)->get($columns); } catch (ModelNotFoundException $e) { return $this->model->newCollection(); } }
php
{ "resource": "" }
q260529
Builder.withDepth
test
public function withDepth($as = 'depth') { if ($this->query->columns === null) $this->query->columns = ['*']; $table = $this->wrappedTable(); list($lft, $rgt) = $this->wrappedColumns(); $alias = '_d'; $wrappedAlias = $this->query->getGrammar()->wrapTable($alias); $query = $this->model ->newScopedQuery('_d') ->toBase() ->selectRaw('count(1) - 1') ->from($this->model->getTable().' as '.$alias) ->whereRaw("{$table}.{$lft} between {$wrappedAlias}.{$lft} and {$wrappedAlias}.{$rgt}"); $this->query->selectSub($query, $as); return $this; }
php
{ "resource": "" }
q260530
Builder.wrappedColumns
test
protected function wrappedColumns() { $grammar = $this->query->getGrammar(); return [ $grammar->wrap($this->model->getLftName()), $grammar->wrap($this->model->getRgtName()), ]; }
php
{ "resource": "" }
q260531
Builder.hasChildren
test
public function hasChildren() { list($lft, $rgt) = $this->wrappedColumns(); $this->query->whereRaw("{$rgt} > {$lft} + 1"); return $this; }
php
{ "resource": "" }
q260532
Builder.defaultOrder
test
public function defaultOrder($dir = 'asc') { $this->query->orders = null; $this->query->orderBy($this->model->getLftName(), $dir); return $this; }
php
{ "resource": "" }
q260533
Builder.moveNode
test
public function moveNode($key, $position) { list($lft, $rgt) = $this->model->newNestedSetQuery() ->getPlainNodeData($key, TRUE); if ($lft < $position && $position <= $rgt) { throw new LogicException('Cannot move node into itself.'); } // Get boundaries of nodes that should be moved to new position $from = min($lft, $position); $to = max($rgt, $position - 1); // The height of node that is being moved $height = $rgt - $lft + 1; // The distance that our node will travel to reach it's destination $distance = $to - $from + 1 - $height; // If no distance to travel, just return if ($distance === 0) { return 0; } if ($position > $lft) { $height *= -1; } else { $distance *= -1; } $params = compact('lft', 'rgt', 'from', 'to', 'height', 'distance'); $boundary = [$from, $to]; $query = $this->toBase()->where(function (Query $inner) use ($boundary) { $inner->whereBetween($this->model->getLftName(), $boundary); $inner->orWhereBetween($this->model->getRgtName(), $boundary); }); return $query->update($this->patch($params)); }
php
{ "resource": "" }
q260534
Builder.makeGap
test
public function makeGap($cut, $height) { $params = compact('cut', 'height'); $query = $this->toBase()->whereNested(function (Query $inner) use ($cut) { $inner->where($this->model->getLftName(), '>=', $cut); $inner->orWhere($this->model->getRgtName(), '>=', $cut); }); return $query->update($this->patch($params)); }
php
{ "resource": "" }
q260535
Builder.patch
test
protected function patch(array $params) { $grammar = $this->query->getGrammar(); $columns = []; foreach ([$this->model->getLftName(), $this->model->getRgtName()] as $col) { $columns[$col] = $this->columnPatch($grammar->wrap($col), $params); } return $columns; }
php
{ "resource": "" }
q260536
Builder.columnPatch
test
protected function columnPatch($col, array $params) { extract($params); /** @var int $height */ if ($height > 0) $height = '+'.$height; if (isset($cut)) { return new Expression("case when {$col} >= {$cut} then {$col}{$height} else {$col} end"); } /** @var int $distance */ /** @var int $lft */ /** @var int $rgt */ /** @var int $from */ /** @var int $to */ if ($distance > 0) $distance = '+'.$distance; return new Expression("case ". "when {$col} between {$lft} and {$rgt} then {$col}{$distance} ". // Move the node "when {$col} between {$from} and {$to} then {$col}{$height} ". // Move other nodes "else {$col} end" ); }
php
{ "resource": "" }
q260537
Builder.countErrors
test
public function countErrors() { $checks = []; // Check if lft and rgt values are ok $checks['oddness'] = $this->getOdnessQuery(); // Check if lft and rgt values are unique $checks['duplicates'] = $this->getDuplicatesQuery(); // Check if parent_id is set correctly $checks['wrong_parent'] = $this->getWrongParentQuery(); // Check for nodes that have missing parent $checks['missing_parent'] = $this->getMissingParentQuery(); $query = $this->query->newQuery(); foreach ($checks as $key => $inner) { $inner->selectRaw('count(1)'); $query->selectSub($inner, $key); } return (array)$query->first(); }
php
{ "resource": "" }
q260538
Builder.fixTree
test
public function fixTree() { $columns = [ $this->model->getKeyName(), $this->model->getParentIdName(), $this->model->getLftName(), $this->model->getRgtName(), ]; $dictionary = $this->model->newNestedSetQuery() ->defaultOrder() ->get($columns) ->groupBy($this->model->getParentIdName()) ->all(); return self::fixNodes($dictionary); }
php
{ "resource": "" }
q260539
Builder.rebuildTree
test
public function rebuildTree(array $data, $delete = FALSE) { if ($this->model->usesSoftDelete()) { $this->withTrashed(); } $existing = $this->get()->getDictionary(); $dictionary = []; $this->buildRebuildDictionary($dictionary, $data, $existing); if (!empty($existing)) { if ($delete && !$this->model->usesSoftDelete()) { $this->model ->newScopedQuery() ->whereIn($this->model->getKeyName(), array_keys($existing)) ->delete(); } else { foreach ($existing as $model) { $dictionary[$model->getParentId()][] = $model; if ($delete && $this->model->usesSoftDelete() && !$model->{$model->getDeletedAtColumn()} ) { $time = $this->model->fromDateTime($this->model->freshTimestamp()); $model->{$model->getDeletedAtColumn()} = $time; } } } } return $this->fixNodes($dictionary); }
php
{ "resource": "" }
q260540
Purgeable.bootPurgeable
test
public static function bootPurgeable() { if (!property_exists(get_called_class(), 'purgeable')) throw new Exception(sprintf( 'You must define a $purgeable property in %s to use the Purgeable trait.', get_called_class() )); /* * Remove any purge attributes from the data set */ static::extend(function ($model) { $model->bindEvent('model.saveInternal', function () use ($model) { $model->purgeAttributes(); }); }); }
php
{ "resource": "" }
q260541
Purgeable.addPurgeable
test
public function addPurgeable($attributes = null) { $attributes = is_array($attributes) ? $attributes : func_get_args(); $this->purgeable = array_merge($this->purgeable, $attributes); return $this; }
php
{ "resource": "" }
q260542
Purgeable.purgeAttributes
test
public function purgeAttributes($attributesToPurge = null) { if ($attributesToPurge !== null) { $purgeable = is_array($attributesToPurge) ? $attributesToPurge : [$attributesToPurge]; } else { $purgeable = $this->getPurgeableAttributes(); } $attributes = $this->getAttributes(); $cleanAttributes = array_diff_key($attributes, array_flip($purgeable)); $originalAttributes = array_diff_key($attributes, $cleanAttributes); if (is_array($this->originalPurgeableValues)) { $this->originalPurgeableValues = array_merge($this->originalPurgeableValues, $originalAttributes); } else { $this->originalPurgeableValues = $originalAttributes; } return $this->attributes = $cleanAttributes; }
php
{ "resource": "" }
q260543
Purgeable.getOriginalPurgeValue
test
public function getOriginalPurgeValue($attribute) { return isset($this->originalPurgeableValues[$attribute]) ? $this->originalPurgeableValues[$attribute] : null; }
php
{ "resource": "" }
q260544
SettingStore.get
test
public function get($key, $default = null) { $this->load(); return Arr::get($this->items, $key, $default); }
php
{ "resource": "" }
q260545
SettingStore.set
test
public function set($key, $value = null) { $this->load(); $this->unsaved = TRUE; if (is_array($key)) { foreach ($key as $k => $v) { Arr::set($this->items, $k, $v); } } else { Arr::set($this->items, $key, $value); } return $this; }
php
{ "resource": "" }
q260546
SettingStore.forget
test
public function forget($key) { $this->unsaved = TRUE; if ($this->has($key)) { Arr::forget($this->items, $key); } }
php
{ "resource": "" }
q260547
SettingStore.save
test
public function save() { if (!$this->unsaved) { // either nothing has been changed, or data has not been loaded, so // do nothing by returning early return; } $this->write($this->items); $this->unsaved = FALSE; }
php
{ "resource": "" }
q260548
SettingStore.load
test
public function load($force = FALSE) { if (!$this->loaded || $force) { $this->items = $this->read(); $this->loaded = TRUE; } }
php
{ "resource": "" }
q260549
StrExtension.compileFunction
test
public function compileFunction($name, $arguments, $funcArguments) { if (!Str::startsWith($name, 'str_') || function_exists($name)) { return null; } $name = substr($name, 4); if (method_exists(Str::class, $name) && Reflexion::getReflectionMethod(Str::class, $name)->isPublic()) { return Str::class . '::' . $name . '(' . $arguments . ')'; } return null; }
php
{ "resource": "" }
q260550
OptimizeTask.mainAction
test
public function mainAction() { if (APP_DEBUG && !$this->hasOption('f', 'force')) { $this->info('Application is in debug mode.'); $this->info('For optimize in debug please use the --force, -f option.'); return; } $this->optimizer = $this->getDI()->get(Composer::class, [ BASE_PATH . '/bootstrap/compile/loader.php', BASE_PATH . '/vendor/composer', BASE_PATH ]); if ($this->hasOption('m', 'memory')) { $this->optimizeMemory(); } else { $this->optimizeProcess(); } $this->optimizeClass(); foreach ($this->compileTasks as $compileTask) { $this->application->handle([ 'task' => $compileTask ]); } }
php
{ "resource": "" }
q260551
Throttle.after
test
public function after(Event $event, $source, $data = null) { $this->addHeader($this->resolveRequestSignature(), false); return true; }
php
{ "resource": "" }
q260552
Throttle.addHeader
test
protected function addHeader($signature, $tooManyAttempts = false) { /** @var \Phalcon\Http\Response $response */ $response = $this->getDI()->getShared(Services::RESPONSE); $limiter = $this->getLimiter(); $response->setHeader('X-RateLimit-Limit', $this->max); if ($tooManyAttempts) { $msg = StatusCode::message(StatusCode::TOO_MANY_REQUESTS); $response ->setContent($msg) ->setStatusCode(StatusCode::TOO_MANY_REQUESTS, $msg) ->setHeader('X-RateLimit-Remaining', 0) ->setHeader( 'Retry-After', $limiter->availableIn($signature, $this->decay) ); } else { $response->setHeader( 'X-RateLimit-Remaining', $limiter->retriesLeft($signature, $this->max, $this->decay) ); } }
php
{ "resource": "" }
q260553
Throttle.getLimiter
test
protected function getLimiter() { if (!isset($this->limiter)) { $this->limiter = $this->getDI()->get(RateLimiter::class, [$this->name]); } return $this->limiter; }
php
{ "resource": "" }
q260554
Message.update
test
public function update($attributes = []) { $attributes = array_filter($attributes); foreach ($attributes as $key => $attribute) { $this->$key = $attribute; } return $this; }
php
{ "resource": "" }
q260555
DatabaseMigrationRepository.log
test
public function log($file, $batch) { $record = ['migration' => $file, 'group' => $this->getGroup(), 'batch' => $batch]; $this->table()->insert($record); }
php
{ "resource": "" }
q260556
DatabaseMigrationRepository.createRepository
test
public function createRepository() { $schema = $this->getConnection()->getSchemaBuilder(); $method = (!$schema->hasTable($this->table)) ? 'create' : 'table'; $schema->$method($this->table, function (Blueprint $table) use ($method) { // Drop old columns from CI_Migration library if ($method == 'table') { $table->dropColumn('type'); $table->dropColumn('version'); } // The migrations table is responsible for keeping track of which of the // migrations have actually run for the application. We'll create the // table to hold the migration file's path as well as the batch ID. $table->increments('id'); $table->string('group'); $table->string('migration'); $table->integer('batch'); }); }
php
{ "resource": "" }
q260557
DatabaseMigrationRepository.table
test
protected function table() { return $this->getConnection() ->table($this->table) ->where('group', $this->getGroup()) ->useWritePdo(); }
php
{ "resource": "" }
q260558
NetteDatabaseHandler.getDatabaseName
test
public function getDatabaseName() { $dsn = $this->result->connection->getDsn(); $matches = []; if (preg_match('~\b(database|dbname)=(.*?)(;|$)~', $dsn, $matches)) { return $matches[2]; } return NULL; }
php
{ "resource": "" }
q260559
HtmlElementAbstract.setAttribute
test
public function setAttribute($key, $value = null) { if (is_null($value)) { $this->getAttributeMap()->remove($key); } else { $this->getAttributeMap()->set($key, $value); } return $this; }
php
{ "resource": "" }
q260560
HtmlElementAbstract.appendAttribute
test
public function appendAttribute($key, $value = null, $seperater = null) { if (!is_null($value)) { if ($this->getAttributeMap()->hasKey($key)) { if (strlen($seperater) > 0) { $values = array(); $values[] = $this->getAttributeMap()->get($key); $values[] = $value; $newValue = implode($seperater, $values); } else { $newValue = $this->getAttributeMap()->get($key) . $value; } } else { $newValue = $value; } $this->getAttributeMap()->set($key, $newValue); } return $this; }
php
{ "resource": "" }
q260561
HtmlElementAbstract.setContent
test
public function setContent($content) { if (!is_null($content)) { if ($content instanceof HtmlElementInterface) { $htmlElementObject = $content; } else { $htmlElementObject = new HtmlElementContent($content); } $this->getChildElementCollection()->clear(); $this->getChildElementCollection()->add($htmlElementObject); } return $this; }
php
{ "resource": "" }
q260562
HtmlElementAbstract.addContent
test
public function addContent($content = null) { if (!is_null($content)) { $htmlElementObject = new HtmlElementContent($content); $this->getChildElementCollection()->add($htmlElementObject); } return $this; }
php
{ "resource": "" }
q260563
ScaffoldServiceProvider.registerCommands
test
protected function registerCommands(array $commands) { foreach ($commands as $class => $command) { $this->{"register{$class}Command"}($command); } $this->commands(array_values($commands)); }
php
{ "resource": "" }
q260564
RouteCacheTask.mainAction
test
public function mainAction() { $this->output->write(Decorate::notice(str_pad('Generating http-routes cache', 40, ' ')), false); try { $router = $this->loadHttpRouter(); $str = $this->compile($router); file_put_contents(BASE_PATH . '/bootstrap/compile/http-routes.php', "<?php\n$str"); $this->info("Success"); } catch (\Exception $e) { $this->error("Error"); $this->block([$e->getMessage()], 'error'); @unlink(BASE_PATH . '/bootstrap/compile/http-routes.php'); } }
php
{ "resource": "" }
q260565
Db.getQueries
test
public static function getQueries(\Closure $callback, $pretend = false) { $db = Di::getDefault()->get(Services::DB); if (is_null($em = $db->getEventsManager())) { $db->setEventsManager($em = new Manager()); } $queries = []; $listener = function (Event $event, Adapter $db) use (&$queries, $pretend) { $queries[] = $db->getRealSQLStatement(); if ($pretend && $event->isCancelable()) { $event->stop(); } return !$pretend; }; $em->attach(Events\Db::BEFORE_QUERY, $listener); $callback(); $em->detach(Events\Db::BEFORE_QUERY, $listener); return $queries; }
php
{ "resource": "" }
q260566
RateLimiter.tooManyAttempts
test
public function tooManyAttempts($key, $maxAttempts, $decaySeconds = 1) { /** @var \Neutrino\Cache\CacheStrategy $cache */ $cache = $this->{Services::CACHE}; if ($cache->exists($this->name . $key . $this->klock, $decaySeconds)) { return true; } if ($this->attempts($key, $decaySeconds) >= $maxAttempts) { $cache->save( $this->name . $key . $this->klock, time() + ($decaySeconds), $decaySeconds ); $this->resetAttempts($key); return true; } return false; }
php
{ "resource": "" }
q260567
RateLimiter.hit
test
public function hit($key, $decaySeconds = 1) { $key = $this->name . $key; /** @var \Neutrino\Cache\CacheStrategy $cache */ $cache = $this->{Services::CACHE}; if (!$cache->exists($key, $decaySeconds)) { $cache->save($key, 0, $decaySeconds); } $value = (int)$cache->get($key, $decaySeconds); $value++; $cache->save($key, $value, $decaySeconds); return $value; }
php
{ "resource": "" }
q260568
RateLimiter.attempts
test
public function attempts($key, $decaySeconds = 1) { $value = $this->{Services::CACHE}->get($this->name . $key, $decaySeconds); return is_null($value) ? 0 : (int)$value; }
php
{ "resource": "" }
q260569
RateLimiter.clear
test
public function clear($key) { $this->resetAttempts($key); $this->{Services::CACHE}->delete($this->name . $key . $this->klock); }
php
{ "resource": "" }
q260570
RateLimiter.availableIn
test
public function availableIn($key, $decaySeconds) { $time = $this->{Services::CACHE}->get($this->name . $key . $this->klock, $decaySeconds); return $time - time(); }
php
{ "resource": "" }
q260571
DotconstCacheTask.mainAction
test
public function mainAction() { $this->output->write(Decorate::notice(str_pad('Generating dotconst cache', 40, ' ')), false); try { self::generateCache(); $this->info("Success"); } catch (\Exception $e) { $this->error("Error"); $this->block([$e->getMessage()], 'error'); } }
php
{ "resource": "" }
q260572
FilesystemServiceProvider.registerNativeFilesystem
test
protected function registerNativeFilesystem() { $this->app->singleton('files', function () { $config = $this->app['config']; $files = new Filesystem; $files->filePermissions = $config->get('system.filePermissions', null); $files->folderPermissions = $config->get('system.folderPermissions', null); $files->pathSymbols = [ '$' => $config->get('system.extensionsPath', base_path('extensions')), '~' => base_path(), ]; return $files; }); }
php
{ "resource": "" }
q260573
Facade.swap
test
public static function swap($instance) { self::$resolvedInstance[static::getFacadeAccessor()] = $instance; static::$di->setShared(static::getFacadeAccessor(), $instance); }
php
{ "resource": "" }
q260574
Facade.shouldReceive
test
public static function shouldReceive(...$params) { $name = static::getFacadeAccessor(); if (static::isMock()) { $mock = self::$resolvedInstance[$name]; } else { $mock = static::createFreshMockInstance(); } return $mock->shouldReceive(...$params); }
php
{ "resource": "" }
q260575
Facade.createFreshMockInstance
test
protected static function createFreshMockInstance() { $name = static::getFacadeAccessor(); self::$resolvedInstance[$name] = $mock = static::createMockInstance(); $mock->shouldAllowMockingProtectedMethods(); if (isset(static::$di)) { static::$di->setShared($name, $mock); } return $mock; }
php
{ "resource": "" }
q260576
Facade.isMock
test
protected static function isMock() { $name = static::getFacadeAccessor(); return isset(self::$resolvedInstance[$name]) && self::$resolvedInstance[$name] instanceof MockInterface; }
php
{ "resource": "" }
q260577
Facade.resolveFacadeInstance
test
protected static function resolveFacadeInstance($name) { if (is_object($name)) { return $name; } if (isset(self::$resolvedInstance[$name])) { return self::$resolvedInstance[$name]; } return self::$resolvedInstance[$name] = static::$di->getShared($name); }
php
{ "resource": "" }
q260578
Processor.processSelect
test
public function processSelect(Finder $finder, $result) { if ($result === null) { return null; } $fileName = array_get($result, 'fileName'); return [$fileName => $this->parseTemplateContent($result, $fileName)]; }
php
{ "resource": "" }
q260579
Processor.processSelectAll
test
public function processSelectAll(Finder $finder, $results) { if (!count($results)) { return []; } $items = []; foreach ($results as $result) { $fileName = array_get($result, 'fileName'); $items[$fileName] = $this->parseTemplateContent($result, $fileName); } return $items; }
php
{ "resource": "" }
q260580
Processor.parseTemplateContent
test
protected function parseTemplateContent($result, $fileName) { $content = array_get($result, 'content'); $processed = FileParser::parse($content); $content = [ 'fileName' => $fileName, 'mTime' => array_get($result, 'mTime'), 'content' => $content, 'markup' => $processed['markup'], 'code' => $processed['code'], ]; if (!empty($processed['data'])) $content = $content + $processed['data']; return $content; }
php
{ "resource": "" }
q260581
Processor.processUpdate
test
public function processUpdate(Finder $finder, $data) { $existingData = $finder->getModel()->attributesToArray(); return FileParser::render($data + $existingData); }
php
{ "resource": "" }
q260582
Listener.attach
test
public function attach() { $em = $this->getEventsManager(); if (!empty($this->space)) { foreach ($this->space as $space) { $em->attach($space, $this); } } if (!empty($this->listen)) { foreach ($this->listen as $event => $callback) { if (!method_exists($this, $callback)) { throw new \RuntimeException( "Method '$callback' not exist in " . get_class($this) ); } $this->closures[$event] = $closure = function (Event $event, $handler, $data = null) use ($callback) { return $this->$callback($event, $handler, $data); }; $em->attach($event, $closure); } } }
php
{ "resource": "" }
q260583
Listener.detach
test
public function detach() { $em = $this->getEventsManager(); if (!empty($this->space)) { foreach ($this->space as $space) { $em->detach($space, $this); } } foreach ($this->closures as $event => $closure) { $em->detach($event, $closure); } $this->closures = []; }
php
{ "resource": "" }
q260584
NominatimProvider.geocodeQuery
test
public function geocodeQuery(GeoQueryInterface $query): Collection { $url = sprintf( array_get($this->config, 'endpoints.geocode'), urlencode($query->getText()), $query->getLimit() ); $result = []; try { $result = $this->cacheCallback($url, function () use ($query, $url) { return $this->hydrateResponse( $this->requestUrl($url, $query) ); }); } catch (Throwable $ex) { $this->log(sprintf( 'Provider "%s" could not geocode address, "%s".', $this->getName(), $ex->getMessage() )); } return new Collection($result); }
php
{ "resource": "" }
q260585
NominatimProvider.reverseQuery
test
public function reverseQuery(GeoQueryInterface $query): Collection { $coordinates = $query->getCoordinates(); $url = sprintf( array_get($this->config, 'endpoints.reverse'), $coordinates->getLatitude(), $coordinates->getLongitude(), $query->getData('zoom', 18) ); $result = []; try { $result = $this->cacheCallback($url, function () use ($query, $url) { return $this->hydrateResponse( $this->requestUrl($url, $query) ); }); } catch (Throwable $e) { $coordinates = $query->getCoordinates(); $this->log(sprintf( 'Provider "%s" could not reverse coordinates: "%f %f".', $this->getName(), $coordinates->getLatitude(), $coordinates->getLongitude() )); } return new Collection($result); }
php
{ "resource": "" }
q260586
StatusTask.getStatusFor
test
protected function getStatusFor(array $ran) { return array_map(function ($migration) use ($ran) { $migrationName = $this->migrator->getMigrationName($migration); return [ 'Ran?' => in_array($migrationName, $ran) ? Decorate::info('Y') : Decorate::apply('N', 'red'), 'Migration' => $migrationName ]; }, $this->getAllMigrationFiles()); }
php
{ "resource": "" }
q260587
RouteListTask.mainAction
test
public function mainAction() { $infos = $this->getHttpRoutesInfos(); $datas = []; foreach ($infos['routes'] as $route) { /** @var \Phalcon\Mvc\Router\Route $route */ $paths = $route->getPaths(); if (!$this->hasOption('no-substitution')) { $compiled = Helper::describeRoutePattern($route, true); } else { $compiled = $route->getPattern(); } $httpMethods = $route->getHttpMethods(); if (is_array($httpMethods)) { $httpMethods = implode('|', $httpMethods); } $middlewares = Arr::fetch($paths, 'middleware'); if (is_array($middlewares)) { $_middlewares = []; foreach ($middlewares as $key => $middleware) { if (is_int($key)) { $_middlewares[] = $middleware; } else { $_middlewares[] = $key; } } $middleware = implode('|', $_middlewares); } else { $middleware = $middlewares; } if (Arr::has($paths, 'controller')) { $controller = Str::capitalize($paths['controller']); } else { $controller = Decorate::notice('{controller}'); } $controller .= Arr::fetch($infos, 'controllerSuffix', ''); if (Arr::has($paths, 'action')) { $action = $paths['action']; } else { $action = Decorate::notice('{action}'); } $action .= Arr::fetch($infos, 'actionSuffix', ''); $module = Arr::get($paths, 'module'); $namespace = Arr::fetch($paths, 'namespace', Arr::fetch($infos['defaults'], 'namespace')); $datas[$module . '::' . $namespace][] = [ 'domain' => $route->getHostname(), 'name' => $route->getName(), 'method' => $httpMethods, 'pattern' => $compiled, 'action' => $controller . '::' . $action, 'middleware' => $middleware ]; } foreach ($datas as $key => $data) { $parts = explode('::', $key, 2); $this->table([['MODULE : '.$parts[0]],['NAMESPACE : ' . $parts[1]]], [], Table::NO_HEADER); $this->table($data); $this->line(''); } }
php
{ "resource": "" }
q260588
RouteListTask.getHttpRoutesInfos
test
protected function getHttpRoutesInfos() { Router::clearResolvedInstances(); $cliRouter = $this->router; $cliDispatcher = $this->dispatcher; $this->di->remove(Services::ROUTER); $this->di->remove(Services::DISPATCHER); $httpRouterProvider = new \Neutrino\Providers\Http\Router; $httpRouterProvider->registering(); $httpDispatcherProvider = new \Neutrino\Providers\Http\Dispatcher; $httpDispatcherProvider->registering(); require BASE_PATH . '/routes/http.php'; /** @var \Phalcon\Mvc\Dispatcher $httpDispatcher */ $httpDispatcher = $this->di->get(Services::DISPATCHER); $reflexionProperty = (new \ReflectionClass(get_class($httpDispatcher)))->getProperty('_handlerSuffix'); $reflexionProperty->setAccessible(true); $routes = Router::getRoutes(); $defaults = Router::getDefaults(); $actionSuffix = $httpDispatcher->getActionSuffix(); $controllerSuffix = $reflexionProperty->getValue($httpDispatcher); Router::clearResolvedInstances(); $this->di->remove(Services::ROUTER); $this->di->remove(Services::DISPATCHER); $this->di->setShared(Services::ROUTER, $cliRouter); $this->di->setShared(Services::DISPATCHER, $cliDispatcher); return [ 'routes' => $routes, 'defaults' => $defaults, 'actionSuffix' => $actionSuffix, 'controllerSuffix' => $controllerSuffix, ]; }
php
{ "resource": "" }
q260589
Curl.curlOptions
test
protected function curlOptions($ch) { $method = $this->method; if ($method === Method::HEAD) { curl_setopt($ch, CURLOPT_NOBODY, true); } // Default Options curl_setopt_array($ch, [ CURLOPT_URL => $this->uri->build(), CURLOPT_CUSTOMREQUEST => $method, CURLOPT_AUTOREFERER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 20, CURLOPT_HEADER => $this->fullResponse, CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_HEADERFUNCTION => [$this, 'curlHeaderFunction'], ]); curl_setopt_array($ch, $this->options); }
php
{ "resource": "" }
q260590
Curl.curlInfos
test
protected function curlInfos($ch) { $this->response->setCode(curl_getinfo($ch, CURLINFO_HTTP_CODE)); if (($errno = curl_errno($ch)) !== 0) { $this->response->setErrorCode(curl_errno($ch)); $this->response->setError(curl_error($ch)); } $this->response->setProviderDatas(curl_getinfo($ch)); }
php
{ "resource": "" }
q260591
Compile.compile
test
public static function compile($basePath, $compilePath) { $extensions = Dotconst::getExtensions(); $raw = Loader::loadRaw($basePath); $config = Loader::fromFiles($basePath); $r = fopen($compilePath . '/consts.php', 'w'); if ($r === false) { throw new InvalidFileException('Can\'t create file : ' . $compilePath); } fwrite($r, "<?php" . PHP_EOL); $nested = []; foreach ($raw as $const => $value) { foreach ($extensions as $k => $extension) { if(is_string($extension)){ $extensions[$k] = $extension = new $extension; } if ($extension->identify($value)) { fwrite($r, "define('$const', " . $extension->compile($value, $basePath, $compilePath) . ");" . PHP_EOL); continue 2; } } if (preg_match('#^@\{(\w+)\}@?#', $value, $match)) { $key = strtoupper($match[1]); $value = preg_replace('#^@\{(\w+)\}@?#', '', $value); $draw = ''; $require = null; if(isset($config[$key])){ $draw .= $key; $require = $key; } else { $draw .= $match[1] ; } if(!empty($value)){ $draw .= " . '$value'"; } $nested[$const] = ['draw' => $draw, 'require' => $require]; continue; } fwrite($r, "define('$const', " . var_export($value, true) . ");" . PHP_EOL); } $nested = Helper::nestedConstSort($nested); foreach ($nested as $const => $item) { fwrite($r, "define('$const', {$item['draw']});" . PHP_EOL); } fclose($r); }
php
{ "resource": "" }
q260592
Process.start
test
public function start() { $this->spec = [ // 0 => ['pipe', 'w+'], 1 => fopen('php://temp/maxmemory:' . (1024 * 1024), 'w+'), 2 => fopen('php://temp/maxmemory:' . (1024 * 1024), 'w+'), ]; if ('\\' === DIRECTORY_SEPARATOR) { $this->options = array_merge(['bypass_shell' => true], (array)$this->options); } /** @var Error $error */ $error = null; set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) { $error = Error::fromError($errno, $errstr, $errfile, $errline); }); $this->proc = proc_open($this->cmd, $this->spec, $this->pipes, $this->cwd, null, $this->options); restore_error_handler(); $this->pipes = $this->spec; if (!is_null($error)) { throw new Exception('Can\'t create process', 0, new Exception($error->message, $error->code)); } if (!$this->isRunning()) { throw new Exception('Can\'t create process'); } return $this; }
php
{ "resource": "" }
q260593
Process.wait
test
public function wait($timeout = null, $step = 1000) { $withTimeout = false === is_null($timeout); if ($withTimeout) { $start = microtime(true); if ($timeout < $step) { $step = $timeout; } } while ($this->isRunning()) { usleep($step * 1000); if ($withTimeout && ($start + $timeout) > microtime(true)) { return; } } }
php
{ "resource": "" }
q260594
Process.stop
test
public function stop($timeout = 1000) { $timeout = microtime(true) + ($timeout * 1000); if ($this->isRunning()) { proc_terminate($this->proc); } while ($this->isRunning() && microtime(true) < $timeout) { usleep(1000); } $this->readOutput(); $this->readError(); return $this; }
php
{ "resource": "" }
q260595
Process.close
test
public function close() { $this->stop(0); if (is_resource($this->proc)) { proc_close($this->proc); } foreach ($this->pipes as $pipe) { if (is_resource($pipe)) { fclose($pipe); } } }
php
{ "resource": "" }
q260596
Process.exec
test
public function exec($timeout = null) { try { $this->start(); $this->wait($timeout, 500); if ($this->isRunning()) { throw new Timeout; } } finally { $this->close(); } }
php
{ "resource": "" }
q260597
Composer.optimizeMemory
test
public function optimizeMemory() { $this->composer->dumpautoload(false); $files = $this->autoload->getFiles(); $namespaces = $this->autoload->getNamespaces(); $psr = $this->autoload->getPsr4(); $classes = $this->autoload->getClassmap(); $_namespaces = []; $_dirs = []; foreach ($namespaces as $namespace => $directories) { $_namespaces[trim($namespace, '\\')] = $directories; foreach ($directories as $directory) { $_dirs[$directory] = $directory; } } foreach ($psr as $namespace => $dir) { $_namespaces[trim($namespace, '\\')] = $dir; } return $this->generateOutput($files, $_namespaces, $_dirs, $classes); }
php
{ "resource": "" }
q260598
Composer.generateOutput
test
protected function generateOutput($files = null, $namespaces = null, $directories = null, $classmap = null) { $res = fopen($this->loaderFilePath, 'w'); if ($res == false) { return false; } fwrite($res, '<?php' . "\n"); if (isset($this->basePath)) { $relativePath = Path::findRelative(dirname($this->loaderFilePath), $this->basePath); fwrite($res, '$basePath = __DIR__ . ' . var_export('/' . $relativePath . '/', true) . ";\n"); } fwrite($res, '$loader = new Phalcon\Loader;' . "\n"); if (Version::getPart(Version::VERSION_MAJOR) >= 3 && Version::getPart(Version::VERSION_MEDIUM) >= 4) { fwrite($res, '$loader->setFileCheckingCallback("stream_resolve_include_path");' . "\n"); } if (!empty($files)) { fwrite($res, '$loader->registerFiles(' . $this->prepareOutput(array_values($files)) . ');' . "\n"); } if (!empty($directories)) { fwrite($res, '$loader->registerDirs(' . $this->prepareOutput(array_values($directories)) . ');' . "\n"); } if (!empty($namespaces)) { fwrite($res, '$loader->registerNamespaces(' . $this->prepareOutput($namespaces) . ');' . "\n"); } if (!empty($classmap)) { fwrite($res, '$loader->registerClasses(' . $this->prepareOutput($classmap) . ');' . "\n"); } fwrite($res, '$loader->register();' . "\n"); fclose($res); return true; }
php
{ "resource": "" }
q260599
Obj.fill
test
public static function fill(&$target, $key, $value) { return self::set($target, $key, $value, false); }
php
{ "resource": "" }