_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q260300 | Media.getPublicPath | test | public function getPublicPath()
{
$mediaPath = config('system.assets.attachment.path', '/storage/app/attachments');
$mediaPath = $this->isPublic()
? $mediaPath.'/public'
: $mediaPath.'/protected';
return URL::asset($mediaPath).'/';
} | php | {
"resource": ""
} |
q260301 | Media.getTempPath | test | public function getTempPath()
{
$path = temp_path().'/attachments';
if (!File::isDirectory($path))
File::makeDirectory($path, 0777, TRUE, TRUE);
return $path;
} | php | {
"resource": ""
} |
q260302 | PostgresqlTrait.typeEnum | test | public function typeEnum(Fluent $column)
{
$values = array_map(function ($a) {
return "'{$a}'";
}, $column->get('values'));
$maxlen = 0;
foreach ($values as $value) {
$maxlen = max($maxlen, strlen($value));
}
return [
'type' => "varchar($maxlen) check (\"{$column->get('name')}\" in (" . implode(', ', $values) . '))',
'typeReference' => -1
];
} | php | {
"resource": ""
} |
q260303 | PostgresqlTrait.typeTime | test | public function typeTime(Fluent $column)
{
if (!empty($column['precision'])) {
return [
'type' => $this->compileTimableColumn($column, 'TIME'),
'typeReference' => Column::TYPE_DATETIME,
];
}
return $this->_typeTime($column);
} | php | {
"resource": ""
} |
q260304 | PostgresqlTrait.typeTimestamp | test | public function typeTimestamp(Fluent $column)
{
if (!empty($column['precision'])) {
return [
'type' => $this->compileTimableColumn($column, 'TIMESTAMP'),
'typeReference' => Column::TYPE_TIMESTAMP,
];
}
return $this->_typeTimestamp($column);
} | php | {
"resource": ""
} |
q260305 | Streaming.curlWriteFunction | test | protected function curlWriteFunction($ch, $content)
{
if (!$this->hasStarted) {
$this->hasStarted = true;
$this->getEventsManager()->fire(self::EVENT_START, $this);
}
$length = strlen($content);
$this->getEventsManager()->fire(self::EVENT_PROGRESS, $this, $content);
return $length;
} | php | {
"resource": ""
} |
q260306 | AssetsJsTask.mainAction | test | public function mainAction()
{
$this->line('Compiling js... ');
$options = $this->config->assets->js->toArray();
$result = $this->getDI()->get(ClosureCompiler::class)->compile($options);
if (!empty($result['errors'])) {
$this->outputErrors($result['errors'], 'errors', 'error', $options);
}
if (!empty($result['warnings'])) {
$this->outputErrors($result['warnings'], 'warnings', 'warn', $options);
}
$this->block([str_pad(strtoupper('STATISTICS'), 40, ' ', STR_PAD_BOTH)], 'question', 4);
$statistics = [];
foreach ($result['statistics'] as $type => $statistic) {
$statistics[] = ['stats' => $type, 'value' => $statistic];
}
$this->table($statistics);
$this->info('Success');
} | php | {
"resource": ""
} |
q260307 | RegisterTastyIgniter.bootstrap | test | public function bootstrap(Application $app)
{
// Workaround for CLI and URL based in subdirectory
if ($app->runningInConsole()) {
$app['url']->forceRootUrl($app['config']->get('app.url'));
}
// Register singletons
$app->singleton('string', function () {
return new \Igniter\Flame\Support\StrHelper;
});
// Change extensions and themes paths based on config
if ($extensionsPath = $app['config']->get('system.extensionsPath'))
$app->useExtensionsPath($extensionsPath);
if ($themesPath = $app['config']->get('system.themesPath'))
$app->useThemesPath($themesPath);
if ($assetsPath = $app['config']->get('system.assetsPath'))
$app->useAssetsPath($assetsPath);
// Set execution context
$requestPath = $this->normalizeUrl($app['request']->path());
$adminUri = $this->normalizeUrl($app['config']->get('system.adminUri', 'admin'));
$app->setAppContext(starts_with($requestPath, $adminUri) ? 'admin' : 'main');
} | php | {
"resource": ""
} |
q260308 | RegisterTastyIgniter.normalizeUrl | test | protected function normalizeUrl($url)
{
if (substr($url, 0, 1) != '/')
$url = '/'.$url;
if (!strlen($url))
$url = '/';
return $url;
} | php | {
"resource": ""
} |
q260309 | Router.add | test | public function add($pattern, $paths = null, $httpMethods = null)
{
foreach ($httpMethods as $httpMethod) {
$this->application->{strtolower($httpMethod)}($pattern, $this->pathToHandler($paths));
}
return null;
} | php | {
"resource": ""
} |
q260310 | Router.addGet | test | public function addGet($pattern, $paths = null)
{
return $this->application->get($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260311 | Router.addPost | test | public function addPost($pattern, $paths = null)
{
return $this->application->post($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260312 | Router.addPut | test | public function addPut($pattern, $paths = null)
{
return $this->application->put($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260313 | Router.addPatch | test | public function addPatch($pattern, $paths = null)
{
return $this->application->patch($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260314 | Router.addDelete | test | public function addDelete($pattern, $paths = null)
{
return $this->application->delete($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260315 | Router.addOptions | test | public function addOptions($pattern, $paths = null)
{
return $this->application->options($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260316 | Router.addHead | test | public function addHead($pattern, $paths = null)
{
return $this->application->head($pattern, $this->pathToHandler($paths));
} | php | {
"resource": ""
} |
q260317 | Template.render | test | public function render($context = [])
{
$this->mergeGlobals($context);
unset($context['this']);
$obLevel = ob_get_level();
ob_start();
extract($context);
// We'll evaluate the contents of the view inside a try/catch block so we can
// flush out any stray output that might get out before an error occurs or
// an exception is thrown. This prevents any partial views from leaking.
try {
$filePath = $this->path;
include $filePath;
}
catch (Exception $e) {
$this->handleException($e, $obLevel);
}
catch (Throwable $e) {
$this->handleException(new FatalThrowableError($e), $obLevel);
}
return ob_get_clean();
} | php | {
"resource": ""
} |
q260318 | SourceResolver.source | test | public function source($name = null)
{
if (is_null($name)) {
$name = $this->getDefaultSourceName();
}
return $this->sources[$name];
} | php | {
"resource": ""
} |
q260319 | MigrationCreator.create | test | public function create($name, $path, $table = null, $create = false)
{
$this->ensureMigrationDoesntAlreadyExist($name, $path);
$stub = $this->getStubContent($table, $create);
$populatedStub = $this->populateStub($name, $stub, $table);
$path = $this->getPath($name, $path);
file_put_contents($path, $populatedStub);
return $path;
} | php | {
"resource": ""
} |
q260320 | MigrationCreator.ensureMigrationDoesntAlreadyExist | test | protected function ensureMigrationDoesntAlreadyExist($name, $path)
{
if (class_exists($className = $this->getClassName($name))) {
throw new InvalidArgumentException("A {$className} class already exists.");
}
// TODO Review check for version 2.0
if(!empty($files = glob($path . '/*_*.php'))){
foreach ($files as $file) {
$file = str_replace('.php', '', basename($file));
$migration = $this->prefix->deletePrefix($file);
if($className === $this->getClassName($migration)){
throw new InvalidArgumentException("A {$className} class already exists.");
}
}
}
} | php | {
"resource": ""
} |
q260321 | MigrationCreator.getStubContent | test | protected function getStubContent($table, $create)
{
if (is_null($table)) {
$file = $this->stubsPath() . '/blank.stub';
} else {
$stub = $create ? 'create.stub' : 'update.stub';
$file = $this->stubsPath() . '/' . $stub;
}
return file_get_contents($file);
} | php | {
"resource": ""
} |
q260322 | MigrationCreator.getPath | test | protected function getPath($name, $path)
{
if (!is_null($prefix = $this->prefix->getPrefix())) {
$prefix .= '_';
}
return $path . '/' . $prefix . $name . '.php';
} | php | {
"resource": ""
} |
q260323 | Activity.scopeCausedBy | test | public function scopeCausedBy(Builder $query, Model $causer)
{
return $query
->where('causer_type', $causer->getMorphClass())
->where('causer_id', $causer->getKey());
} | php | {
"resource": ""
} |
q260324 | Activity.scopeForSubject | test | public function scopeForSubject(Builder $query, Model $subject)
{
return $query
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey());
} | php | {
"resource": ""
} |
q260325 | ConfigRewrite.buildArrayExpression | test | protected function buildArrayExpression($targetKey, $arrayItems = [])
{
$expression = [];
// Opening expression for array items ($1)
$expression[] = $this->buildArrayOpeningExpression($arrayItems);
// The target key opening ($2)
$expression[] = '([\'|"]'.$targetKey.'[\'|"]\s*=>\s*)';
// The target value to be replaced ($3)
$expression[] = '(?:[aA][rR]{2}[aA][yY]\(|[\[])([^\]|)]*)[\]|)]';
return '/'.implode('', $expression).'/';
} | php | {
"resource": ""
} |
q260326 | BaseTask.getMigrationPaths | test | protected function getMigrationPaths()
{
// Here, we will check to see if a path option has been defined. If it has we will
// use the path relative to the root of the installation folder so our database
// migrations may be run for any customized path from within the application.
if ($this->hasOption('path') && $this->getOption('path')) {
return array_map(function ($path) {
return BASE_PATH . '/' . $path;
}, (array)$this->getOption('path'));
}
return array_merge(
[$this->getMigrationPath()], $this->migrator->paths()
);
} | php | {
"resource": ""
} |
q260327 | ViewClearTask.mainAction | test | public function mainAction()
{
$compileDir = $this->config->view->compiled_path;
$this->rm($compileDir);
$this->info('Compiled views cleared!');
} | php | {
"resource": ""
} |
q260328 | Request.setParams | test | public function setParams($parameters, $merge = false)
{
if ($merge) {
$this->params = array_merge($this->params, $parameters);
} else {
$this->params = $parameters;
}
return $this;
} | php | {
"resource": ""
} |
q260329 | Request.setHeaders | test | public function setHeaders($headers, $merge = false)
{
$this->header->setHeaders($headers, $merge);
return $this;
} | php | {
"resource": ""
} |
q260330 | Request.setProxy | test | public function setProxy($host, $port = 8080, $access = null)
{
$this->proxy = [
'host' => $host,
'port' => $port,
'access' => $access,
];
return $this;
} | php | {
"resource": ""
} |
q260331 | Request.setCookies | test | public function setCookies($cookies, $merge = false)
{
if ($merge) {
$this->cookies = array_merge($this->cookies, $cookies);
} else {
$this->cookies = $cookies;
}
return $this;
} | php | {
"resource": ""
} |
q260332 | Request.setCookie | test | public function setCookie($key, $value)
{
if (is_null($key)) {
$this->cookies[] = $value;
} else {
$this->cookies[$key] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q260333 | Request.setOptions | test | public function setOptions($options, $merge = false)
{
if ($merge) {
$this->options = array_merge($this->options, $options);
} else {
$this->options = $options;
}
return $this;
} | php | {
"resource": ""
} |
q260334 | Request.send | test | public function send()
{
$this
->buildParams()
->buildProxy()
->buildCookies()
->buildHeaders();
$this->response = new Response();
return $this->makeCall();
} | php | {
"resource": ""
} |
q260335 | Request.request | test | public function request($method, $uri, array $params = [], array $options = [])
{
$this
->setMethod($method)
->setUri($uri);
if (!empty($params)) {
$this->setParams($params, true);
}
if (!empty($options['headers'])) {
$this->setHeaders($options['headers'], true);
}
if (isset($options['full'])) {
$this->setFullResponse($options['full']);
}
if (isset($options['json'])) {
$this->setJsonRequest($options['json']);
}
return $this;
} | php | {
"resource": ""
} |
q260336 | Blueprint.build | test | public function build(Db $db, DialectInterface $grammar)
{
switch ($this->action) {
case 'create':
return $this->buildCreate($db, $grammar);
case 'update':
return $this->buildUpdate($db, $grammar);
case 'dropIfExists':
return $this->buildDrop($db, true);
case 'drop':
return $this->buildDrop($db, false);
case 'raw':
return $this->buildRaw($db, $grammar);
default:
if (empty($this->action)) {
$message = "Blueprint must has action";
} else {
$message = "Action '{$this->action}' not supported.";
}
throw new \RuntimeException($message);
}
} | php | {
"resource": ""
} |
q260337 | Blueprint.buildTableDefinition | test | protected function buildTableDefinition(DialectInterface $grammar)
{
// Manage primary key / multiple primary keys
$primaries = [];
// Extract defined primary index
foreach ($this->indexes as $key => $index) {
if ($index->get('type') == 'PRIMARY') {
foreach ($index->get('columns') as $column) {
$this->columns[$column]->primary();
}
unset($this->indexes[$key]);
}
}
// Extract defined primary column
foreach ($this->columns as $column) {
if ($column->get('primary')) {
$primaries[] = $column->get('name');
unset($column['primary']);
}
}
// Re-Build primary index
if (($cprimaries = count($primaries)) === 1) {
$this->columns[array_shift($primaries)]->primary();
} elseif ($cprimaries > 0) {
$this->primary($primaries);
}
// Build table definition
$definition = [];
foreach ($this->columns as $column) {
$definition['columns'][] = $this->fluentToColumn($column, $grammar);
}
foreach ($this->indexes as $index) {
$definition['indexes'][] = $this->fluentToIndex($index, $grammar);
}
foreach ($this->references as $reference) {
$definition['references'][] = $this->fluentToReference($reference);
}
foreach ($this->options as $name => $value) {
$definition['options'][strtoupper($name)] = $value;
}
return $definition;
} | php | {
"resource": ""
} |
q260338 | Blueprint.buildCommands | test | protected function buildCommands(Db $db)
{
$columns = $db->describeColumns($this->table, $this->schema);
foreach ($this->columns as $column) {
$this->buildIndexAndForeignFromFluentColumn($column);
foreach ($columns as $c) {
if ($c->getName() === $column->get('name')) {
$this->addCommand('modifyColumn', ['column' => $column, 'from' => $c]);
continue 2;
}
}
$this->addCommand('addColumn', ['column' => $column]);
}
foreach ($this->indexes as $index) {
$command = $index->get('type') === 'PRIMARY'
? 'addPrimary'
: 'addIndex';
$this->addCommand($command, ['index' => $index]);
}
foreach ($this->references as $reference) {
$this->addCommand('addForeign', ['reference' => $reference]);
}
} | php | {
"resource": ""
} |
q260339 | Blueprint.index | test | public function index($columns, $name = null, $type = __FUNCTION__)
{
return $this->addIndex($type, $columns, $name);
} | php | {
"resource": ""
} |
q260340 | Blueprint.float | test | public function float($column, $scale = null)
{
return $this->addColumn(__FUNCTION__, $column, is_int($scale) ? ['scale' => $scale] : []);
} | php | {
"resource": ""
} |
q260341 | Blueprint.double | test | public function double($column, $scale = null)
{
return $this->addColumn(__FUNCTION__, $column, is_int($scale) ? ['scale' => $scale] : []);
} | php | {
"resource": ""
} |
q260342 | Blueprint.decimal | test | public function decimal($column, $scale = null)
{
return $this->addColumn(__FUNCTION__, $column, is_int($scale) ? ['scale' => $scale] : []);
} | php | {
"resource": ""
} |
q260343 | Blueprint.nullableTimestamps | test | public function nullableTimestamps($precision = 0)
{
$this->timestamps($precision);
$this->columns['created_at']->nullable();
$this->columns['updated_at']->nullable();
} | php | {
"resource": ""
} |
q260344 | Blueprint.nullableTimestampsTz | test | public function nullableTimestampsTz($precision = 0)
{
$this->timestampsTz($precision);
$this->columns['created_at']->nullable();
$this->columns['updated_at']->nullable();
} | php | {
"resource": ""
} |
q260345 | Blueprint.morphs | test | public function morphs($name, $indexName = null)
{
$this->unsignedInteger("{$name}_id");
$this->string("{$name}_type");
$this->index(["{$name}_id", "{$name}_type"], $indexName);
} | php | {
"resource": ""
} |
q260346 | Blueprint.nullableMorphs | test | public function nullableMorphs($name, $indexName = null)
{
$this->unsignedInteger("{$name}_id")->nullable();
$this->string("{$name}_type")->nullable();
$this->index(["{$name}_id", "{$name}_type"], $indexName);
} | php | {
"resource": ""
} |
q260347 | Blueprint.addColumn | test | protected function addColumn($type, $name, array $parameters = [])
{
return $this->columns[$name] = new Definition(array_merge([
'name' => $name,
"type" => $type,
], $parameters));
} | php | {
"resource": ""
} |
q260348 | Blueprint.createReferenceName | test | protected function createReferenceName(array $columns, $on, array $references)
{
$strColumns = implode('_', $columns);
$strReferences = implode('_', $references);
$rawReferenceName = [$this->table, $strColumns, 'foreign', $on, $strReferences];
$rawReferenceName = array_map(function ($value) {
return trim(str_replace(['-', '.'], '_', $value), '_');
}, $rawReferenceName);
$rawReferenceName = array_filter($rawReferenceName);
$index = strtolower(trim(implode('_', $rawReferenceName), '_'));
return $index;
} | php | {
"resource": ""
} |
q260349 | Arr.add | test | public static function add($array, $key, $value)
{
if (is_null(self::get($array, $key))) {
self::set($array, $key, $value);
}
return $array;
} | php | {
"resource": ""
} |
q260350 | Arr.collapse | test | public static function collapse($array)
{
$results = [];
foreach ($array as $values) {
if (!self::accessible($values)) {
continue;
}
$results = array_merge($results, $values);
}
return $results;
} | php | {
"resource": ""
} |
q260351 | Arr.read | test | public static function read($array, $key, $default = null)
{
if (is_null($key)) {
return Obj::value($default);
}
return self::exists($array, $key) ? $array[$key] : Obj::value($default);
} | php | {
"resource": ""
} |
q260352 | Arr.fetch | test | public static function fetch($array, $key, $default = null)
{
if (is_null($key)) {
return Obj::value($default);
}
return isset($array[$key]) ? $array[$key] : Obj::value($default);
} | php | {
"resource": ""
} |
q260353 | Arr.pull | test | public static function pull(&$array, $key, $default = null)
{
$value = self::get($array, $key, $default);
self::forget($array, $key);
return $value;
} | php | {
"resource": ""
} |
q260354 | Arr.map | test | public static function map($callback, array $array, $recursive = false)
{
if($recursive){
$func = function ($item) use (&$func, &$callback) {
return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
};
return array_map($func, $array);
}
return array_map($callback, $array);
} | php | {
"resource": ""
} |
q260355 | Arr.explodePluckParameters | test | public static function explodePluckParameters($value, $key)
{
$value = is_string($value) ? explode('.', $value) : $value;
$key = is_null($key) || is_array($key) ? $key : explode('.', $key);
return [$value, $key];
} | php | {
"resource": ""
} |
q260356 | Str.levenshtein | test | public static function levenshtein($word, $words, $order = SORT_ASC, $sort_flags = SORT_REGULAR)
{
foreach ($words as $w) {
$result[$w] = levenshtein($word, $w);
}
if ($order & SORT_DESC) {
arsort($result, $sort_flags);
} else {
asort($result, $sort_flags);
}
return $result;
} | php | {
"resource": ""
} |
q260357 | Str.capitalize | test | public static function capitalize($value)
{
static $capitalizeCache;
$key = $value;
if (isset($capitalizeCache[$key])) {
return $capitalizeCache[$key];
}
return $capitalizeCache[$key] = ucwords(strtolower($value));
} | php | {
"resource": ""
} |
q260358 | Str.ucfirst | test | public static function ucfirst($string)
{
return Str::upper(Str::substr($string, 0, 1)) . Str::substr($string, 1);
} | php | {
"resource": ""
} |
q260359 | StringFormatter.format | test | public function format(Location $location, string $format): string
{
$replace = [
self::STREET_NUMBER => $location->getStreetNumber(),
self::STREET_NAME => $location->getStreetName(),
self::LOCALITY => $location->getLocality(),
self::POSTAL_CODE => $location->getPostalCode(),
self::SUB_LOCALITY => $location->getSubLocality(),
self::COUNTRY_NAME => $location->getCountryName(),
self::COUNTRY_CODE => $location->getCountryCode(),
self::TIMEZONE => $location->getTimezone(),
];
for ($level = 1; $level <= AdminLevelCollection::MAX_LEVEL_DEPTH; ++$level) {
$adminLevel = $location->getAdminLevels()[$level] ?? null;
$replace[self::ADMIN_LEVEL.$level] = $adminLevel ? $adminLevel->getName() : null;
$replace[self::ADMIN_LEVEL_CODE.$level] = $adminLevel ? $adminLevel->getCode() : null;
}
return strtr($format, $replace);
} | php | {
"resource": ""
} |
q260360 | Url.register | test | protected function register()
{
$url = new \Phalcon\Mvc\Url();
$appConf = $this->getDI()->getShared(Services::CONFIG)->app;
$url->setBaseUri($appConf->base_uri);
$url->setStaticBaseUri(isset($appConf->static_base_uri) ? $appConf->static_base_uri : $appConf->base_uri);
return $url;
} | php | {
"resource": ""
} |
q260361 | Script.getComposerCmd | test | protected function getComposerCmd()
{
if (!file_exists($this->getBasePath() . '/composer.phar')) {
return 'composer';
}
$binary = ($phpBinary = getenv('PHP_BINARY')) ? $phpBinary : PHP_BINARY;
return $binary . ' composer.phar';
} | php | {
"resource": ""
} |
q260362 | StreamContext.buildParams | test | protected function buildParams()
{
if ($this->isPostMethod()) {
$params = $this->params;
if ($this->isJsonRequest()) {
return $this
->setOption('content', $params = json_encode($params))
->setHeader('Content-Type', 'application/json')
->setHeader('Content-Length', strlen($params));
}
if (!empty($params)) {
if (!is_string($params)) {
$params = http_build_query($params);
}
return $this
->setOption('content', $params)
->setHeader('Content-Type', 'application/x-www-form-urlencoded')
->setHeader('Content-Length', strlen($params));
}
return $this;
}
return $this->buildUrl();
} | php | {
"resource": ""
} |
q260363 | StreamContext.buildHeaders | test | protected function buildHeaders()
{
$headers = $this->header->build();
return $this->setOption('header', implode(PHP_EOL, $headers));
} | php | {
"resource": ""
} |
q260364 | StreamContext.buildProxy | test | protected function buildProxy()
{
if (isset($this->proxy['host'])) {
$uri = new Uri([
'scheme' => 'tcp',
'host' => $this->proxy['host'],
'port' => isset($this->proxy['port']) ? $this->proxy['port'] : 80,
]);
if (isset($this->proxy['access'])) {
$uri->user = $this->proxy['access'];
}
$this->setOption('proxy', $uri->build());
}
return $this;
} | php | {
"resource": ""
} |
q260365 | StreamContext.buildCookies | test | protected function buildCookies()
{
if (!empty($this->cookies)) {
return $this->setHeader('Cookie', $this->getCookies(true));
}
return $this;
} | php | {
"resource": ""
} |
q260366 | HasEvents.observe | test | public static function observe($class)
{
$instance = new static;
$className = is_string($class) ? $class : get_class($class);
// When registering a model observer, we will spin through the possible events
// and determine if this observer has that method. If it does, we will hook
// it into the model's event system, making it convenient to watch these.
foreach ($instance->getObservableEvents() as $event) {
if (method_exists($class, $event)) {
static::registerModelEvent($event, $className.'@'.$event);
}
}
} | php | {
"resource": ""
} |
q260367 | HasEvents.registerModelEvent | test | protected static function registerModelEvent($event, $callback, $priority = 0)
{
if (isset(static::$dispatcher)) {
$name = static::class;
static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback, $priority);
}
} | php | {
"resource": ""
} |
q260368 | HasEvents.bootNicerEvents | test | protected function bootNicerEvents()
{
$class = get_called_class();
if (isset(static::$eventsBooted[$class])) {
return;
}
$radicals = ['creat', 'sav', 'updat', 'delet', 'retriev'];
$hooks = ['before' => 'ing', 'after' => 'ed'];
foreach ($radicals as $radical) {
foreach ($hooks as $hook => $event) {
$eventMethod = $radical.$event; // saving / saved
$method = $hook.ucfirst($radical); // beforeSave / afterSave
if ($radical != 'fetch') $method .= 'e';
self::$eventMethod(function ($model) use ($method) {
$model->fireEvent('model.'.$method);
if ($model->methodExists($method))
return $model->$method();
});
}
}
/*
* Hook to boot events
*/
static::registerModelEvent('booted', function ($model) {
$model->fireEvent('model.afterBoot');
if ($model->methodExists('afterBoot'))
return $model->afterBoot();
});
static::$eventsBooted[$class] = TRUE;
} | php | {
"resource": ""
} |
q260369 | HasEvents.flushEventListeners | test | public static function flushEventListeners()
{
if (!isset(static::$dispatcher)) {
return;
}
$instance = new static;
foreach ($instance->getObservableEvents() as $event) {
static::$dispatcher->forget("eloquent.{$event}: ".static::class);
}
} | php | {
"resource": ""
} |
q260370 | Manager.createLocationModelQuery | test | protected function createLocationModelQuery()
{
$model = $this->createLocationModel();
$query = $model->newQuery();
$this->extendLocationQuery($query);
return $query;
} | php | {
"resource": ""
} |
q260371 | Manager.getById | test | public function getById($identifier)
{
$query = $this->createLocationModelQuery();
$location = $query->find($identifier);
return $location ?: null;
} | php | {
"resource": ""
} |
q260372 | Manager.getBySlug | test | public function getBySlug($slug)
{
$model = $this->createLocationModel();
$query = $this->createLocationModelQuery();
$location = $query->where($model->getSlugKeyName(), $slug)->first();
return $location ?: null;
} | php | {
"resource": ""
} |
q260373 | FlashBag.message | test | public function message($message = null, $level = null)
{
// If no message was provided, we should update
// the most recently added message.
if (!$message) {
return $this->updateLastMessage(compact('level'));
}
if (!$message instanceof Message) {
$message = new Message(compact('message', 'level'));
}
$this->messages()->push($message);
return $this->flash();
} | php | {
"resource": ""
} |
q260374 | FlashBag.overlay | test | public function overlay($message = null, $title = '')
{
if (!$message) {
return $this->updateLastMessage(['title' => $title, 'overlay' => TRUE]);
}
return $this->message(
new OverlayMessage(compact('title', 'message'))
);
} | php | {
"resource": ""
} |
q260375 | FlashBag.clear | test | public function clear()
{
$this->store->forget($this->sessionKey);
$this->messages = collect();
return $this;
} | php | {
"resource": ""
} |
q260376 | Router.addTask | test | public function addTask($command, $class, $action = null, array $params = [])
{
$params['task'] = $class;
$params['action'] = $action;
preg_match_all('/\{([\w_]+)\}/', $command, $matches);
foreach ($matches[0] as $k => $match) {
$command = str_replace($match, '([[:word:]]+)', $command);
$params[substr($match, 1, -1)] = $k + 1;
}
return $this->add($command, $params);
} | php | {
"resource": ""
} |
q260377 | MigrationsServicesProvider.registering | test | public function registering()
{
$di = Di::getDefault();
$this->registerPrefix($di);
$this->registerStorage($di);
$this->registerMigrator($di);
$this->registerMigrationCreator($di);
} | php | {
"resource": ""
} |
q260378 | MigrationsServicesProvider.registerPrefix | test | protected function registerPrefix(DiInterface $di)
{
$di->set(PrefixInterface::class, function () {
$config = $this->get(Services::CONFIG);
return new $config->migrations->prefix;
}, true);
} | php | {
"resource": ""
} |
q260379 | MigrationsServicesProvider.registerStorage | test | protected function registerStorage(DiInterface $di)
{
$di->set(StorageInterface::class, function () {
$config = $this->get(Services::CONFIG);
return new $config->migrations->storage;
}, true);
} | php | {
"resource": ""
} |
q260380 | AppServiceProvider.boot | test | public function boot()
{
if ($module = $this->getModule(func_get_args())) {
// Register paths for: config, translator, view
$modulePath = app_path($module);
$this->loadTranslationsFrom($modulePath.DIRECTORY_SEPARATOR.'language', $module);
$this->loadViewsFrom($modulePath.DIRECTORY_SEPARATOR.'views', $module);
}
} | php | {
"resource": ""
} |
q260381 | Builder.like | test | public function like($column, $value, $side = 'both', $boolean = 'and')
{
return $this->likeInternal($column, $value, $side, $boolean);
} | php | {
"resource": ""
} |
q260382 | Builder.pluckDates | test | public function pluckDates($column, $keyFormat = '%Y-%m', $valueFormat = '%F %Y')
{
$dates = [];
$collection = $this->selectRaw("{$column}, MONTH({$column}) as month, YEAR({$column}) as year")
->groupBy([$column, 'month', 'year'])->get();
if ($collection) {
foreach ($collection as $date) {
$key = mdate($keyFormat, strtotime($date[$column]));
$value = mdate($valueFormat, strtotime($date[$column]));
$dates[$key] = $value;
}
}
return $dates;
} | php | {
"resource": ""
} |
q260383 | Builder.findOrNew | test | public function findOrNew($id, $columns = ['*'])
{
if (!is_null($model = $this->find($id, $columns))) {
return $model;
}
$attributes = $this->toBase()->getConnection()->getSchemaBuilder()->getColumnListing($this->model->getTable());
return $this->model->newInstance(array_fill_keys(array_values($attributes), null))->setConnection(
$this->toBase()->getConnection()->getName()
);
} | php | {
"resource": ""
} |
q260384 | Manager.user | test | public function user()
{
if ($this->loggedOut) {
return null;
}
if (!is_null($this->user)) {
return $this->user;
}
$user = null;
if (!is_null($id = $this->retrieveIdentifier())) {
$user = $this->retrieveUserByIdentifier($id);
}
if (empty($user)) {
/** @var \Phalcon\Http\Response\Cookies $cookies */
$cookies = $this->{Services::COOKIES};
if ($cookies->has('remember_me')) {
$recaller = $cookies->get('remember_me')->getValue();
list($identifier, $token) = explode('|', $recaller);
if ($identifier && $token) {
$user = $this->retrieveUserByToken($identifier, $token);
if ($user) {
$this->{Services::SESSION}->set($this->sessionKey(), $user->getAuthIdentifier());
}
}
}
}
$this->user = $user;
return $this->user;
} | php | {
"resource": ""
} |
q260385 | Manager.logout | test | public function logout()
{
$this->user = null;
$this->loggedOut = true;
$this->{Services::SESSION}->destroy();
$this->{Services::COOKIES}->delete('remember_me');
} | php | {
"resource": ""
} |
q260386 | Manager.login | test | public function login(User $user, $remember = false)
{
if (!$user) {
return false;
}
$this->regenerateSessionId();
$this->{Services::SESSION}->set($this->sessionKey(), $user->getAuthIdentifier());
if ($remember) {
$rememberToken = Str::random(60);
/** @var \Phalcon\Http\Response\Cookies|\Phalcon\Http\Response\CookiesInterface $cookies */
$cookies = $this->{Services::COOKIES};
$cookies->set('remember_me', $user->getAuthIdentifier() . '|' . $rememberToken, time() + (100 * 365 * 24 * 60 * 60));
$user->setRememberToken($rememberToken);
$user->save();
}
$this->user = $user;
return true;
} | php | {
"resource": ""
} |
q260387 | Manager.retrieveUserByToken | test | protected function retrieveUserByToken($identifier, $token)
{
$user = $this->retrieveUserByIdentifier($identifier);
if (!empty($user) && $user->getRememberToken() === $token) {
return $user;
}
return null;
} | php | {
"resource": ""
} |
q260388 | Manager.retrieveUserByCredentials | test | protected function retrieveUserByCredentials(array $credentials)
{
$class = $this->modelClass();
$identifier = $class::getAuthIdentifierName();
$password = $class::getAuthPasswordName();
$user = $this->retrieveUserByIdentifier(Arr::fetch($credentials, $identifier));
if ($user) {
/** @var \Phalcon\Security $security */
$security = $this->{Services::SECURITY};
if($security->checkHash(Arr::fetch($credentials, $password), $user->getAuthPassword())){
return $user;
}
}
return null;
} | php | {
"resource": ""
} |
q260389 | Debugger.dbProfilerRegister | test | private function dbProfilerRegister()
{
$profiler = self::registerProfiler('db', '<i class="nuc db"></i>');
$this->em->attach(
Events::DB,
function (Event $event, Adapter\Pdo $connection) use ($profiler) {
$eventType = $event->getType();
if ($eventType === 'beforeQuery') {
// Start a profile with the active connection
$profiler->startProfile(
$connection->getSQLStatement(),
$connection->getSqlVariables(),
$connection->getSQLBindTypes()
);
}
if ($eventType === 'afterQuery') {
// Stop the active profile
$profiler->stopProfile();
}
}
);
} | php | {
"resource": ""
} |
q260390 | Debugger.viewProfilerRegister | test | private function viewProfilerRegister()
{
$this->em->attach(
Events::VIEW,
function (Event $event, $src, $data) {
$eventType = $event->getType();
if ($eventType === 'beforeRender') {
self::$viewProfiles['render'][] = self::$viewProfiles['__render'][] = [
'initialTime' => microtime(true)
];
} elseif ($eventType === 'beforeRenderView') {
self::$viewProfiles['__renderViews'][] = self::$viewProfiles['renderViews'][] = [
'file' => $data,
'initialTime' => microtime(true)
];
} elseif ($eventType === 'afterRenderView') {
$profile = array_pop(self::$viewProfiles['__renderViews']);
$profile['finalTime'] = microtime(true);
$profile['elapsedTime'] = $profile['finalTime'] - $profile['initialTime'];
self::$viewProfiles['renderViews'][count(self::$viewProfiles['__renderViews'])] = $profile;
} elseif ($eventType === 'notFoundView') {
self::$viewProfiles['notFoundView'][] = $data;
} elseif ($eventType === 'afterRender') {
$profile = array_pop(self::$viewProfiles['__render']);
$profile['finalTime'] = microtime(true);
$profile['elapsedTime'] = $profile['finalTime'] - $profile['initialTime'];
self::$viewProfiles['render'][count(self::$viewProfiles['__render'])] = $profile;
}
}
);
} | php | {
"resource": ""
} |
q260391 | MakerTask.writeMigration | test | protected function writeMigration($name, $table, $create)
{
$file = pathinfo($this->creator->create(
$name, $this->getMigrationPath(), $table, $create
), PATHINFO_FILENAME);
$this->info("Created Migration: {$file}");
} | php | {
"resource": ""
} |
q260392 | LogsActivity.eventsToBeRecorded | test | protected static function eventsToBeRecorded()
{
if (isset(static::$recordEvents)) {
return collect(static::$recordEvents);
}
$events = collect([
'created',
'updated',
'deleted',
]);
if (collect(class_uses(__CLASS__))->contains(SoftDeletes::class)) {
$events->push('restored');
}
return $events;
} | php | {
"resource": ""
} |
q260393 | VarDump.arrayDump | test | private function arrayDump($var, $id = null, $idLabel = null)
{
$dump = '';
if (!is_null($id)) {
if (is_null($idLabel)) {
$idLabel = '#' . $id;
}
$dump .= '<span class="nuc-toggle nuc-toggle-array" data-target="nuc-ref-' . $id . '">' . $idLabel . '</span>';
$dump .= '<ul class="nuc-array" id="nuc-ref-' . $id . '">';
} else {
$dump .= '<span class="nuc-toggle nuc-toggle-array"></span>';
$dump .= '<ul class="nuc-array">';
}
foreach ($var as $key => $val) {
$dump .= '<li class="nuc-' . str_replace(' ', '-', gettype($val)) . ($this->canHasChild($val) ? ' nuc-close' : '') . '">';
$dump .= $this->varDump($key) . ' <span class="nuc-sep">=></span> ';
$dump .= $this->varDump($val);
$dump .= '</li>';
}
$dump .= '</ul>';
return $dump;
} | php | {
"resource": ""
} |
q260394 | VarDump.getVarId | test | private function getVarId($var)
{
if (is_object($var)) {
$hash = spl_object_hash($var);
} elseif (is_resource($var)) {
$hash = intval($var) . '#resource#' . get_resource_type($var);
} elseif (is_array($var) && $this->checkArrayRecursion($var)) {
$hash = $this->getArrayId($var);
}
if (isset($hash)) {
if (isset($this->hash[$hash])) {
return $this->hash[$hash];
}
return $this->hash[$hash] = self::uid();
}
return null;
} | php | {
"resource": ""
} |
q260395 | VarDump.genArrayHash | test | private function genArrayHash(array $var)
{
static $dump;
if (!isset($dump)) {
$dump = [];
}
if (in_array($var, $dump, true)) {
return 'array recursion';
}
$dump[] = $var;
$hash = [];
foreach ($var as $k => $v) {
if (is_object($v)) {
$hash[$k] = spl_object_hash($v);
} elseif (is_array($v)) {
$hash[$k] = $this->genArrayHash($v);
} elseif (is_resource($v)) {
$hash[$k] = intval($v) . get_resource_type($v);
} else {
$hash[$k] = $v;
}
}
$hash = json_encode($hash);
array_pop($dump);
return $hash;
} | php | {
"resource": ""
} |
q260396 | VarDump.checkArrayRecursion | test | private function checkArrayRecursion(array $var)
{
static $dump;
if (!isset($dump)) {
$dump = [];
}
if (in_array($var, $dump, true)) {
return true;
}
$dump[] = $var;
$return = false;
foreach ($var as $item) {
if (is_object($item) && $this->checkObjectRecursion($item)) {
$return = true;
break;
}
if (is_array($item) && $this->checkArrayRecursion($item)) {
$return = true;
break;
}
}
array_pop($dump);
return $return;
} | php | {
"resource": ""
} |
q260397 | VarDump.checkObjectRecursion | test | private function checkObjectRecursion($obj)
{
static $dump;
if (!isset($dump)) {
$dump = [];
}
if (in_array($obj, $dump, true)) {
return true;
}
$dump[] = $obj;
$return = false;
$props = Reflexion::getReflectionProperties($obj);
foreach ($props as $prop) {
$val = Reflexion::get($obj, $prop->getName());
if (is_array($val) && $this->checkArrayRecursion($val)) {
$return = true;
break;
} elseif (is_object($val) && $this->checkObjectRecursion($val)) {
$return = true;
break;
}
}
foreach ($obj as $val) {
if (is_array($val) && $this->checkArrayRecursion($val)) {
$return = true;
break;
} elseif (is_object($val) && $this->checkObjectRecursion($val)) {
$return = true;
break;
}
}
array_pop($dump);
return $return;
} | php | {
"resource": ""
} |
q260398 | VarDump.dump | test | public static function dump(...$vars)
{
// We force the start of the session so that it is initialized before the first exit.
switch (session_status()) {
case PHP_SESSION_DISABLED:
case PHP_SESSION_ACTIVE:
break;
default:
$di = Di::getDefault();
if ($di->has(Services::SESSION)) {
$di->get(Services::SESSION);
} else {
session_start();
}
}
foreach ($vars as $var) {
$id = 'nuc-dump-' . self::uid();
$dump = (new self)->varDump($var);
echo self::outputBasic() . "<pre class='nuc-dump' id='$id'>$dump</pre><script>nucDumper('$id')</script>";
}
} | php | {
"resource": ""
} |
q260399 | ListTask.mainAction | test | public function mainAction()
{
$this->displayHeader();
$routes = $this->router->getRoutes();
$delimiter = Route::getDelimiter();
foreach ($routes as $route) {
/** @var Route $route */
// Default route
$pattern = $route->getPattern();
if ($pattern === "#^(?:$delimiter)?([a-zA-Z0-9\\_\\-]+)[$delimiter]{0,1}$#" ||
$pattern === "#^(?:$delimiter)?([a-zA-Z0-9\\_\\-]+)$delimiter([a-zA-Z0-9\\.\\_]+)($delimiter.*)*$#"
) {
continue;
}
$this->describeRoute($route);
}
$datas = [];
foreach ($this->describes as $describe) {
if (isset($describe['__exception'])) {
$datas[$describe['cmd']] = Decorate::error(explode(PHP_EOL, $describe['__exception'], 2)[0]);
} else {
$datas[$describe['cmd']] = explode(PHP_EOL, $describe['description'], 2)[0];
}
}
$this->notice('Available Commands :');
(new Group($this->output, $datas, Group::SORT_ASC))->display();
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.