Skip to content

Commit

Permalink
Lazily get user context if we should be able to (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
indykoning authored Dec 11, 2024
1 parent e7015f5 commit 13747c7
Showing 1 changed file with 40 additions and 8 deletions.
48 changes: 40 additions & 8 deletions Model/SentryInteraction.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,17 @@

class SentryInteraction
{
/**
* @var ?UserContextInterface
*/
private ?UserContextInterface $userContext = null;

/**
* SentryInteraction constructor.
*
* @param UserContextInterface $userContext
* @param State $appState
* @param State $appState
*/
public function __construct(
private UserContextInterface $userContext,
private State $appState
) {
}
Expand All @@ -45,10 +48,37 @@ public function initialize($config)
init($config);
}

/**
* Check if we might be able to get user context.
*/
public function canGetUserContext()
{
try {
// @phpcs:ignore Generic.PHP.NoSilencedErrors
return in_array(@$this->appState->getAreaCode(), [Area::AREA_ADMINHTML, Area::AREA_FRONTEND, Area::AREA_WEBAPI_REST, Area::AREA_WEBAPI_SOAP, Area::AREA_GRAPHQL]);
} catch (LocalizedException $ex) {
return false;
}
}

/**
* Attempt to get userContext from the objectManager, so we don't request it too early.
*/
public function getUserContext(): ?UserContextInterface
{
if ($this->userContext) {
return $this->userContext;
}

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

return $this->userContext = $objectManager->get(UserContextInterface::class);
}

/**
* Check if we might be able to get the user data.
*/
private function canGetUserData()
public function canGetUserData()
{
try {
// @phpcs:ignore Generic.PHP.NoSilencedErrors
Expand Down Expand Up @@ -120,12 +150,14 @@ public function addUserContext()
\Magento\Framework\Profiler::start('SENTRY::add_user_context');

try {
$userId = $this->userContext->getUserId();
if ($userId) {
$userType = $this->userContext->getUserType();
if ($this->canGetUserContext()) {
$userId = $this->getUserContext()->getUserId();
if ($userId) {
$userType = $this->getUserContext()->getUserType();
}
}

if ($this->canGetUserData() && count($userData = $this->getSessionUserData())) {
if (count($userData = $this->getSessionUserData())) {
$userId = $userData['id'] ?? $userId;
$userType = $userData['user_type'] ?? $userType;
unset($userData['user_type']);
Expand Down

0 comments on commit 13747c7

Please sign in to comment.