Skip to content

Instantly share code, notes, and snippets.

@cmtickle
Last active May 4, 2023 10:13
Show Gist options
  • Save cmtickle/e2abf7f0bda7cabd5449a262ebcee7ed to your computer and use it in GitHub Desktop.
Save cmtickle/e2abf7f0bda7cabd5449a262ebcee7ed to your computer and use it in GitHub Desktop.
My Magento 2 Observer was called multiple times due to Plugins/Interceptors. This Observer will not be triggered by Plugins.
<?php
namespace Cmtickle\Sample\Observer;
use Magento\Framework\Event\Observer;
class NotTriggeredByPluginsObserver implements \Magento\Framework\Event\ObserverInterface
{
const INTERCEPTOR_FUNCTION = 'Magento\Framework\Interception\{closure}';
/**
* @return bool
*/
private function isTriggeredByPlugin()
{
$stackTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$callCount = count($stackTrace);
for ($callPos = $callCount - 2 ; $callPos >= 1; $callPos--) {
$calledByInterceptor = self::INTERCEPTOR_FUNCTION === $stackTrace[$callPos - 1]['function'] &&
self::INTERCEPTOR_FUNCTION === $stackTrace[$callPos + 1]['function'];
if ($calledByInterceptor) return true;
}
return false;
}
/**
* @param Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
if($this->isTriggeredByPlugin()) {
return;
}
# Your code here.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment