| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | Copyright CiviCRM LLC. All rights reserved. | |
| 5 | | | |
| 6 | | This work is published under the GNU AGPLv3 license with some | |
| 7 | | permitted exceptions and without any warranty. For full license | |
| 8 | | and copyright information, see https://civicrm.org/licensing | |
| 9 | +--------------------------------------------------------------------+ |
| 10 | */ |
| 11 | |
| 12 | namespace Civi\API\Subscriber; |
| 13 | |
| 14 | use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 15 | |
| 16 | /** |
| 17 | * Class XDebugSubscriber |
| 18 | * @package Civi\API\Subscriber |
| 19 | */ |
| 20 | class DebugSubscriber implements EventSubscriberInterface { |
| 21 | |
| 22 | /** |
| 23 | * @var \Civi\API\LogObserver |
| 24 | */ |
| 25 | private $debugLog; |
| 26 | |
| 27 | /** |
| 28 | * @return array |
| 29 | */ |
| 30 | public static function getSubscribedEvents() { |
| 31 | return [ |
| 32 | 'civi.api.prepare' => ['onApiPrepare', 999], |
| 33 | 'civi.api.respond' => ['onApiRespond', -999], |
| 34 | ]; |
| 35 | } |
| 36 | |
| 37 | public function onApiPrepare(\Civi\API\Event\PrepareEvent $event) { |
| 38 | $apiRequest = $event->getApiRequest(); |
| 39 | if (!isset($this->debugLog) |
| 40 | && !empty($apiRequest['params']['debug']) |
| 41 | && (empty($apiRequest['params']['check_permissions']) || \CRM_Core_Permission::check('view debug output')) |
| 42 | ) { |
| 43 | $this->debugLog = new \Civi\API\LogObserver(); |
| 44 | \CRM_Core_Error::createDebugLogger()->attach($this->debugLog); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * @param \Civi\API\Event\RespondEvent $event |
| 50 | * API response event. |
| 51 | */ |
| 52 | public function onApiRespond(\Civi\API\Event\RespondEvent $event) { |
| 53 | $apiRequest = $event->getApiRequest(); |
| 54 | $result = $event->getResponse(); |
| 55 | if (!empty($apiRequest['params']['debug']) |
| 56 | && (empty($apiRequest['params']['check_permissions']) || \CRM_Core_Permission::check('view debug output')) |
| 57 | ) { |
| 58 | if (is_a($result, '\Civi\Api4\Generic\Result')) { |
| 59 | $result->debug = $result->debug ?? []; |
| 60 | $debug =& $result->debug; |
| 61 | } |
| 62 | // result would not be an array for api3 getvalue |
| 63 | elseif (is_array($result)) { |
| 64 | $result['xdebug'] = $result['xdebug'] ?? []; |
| 65 | $debug =& $result['xdebug']; |
| 66 | } |
| 67 | else { |
| 68 | return; |
| 69 | } |
| 70 | if (isset($this->debugLog) && $this->debugLog->getMessages()) { |
| 71 | $debug['log'] = $this->debugLog->getMessages(); |
| 72 | } |
| 73 | if (function_exists('xdebug_time_index')) { |
| 74 | $debug['peakMemory'] = xdebug_peak_memory_usage(); |
| 75 | $debug['memory'] = xdebug_memory_usage(); |
| 76 | $debug['timeIndex'] = xdebug_time_index(); |
| 77 | } |
| 78 | $event->setResponse($result); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | } |