Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
PHP_Shutdown_Handler
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
3 / 3
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * When PHP is shutting down, check for any errors, log if appropriate.
4 *
5 * @package brianhenryie/bh-wp-logger
6 */
7
8namespace BrianHenryIE\WP_Logger\PHP;
9
10use BrianHenryIE\WP_Logger\API_Interface;
11use BrianHenryIE\WP_Logger\Logger_Settings_Interface;
12use Psr\Log\LoggerAwareTrait;
13use Psr\Log\LoggerInterface;
14
15/**
16 * Listens for errors from register_shutdown_function and logs them to the PSR logger if they are from this plugin.
17 *
18 * @see register_shutdown_function()
19 */
20class PHP_Shutdown_Handler {
21
22    use LoggerAwareTrait;
23
24    /**
25     * Constructor.
26     *
27     * @param API_Interface             $api The main logger functions. Used to determine is the error related to this plugin.
28     * @param Logger_Settings_Interface $settings The logger settings. Not used.
29     * @param LoggerInterface           $logger A PSR logger.
30     */
31    public function __construct(
32        protected API_Interface $api,
33        protected Logger_Settings_Interface $settings,
34        LoggerInterface $logger
35    ) {
36        $this->setLogger( $logger );
37    }
38
39    /**
40     * This should maybe be run immediately rather than hooked. It _is_ hooked to enable it to be unhooked.
41     *
42     * @hooked plugins_loaded
43     */
44    public function init(): void {
45        register_shutdown_function( array( $this, 'handle' ) );
46    }
47
48    /**
49     * The handler itself. Check is the error related to this plugin, then logs an error to the PSR logger.
50     */
51    public function handle(): void {
52
53        /**
54         * The error from PHP.
55         *
56         * @var ?array{type:int, message:string, file:string, line:int} $error
57         */
58        $error = error_get_last();
59
60        if ( empty( $error ) ) {
61            return;
62        }
63
64        if ( ! $this->api->is_file_from_plugin( $error['file'] ) ) {
65            return;
66        }
67
68        // "Clears the most recent errors, making it unable to be retrieved with error_get_last().".
69        error_clear_last();
70
71        $this->logger->error( $error['message'], $error );
72    }
73}