Skip to content

Commit

Permalink
Add stackframe information to deprecation message.
Browse files Browse the repository at this point in the history
Having the userland method line/file should help in fixing deprecation
warnings. I've not used Debugger here as it would add a dependency to
cakephp/core that will not be easy to satisfy for standalone packages.
  • Loading branch information
markstory committed Aug 26, 2017
1 parent bf41ee7 commit 65c6e1c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
20 changes: 19 additions & 1 deletion src/Core/functions.php
Expand Up @@ -254,10 +254,28 @@ function env($key, $default = null)
* Helper method for outputting deprecation warnings
*
* @param string $message The message to output as a deprecation warning.
* @param int $stackFrame The stack frame to include in the error. Defaults to 2
* as that should point to application/plugin code.
* @return void
*/
function deprecationWarning($message)
function deprecationWarning($message, $stackFrame = 2)
{
if (!Configure::read('debug')) {
return;
}
$trace = debug_backtrace();
if (isset($trace[$stackFrame])) {
$frame = $trace[$stackFrame];
$frame += ['file' => '[internal]', 'line' => '??'];

$message = sprintf(
'%s - %s, line: %s',
$message,
$frame['file'],
$frame['line']
);
}

trigger_error($message, E_USER_DEPRECATED);
}
}
33 changes: 31 additions & 2 deletions tests/TestCase/Core/FunctionsTest.php
Expand Up @@ -14,6 +14,7 @@
*/
namespace Cake\Test\TestCase\Core;

use Cake\Core\Configure;
use Cake\TestSuite\TestCase;

/**
Expand Down Expand Up @@ -44,12 +45,40 @@ public function testEnv()
}

/**
* Test error messages coming out when debug is on
*
* @expectedException PHPUnit\Framework\Error\Deprecated
* @expectedExceptionMessage This is going away
* @expectedExceptionMessage This is going away - [internal], line: ??
*/
public function testDeprecationWarning()
public function testDeprecationWarningDebugEnabled()
{
Configure::write('debug', true);
error_reporting(E_ALL);
deprecationWarning('This is going away', 1);
}

/**
* Test error messages coming out when debug is on
*
* @expectedException PHPUnit\Framework\Error\Deprecated
* @expectedExceptionMessageRegExp /This is going away - (.*?)\/TestCase.php, line\: \d+/
*/
public function testDeprecationWarningDebugEnabledDefaultFrame()
{
Configure::write('debug', true);
error_reporting(E_ALL);
deprecationWarning('This is going away');
}

/**
* Test no error when debug is off.
*
* @return void
*/
public function testDeprecationWarningDebugDisabled()
{
Configure::write('debug', false);
error_reporting(E_ALL);
$this->assertNull(deprecationWarning('This is going away'));
}
}

0 comments on commit 65c6e1c

Please sign in to comment.