diff --git a/README.md b/README.md index 30be5cbd..ca74a393 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ try { - Laravel `<= 4.2.x` is supported until `0.8.x` - Laravel `<= 5.7.x` on PHP `<= 7.0` is supported until `0.11.x` -- Laravel `>= 5.x.x` on PHP `>= 7.1` is supported in all versions +- Laravel `>= 5.x.x` on PHP `>= 7.1` is supported until `2.14.x` - Laravel `>= 6.x.x` on PHP `>= 7.2` is supported starting from `1.2.0` - Laravel `>= 7.x.x` on PHP `>= 7.2` is supported starting from `1.7.0` - Laravel `>= 8.x.x` on PHP `>= 7.3` is supported starting from `1.9.0` diff --git a/src/Sentry/Laravel/EventHandler.php b/src/Sentry/Laravel/EventHandler.php index 8db2bb1d..61fed658 100644 --- a/src/Sentry/Laravel/EventHandler.php +++ b/src/Sentry/Laravel/EventHandler.php @@ -3,24 +3,19 @@ namespace Sentry\Laravel; use Exception; -use Illuminate\Auth\Events\Authenticated; -use Illuminate\Console\Events\CommandFinished; -use Illuminate\Console\Events\CommandStarting; +use Illuminate\Auth\Events as AuthEvents; +use Illuminate\Console\Events as ConsoleEvents; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Events\QueryExecuted; +use Illuminate\Database\Events as DatabaseEvents; use Illuminate\Http\Request; -use Illuminate\Log\Events\MessageLogged; -use Illuminate\Queue\Events\JobExceptionOccurred; -use Illuminate\Queue\Events\JobProcessed; -use Illuminate\Queue\Events\JobProcessing; -use Illuminate\Queue\Events\WorkerStopping; +use Illuminate\Log\Events as LogEvents; +use Illuminate\Queue\Events as QueueEvents; use Illuminate\Queue\QueueManager; -use Illuminate\Routing\Events\RouteMatched; -use Illuminate\Routing\Route; +use Illuminate\Routing\Events as RoutingEvents; use Laravel\Octane\Events as Octane; use Laravel\Sanctum\Events as Sanctum; use RuntimeException; @@ -36,17 +31,11 @@ class EventHandler * @var array */ protected static $eventHandlerMap = [ - 'router.matched' => 'routerMatched', // Until Laravel 5.1 - 'Illuminate\Routing\Events\RouteMatched' => 'routeMatched', // Since Laravel 5.2 - - 'illuminate.query' => 'query', // Until Laravel 5.1 - 'Illuminate\Database\Events\QueryExecuted' => 'queryExecuted', // Since Laravel 5.2 - - 'illuminate.log' => 'log', // Until Laravel 5.3 - 'Illuminate\Log\Events\MessageLogged' => 'messageLogged', // Since Laravel 5.4 - - 'Illuminate\Console\Events\CommandStarting' => 'commandStarting', // Since Laravel 5.5 - 'Illuminate\Console\Events\CommandFinished' => 'commandFinished', // Since Laravel 5.5 + LogEvents\MessageLogged::class => 'messageLogged', + RoutingEvents\RouteMatched::class => 'routeMatched', + DatabaseEvents\QueryExecuted::class => 'queryExecuted', + ConsoleEvents\CommandStarting::class => 'commandStarting', + ConsoleEvents\CommandFinished::class => 'commandFinished', ]; /** @@ -55,8 +44,8 @@ class EventHandler * @var array */ protected static $authEventHandlerMap = [ - 'Illuminate\Auth\Events\Authenticated' => 'authenticated', // Since Laravel 5.3 - 'Laravel\Sanctum\Events\TokenAuthenticated' => 'sanctumTokenAuthenticated', // Since Sanctum 2.13 + AuthEvents\Authenticated::class => 'authenticated', + Sanctum\TokenAuthenticated::class => 'sanctumTokenAuthenticated', // Since Sanctum 2.13 ]; /** @@ -65,10 +54,10 @@ class EventHandler * @var array */ protected static $queueEventHandlerMap = [ - 'Illuminate\Queue\Events\JobProcessed' => 'queueJobProcessed', // Since Laravel 5.2 - 'Illuminate\Queue\Events\JobProcessing' => 'queueJobProcessing', // Since Laravel 5.2 - 'Illuminate\Queue\Events\WorkerStopping' => 'queueWorkerStopping', // Since Laravel 5.2 - 'Illuminate\Queue\Events\JobExceptionOccurred' => 'queueJobExceptionOccurred', // Since Laravel 5.2 + QueueEvents\JobProcessed::class => 'queueJobProcessed', + QueueEvents\JobProcessing::class => 'queueJobProcessing', + QueueEvents\WorkerStopping::class => 'queueWorkerStopping', + QueueEvents\JobExceptionOccurred::class => 'queueJobExceptionOccurred', ]; /** @@ -77,17 +66,17 @@ class EventHandler * @var array */ protected static $octaneEventHandlerMap = [ - 'Laravel\Octane\Events\RequestReceived' => 'octaneRequestReceived', - 'Laravel\Octane\Events\RequestTerminated' => 'octaneRequestTerminated', + Octane\RequestReceived::class => 'octaneRequestReceived', + Octane\RequestTerminated::class => 'octaneRequestTerminated', - 'Laravel\Octane\Events\TaskReceived' => 'octaneTaskReceived', - 'Laravel\Octane\Events\TaskTerminated' => 'octaneTaskTerminated', + Octane\TaskReceived::class => 'octaneTaskReceived', + Octane\TaskTerminated::class => 'octaneTaskTerminated', - 'Laravel\Octane\Events\TickReceived' => 'octaneTickReceived', - 'Laravel\Octane\Events\TickTerminated' => 'octaneTickTerminated', + Octane\TickReceived::class => 'octaneTickReceived', + Octane\TickTerminated::class => 'octaneTickTerminated', - 'Laravel\Octane\Events\WorkerErrorOccurred' => 'octaneWorkerErrorOccurred', - 'Laravel\Octane\Events\WorkerStopping' => 'octaneWorkerStopping', + Octane\WorkerErrorOccurred::class => 'octaneWorkerErrorOccurred', + Octane\WorkerStopping::class => 'octaneWorkerStopping', ]; /** @@ -261,7 +250,7 @@ public function subscribeQueueEvents(QueueManager $queue): void * @param string $method * @param array $arguments */ - public function __call($method, $arguments) + public function __call(string $method, array $arguments) { $handlerMethod = "{$method}Handler"; @@ -276,14 +265,9 @@ public function __call($method, $arguments) } } - /** - * Until Laravel 5.1 - * - * @param Route $route - */ - protected function routerMatchedHandler(Route $route) + protected function routeMatchedHandler(RoutingEvents\RouteMatched $match): void { - [$routeName] = Integration::extractNameAndSourceForRoute($route); + [$routeName] = Integration::extractNameAndSourceForRoute($match->route); Integration::addBreadcrumb(new Breadcrumb( Breadcrumb::LEVEL_INFO, @@ -295,106 +279,32 @@ protected function routerMatchedHandler(Route $route) Integration::setTransaction($routeName); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Routing\Events\RouteMatched $match - */ - protected function routeMatchedHandler(RouteMatched $match) - { - $this->routerMatchedHandler($match->route); - } - - /** - * Until Laravel 5.1 - * - * @param string $query - * @param array $bindings - * @param int $time - * @param string $connectionName - */ - protected function queryHandler($query, $bindings, $time, $connectionName) + protected function queryExecutedHandler(DatabaseEvents\QueryExecuted $query): void { if (!$this->recordSqlQueries) { return; } - $this->addQueryBreadcrumb($query, $bindings, $time, $connectionName); - } + $data = ['connectionName' => $query->connectionName]; - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Database\Events\QueryExecuted $query - */ - protected function queryExecutedHandler(QueryExecuted $query) - { - if (!$this->recordSqlQueries) { - return; - } - - $this->addQueryBreadcrumb($query->sql, $query->bindings, $query->time, $query->connectionName); - } - - /** - * Helper to add an query breadcrumb. - * - * @param string $query - * @param array $bindings - * @param float|null $time - * @param string $connectionName - */ - private function addQueryBreadcrumb($query, $bindings, $time, $connectionName) - { - $data = ['connectionName' => $connectionName]; - - if ($time !== null) { - $data['executionTimeMs'] = $time; + if ($query->time !== null) { + $data['executionTimeMs'] = $query->time; } if ($this->recordSqlBindings) { - $data['bindings'] = $bindings; + $data['bindings'] = $query->bindings; } Integration::addBreadcrumb(new Breadcrumb( Breadcrumb::LEVEL_INFO, Breadcrumb::TYPE_DEFAULT, 'sql.query', - $query, + $query->sql, $data )); } - /** - * Until Laravel 5.3 - * - * @param string $level - * @param string $message - * @param array|null $context - */ - protected function logHandler($level, $message, $context) - { - $this->addLogBreadcrumb($level, $message, is_array($context) ? $context : []); - } - - /** - * Since Laravel 5.4 - * - * @param \Illuminate\Log\Events\MessageLogged $logEntry - */ - protected function messageLoggedHandler(MessageLogged $logEntry) - { - $this->addLogBreadcrumb($logEntry->level, $logEntry->message, $logEntry->context); - } - - /** - * Helper to add an log breadcrumb. - * - * @param string $level Log level. May be any standard. - * @param string|null $message Log message. - * @param array $context Log context. - */ - private function addLogBreadcrumb(string $level, ?string $message, array $context = []): void + protected function messageLoggedHandler(LogEvents\MessageLogged $logEntry): void { if (!$this->recordLaravelLogs) { return; @@ -403,35 +313,25 @@ private function addLogBreadcrumb(string $level, ?string $message, array $contex // A log message with `null` as value will not be recorded by Laravel // however empty strings are logged so we mimick that behaviour to // check for `null` to stay consistent with how Laravel logs it - if ($message === null) { + if ($logEntry->message === null) { return; } Integration::addBreadcrumb(new Breadcrumb( - $this->logLevelToBreadcrumbLevel($level), + $this->logLevelToBreadcrumbLevel($logEntry->level), Breadcrumb::TYPE_DEFAULT, - 'log.' . $level, - $message, - $context + 'log.' . $logEntry->level, + $logEntry->message, + $logEntry->context )); } - /** - * Since Laravel 5.3 - * - * @param \Illuminate\Auth\Events\Authenticated $event - */ - protected function authenticatedHandler(Authenticated $event) + protected function authenticatedHandler(AuthEvents\Authenticated $event): void { $this->configureUserScopeFromModel($event->user); } - /** - * Since Sanctum 2.13 - * - * @param \Laravel\Sanctum\Events\TokenAuthenticated $event - */ - protected function sanctumTokenAuthenticatedHandler(Sanctum\TokenAuthenticated $event) + protected function sanctumTokenAuthenticatedHandler(Sanctum\TokenAuthenticated $event): void { $this->configureUserScopeFromModel($event->token->tokenable); } @@ -478,12 +378,7 @@ private function configureUserScopeFromModel($authUser): void }); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\JobProcessing $event - */ - protected function queueJobProcessingHandler(JobProcessing $event) + protected function queueJobProcessingHandler(QueueEvents\JobProcessing $event): void { $this->cleanupScopeForTaskWithinLongRunningProcessWhen($this->pushedQueueScope); @@ -516,43 +411,23 @@ protected function queueJobProcessingHandler(JobProcessing $event) )); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\JobExceptionOccurred $event - */ - protected function queueJobExceptionOccurredHandler(JobExceptionOccurred $event) + protected function queueJobExceptionOccurredHandler(QueueEvents\JobExceptionOccurred $event): void { $this->afterTaskWithinLongRunningProcess(); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\JobProcessed $event - */ - protected function queueJobProcessedHandler(JobProcessed $event) + protected function queueJobProcessedHandler(QueueEvents\JobProcessed $event): void { $this->afterTaskWithinLongRunningProcess(); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\WorkerStopping $event - */ - protected function queueWorkerStoppingHandler(WorkerStopping $event) + protected function queueWorkerStoppingHandler(QueueEvents\WorkerStopping $event): void { // Flush any and all events that were possibly generated by queue jobs Integration::flushEvents(); } - /** - * Since Laravel 5.5 - * - * @param \Illuminate\Console\Events\CommandStarting $event - */ - protected function commandStartingHandler(CommandStarting $event) + protected function commandStartingHandler(ConsoleEvents\CommandStarting $event): void { if ($event->command) { Integration::configureScope(static function (Scope $scope) use ($event): void { @@ -575,12 +450,7 @@ protected function commandStartingHandler(CommandStarting $event) } } - /** - * Since Laravel 5.5 - * - * @param \Illuminate\Console\Events\CommandFinished $event - */ - protected function commandFinishedHandler(CommandFinished $event) + protected function commandFinishedHandler(ConsoleEvents\CommandFinished $event): void { if ($this->recordCommandInfo) { Integration::addBreadcrumb(new Breadcrumb( diff --git a/src/Sentry/Laravel/Http/SetRequestMiddleware.php b/src/Sentry/Laravel/Http/SetRequestMiddleware.php index bbdfca4e..ffa85e6a 100644 --- a/src/Sentry/Laravel/Http/SetRequestMiddleware.php +++ b/src/Sentry/Laravel/Http/SetRequestMiddleware.php @@ -4,11 +4,10 @@ use Closure; use Illuminate\Container\Container; +use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Http\Request; -use Nyholm\Psr7\Factory\Psr17Factory; use Psr\Http\Message\ServerRequestInterface; use Sentry\State\HubInterface; -use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; /** * This middleware caches a PSR-7 version of the request as early as possible. @@ -21,7 +20,7 @@ public function handle(Request $request, Closure $next) $container = Container::getInstance(); if ($container->bound(HubInterface::class)) { - $psrRequest = $this->resolvePsrRequest($request); + $psrRequest = $this->resolvePsrRequest($container); if ($psrRequest !== null) { $container->instance(LaravelRequestFetcher::CONTAINER_PSR7_INSTANCE_KEY, $psrRequest); @@ -31,26 +30,12 @@ public function handle(Request $request, Closure $next) return $next($request); } - /** - * This code was copied from the Laravel codebase which was introduced in Laravel 6. - * - * The reason we have it copied here is because older (<6.0) versions of Laravel use a different - * method to construct the PSR-7 request object which requires other packages to create that object - * but most importantly it does not function when those packages are not available resulting in errors - * - * So long story short, this is here to backport functionality to Laravel <6.0 - * if we drop support for those versions in the future we can reconsider this and - * move back to using the container binding provided by Laravel for the PSR-7 object - * - * @see https://github.com/laravel/framework/blob/cb550b5bdc2b2c4cf077082adabde0144a72d190/src/Illuminate/Routing/RoutingServiceProvider.php#L127-L146 - */ - private function resolvePsrRequest(Request $request): ?ServerRequestInterface + private function resolvePsrRequest(Container $container): ?ServerRequestInterface { - if (class_exists(Psr17Factory::class) && class_exists(PsrHttpFactory::class)) { - $psr17Factory = new Psr17Factory; - - return (new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory)) - ->createRequest($request); + try { + return $container->make(ServerRequestInterface::class); + } catch (BindingResolutionException $e) { + // This happens if Laravel doesn't have the correct classes available to construct the PSR-7 object } return null; diff --git a/src/Sentry/Laravel/Integration.php b/src/Sentry/Laravel/Integration.php index 905d3622..e2fdf043 100644 --- a/src/Sentry/Laravel/Integration.php +++ b/src/Sentry/Laravel/Integration.php @@ -273,8 +273,7 @@ private static function extractNameForActionRoute(string $action): string } // Strip away the base namespace from the action name - // @see: Str::after, but this is not available before Laravel 5.4 so we use a inlined version - return array_reverse(explode($baseNamespace . '\\', $routeName, 2))[0]; + return ltrim(Str::after($routeName, $baseNamespace), '\\'); } /** diff --git a/src/Sentry/Laravel/Tracing/EventHandler.php b/src/Sentry/Laravel/Tracing/EventHandler.php index 1fafb3bd..fcae4a81 100644 --- a/src/Sentry/Laravel/Tracing/EventHandler.php +++ b/src/Sentry/Laravel/Tracing/EventHandler.php @@ -30,8 +30,7 @@ class EventHandler * @var array */ protected static $eventHandlerMap = [ - 'illuminate.query' => 'query', // Until Laravel 5.1 - DatabaseEvents\QueryExecuted::class => 'queryExecuted', // Since Laravel 5.2 + DatabaseEvents\QueryExecuted::class => 'queryExecuted', ]; /** @@ -40,9 +39,9 @@ class EventHandler * @var array */ protected static $queueEventHandlerMap = [ - QueueEvents\JobProcessing::class => 'queueJobProcessing', // Since Laravel 5.2 - QueueEvents\JobProcessed::class => 'queueJobProcessed', // Since Laravel 5.2 - QueueEvents\JobExceptionOccurred::class => 'queueJobExceptionOccurred', // Since Laravel 5.2 + QueueEvents\JobProcessing::class => 'queueJobProcessing', + QueueEvents\JobProcessed::class => 'queueJobProcessed', + QueueEvents\JobExceptionOccurred::class => 'queueJobExceptionOccurred', ]; /** @@ -149,19 +148,16 @@ public function subscribeQueueEvents(QueueManager $queue): void return; } - // The payload create callback was introduced in Laravel 5.7 so we need to guard against older versions - if (method_exists(Queue::class, 'createPayloadUsing')) { - Queue::createPayloadUsing(static function (?string $connection, ?string $queue, ?array $payload): ?array { - $currentSpan = Integration::currentTracingSpan(); + Queue::createPayloadUsing(static function (?string $connection, ?string $queue, ?array $payload): ?array { + $currentSpan = Integration::currentTracingSpan(); - if ($currentSpan !== null && $payload !== null) { - $payload[self::QUEUE_PAYLOAD_TRACE_PARENT_DATA] = $currentSpan->toTraceparent(); - $payload[self::QUEUE_PAYLOAD_BAGGAGE_DATA] = $currentSpan->toBaggage(); - } + if ($currentSpan !== null && $payload !== null) { + $payload[self::QUEUE_PAYLOAD_TRACE_PARENT_DATA] = $currentSpan->toTraceparent(); + $payload[self::QUEUE_PAYLOAD_BAGGAGE_DATA] = $currentSpan->toBaggage(); + } - return $payload; - }); - } + return $payload; + }); $queue->looping(function () { $this->afterQueuedJob(); @@ -185,7 +181,7 @@ public function subscribeQueueEvents(QueueManager $queue): void * @param string $method * @param array $arguments */ - public function __call($method, $arguments) + public function __call(string $method, array $arguments) { $handlerMethod = "{$method}Handler"; @@ -200,36 +196,7 @@ public function __call($method, $arguments) } } - /** - * Until Laravel 5.1 - * - * @param string $query - * @param array $bindings - * @param int $time - * @param string $connectionName - */ - protected function queryHandler($query, $bindings, $time, $connectionName): void - { - $this->recordQuerySpan($query, $time); - } - - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Database\Events\QueryExecuted $query - */ protected function queryExecutedHandler(DatabaseEvents\QueryExecuted $query): void - { - $this->recordQuerySpan($query->sql, $query->time); - } - - /** - * Helper to add an query breadcrumb. - * - * @param string $query - * @param float|null $time - */ - private function recordQuerySpan($query, $time): void { if (!$this->traceSqlQueries) { return; @@ -244,12 +211,12 @@ private function recordQuerySpan($query, $time): void $context = new SpanContext(); $context->setOp('db.sql.query'); - $context->setDescription($query); - $context->setStartTimestamp(microtime(true) - $time / 1000); - $context->setEndTimestamp($context->getStartTimestamp() + $time / 1000); + $context->setDescription($query->sql); + $context->setStartTimestamp(microtime(true) - $query->time / 1000); + $context->setEndTimestamp($context->getStartTimestamp() + $query->time / 1000); if ($this->traceSqlQueryOrigins) { - $queryOrigin = $this->resolveQueryOriginFromBacktrace($context); + $queryOrigin = $this->resolveQueryOriginFromBacktrace(); if ($queryOrigin !== null) { $context->setData(['sql.origin' => $queryOrigin]); @@ -277,12 +244,7 @@ private function resolveQueryOriginFromBacktrace(): ?string return "{$filePath}:{$firstAppFrame->getLine()}"; } - /* - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\JobProcessing $event - */ - protected function queueJobProcessingHandler(QueueEvents\JobProcessing $event) + protected function queueJobProcessingHandler(QueueEvents\JobProcessing $event): void { $parentSpan = Integration::currentTracingSpan(); @@ -347,22 +309,12 @@ protected function queueJobProcessingHandler(QueueEvents\JobProcessing $event) SentrySdk::getCurrentHub()->setSpan($this->currentQueueJobSpan); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\JobExceptionOccurred $event - */ - protected function queueJobExceptionOccurredHandler(QueueEvents\JobExceptionOccurred $event) + protected function queueJobExceptionOccurredHandler(QueueEvents\JobExceptionOccurred $event): void { $this->afterQueuedJob(SpanStatus::internalError()); } - /** - * Since Laravel 5.2 - * - * @param \Illuminate\Queue\Events\JobProcessed $event - */ - protected function queueJobProcessedHandler(QueueEvents\JobProcessed $event) + protected function queueJobProcessedHandler(QueueEvents\JobProcessed $event): void { $this->afterQueuedJob(SpanStatus::ok()); } diff --git a/test/Sentry/CommandInfoInBreadcrumbsTest.php b/test/Sentry/CommandInfoInBreadcrumbsTest.php index f0b0a61c..0a7929f2 100644 --- a/test/Sentry/CommandInfoInBreadcrumbsTest.php +++ b/test/Sentry/CommandInfoInBreadcrumbsTest.php @@ -10,10 +10,6 @@ class CommandInfoInBreadcrumbsTest extends SentryLaravelTestCase { public function testCommandInfoAreRecordedWhenEnabled() { - if ($this->shouldSkip()) { - $this->markTestSkipped('Laravel version <5.5 does not contain the events tested.'); - } - $this->resetApplicationWithConfig([ 'sentry.breadcrumbs.command_info' => true, ]); @@ -30,10 +26,6 @@ public function testCommandInfoAreRecordedWhenEnabled() public function testCommandInfoAreRecordedWhenDisabled() { - if ($this->shouldSkip()) { - $this->markTestSkipped('Laravel version <5.5 does not contain the events tested.'); - } - $this->resetApplicationWithConfig([ 'sentry.breadcrumbs.command_info' => false, ]); @@ -60,9 +52,4 @@ private function dispatchCommandStartEvent() ) ); } - - private function shouldSkip() - { - return !class_exists(CommandStarting::class); - } } diff --git a/test/Sentry/IntegrationTest.php b/test/Sentry/IntegrationTest.php index c116bfc2..c3ba474e 100644 --- a/test/Sentry/IntegrationTest.php +++ b/test/Sentry/IntegrationTest.php @@ -22,10 +22,6 @@ public function testIntegrationIsRegistered(): void public function testTransactionIsSetWhenRouteMatchedEventIsFired(): void { - if (!class_exists(RouteMatched::class)) { - $this->markTestSkipped('RouteMatched event class does not exist on this version of Laravel.'); - } - Integration::setTransaction(null); $event = new RouteMatched( @@ -38,17 +34,6 @@ public function testTransactionIsSetWhenRouteMatchedEventIsFired(): void $this->assertSame($routeUrl, Integration::getTransaction()); } - public function testTransactionIsSetWhenRouterMatchedEventIsFired(): void - { - Integration::setTransaction(null); - - $this->dispatchLaravelEvent('router.matched', [ - new Route('GET', $routeUrl = '/sentry-router-matched-event', []), - ]); - - $this->assertSame($routeUrl, Integration::getTransaction()); - } - public function testTransactionIsAppliedToEventWithoutTransaction(): void { Integration::setTransaction($transaction = 'some-transaction-name'); diff --git a/test/Sentry/Laravel/LogChannelTest.php b/test/Sentry/Laravel/LogChannelTest.php index 26727660..e0ecc850 100644 --- a/test/Sentry/Laravel/LogChannelTest.php +++ b/test/Sentry/Laravel/LogChannelTest.php @@ -2,7 +2,6 @@ namespace Sentry\Laravel\Tests\Sentry\Laravel; -use Illuminate\Log\LogManager; use Monolog\Handler\FingersCrossedHandler; use Sentry\Laravel\LogChannel; use Sentry\Laravel\SentryHandler; @@ -12,8 +11,6 @@ class LogChannelTest extends SentryLaravelTestCase { public function test_creating_handler_without_action_level_config() { - $this->skipIfLogManagerNotAvailable(); - $logChannel = new LogChannel($this->app); $logger = $logChannel([]); @@ -22,8 +19,6 @@ public function test_creating_handler_without_action_level_config() public function test_creating_handler_with_action_level_config() { - $this->skipIfLogManagerNotAvailable(); - $logChannel = new LogChannel($this->app); $logger = $logChannel(['action_level' => 'critical']); @@ -36,13 +31,4 @@ public function test_creating_handler_with_action_level_config() $this->assertContainsOnlyInstancesOf(SentryHandler::class, $loggerWithoutActionLevel->getHandlers()); } - - private function skipIfLogManagerNotAvailable() - { - if (class_exists(LogManager::class)) { - return; - } - - $this->markTestSkipped('Laravel version <=5.5 does not contain the LogManager required for this functionality.'); - } } diff --git a/test/Sentry/LaravelLogsInBreadcrumbsTest.php b/test/Sentry/LaravelLogsInBreadcrumbsTest.php index 6fa09ebd..724bec96 100644 --- a/test/Sentry/LaravelLogsInBreadcrumbsTest.php +++ b/test/Sentry/LaravelLogsInBreadcrumbsTest.php @@ -2,9 +2,12 @@ namespace Sentry\Laravel\Tests; +use Illuminate\Log\Events\MessageLogged; +use Mockery; + class LaravelLogsInBreadcrumbsTest extends SentryLaravelTestCase { - public function testLaravelLogsAreRecordedWhenEnabled() + public function testLaravelLogsAreRecordedWhenEnabled(): void { $this->resetApplicationWithConfig([ 'sentry.breadcrumbs.logs' => true, @@ -12,11 +15,11 @@ public function testLaravelLogsAreRecordedWhenEnabled() $this->assertTrue($this->app['config']->get('sentry.breadcrumbs.logs')); - $this->dispatchLaravelEvent('illuminate.log', [ + $this->dispatchLaravelEvent(new MessageLogged( $level = 'debug', $message = 'test message', - $context = ['1'], - ]); + $context = ['1'] + )); $lastBreadcrumb = $this->getLastBreadcrumb(); @@ -25,7 +28,7 @@ public function testLaravelLogsAreRecordedWhenEnabled() $this->assertEquals($context, $lastBreadcrumb->getMetadata()); } - public function testLaravelLogsAreRecordedWhenDisabled() + public function testLaravelLogsAreRecordedWhenDisabled(): void { $this->resetApplicationWithConfig([ 'sentry.breadcrumbs.logs' => false, diff --git a/test/Sentry/SentryLaravelTestCase.php b/test/Sentry/SentryLaravelTestCase.php index eab9b670..fdb72835 100644 --- a/test/Sentry/SentryLaravelTestCase.php +++ b/test/Sentry/SentryLaravelTestCase.php @@ -42,14 +42,9 @@ protected function resetApplicationWithConfig(array $config) $this->refreshApplication(); } - protected function dispatchLaravelEvent($event, array $payload = []) + protected function dispatchLaravelEvent($event, array $payload = []): void { - $dispatcher = $this->app['events']; - - // Laravel 5.4+ uses the dispatch method to dispatch/fire events - return method_exists($dispatcher, 'dispatch') - ? $dispatcher->dispatch($event, $payload) - : $dispatcher->fire($event, $payload); + $this->app['events']->dispatch($event, $payload); } protected function getHubFromContainer(): HubInterface diff --git a/test/Sentry/SqlBindingsInBreadcrumbsTest.php b/test/Sentry/SqlBindingsInBreadcrumbsTest.php index 65affa33..e8e09300 100644 --- a/test/Sentry/SqlBindingsInBreadcrumbsTest.php +++ b/test/Sentry/SqlBindingsInBreadcrumbsTest.php @@ -2,9 +2,13 @@ namespace Sentry\Laravel\Tests; +use Illuminate\Database\Connection; +use Illuminate\Database\Events\QueryExecuted; +use Mockery; + class SqlBindingsInBreadcrumbsTest extends SentryLaravelTestCase { - public function testSqlBindingsAreRecordedWhenEnabled() + public function testSqlBindingsAreRecordedWhenEnabled(): void { $this->resetApplicationWithConfig([ 'sentry.breadcrumbs.sql_bindings' => true, @@ -12,12 +16,15 @@ public function testSqlBindingsAreRecordedWhenEnabled() $this->assertTrue($this->app['config']->get('sentry.breadcrumbs.sql_bindings')); - $this->dispatchLaravelEvent('illuminate.query', [ + $connection = Mockery::mock(Connection::class) + ->shouldReceive('getName')->andReturn('test'); + + $this->dispatchLaravelEvent(new QueryExecuted( $query = 'SELECT * FROM breadcrumbs WHERE bindings = ?;', $bindings = ['1'], 10, - 'test', - ]); + $connection + )); $lastBreadcrumb = $this->getLastBreadcrumb(); @@ -25,7 +32,7 @@ public function testSqlBindingsAreRecordedWhenEnabled() $this->assertEquals($bindings, $lastBreadcrumb->getMetadata()['bindings']); } - public function testSqlBindingsAreRecordedWhenDisabled() + public function testSqlBindingsAreRecordedWhenDisabled(): void { $this->resetApplicationWithConfig([ 'sentry.breadcrumbs.sql_bindings' => false, @@ -33,12 +40,15 @@ public function testSqlBindingsAreRecordedWhenDisabled() $this->assertFalse($this->app['config']->get('sentry.breadcrumbs.sql_bindings')); - $this->dispatchLaravelEvent('illuminate.query', [ + $connection = Mockery::mock(Connection::class) + ->shouldReceive('getName')->andReturn('test'); + + $this->dispatchLaravelEvent(new QueryExecuted( $query = 'SELECT * FROM breadcrumbs WHERE bindings <> ?;', ['1'], 10, - 'test', - ]); + $connection + )); $lastBreadcrumb = $this->getLastBreadcrumb(); diff --git a/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyDisabledTest.php b/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyDisabledTest.php index c60295bf..3b97bfc1 100644 --- a/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyDisabledTest.php +++ b/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyDisabledTest.php @@ -3,6 +3,9 @@ namespace Sentry\Laravel\Tests; use Illuminate\Config\Repository; +use Illuminate\Database\Connection; +use Illuminate\Database\Events\QueryExecuted; +use Mockery; class SqlBindingsInBreadcrumbsWithOldConfigKeyDisabledTest extends SentryLaravelTestCase { @@ -17,16 +20,19 @@ protected function getEnvironmentSetUp($app) $app['config'] = new Repository($config); } - public function testSqlBindingsAreRecordedWhenDisabledByOldConfigKey() + public function testSqlBindingsAreRecordedWhenDisabledByOldConfigKey(): void { $this->assertFalse($this->app['config']->get('sentry')['breadcrumbs.sql_bindings']); - $this->dispatchLaravelEvent('illuminate.query', [ + $connection = Mockery::mock(Connection::class) + ->shouldReceive('getName')->andReturn('test'); + + $this->dispatchLaravelEvent(new QueryExecuted( $query = 'SELECT * FROM breadcrumbs WHERE bindings = ?;', ['1'], 10, - 'test', - ]); + $connection + )); $lastBreadcrumb = $this->getLastBreadcrumb(); diff --git a/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyEnabledTest.php b/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyEnabledTest.php index 3850ac32..f2a15f68 100644 --- a/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyEnabledTest.php +++ b/test/Sentry/SqlBindingsInBreadcrumbsWithOldConfigKeyEnabledTest.php @@ -3,6 +3,9 @@ namespace Sentry\Laravel\Tests; use Illuminate\Config\Repository; +use Illuminate\Database\Connection; +use Illuminate\Database\Events\QueryExecuted; +use Mockery; class SqlBindingsInBreadcrumbsWithOldConfigKeyEnabledTest extends SentryLaravelTestCase { @@ -17,16 +20,21 @@ protected function getEnvironmentSetUp($app) $app['config'] = new Repository($config); } - public function testSqlBindingsAreRecordedWhenEnabledByOldConfigKey() + public function testSqlBindingsAreRecordedWhenEnabledByOldConfigKey(): void { $this->assertTrue($this->app['config']->get('sentry')['breadcrumbs.sql_bindings']); - $this->dispatchLaravelEvent('illuminate.query', [ + $connection = Mockery::mock(Connection::class) + ->shouldReceive('getName')->andReturn('test'); + + + + $this->dispatchLaravelEvent(new QueryExecuted( $query = 'SELECT * FROM breadcrumbs WHERE bindings = ?;', $bindings = ['1'], 10, - 'test', - ]); + $connection + )); $lastBreadcrumb = $this->getLastBreadcrumb(); diff --git a/test/Sentry/SqlQueriesInBreadcrumbsTest.php b/test/Sentry/SqlQueriesInBreadcrumbsTest.php index 2d718e95..6a26b506 100644 --- a/test/Sentry/SqlQueriesInBreadcrumbsTest.php +++ b/test/Sentry/SqlQueriesInBreadcrumbsTest.php @@ -2,6 +2,10 @@ namespace Sentry\Laravel\Tests; +use Illuminate\Database\Connection; +use Illuminate\Database\Events\QueryExecuted; +use Mockery; + class SqlQueriesInBreadcrumbsTest extends SentryLaravelTestCase { public function testSqlQueriesAreRecordedWhenEnabled() @@ -12,12 +16,15 @@ public function testSqlQueriesAreRecordedWhenEnabled() $this->assertTrue($this->app['config']->get('sentry.breadcrumbs.sql_queries')); - $this->dispatchLaravelEvent('illuminate.query', [ + $connection = Mockery::mock(Connection::class) + ->shouldReceive('getName')->andReturn('test'); + + $this->dispatchLaravelEvent(new QueryExecuted( $query = 'SELECT * FROM breadcrumbs WHERE bindings = ?;', ['1'], 10, - 'test', - ]); + $connection + )); $lastBreadcrumb = $this->getLastBreadcrumb();