Unpossible
Unpossible

Reputation: 10697

Hiding deprecation warnings from a vendor-provided class only

We have an app that includes a very very old class to connect to a proprietary database's API. This code is generating a large number of deprecation errors that then get logged, polluting our log files.

We'd like to essentially ignore the deprecation errors only for this vendor-provided class, but I am having trouble finding the best way to do this. Options that I've seen:

Supressing the warnings using @. It looks like this does not work for includes, only for functions that return a value.

Creating a wrapper script that contains the include, and turn off the warnings prior to the include statement. As ini_set acts globally, turning off all deprecation warnings, this is not a viable solution.

Updating the vendor-provided script. We'd rather not go down this path, given the extra work and maintenance should a new version arrive that does not fully address these errors, but adds new functionality, for example.

Any other options to disable warnings in this one particular vendor library that I am missing?

Upvotes: 4

Views: 849

Answers (2)

johnny Slakva
johnny Slakva

Reputation: 11

You can attach the error handler that would prevent the /vendor/ directory from reporting errors, or just a single library.

set_error_handler(
  function($code, $error, $file) {
    return str_contains($file, '/vendor/');
  },
  E_DEPRECATED);

This snippet assumes the deprecations we need to skip are all in /vendor/ directory.

When the callback returns false, PHP would fall back to processing the error regular way. If the callback returns true, PHP assumes we have processed the error ourselves and does nothing further.

Upvotes: 1

Jon
Jon

Reputation: 437664

You can attach a user error handler to eat the error up before PHP sees it. This handler would only intervene if the error was generated inside the source of the guilty library. For example:

class SingleSourceFileErrorSuppressor
{
    private $_file;

    public function __construct($file)
    {
        $this->_file = $file;
    }

    public function handleError($errno, $message, $file)
    {
        if ($file !== $this->file) return false;
    }
}

You would use the class like this:

$naughtyLibrary = realpath('naughty.class.php');
$suppressor = new SingleSourceFileErrorSuppressor($naughtyLibrary);
set_error_handler([$suppressor, 'handleError'], E_DEPRECATED);
require($naughtyLibrary);

Updated: I decided that modifying the vendor's library source is not the best idea even for trivial modifications because you have to remember to maintain them, so changed the suggested installation procedure. The new procedure has a different drawback: it doesn't automatically search the include_path. The original suggestion is available through the answer's edit history. Choose your poison.

Upvotes: 4

Related Questions