_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q14000
ExtractsMailableTags.registerMailableTagExtractor
train
protected static function registerMailableTagExtractor() { Mailable::buildViewDataUsing(function ($mailable) { return [ '__telescope' => ExtractTags::from($mailable), '__telescope_mailable' => get_class($mailable), '__telescope_queued' => in_array(ShouldQueue::class, class_implements($mailable)), ]; }); }
php
{ "resource": "" }
q14001
QueryWatcher.recordQuery
train
public function recordQuery(QueryExecuted $event) { if (! Telescope::isRecording()) { return; } $time = $event->time; $caller = $this->getCallerFromStackTrace(); Telescope::recordQuery(IncomingEntry::make([ 'connection' => $event->connectionName, 'bindings' => $this->formatBindings($event), 'sql' => $event->sql, 'time' => number_format($time, 2), 'slow' => isset($this->options['slow']) && $time >= $this->options['slow'], 'file' => $caller['file'], 'line' => $caller['line'], ])->tags($this->tags($event))); }
php
{ "resource": "" }
q14002
RecordingController.toggle
train
public function toggle() { if ($this->cache->get('telescope:pause-recording')) { $this->cache->forget('telescope:pause-recording'); } else { $this->cache->put('telescope:pause-recording', true, now()->addDays(30)); } }
php
{ "resource": "" }
q14003
EventWatcher.recordEvent
train
public function recordEvent($eventName, $payload) { if (! Telescope::isRecording() || $this->shouldIgnore($eventName)) { return; } $formattedPayload = $this->extractPayload($eventName, $payload); Telescope::recordEvent(IncomingEntry::make([ 'name' => $eventName, 'payload' => empty($formattedPayload) ? null : $formattedPayload, 'listeners' => $this->formatListeners($eventName), 'broadcast' => class_exists($eventName) ? in_array(ShouldBroadcast::class, (array) class_implements($eventName)) : false, ])->tags(class_exists($eventName) && isset($payload[0]) ? ExtractTags::from($payload[0]) : [])); }
php
{ "resource": "" }
q14004
EventWatcher.extractPayload
train
protected function extractPayload($eventName, $payload) { if (class_exists($eventName) && isset($payload[0]) && is_object($payload[0])) { return ExtractProperties::from($payload[0]); } return collect($payload)->map(function ($value) { return is_object($value) ? [ 'class' => get_class($value), 'properties' => json_decode(json_encode($value), true), ] : $value; })->toArray(); }
php
{ "resource": "" }
q14005
EventWatcher.formatListeners
train
protected function formatListeners($eventName) { return collect(app('events')->getListeners($eventName)) ->map(function ($listener) { $listener = (new ReflectionFunction($listener)) ->getStaticVariables()['listener']; if (is_string($listener)) { return Str::contains($listener, '@') ? $listener : $listener.'@handle'; } elseif (is_array($listener)) { return get_class($listener[0]).'@'.$listener[1]; } return $this->formatClosureListener($listener); })->reject(function ($listener) { return Str::contains($listener, 'Laravel\\Telescope'); })->map(function ($listener) { if (Str::contains($listener, '@')) { $queued = in_array(ShouldQueue::class, class_implements(explode('@', $listener)[0])); } return [ 'name' => $listener, 'queued' => $queued ?? false, ]; })->values()->toArray(); }
php
{ "resource": "" }
q14006
EventWatcher.formatClosureListener
train
protected function formatClosureListener(Closure $listener) { $listener = new ReflectionFunction($listener); return sprintf('Closure at %s[%s:%s]', $listener->getFileName(), $listener->getStartLine(), $listener->getEndLine() ); }
php
{ "resource": "" }
q14007
Telescope.start
train
public static function start($app) { if (! config('telescope.enabled')) { return; } static::registerWatchers($app); static::registerMailableTagExtractor(); if (static::runningApprovedArtisanCommand($app) || static::handlingApprovedRequest($app) ) { static::startRecording(); } }
php
{ "resource": "" }
q14008
Telescope.runningApprovedArtisanCommand
train
protected static function runningApprovedArtisanCommand($app) { return $app->runningInConsole() && ! in_array( $_SERVER['argv'][1] ?? null, array_merge([ // 'migrate', 'migrate:rollback', 'migrate:fresh', // 'migrate:refresh', 'migrate:reset', 'migrate:install', 'package:discover', 'queue:listen', 'queue:work', 'horizon', 'horizon:work', 'horizon:supervisor', ], config('telescope.ignoreCommands', []), config('telescope.ignore_commands', [])) ); }
php
{ "resource": "" }
q14009
Telescope.withoutRecording
train
public static function withoutRecording($callback) { $shouldRecord = static::$shouldRecord; static::$shouldRecord = false; call_user_func($callback); static::$shouldRecord = $shouldRecord; }
php
{ "resource": "" }
q14010
Telescope.record
train
protected static function record(string $type, IncomingEntry $entry) { if (! static::isRecording()) { return; } $entry->type($type)->tags( static::$tagUsing ? call_user_func(static::$tagUsing, $entry) : [] ); try { if (Auth::hasUser()) { $entry->user(Auth::user()); } } catch (Throwable $e) { // Do nothing. } static::withoutRecording(function () use ($entry) { if (collect(static::$filterUsing)->every->__invoke($entry)) { static::$entriesQueue[] = $entry; } if (static::$afterRecordingHook) { call_user_func(static::$afterRecordingHook, new static); } }); }
php
{ "resource": "" }
q14011
Telescope.catch
train
public static function catch($e, $tags = []) { if ($e instanceof Throwable && ! $e instanceof Exception) { $e = new FatalThrowableError($e); } event(new MessageLogged('error', $e->getMessage(), [ 'exception' => $e, 'telescope' => $tags, ])); }
php
{ "resource": "" }
q14012
Telescope.store
train
public static function store(EntriesRepository $storage) { if (empty(static::$entriesQueue) && empty(static::$updatesQueue)) { return; } if (! collect(static::$filterBatchUsing)->every->__invoke(collect(static::$entriesQueue))) { static::flushEntries(); } try { $batchId = Str::orderedUuid()->toString(); $storage->store(static::collectEntries($batchId)); $storage->update(static::collectUpdates($batchId)); if ($storage instanceof TerminableRepository) { $storage->terminate(); } } catch (Exception $e) { app(ExceptionHandler::class)->report($e); } static::$entriesQueue = []; static::$updatesQueue = []; }
php
{ "resource": "" }
q14013
Telescope.collectEntries
train
protected static function collectEntries($batchId) { return collect(static::$entriesQueue) ->each(function ($entry) use ($batchId) { $entry->batchId($batchId); if ($entry->isDump()) { $entry->assignEntryPointFromBatch(static::$entriesQueue); } }); }
php
{ "resource": "" }
q14014
Telescope.collectUpdates
train
protected static function collectUpdates($batchId) { return collect(static::$updatesQueue) ->each(function ($entry) use ($batchId) { $entry->change(['updated_batch_id' => $batchId]); }); }
php
{ "resource": "" }
q14015
TelescopeServiceProvider.registerStorageDriver
train
protected function registerStorageDriver() { $driver = config('telescope.driver'); if (method_exists($this, $method = 'register'.ucfirst($driver).'Driver')) { $this->$method(); } }
php
{ "resource": "" }
q14016
TelescopeServiceProvider.registerDatabaseDriver
train
protected function registerDatabaseDriver() { $this->app->singleton( EntriesRepository::class, DatabaseEntriesRepository::class ); $this->app->singleton( ClearableRepository::class, DatabaseEntriesRepository::class ); $this->app->singleton( PrunableRepository::class, DatabaseEntriesRepository::class ); $this->app->when(DatabaseEntriesRepository::class) ->needs('$connection') ->give(config('telescope.storage.database.connection')); $this->app->when(DatabaseEntriesRepository::class) ->needs('$chunkSize') ->give(config('telescope.storage.database.chunk')); }
php
{ "resource": "" }
q14017
EntryController.status
train
protected function status() { if (! config('telescope.enabled', false)) { return 'disabled'; } if (cache('telescope:pause-recording', false)) { return 'paused'; } $watcher = config('telescope.watchers.'.$this->watcher()); if (! $watcher || (isset($watcher['enabled']) && ! $watcher['enabled'])) { return 'off'; } return 'enabled'; }
php
{ "resource": "" }
q14018
ExceptionWatcher.recordException
train
public function recordException(MessageLogged $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } $exception = $event->context['exception']; Telescope::recordException( IncomingExceptionEntry::make($exception, [ 'class' => get_class($exception), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $exception->getMessage(), 'trace' => $exception->getTrace(), 'line_preview' => ExceptionContext::get($exception), ])->tags($this->tags($event)) ); }
php
{ "resource": "" }
q14019
JobWatcher.recordJob
train
public function recordJob($connection, $queue, array $payload) { if (! Telescope::isRecording()) { return; } $content = array_merge([ 'status' => 'pending', ], $this->defaultJobData($connection, $queue, $payload, $this->data($payload))); Telescope::recordJob( $entry = IncomingEntry::make($content) ->tags($this->tags($payload)) ); return $entry; }
php
{ "resource": "" }
q14020
JobWatcher.recordProcessedJob
train
public function recordProcessedJob(JobProcessed $event) { if (! Telescope::isRecording()) { return; } $uuid = $event->job->payload()['telescope_uuid'] ?? null; if (! $uuid) { return; } Telescope::recordUpdate(EntryUpdate::make( $uuid, EntryType::JOB, ['status' => 'processed'] )); }
php
{ "resource": "" }
q14021
JobWatcher.recordFailedJob
train
public function recordFailedJob(JobFailed $event) { if (! Telescope::isRecording()) { return; } $uuid = $event->job->payload()['telescope_uuid'] ?? null; if (! $uuid) { return; } Telescope::recordUpdate(EntryUpdate::make( $uuid, EntryType::JOB, [ 'status' => 'failed', 'exception' => [ 'message' => $event->exception->getMessage(), 'trace' => $event->exception->getTrace(), 'line' => $event->exception->getLine(), 'line_preview' => ExceptionContext::get($event->exception), ], ] )->addTags(['failed'])); }
php
{ "resource": "" }
q14022
JobWatcher.defaultJobData
train
protected function defaultJobData($connection, $queue, array $payload, array $data) { return [ 'connection' => $connection, 'queue' => $queue, 'name' => $payload['displayName'], 'tries' => $payload['maxTries'], 'timeout' => $payload['timeout'], 'data' => $data, ]; }
php
{ "resource": "" }
q14023
TelescopeApplicationServiceProvider.authorization
train
protected function authorization() { $this->gate(); Telescope::auth(function ($request) { return app()->environment('local') || Gate::check('viewTelescope', [$request->user()]); }); }
php
{ "resource": "" }
q14024
EntryUpdate.addTags
train
public function addTags(array $tags) { $this->tagsChanges['added'] = array_unique( array_merge($this->tagsChanges['added'], $tags) ); return $this; }
php
{ "resource": "" }
q14025
EntryUpdate.removeTags
train
public function removeTags(array $tags) { $this->tagsChanges['removed'] = array_unique( array_merge($this->tagsChanges['removed'], $tags) ); return $this; }
php
{ "resource": "" }
q14026
RedisWatcher.recordCommand
train
public function recordCommand(CommandExecuted $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } Telescope::recordRedis(IncomingEntry::make([ 'connection' => $event->connectionName, 'command' => $this->formatCommand($event->command, $event->parameters), 'time' => number_format($event->time, 2), ])); }
php
{ "resource": "" }
q14027
RedisWatcher.formatCommand
train
private function formatCommand($command, $parameters) { $parameters = collect($parameters)->map(function ($parameter) { if (is_array($parameter)) { return collect($parameter)->map(function ($value, $key) { return is_int($key) ? $value : "{$key} {$value}"; })->implode(' '); } return $parameter; })->implode(' '); return "{$command} {$parameters}"; }
php
{ "resource": "" }
q14028
ExtractTags.from
train
public static function from($target) { if ($tags = static::explicitTags([$target])) { return $tags; } return static::modelsFor([$target])->map(function ($model) { return FormatModel::given($model); })->all(); }
php
{ "resource": "" }
q14029
ExtractTags.fromArray
train
public static function fromArray(array $data) { $models = collect($data)->map(function ($value) { if ($value instanceof Model) { return [$value]; } elseif ($value instanceof EloquentCollection) { return $value->flatten(); } })->collapse()->filter(); return $models->map(function ($model) { return FormatModel::given($model); })->all(); }
php
{ "resource": "" }
q14030
ExtractTags.tagsForListener
train
protected static function tagsForListener($job) { return collect( [static::extractListener($job), static::extractEvent($job), ])->map(function ($job) { return static::from($job); })->collapse()->unique()->toArray(); }
php
{ "resource": "" }
q14031
ExtractTags.targetsFor
train
protected static function targetsFor($job) { switch (true) { case $job instanceof BroadcastEvent: return [$job->event]; case $job instanceof CallQueuedListener: return [static::extractEvent($job)]; case $job instanceof SendQueuedMailable: return [$job->mailable]; case $job instanceof SendQueuedNotifications: return [$job->notification]; default: return [$job]; } }
php
{ "resource": "" }
q14032
ExtractTags.modelsFor
train
protected static function modelsFor(array $targets) { $models = []; foreach ($targets as $target) { $models[] = collect((new ReflectionClass($target))->getProperties())->map(function ($property) use ($target) { $property->setAccessible(true); $value = $property->getValue($target); if ($value instanceof Model) { return [$value]; } elseif ($value instanceof EloquentCollection) { return $value->flatten(); } })->collapse()->filter()->all(); } return collect(Arr::collapse($models))->unique(); }
php
{ "resource": "" }
q14033
ExtractTags.extractEvent
train
protected static function extractEvent($job) { return isset($job->data[0]) && is_object($job->data[0]) ? $job->data[0] : new stdClass; }
php
{ "resource": "" }
q14034
ExtractProperties.from
train
public static function from($target) { return collect((new ReflectionClass($target))->getProperties()) ->mapWithKeys(function ($property) use ($target) { $property->setAccessible(true); if (($value = $property->getValue($target)) instanceof Model) { return [$property->getName() => FormatModel::given($value)]; } elseif (is_object($value)) { return [ $property->getName() => [ 'class' => get_class($value), 'properties' => json_decode(json_encode($value), true), ], ]; } else { return [$property->getName() => json_decode(json_encode($value), true)]; } })->toArray(); }
php
{ "resource": "" }
q14035
EntryModel.scopeWithTelescopeOptions
train
public function scopeWithTelescopeOptions($query, $type, EntryQueryOptions $options) { $this->whereType($query, $type) ->whereBatchId($query, $options) ->whereTag($query, $options) ->whereFamilyHash($query, $options) ->whereBeforeSequence($query, $options) ->filter($query, $options); return $query; }
php
{ "resource": "" }
q14036
EntryModel.whereBatchId
train
protected function whereBatchId($query, EntryQueryOptions $options) { $query->when($options->batchId, function ($query, $batchId) { return $query->where('batch_id', $batchId); }); return $this; }
php
{ "resource": "" }
q14037
EntryModel.whereBeforeSequence
train
protected function whereBeforeSequence($query, EntryQueryOptions $options) { $query->when($options->beforeSequence, function ($query, $beforeSequence) { return $query->where('sequence', '<', $beforeSequence); }); return $this; }
php
{ "resource": "" }
q14038
EntryModel.filter
train
protected function filter($query, EntryQueryOptions $options) { if ($options->familyHash || $options->tag || $options->batchId) { return $this; } $query->where('should_display_on_index', true); return $this; }
php
{ "resource": "" }
q14039
InstallCommand.registerTelescopeServiceProvider
train
protected function registerTelescopeServiceProvider() { $namespace = str_replace_last('\\', '', $this->getAppNamespace()); $appConfig = file_get_contents(config_path('app.php')); if (Str::contains($appConfig, $namespace.'\\Providers\\TelescopeServiceProvider::class')) { return; } $lineEndingCount = [ "\r\n" => substr_count($appConfig, "\r\n"), "\r" => substr_count($appConfig, "\r"), "\n" => substr_count($appConfig, "\n"), ]; $eol = array_keys($lineEndingCount, max($lineEndingCount))[0]; file_put_contents(config_path('app.php'), str_replace( "{$namespace}\\Providers\EventServiceProvider::class,".$eol, "{$namespace}\\Providers\EventServiceProvider::class,".$eol." {$namespace}\Providers\TelescopeServiceProvider::class,".$eol, $appConfig )); file_put_contents(app_path('Providers/TelescopeServiceProvider.php'), str_replace( "namespace App\Providers;", "namespace {$namespace}\Providers;", file_get_contents(app_path('Providers/TelescopeServiceProvider.php')) )); }
php
{ "resource": "" }
q14040
DatabaseEntriesRepository.find
train
public function find($id): EntryResult { $entry = EntryModel::on($this->connection)->whereUuid($id)->firstOrFail(); $tags = $this->table('telescope_entries_tags') ->where('entry_uuid', $id) ->pluck('tag') ->all(); return new EntryResult( $entry->uuid, null, $entry->batch_id, $entry->type, $entry->family_hash, $entry->content, $entry->created_at, $tags ); }
php
{ "resource": "" }
q14041
DatabaseEntriesRepository.get
train
public function get($type, EntryQueryOptions $options) { return EntryModel::on($this->connection) ->withTelescopeOptions($type, $options) ->take($options->limit) ->orderByDesc('sequence') ->get()->reject(function ($entry) { return ! is_array($entry->content); })->map(function ($entry) { return new EntryResult( $entry->uuid, $entry->sequence, $entry->batch_id, $entry->type, $entry->family_hash, $entry->content, $entry->created_at, [] ); })->values(); }
php
{ "resource": "" }
q14042
DatabaseEntriesRepository.store
train
public function store(Collection $entries) { if ($entries->isEmpty()) { return; } [$exceptions, $entries] = $entries->partition->isException(); $this->storeExceptions($exceptions); $table = $this->table('telescope_entries'); $entries->chunk($this->chunkSize)->each(function ($chunked) use ($table) { $table->insert($chunked->map(function ($entry) { $entry->content = json_encode($entry->content); return $entry->toArray(); })->toArray()); }); $this->storeTags($entries->pluck('tags', 'uuid')); }
php
{ "resource": "" }
q14043
DatabaseEntriesRepository.storeExceptions
train
protected function storeExceptions(Collection $exceptions) { $this->table('telescope_entries')->insert($exceptions->map(function ($exception) { $occurrences = $this->table('telescope_entries') ->where('type', EntryType::EXCEPTION) ->where('family_hash', $exception->familyHash()) ->count(); $this->table('telescope_entries') ->where('type', EntryType::EXCEPTION) ->where('family_hash', $exception->familyHash()) ->update(['should_display_on_index' => false]); return array_merge($exception->toArray(), [ 'family_hash' => $exception->familyHash(), 'content' => json_encode(array_merge( $exception->content, ['occurrences' => $occurrences + 1] )), ]); })->toArray()); $this->storeTags($exceptions->pluck('tags', 'uuid')); }
php
{ "resource": "" }
q14044
DatabaseEntriesRepository.storeTags
train
protected function storeTags($results) { $this->table('telescope_entries_tags')->insert($results->flatMap(function ($tags, $uuid) { return collect($tags)->map(function ($tag) use ($uuid) { return [ 'entry_uuid' => $uuid, 'tag' => $tag, ]; }); })->all()); }
php
{ "resource": "" }
q14045
DatabaseEntriesRepository.update
train
public function update(Collection $updates) { foreach ($updates as $update) { $entry = $this->table('telescope_entries') ->where('uuid', $update->uuid) ->where('type', $update->type) ->first(); if (! $entry) { continue; } $content = json_encode(array_merge( json_decode($entry->content, true) ?: [], $update->changes )); $this->table('telescope_entries') ->where('uuid', $update->uuid) ->where('type', $update->type) ->update(['content' => $content]); $this->updateTags($update); } }
php
{ "resource": "" }
q14046
DatabaseEntriesRepository.updateTags
train
protected function updateTags($entry) { if (! empty($entry->tagsChanges['added'])) { $this->table('telescope_entries_tags')->insert( collect($entry->tagsChanges['added'])->map(function ($tag) use ($entry) { return [ 'entry_uuid' => $entry->uuid, 'tag' => $tag, ]; })->toArray() ); } collect($entry->tagsChanges['removed'])->each(function ($tag) use ($entry) { $this->table('telescope_entries_tags')->where([ 'entry_uuid' => $entry->uuid, 'tag' => $tag, ])->delete(); }); }
php
{ "resource": "" }
q14047
DatabaseEntriesRepository.isMonitoring
train
public function isMonitoring(array $tags) { if (is_null($this->monitoredTags)) { $this->loadMonitoredTags(); } return count(array_intersect($tags, $this->monitoredTags)) > 0; }
php
{ "resource": "" }
q14048
DatabaseEntriesRepository.monitor
train
public function monitor(array $tags) { $tags = array_diff($tags, $this->monitoring()); if (empty($tags)) { return; } $this->table('telescope_monitoring') ->insert(collect($tags) ->mapWithKeys(function ($tag) { return ['tag' => $tag]; })->all()); }
php
{ "resource": "" }
q14049
RegistersWatchers.registerWatchers
train
protected static function registerWatchers($app) { foreach (config('telescope.watchers') as $key => $watcher) { if (is_string($key) && $watcher === false) { continue; } if (is_array($watcher) && ! ($watcher['enabled'] ?? true)) { continue; } $watcher = $app->make(is_string($key) ? $key : $watcher, [ 'options' => is_array($watcher) ? $watcher : [], ]); static::$watchers[] = get_class($watcher); $watcher->register($app); } }
php
{ "resource": "" }
q14050
IncomingExceptionEntry.isReportableException
train
public function isReportableException() { $handler = app(ExceptionHandler::class); return method_exists($handler, 'shouldReport') ? $handler->shouldReport($this->exception) : true; }
php
{ "resource": "" }
q14051
GateWatcher.recordGateCheck
train
public function recordGateCheck(?Authenticatable $user, $ability, $result, $arguments) { if (! Telescope::isRecording() || $this->shouldIgnore($ability)) { return; } $caller = $this->getCallerFromStackTrace(); Telescope::recordGate(IncomingEntry::make([ 'ability' => $ability, 'result' => $result ? 'allowed' : 'denied', 'arguments' => $this->formatArguments($arguments), 'file' => $caller['file'], 'line' => $caller['line'], ])); return $result; }
php
{ "resource": "" }
q14052
GateWatcher.formatArguments
train
private function formatArguments($arguments) { return collect($arguments)->map(function ($argument) { return $argument instanceof Model ? FormatModel::given($argument) : $argument; })->toArray(); }
php
{ "resource": "" }
q14053
MailWatcher.recordMail
train
public function recordMail(MessageSent $event) { if (! Telescope::isRecording()) { return; } Telescope::recordMail(IncomingEntry::make([ 'mailable' => $this->getMailable($event), 'queued' => $this->getQueuedStatus($event), 'from' => $event->message->getFrom(), 'replyTo' => $event->message->getReplyTo(), 'to' => $event->message->getTo(), 'cc' => $event->message->getCc(), 'bcc' => $event->message->getBcc(), 'subject' => $event->message->getSubject(), 'html' => $event->message->getBody(), 'raw' => $event->message->toString(), ])->tags($this->tags($event->message, $event->data))); }
php
{ "resource": "" }
q14054
MailWatcher.getQueuedStatus
train
protected function getQueuedStatus($event) { if (isset($event->data['__laravel_notification_queued'])) { return $event->data['__laravel_notification_queued']; } return $event->data['__telescope_queued'] ?? false; }
php
{ "resource": "" }
q14055
MailWatcher.tags
train
private function tags($message, $data) { return array_merge( array_keys($message->getTo() ?: []), array_keys($message->getCc() ?: []), array_keys($message->getBcc() ?: []), $data['__telescope'] ?? [] ); }
php
{ "resource": "" }
q14056
MailEmlController.show
train
public function show(EntriesRepository $storage, $id) { return response($storage->find($id)->content['raw'], 200, [ 'Content-Type' => 'message/rfc822', 'Content-Disposition' => 'attachment; filename="mail-'.$id.'.eml"', ]); }
php
{ "resource": "" }
q14057
ModelWatcher.recordAction
train
public function recordAction($event, $data) { if (! Telescope::isRecording() || ! $this->shouldRecord($event)) { return; } $model = FormatModel::given($data[0]); $changes = $data[0]->getChanges(); Telescope::recordModelEvent(IncomingEntry::make(array_filter([ 'action' => $this->action($event), 'model' => $model, 'changes' => empty($changes) ? null : $changes, ]))->tags([$model])); }
php
{ "resource": "" }
q14058
ScheduleWatcher.recordCommand
train
public function recordCommand(CommandStarting $event) { if (! Telescope::isRecording() || $event->command !== 'schedule:run' && $event->command !== 'schedule:finish') { return; } collect(app(Schedule::class)->events())->each(function ($event) { $event->then(function () use ($event) { Telescope::recordScheduledCommand(IncomingEntry::make([ 'command' => $event instanceof CallbackEvent ? 'Closure' : $event->command, 'description' => $event->description, 'expression' => $event->expression, 'timezone' => $event->timezone, 'user' => $event->user, 'output' => $this->getEventOutput($event), ])); }); }); }
php
{ "resource": "" }
q14059
ScheduleWatcher.getEventOutput
train
protected function getEventOutput(Event $event) { if (! $event->output || $event->output === $event->getDefaultOutput() || $event->shouldAppendOutput || ! file_exists($event->output)) { return ''; } return trim(file_get_contents($event->output)); }
php
{ "resource": "" }
q14060
ListensForStorageOpportunities.storeEntriesAfterWorkerLoop
train
protected static function storeEntriesAfterWorkerLoop($app) { $app['events']->listen(JobProcessing::class, function () { static::startRecording(); static::$processingJobs[] = true; }); $app['events']->listen(JobProcessed::class, function ($event) use ($app) { static::storeIfDoneProcessingJob($event, $app); }); $app['events']->listen(JobFailed::class, function ($event) use ($app) { static::storeIfDoneProcessingJob($event, $app); }); $app['events']->listen(JobExceptionOccurred::class, function () { array_pop(static::$processingJobs); }); }
php
{ "resource": "" }
q14061
ListensForStorageOpportunities.storeIfDoneProcessingJob
train
protected static function storeIfDoneProcessingJob($event, $app) { array_pop(static::$processingJobs); if (empty(static::$processingJobs)) { static::store($app[EntriesRepository::class]); if ($event->connectionName !== 'sync') { static::stopRecording(); } } }
php
{ "resource": "" }
q14062
NotificationWatcher.recordNotification
train
public function recordNotification(NotificationSent $event) { if (! Telescope::isRecording()) { return; } Telescope::recordNotification(IncomingEntry::make([ 'notification' => get_class($event->notification), 'queued' => in_array(ShouldQueue::class, class_implements($event->notification)), 'notifiable' => $this->formatNotifiable($event->notifiable), 'channel' => $event->channel, 'response' => $event->response, ])->tags($this->tags($event))); }
php
{ "resource": "" }
q14063
NotificationWatcher.tags
train
private function tags($event) { return array_merge([ $this->formatNotifiable($event->notifiable), ], ExtractTags::from($event->notification)); }
php
{ "resource": "" }
q14064
NotificationWatcher.formatNotifiable
train
private function formatNotifiable($notifiable) { if ($notifiable instanceof Model) { return FormatModel::given($notifiable); } elseif ($notifiable instanceof AnonymousNotifiable) { return 'Anonymous:'.implode(',', $notifiable->routes); } return get_class($notifiable); }
php
{ "resource": "" }
q14065
ExceptionContext.get
train
public static function get(Throwable $exception) { return collect(explode("\n", file_get_contents($exception->getFile()))) ->slice($exception->getLine() - 10, 20) ->mapWithKeys(function ($value, $key) { return [$key + 1 => $value]; })->all(); }
php
{ "resource": "" }
q14066
LogWatcher.recordLog
train
public function recordLog(MessageLogged $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } Telescope::recordLog( IncomingEntry::make([ 'level' => $event->level, 'message' => $event->message, 'context' => Arr::except($event->context, ['telescope']), ])->tags($this->tags($event)) ); }
php
{ "resource": "" }
q14067
EntryQueryOptions.fromRequest
train
public static function fromRequest(Request $request) { return (new static) ->batchId($request->batch_id) ->uuids($request->uuids) ->beforeSequence($request->before) ->tag($request->tag) ->familyHash($request->family_hash) ->limit($request->take ?? 50); }
php
{ "resource": "" }
q14068
RequestWatcher.recordRequest
train
public function recordRequest(RequestHandled $event) { if (! Telescope::isRecording()) { return; } Telescope::recordRequest(IncomingEntry::make([ 'uri' => str_replace($event->request->root(), '', $event->request->fullUrl()) ?: '/', 'method' => $event->request->method(), 'controller_action' => optional($event->request->route())->getActionName(), 'middleware' => array_values(optional($event->request->route())->gatherMiddleware() ?? []), 'headers' => $this->headers($event->request->headers->all()), 'payload' => $this->payload($this->input($event->request)), 'session' => $this->payload($this->sessionVariables($event->request)), 'response_status' => $event->response->getStatusCode(), 'response' => $this->response($event->response), 'duration' => defined('LARAVEL_START') ? floor((microtime(true) - LARAVEL_START) * 1000) : null, ])); }
php
{ "resource": "" }
q14069
RequestWatcher.headers
train
protected function headers($headers) { $headers = collect($headers)->map(function ($header) { return $header[0]; })->toArray(); return $this->hideParameters($headers, Telescope::$hiddenRequestHeaders ); }
php
{ "resource": "" }
q14070
RequestWatcher.hideParameters
train
protected function hideParameters($data, $hidden) { foreach ($hidden as $parameter) { if (Arr::get($data, $parameter)) { Arr::set($data, $parameter, '********'); } } return $data; }
php
{ "resource": "" }
q14071
RequestWatcher.input
train
private function input(Request $request) { $files = $request->files->all(); array_walk_recursive($files, function (&$file) { $file = [ 'name' => $file->getClientOriginalName(), 'size' => $file->isFile() ? ($file->getSize() / 1000).'KB' : '0', ]; }); return array_replace_recursive($request->input(), $files); }
php
{ "resource": "" }
q14072
RequestWatcher.response
train
protected function response(Response $response) { $content = $response->getContent(); if (is_string($content) && is_array(json_decode($content, true)) && json_last_error() === JSON_ERROR_NONE) { return $this->contentWithinLimits($content) ? $this->hideParameters(json_decode($content, true), Telescope::$hiddenResponseParameters) : 'Purged By Telescope'; } if ($response instanceof RedirectResponse) { return 'Redirected to '.$response->getTargetUrl(); } if ($response instanceof IlluminateResponse && $response->getOriginalContent() instanceof View) { return [ 'view' => $response->getOriginalContent()->getPath(), 'data' => $this->extractDataFromView($response->getOriginalContent()), ]; } return 'HTML Response'; }
php
{ "resource": "" }
q14073
RequestWatcher.extractDataFromView
train
protected function extractDataFromView($view) { return collect($view->getData())->map(function ($value) { if ($value instanceof Model) { return FormatModel::given($value); } elseif (is_object($value)) { return [ 'class' => get_class($value), 'properties' => json_decode(json_encode($value), true), ]; } else { return json_decode(json_encode($value), true); } })->toArray(); }
php
{ "resource": "" }
q14074
CommandWatcher.recordCommand
train
public function recordCommand(CommandFinished $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } Telescope::recordCommand(IncomingEntry::make([ 'command' => $event->command ?? $event->input->getArguments()['command'] ?? 'default', 'exit_code' => $event->exitCode, 'arguments' => $event->input->getArguments(), 'options' => $event->input->getOptions(), ])); }
php
{ "resource": "" }
q14075
CacheWatcher.recordCacheHit
train
public function recordCacheHit(CacheHit $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } Telescope::recordCache(IncomingEntry::make([ 'type' => 'hit', 'key' => $event->key, 'value' => $event->value, ])); }
php
{ "resource": "" }
q14076
CacheWatcher.recordCacheMissed
train
public function recordCacheMissed(CacheMissed $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } Telescope::recordCache(IncomingEntry::make([ 'type' => 'missed', 'key' => $event->key, ])); }
php
{ "resource": "" }
q14077
CacheWatcher.recordKeyWritten
train
public function recordKeyWritten(KeyWritten $event) { if (! Telescope::isRecording() || $this->shouldIgnore($event)) { return; } Telescope::recordCache(IncomingEntry::make([ 'type' => 'set', 'key' => $event->key, 'value' => $event->value, 'expiration' => $this->formatExpiration($event), ])); }
php
{ "resource": "" }
q14078
IncomingEntry.user
train
public function user($user) { $this->user = $user; $this->content = array_merge($this->content, [ 'user' => [ 'id' => $user->getAuthIdentifier(), 'name' => $user->name ?? null, 'email' => $user->email ?? null, ], ]); $this->tags(['Auth:'.$user->getAuthIdentifier()]); return $this; }
php
{ "resource": "" }
q14079
IncomingEntry.tags
train
public function tags(array $tags) { $this->tags = array_unique(array_merge($this->tags, $tags)); return $this; }
php
{ "resource": "" }
q14080
IncomingEntry.hasMonitoredTag
train
public function hasMonitoredTag() { if (! empty($this->tags)) { return app(EntriesRepository::class)->isMonitoring($this->tags); } return false; }
php
{ "resource": "" }
q14081
IncomingEntry.toArray
train
public function toArray() { return [ 'uuid' => $this->uuid, 'batch_id' => $this->batchId, 'type' => $this->type, 'content' => $this->content, 'created_at' => $this->recordedAt->toDateTimeString(), ]; }
php
{ "resource": "" }
q14082
IncomingDumpEntry.assignEntryPointFromBatch
train
public function assignEntryPointFromBatch(array $batch) { $entryPoint = collect($batch)->first(function ($entry) { return in_array($entry->type, [EntryType::REQUEST, EntryType::JOB, EntryType::COMMAND]); }); if (! $entryPoint) { return; } $this->content = array_merge($this->content, [ 'entry_point_type' => $entryPoint->type, 'entry_point_uuid' => $entryPoint->uuid, 'entry_point_description' => $this->entryPointDescription($entryPoint), ]); }
php
{ "resource": "" }
q14083
IncomingDumpEntry.entryPointDescription
train
private function entryPointDescription($entryPoint) { switch ($entryPoint->type) { case EntryType::REQUEST: return $entryPoint->content['method'].' '.$entryPoint->content['uri']; case EntryType::JOB: return $entryPoint->content['name']; case EntryType::COMMAND: return $entryPoint->content['command']; } return ''; }
php
{ "resource": "" }
q14084
EntryResult.jsonSerialize
train
public function jsonSerialize() { return [ 'id' => $this->id, 'sequence' => $this->sequence, 'batch_id' => $this->batchId, 'type' => $this->type, 'content' => $this->content, 'tags' => $this->tags, 'family_hash' => $this->familyHash, 'created_at' => $this->createdAt->toDateTimeString(), ]; }
php
{ "resource": "" }
q14085
GitInfoCollector.collect
train
public function collect() : GitInfo { $branch = $this->collectBranch(); $commit = $this->collectCommit(); $remotes = $this->collectRemotes(); return new GitInfo($branch, $commit, $remotes); }
php
{ "resource": "" }
q14086
Message.parse
train
public static function parse(string $msg): Message { $obj = new self; $parts = explode("\r\n", $msg); $obj->body = MessageBody::parse(array_pop($parts)); foreach ($parts as $line) { if ($line) { $pair = explode(': ', $line); $obj->headers[$pair[0]] = $pair[1]; } } return $obj; }
php
{ "resource": "" }
q14087
SimpleNameResolver.resolveName
train
protected function resolveName(Name $name, $type) { $resolvedName = $this->nameContext->getResolvedName($name, $type); if (null !== $resolvedName) { $name->setAttribute('resolvedName', $resolvedName->toString()); } return $name; }
php
{ "resource": "" }
q14088
Pool.streamForParent
train
private static function streamForParent(array $sockets) { list($for_read, $for_write) = $sockets; // The parent will not use the write channel, so it // must be closed to prevent deadlock. fclose($for_write); // stream_select will be used to read multiple streams, so these // must be set to non-blocking mode. if (!stream_set_blocking($for_read, false)) { error_log('unable to set read stream to non-blocking'); exit(self::EXIT_FAILURE); } return $for_read; }
php
{ "resource": "" }
q14089
Pool.readResultsFromChildren
train
private function readResultsFromChildren() { // Create an array of all active streams, indexed by // resource id. $streams = []; foreach ($this->read_streams as $stream) { $streams[intval($stream)] = $stream; } // Create an array for the content received on each stream, // indexed by resource id. $content = array_fill_keys(array_keys($streams), ''); // Read the data off of all the stream. while (count($streams) > 0) { $needs_read = array_values($streams); $needs_write = null; $needs_except = null; // Wait for data on at least one stream. $num = stream_select($needs_read, $needs_write, $needs_except, null /* no timeout */); if ($num === false) { error_log('unable to select on read stream'); exit(self::EXIT_FAILURE); } // For each stream that was ready, read the content. foreach ($needs_read as $file) { $buffer = fread($file, 1024); if ($buffer) { $content[intval($file)] .= $buffer; } // If the stream has closed, stop trying to select on it. if (feof($file)) { fclose($file); unset($streams[intval($file)]); } } } // Unmarshal the content into its original form. return array_values( array_map( /** * @param string $data * * @return array */ function ($data) { /** @var array */ $result = unserialize($data); /** @psalm-suppress DocblockTypeContradiction */ if (!\is_array($result)) { error_log( 'Child terminated without returning a serialized array - response type=' . gettype($result) ); $this->did_have_error = true; } return $result; }, $content ) ); }
php
{ "resource": "" }
q14090
Pool.wait
train
public function wait(): array { // Read all the streams from child processes into an array. $content = $this->readResultsFromChildren(); // Wait for all children to return foreach ($this->child_pid_list as $child_pid) { $process_lookup = posix_kill($child_pid, 0); $status = 0; if ($process_lookup) { /** * @psalm-suppress UndefinedConstant - does not exist on windows * @psalm-suppress MixedArgument */ posix_kill($child_pid, SIGALRM); if (pcntl_waitpid($child_pid, $status) < 0) { error_log(posix_strerror(posix_get_last_error())); } } // Check to see if the child died a graceful death if (pcntl_wifsignaled($status)) { $return_code = pcntl_wexitstatus($status); $term_sig = pcntl_wtermsig($status); /** * @psalm-suppress UndefinedConstant - does not exist on windows */ if ($term_sig !== SIGALRM) { $this->did_have_error = true; error_log("Child terminated with return code $return_code and signal $term_sig"); } } } return $content; }
php
{ "resource": "" }
q14091
CustomTraverser.traverseNode
train
protected function traverseNode(Node $node) : Node { foreach ($node->getSubNodeNames() as $name) { $subNode =& $node->$name; if (\is_array($subNode)) { $subNode = $this->traverseArray($subNode); if ($this->stopTraversal) { break; } } elseif ($subNode instanceof Node) { $traverseChildren = true; foreach ($this->visitors as $visitor) { $return = $visitor->enterNode($subNode, $traverseChildren); if (null !== $return) { if ($return instanceof Node) { $subNode = $return; } elseif (self::DONT_TRAVERSE_CHILDREN === $return) { $traverseChildren = false; } elseif (self::STOP_TRAVERSAL === $return) { $this->stopTraversal = true; break 2; } else { throw new \LogicException( 'enterNode() returned invalid value of type ' . gettype($return) ); } } } if ($traverseChildren) { $subNode = $this->traverseNode($subNode); if ($this->stopTraversal) { break; } } foreach ($this->visitors as $visitor) { $return = $visitor->leaveNode($subNode); if (null !== $return) { if ($return instanceof Node) { $subNode = $return; } elseif (self::STOP_TRAVERSAL === $return) { $this->stopTraversal = true; break 2; } elseif (\is_array($return)) { throw new \LogicException( 'leaveNode() may only return an array ' . 'if the parent structure is an array' ); } else { throw new \LogicException( 'leaveNode() returned invalid value of type ' . gettype($return) ); } } } } } return $node; }
php
{ "resource": "" }
q14092
ClassLikeAnalyzer.getFQCLNFromNameObject
train
public static function getFQCLNFromNameObject( PhpParser\Node\Name $class_name, Aliases $aliases ) { /** @var string|null */ $resolved_name = $class_name->getAttribute('resolvedName'); if ($resolved_name) { return $resolved_name; } if ($class_name instanceof PhpParser\Node\Name\FullyQualified) { return implode('\\', $class_name->parts); } if (in_array($class_name->parts[0], ['self', 'static', 'parent'], true)) { return $class_name->parts[0]; } return Type::getFQCLNFromString( implode('\\', $class_name->parts), $aliases ); }
php
{ "resource": "" }
q14093
ClassLikeAnalyzer.getTypeFromValue
train
public static function getTypeFromValue($value) { switch (gettype($value)) { case 'boolean': if ($value) { return Type::getTrue(); } return Type::getFalse(); case 'integer': return Type::getInt(false, $value); case 'double': return Type::getFloat($value); case 'string': return Type::getString($value); case 'array': return Type::getArray(); case 'NULL': return Type::getNull(); default: return Type::getMixed(); } }
php
{ "resource": "" }
q14094
EchoChecker.afterStatementAnalysis
train
public static function afterStatementAnalysis( PhpParser\Node\Stmt $stmt, Context $context, StatementsSource $statements_source, Codebase $codebase, array &$file_replacements = [] ) { if ($stmt instanceof PhpParser\Node\Stmt\Echo_) { foreach ($stmt->exprs as $expr) { if (!isset($expr->inferredType) || $expr->inferredType->hasMixed()) { if (IssueBuffer::accepts( new ArgumentTypeCoercion( 'Echo requires an unescaped string, ' . $expr->inferredType . ' provided', new CodeLocation($statements_source, $expr), 'echo' ), $statements_source->getSuppressedIssues() )) { // keep soldiering on } continue; } $types = $expr->inferredType->getTypes(); foreach ($types as $type) { if ($type instanceof \Psalm\Type\Atomic\TString && !$type instanceof \Psalm\Type\Atomic\TLiteralString && !$type instanceof \Psalm\Type\Atomic\THtmlEscapedString ) { if (IssueBuffer::accepts( new ArgumentTypeCoercion( 'Echo requires an unescaped string, ' . $expr->inferredType . ' provided', new CodeLocation($statements_source, $expr), 'echo' ), $statements_source->getSuppressedIssues() )) { // keep soldiering on } } } } } }
php
{ "resource": "" }
q14095
Scanner.fileExistsForClassLike
train
private function fileExistsForClassLike(ClassLikes $classlikes, $fq_class_name) { $fq_class_name_lc = strtolower($fq_class_name); if (isset($this->classlike_files[$fq_class_name_lc])) { return true; } if ($fq_class_name === 'self') { return false; } if (isset($this->existing_classlikes_lc[$fq_class_name_lc])) { throw new \InvalidArgumentException('Why are you asking about a builtin class?'); } $composer_file_path = $this->config->getComposerFilePathForClassLike($fq_class_name); if ($composer_file_path && file_exists($composer_file_path)) { if ($this->debug_output) { echo 'Using composer to locate file for ' . $fq_class_name . "\n"; } $classlikes->addFullyQualifiedClassLikeName( $fq_class_name_lc, realpath($composer_file_path) ); return true; } $old_level = error_reporting(); if (!$this->debug_output) { error_reporting(E_ERROR); } try { if ($this->debug_output) { echo 'Using reflection to locate file for ' . $fq_class_name . "\n"; } /** @psalm-suppress TypeCoercion */ $reflected_class = new \ReflectionClass($fq_class_name); } catch (\Throwable $e) { error_reporting($old_level); // do not cache any results here (as case-sensitive filenames can screw things up) return false; } error_reporting($old_level); /** @psalm-suppress MixedMethodCall due to Reflection class weirdness */ $file_path = (string)$reflected_class->getFileName(); // if the file was autoloaded but exists in evaled code only, return false if (!file_exists($file_path)) { return false; } $new_fq_class_name = $reflected_class->getName(); if (strtolower($new_fq_class_name) !== strtolower($fq_class_name)) { $classlikes->addClassAlias($new_fq_class_name, strtolower($fq_class_name)); $fq_class_name_lc = strtolower($new_fq_class_name); } $fq_class_name = $new_fq_class_name; $classlikes->addFullyQualifiedClassLikeName($fq_class_name_lc); if ($reflected_class->isInterface()) { $classlikes->addFullyQualifiedInterfaceName($fq_class_name, $file_path); } elseif ($reflected_class->isTrait()) { $classlikes->addFullyQualifiedTraitName($fq_class_name, $file_path); } else { $classlikes->addFullyQualifiedClassName($fq_class_name, $file_path); } return true; }
php
{ "resource": "" }
q14096
TypeAnalyzer.isContainedByInPhp
train
public static function isContainedByInPhp( Type\Union $input_type = null, Type\Union $container_type ) { if (!$input_type) { return false; } if ($input_type->getId() === $container_type->getId()) { return true; } if ($input_type->isNullable() && !$container_type->isNullable()) { return false; } $input_type_not_null = clone $input_type; $input_type_not_null->removeType('null'); $container_type_not_null = clone $container_type; $container_type_not_null->removeType('null'); if ($input_type_not_null->getId() === $container_type_not_null->getId()) { return true; } if ($input_type_not_null->hasArray() && $container_type_not_null->hasType('iterable')) { return true; } return false; }
php
{ "resource": "" }
q14097
TypeAnalyzer.isSimplyContainedBy
train
public static function isSimplyContainedBy( Type\Union $input_type, Type\Union $container_type ) { if ($input_type->getId() === $container_type->getId()) { return true; } if ($input_type->isNullable() && !$container_type->isNullable()) { return false; } $input_type_not_null = clone $input_type; $input_type_not_null->removeType('null'); $container_type_not_null = clone $container_type; $container_type_not_null->removeType('null'); return (bool) array_intersect_key( $input_type_not_null->getTypes(), $container_type_not_null->getTypes() ); }
php
{ "resource": "" }
q14098
BuildInfoCollector.fillJenkins
train
protected function fillJenkins() : self { if (isset($this->env['JENKINS_URL']) && isset($this->env['BUILD_NUMBER'])) { $this->readEnv['CI_BUILD_NUMBER'] = $this->env['BUILD_NUMBER']; $this->readEnv['CI_BUILD_URL'] = $this->env['JENKINS_URL']; $this->env['CI_NAME'] = 'jenkins'; // backup $this->readEnv['BUILD_NUMBER'] = $this->env['BUILD_NUMBER']; $this->readEnv['JENKINS_URL'] = $this->env['JENKINS_URL']; $this->readEnv['CI_NAME'] = $this->env['CI_NAME']; } return $this; }
php
{ "resource": "" }
q14099
BuildInfoCollector.fillScrutinizer
train
protected function fillScrutinizer() : self { if (isset($this->env['SCRUTINIZER']) && $this->env['SCRUTINIZER']) { $this->readEnv['CI_JOB_ID'] = $this->env['SCRUTINIZER_INSPECTION_UUID']; $this->readEnv['CI_BRANCH'] = $this->env['SCRUTINIZER_BRANCH']; $this->readEnv['CI_PR_NUMBER'] = $this->env['SCRUTINIZER_PR_NUMBER'] ?? ''; // backup $this->readEnv['CI_NAME'] = 'Scrutinizer'; $repo_slug = (string) $this->env['SCRUTINIZER_PROJECT'] ?? ''; if ($repo_slug) { $slug_parts = explode('/', $repo_slug); if ($this->readEnv['CI_PR_NUMBER']) { $this->readEnv['CI_PR_REPO_OWNER'] = $slug_parts[1]; $this->readEnv['CI_PR_REPO_NAME'] = $slug_parts[2]; } else { $this->readEnv['CI_REPO_OWNER'] = $slug_parts[1]; $this->readEnv['CI_REPO_NAME'] = $slug_parts[2]; } } } return $this; }
php
{ "resource": "" }