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

Lazily get user context if we should be able to #152

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
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
Loading