Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reporter for Model::preventSilentlyDiscardingAttributes() #830

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/Sentry/Laravel/Integration.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Database\MassAssignmentException;
use Illuminate\Routing\Route;
use Sentry\EventHint;
use Sentry\EventId;
Expand Down Expand Up @@ -269,6 +270,60 @@
};
}

/**
* Returns a callback that can be passed to `Model::handleDiscardedAttributeViolationUsing` to report discarded attribute violations to Sentry.
*
* @param callable|null $callback Optional callback to be called after the violation is reported to Sentry.
*
* @return callable
*/
public static function discardedAttributeViolationReporter(?callable $callback = null): callable
{
return new class($callback) {
use ResolvesEventOrigin;

/** @var callable|null $callback */
private $callback;

public function __construct(?callable $callback)
{
$this->callback = $callback;
}

public function __invoke(Model $model, array $attributes): void
{
$attributes_imploded = implode(', ', $attributes);
SentrySdk::getCurrentHub()->withScope(function (Scope $scope) use ($model, $attributes_imploded) {
$scope->setContext('violation', [
'model' => get_class($model),
'attributes' => $attributes_imploded,
'origin' => $this->resolveEventOrigin(),
'kind' => 'discarded_attributes',
]);

SentrySdk::getCurrentHub()->captureEvent(
tap(Event::createEvent(), static function (Event $event) {
$event->setLevel(Severity::warning());
}),
EventHint::fromArray([
'exception' => new MassAssignmentException(sprintf(

Check failure on line 309 in src/Sentry/Laravel/Integration.php

View workflow job for this annotation

GitHub Actions / PHPStan

Instantiated class Illuminate\Database\MassAssignmentException not found.
'Add fillable property [%s] to allow mass assignment on [%s].',
$attributes_imploded,
get_class($model)
)),
'mechanism' => new ExceptionMechanism(ExceptionMechanism::TYPE_GENERIC, true),
])
);
});

// Forward the violation to the next handler if there is one
if ($this->callback !== null) {
call_user_func($this->callback, $model, $attributes);
}
}
};
}

/**
* Try to make an educated guess if the call came from the Laravel `report` helper.
*
Expand Down
Loading