Compare commits

..

2 Commits

Author SHA1 Message Date
Steve Boyd
edf8a32884
Merge a1f73378da into ebbd6427b2 2024-10-17 02:39:44 +00:00
Steve Boyd
a1f73378da ENH Do not output core code deprecation messages by default 2024-10-17 15:39:38 +13:00
4 changed files with 69 additions and 51 deletions

View File

@ -36,8 +36,9 @@
"psr/container": "^1.1 || ^2.0", "psr/container": "^1.1 || ^2.0",
"psr/http-message": "^1", "psr/http-message": "^1",
"sebastian/diff": "^4.0", "sebastian/diff": "^4.0",
"silverstripe/config": "^2", "silverstripe/config": "^2.2",
"silverstripe/assets": "^2.3", "silverstripe/assets": "^2.3",
"silverstripe/supported-modules": "^1",
"silverstripe/vendor-plugin": "^2", "silverstripe/vendor-plugin": "^2",
"sminnee/callbacklist": "^0.1.1", "sminnee/callbacklist": "^0.1.1",
"symfony/cache": "^6.1", "symfony/cache": "^6.1",

View File

@ -19,7 +19,6 @@ use SilverStripe\View\TemplateGlobalProvider;
*/ */
class Controller extends RequestHandler implements TemplateGlobalProvider class Controller extends RequestHandler implements TemplateGlobalProvider
{ {
/** /**
* An array of arguments extracted from the URL. * An array of arguments extracted from the URL.
* *

View File

@ -3,11 +3,13 @@
namespace SilverStripe\Dev; namespace SilverStripe\Dev;
use BadMethodCallException; use BadMethodCallException;
use RuntimeException;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use SilverStripe\Core\Environment; use SilverStripe\Core\Environment;
use SilverStripe\Core\Injector\InjectionCreator; use SilverStripe\Core\Injector\InjectionCreator;
use SilverStripe\Core\Injector\InjectorLoader; use SilverStripe\Core\Injector\InjectorLoader;
use SilverStripe\Core\Manifest\Module; use SilverStripe\Core\Manifest\Module;
use SilverStripe\Core\Path;
/** /**
* Handles raising an notice when accessing a deprecated method, class, configuration, or behaviour. * Handles raising an notice when accessing a deprecated method, class, configuration, or behaviour.
@ -80,7 +82,14 @@ class Deprecation
/** /**
* @internal * @internal
*/ */
private static bool $showCalledFromSupportedCodeNotices = false; private static bool $showNoticesCalledFromSupportedCode = false;
/**
* Cache of supported module directories, read from silverstripe/supported-modules repositories.json
*
* @internal
*/
private static array $supportedModuleDirectories = [];
/** /**
* Enable throwing deprecation warnings. By default, this excludes warnings for * Enable throwing deprecation warnings. By default, this excludes warnings for
@ -158,12 +167,12 @@ class Deprecation
private static function get_called_from_trace(array $backtrace, int $level): array private static function get_called_from_trace(array $backtrace, int $level): array
{ {
$newLevel = $level; $newLevel = $level;
if (Deprecation::$insideNoticeSuppression) {
// handle closures inside withSuppressedNotice() // handle closures inside withSuppressedNotice()
if (substr($backtrace[$newLevel]['function'], -strlen('{closure}')) === '{closure}') { if (Deprecation::$insideNoticeSuppression
&& substr($backtrace[$newLevel]['function'], -strlen('{closure}')) === '{closure}'
) {
$newLevel = $newLevel + 2; $newLevel = $newLevel + 2;
} }
}
// handle call_user_func // handle call_user_func
if ($level === 4 && strpos($backtrace[2]['function'] ?? '', 'call_user_func') !== false) { if ($level === 4 && strpos($backtrace[2]['function'] ?? '', 'call_user_func') !== false) {
$newLevel = 5; $newLevel = 5;
@ -187,40 +196,46 @@ class Deprecation
return $called; return $called;
} }
private static function calledFromSupportedCode(array $backtrace): bool private static function isCalledFromSupportedCode(array $backtrace): bool
{ {
$called = Deprecation::get_called_from_trace($backtrace, 1); $called = Deprecation::get_called_from_trace($backtrace, 1);
$file = $called['file'] ?? ''; $file = $called['file'] ?? '';
if ($file) { if (!$file) {
$isSupportedVendorFile = Deprecation::isSupportedVendorFile($file);
if (!$isSupportedVendorFile) {
return false; return false;
} }
} return Deprecation::fileIsInSupportedModule($file);
return true;
} }
/** /**
* Whether the given file is supported code * Check whether a file (path to file) is in a supported module
*/ */
private static function isSupportedVendorFile(string $file): bool public static function fileIsInSupportedModule(string $file): bool
{ {
// Cache the supported modules list
if (count(Deprecation::$supportedModuleDirectories) === 0) {
// Manually load the supported modules list rather than use MetaData::getAllRepositoryMetaData()
// because we do not want to make a network request which could slow down a website
// While there is a small risk of the list being out of date, there is minimal downside to this
$path = Path::join(BASE_PATH, 'vendor/silverstripe/supported-modules/repositories.json');
if (!file_exists($path)) {
throw new RuntimeException('Could not find supported modules list');
}
$json = json_decode(file_get_contents($path), true);
if (is_null($json)) {
throw new RuntimeException('Could not parse supported modules list');
}
$dirs = array_map(fn($module) => "/vendor/{$module['packagist']}/", $json['supportedModules']);
// This is a special case for silverstripe-framework when running in CI // This is a special case for silverstripe-framework when running in CI
if (str_contains($file, '/silverstripe-framework/')) { // Needed because module is run in the root folder rather than in the vendor folder
$dirs[] = '/silverstripe-framework/';
Deprecation::$supportedModuleDirectories = $dirs;
}
foreach (Deprecation::$supportedModuleDirectories as $dir) {
if (str_contains($file, $dir)) {
return true; return true;
} }
// Doing a fairly simple check to see if a file is in a supported vendor folder, rather than whether }
// the module itself is actually supported return false;
$vendors = implode('|', [
'bringyourownideas',
'colymba',
'cwp',
'dnadesign',
'silverstripe',
'symbiote',
'tractorcow',
]);
return (bool) preg_match("#/vendor/($vendors)/#", $file);
} }
public static function isEnabled(): bool public static function isEnabled(): bool
@ -304,14 +319,17 @@ class Deprecation
/** /**
* If true, deprecation warnings will be shown for deprecated code which is called by core Silverstripe modules. * If true, deprecation warnings will be shown for deprecated code which is called by core Silverstripe modules.
*/ */
public static function getShowCalledFromSupportedCodeNotices(): bool public static function getShowNoticesCalledFromSupportedCode(): bool
{ {
return Deprecation::$showCalledFromSupportedCodeNotices; return Deprecation::$showNoticesCalledFromSupportedCode;
} }
public static function setShowCalledFromSupportedCodeNotices(bool $value): void /**
* Set whether deprecation warnings will be shown for deprecated code which is called by core Silverstripe modules.
*/
public static function setShowNoticesCalledFromSupportedCode(bool $value): void
{ {
Deprecation::$showCalledFromSupportedCodeNotices = $value; Deprecation::$showNoticesCalledFromSupportedCode = $value;
} }
public static function outputNotices(): void public static function outputNotices(): void
@ -327,11 +345,11 @@ class Deprecation
$arr = array_shift(Deprecation::$userErrorMessageBuffer); $arr = array_shift(Deprecation::$userErrorMessageBuffer);
$message = $arr['message']; $message = $arr['message'];
$calledWithNoticeSuppression = $arr['calledWithNoticeSuppression']; $calledWithNoticeSuppression = $arr['calledWithNoticeSuppression'];
$calledFromSupportedCode = $arr['calledFromSupportedCode']; $isCalledFromSupportedCode = $arr['isCalledFromSupportedCode'];
if ($calledWithNoticeSuppression && !Deprecation::$showNoReplacementNotices) { if ($calledWithNoticeSuppression && !Deprecation::$showNoReplacementNotices) {
continue; continue;
} }
if ($calledFromSupportedCode && !Deprecation::$showCalledFromSupportedCodeNotices) { if ($isCalledFromSupportedCode && !Deprecation::$showNoticesCalledFromSupportedCode) {
continue; continue;
} }
Deprecation::$isTriggeringError = true; Deprecation::$isTriggeringError = true;
@ -367,7 +385,10 @@ class Deprecation
$data = [ $data = [
'key' => sha1($string), 'key' => sha1($string),
'message' => $string, 'message' => $string,
'calledFromSupportedCode' => false, // Setting to `false` as here as any SCOPE_CONFIG notices from supported modules have
// already been filtered out if needed if they came from a supported module in
// SilverStripe\Config\Transformer\YamlTransformer::checkForDeprecatedConfig()
'isCalledFromSupportedCode' => false,
'calledWithNoticeSuppression' => Deprecation::$insideNoticeSuppression 'calledWithNoticeSuppression' => Deprecation::$insideNoticeSuppression
]; ];
} else { } else {
@ -402,7 +423,7 @@ class Deprecation
$data = [ $data = [
'key' => sha1($string), 'key' => sha1($string),
'message' => $string, 'message' => $string,
'calledFromSupportedCode' => Deprecation::calledFromSupportedCode($backtrace), 'isCalledFromSupportedCode' => Deprecation::isCalledFromSupportedCode($backtrace),
'calledWithNoticeSuppression' => Deprecation::$insideNoticeSuppression 'calledWithNoticeSuppression' => Deprecation::$insideNoticeSuppression
]; ];
} }
@ -436,8 +457,7 @@ class Deprecation
/** /**
* Shorthand method to create a suppressed notice for something with no immediate replacement. * Shorthand method to create a suppressed notice for something with no immediate replacement.
* If $string is empty, then a standardised message will be used, which is: * If $string is empty, then a standardised message will be used
* Will be removed without equivalent functionality to replace it.
*/ */
public static function noticeWithNoReplacment( public static function noticeWithNoReplacment(
string $atVersion, string $atVersion,

View File

@ -33,7 +33,7 @@ class DeprecationTest extends SapphireTest
// https://github.com/laminas/laminas-di/pull/30#issuecomment-927585210 // https://github.com/laminas/laminas-di/pull/30#issuecomment-927585210
parent::setup(); parent::setup();
$this->noticesWereEnabled = Deprecation::isEnabled(); $this->noticesWereEnabled = Deprecation::isEnabled();
$this->showSupportedNoticesWasEnabled = Deprecation::getShowCalledFromSupportedCodeNotices(); $this->showSupportedNoticesWasEnabled = Deprecation::getShowNoticesCalledFromSupportedCode();
$this->oldHandler = set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { $this->oldHandler = set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) {
if ($errno === E_USER_DEPRECATED) { if ($errno === E_USER_DEPRECATED) {
if (str_contains($errstr, 'SilverStripe\\Dev\\Tests\\DeprecationTest')) { if (str_contains($errstr, 'SilverStripe\\Dev\\Tests\\DeprecationTest')) {
@ -49,9 +49,7 @@ class DeprecationTest extends SapphireTest
// Fallback to default PHP error handler // Fallback to default PHP error handler
return false; return false;
}); });
// This is required to clear out the message // This is required to clear out the notice from instantiating DeprecationTestObject in TableBuilder::buildTables().
// 'SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject is deprecated. Some class message. Called from
// SilverStripe\ORM\Connect\TableBuilder->buildTables."
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -62,7 +60,7 @@ class DeprecationTest extends SapphireTest
} else { } else {
Deprecation::disable(); Deprecation::disable();
} }
Deprecation::setShowCalledFromSupportedCodeNotices($this->showSupportedNoticesWasEnabled); Deprecation::setShowNoticesCalledFromSupportedCode($this->showSupportedNoticesWasEnabled);
restore_error_handler(); restore_error_handler();
$this->oldHandler = null; $this->oldHandler = null;
parent::tearDown(); parent::tearDown();
@ -83,7 +81,7 @@ class DeprecationTest extends SapphireTest
private function enableDeprecationNotices(bool $showNoReplacementNotices = false): void private function enableDeprecationNotices(bool $showNoReplacementNotices = false): void
{ {
Deprecation::enable($showNoReplacementNotices); Deprecation::enable($showNoReplacementNotices);
Deprecation::setShowCalledFromSupportedCodeNotices(true); Deprecation::setShowNoticesCalledFromSupportedCode(true);
} }
public function testNotice() public function testNotice()
@ -260,11 +258,11 @@ class DeprecationTest extends SapphireTest
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
public function testShowCalledFromSupportedCodeNotices() public function testshowNoticesCalledFromSupportedCode()
{ {
$this->expectNotToPerformAssertions(); $this->expectNotToPerformAssertions();
$this->enableDeprecationNotices(true); $this->enableDeprecationNotices(true);
// showCalledFromSupportedCodeNotices is set to true by default for these unit tests // showNoticesCalledFromSupportedCode is set to true by default for these unit tests
// as it is testing code within vendor/silverstripe // as it is testing code within vendor/silverstripe
// This test is to ensure that the method works as expected when we disable this // This test is to ensure that the method works as expected when we disable this
// and we should expect no exceptions to be thrown // and we should expect no exceptions to be thrown
@ -274,7 +272,7 @@ class DeprecationTest extends SapphireTest
// Deprecation::withSuppressedNotice(function () { // Deprecation::withSuppressedNotice(function () {
// Deprecation::notice('123', 'My message.'); // Deprecation::notice('123', 'My message.');
// }); // });
Deprecation::setShowCalledFromSupportedCodeNotices(false); Deprecation::setShowNoticesCalledFromSupportedCode(false);
// notice() // notice()
$this->myDeprecatedMethod(); $this->myDeprecatedMethod();
// noticeNoReplacement() // noticeNoReplacement()