Compare commits

...

10 Commits

Author SHA1 Message Date
Niklas Forsdahl
e697197ace
Merge 6b69db1e3b into 82b0851a2a 2024-10-22 05:30:41 +13:00
Guy Sartorelli
82b0851a2a
Merge pull request #11429 from creative-commoners/pulls/5/core-deprecation
ENH Do not output core code deprecation messages by default
2024-10-21 13:57:52 +13:00
Steve Boyd
7401bcf02e ENH Do not output core code deprecation messages by default 2024-10-21 10:20:44 +13:00
Guy Sartorelli
969d7b4bd2
Merge pull request #11427 from creative-commoners/pulls/5/field-validator-depr
API Add deprecation
2024-10-21 10:05:32 +13:00
Steve Boyd
8ec068f3fd API Add deprecation 2024-10-17 16:06:06 +13:00
Niklas Forsdahl
6b69db1e3b Fix for UnitTest failure with new SessionGridFieldStateManager functionality 2024-06-27 16:06:32 +03:00
Niklas Forsdahl
898ef9ba31 Removed custom interface for SessionGridFieldStateManager, the extra methods
will be incorporated into GridFieldStateManagerInterface in the future.
2024-06-20 15:12:56 +03:00
Niklas Forsdahl
e9cd597a22 Fixed SessionGridFieldStateManager unit test to work regardless of
current gridfield state manager configuration.
2024-06-20 15:12:56 +03:00
Niklas Forsdahl
d448708fb3 Added Unit Tests for SessionGridFieldStateManager 2024-06-20 15:12:56 +03:00
Niklas Forsdahl
4714a83333 NEW Initial SessionGridFieldStateManager implementation, for managing
GridField states in session.
2024-06-20 15:12:54 +03:00
13 changed files with 494 additions and 31 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.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,14 @@
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;
use SilverStripe\SupportedModules\MetaData;
/** /**
* 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.
@ -77,6 +80,18 @@ class Deprecation
*/ */
private static bool $showNoReplacementNotices = false; private static bool $showNoReplacementNotices = false;
/**
* @internal
*/
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
* deprecated code which is called by core Silverstripe modules. * deprecated code which is called by core Silverstripe modules.
@ -146,6 +161,12 @@ class Deprecation
if (!$level) { if (!$level) {
$level = 1; $level = 1;
} }
$called = Deprecation::get_called_from_trace($backtrace, $level);
return ($called['class'] ?? '') . ($called['type'] ?? '') . ($called['function'] ?? '');
}
private static function get_called_from_trace(array $backtrace, int $level): array
{
$newLevel = $level; $newLevel = $level;
// handle closures inside withSuppressedNotice() // handle closures inside withSuppressedNotice()
if (Deprecation::$insideNoticeSuppression if (Deprecation::$insideNoticeSuppression
@ -163,8 +184,51 @@ class Deprecation
if ($level == 4 && ($backtrace[$newLevel]['class'] ?? '') === InjectionCreator::class) { if ($level == 4 && ($backtrace[$newLevel]['class'] ?? '') === InjectionCreator::class) {
$newLevel = $newLevel + 4; $newLevel = $newLevel + 4;
} }
// handle noticeWithNoReplacment()
foreach ($backtrace as $trace) {
if (($trace['class'] ?? '') === Deprecation::class
&& ($trace['function'] ?? '') === 'noticeWithNoReplacment'
) {
$newLevel = $newLevel + 1;
break;
}
}
$called = $backtrace[$newLevel] ?? []; $called = $backtrace[$newLevel] ?? [];
return ($called['class'] ?? '') . ($called['type'] ?? '') . ($called['function'] ?? ''); return $called;
}
private static function isCalledFromSupportedCode(array $backtrace): bool
{
$called = Deprecation::get_called_from_trace($backtrace, 1);
$file = $called['file'] ?? '';
if (!$file) {
return false;
}
return Deprecation::fileIsInSupportedModule($file);
}
/**
* Check whether a file (path to file) is in a supported module
*/
public static function fileIsInSupportedModule(string $file): bool
{
// Cache the supported modules list
if (count(Deprecation::$supportedModuleDirectories) === 0) {
// Do not make a network request when fetching metadata 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
$metaData = MetaData::getAllRepositoryMetaData(fromRemote: false);
$dirs = array_map(fn($module) => "/vendor/{$module['packagist']}/", $metaData['supportedModules']);
// This is a special case for silverstripe-framework when running in CI
// 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 false;
} }
public static function isEnabled(): bool public static function isEnabled(): bool
@ -245,6 +309,22 @@ class Deprecation
return Deprecation::$shouldShowForCli; return Deprecation::$shouldShowForCli;
} }
/**
* If true, deprecation warnings will be shown for deprecated code which is called by core Silverstripe modules.
*/
public static function getShowNoticesCalledFromSupportedCode(): bool
{
return Deprecation::$showNoticesCalledFromSupportedCode;
}
/**
* 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::$showNoticesCalledFromSupportedCode = $value;
}
public static function outputNotices(): void public static function outputNotices(): void
{ {
if (!Deprecation::isEnabled()) { if (!Deprecation::isEnabled()) {
@ -258,9 +338,13 @@ class Deprecation
$arr = array_shift(Deprecation::$userErrorMessageBuffer); $arr = array_shift(Deprecation::$userErrorMessageBuffer);
$message = $arr['message']; $message = $arr['message'];
$calledWithNoticeSuppression = $arr['calledWithNoticeSuppression']; $calledWithNoticeSuppression = $arr['calledWithNoticeSuppression'];
$isCalledFromSupportedCode = $arr['isCalledFromSupportedCode'];
if ($calledWithNoticeSuppression && !Deprecation::$showNoReplacementNotices) { if ($calledWithNoticeSuppression && !Deprecation::$showNoReplacementNotices) {
continue; continue;
} }
if ($isCalledFromSupportedCode && !Deprecation::$showNoticesCalledFromSupportedCode) {
continue;
}
Deprecation::$isTriggeringError = true; Deprecation::$isTriggeringError = true;
user_error($message, E_USER_DEPRECATED); user_error($message, E_USER_DEPRECATED);
Deprecation::$isTriggeringError = false; Deprecation::$isTriggeringError = false;
@ -294,6 +378,10 @@ class Deprecation
$data = [ $data = [
'key' => sha1($string), 'key' => sha1($string),
'message' => $string, 'message' => $string,
// 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 {
@ -322,13 +410,13 @@ class Deprecation
$level = Deprecation::$insideNoticeSuppression ? 4 : 2; $level = Deprecation::$insideNoticeSuppression ? 4 : 2;
$string .= " Called from " . Deprecation::get_called_method_from_trace($backtrace, $level) . '.'; $string .= " Called from " . Deprecation::get_called_method_from_trace($backtrace, $level) . '.';
if ($caller) { if ($caller) {
$string = $caller . ' is deprecated.' . ($string ? ' ' . $string : ''); $string = $caller . ' is deprecated.' . ($string ? ' ' . $string : '');
} }
$data = [ $data = [
'key' => sha1($string), 'key' => sha1($string),
'message' => $string, 'message' => $string,
'isCalledFromSupportedCode' => Deprecation::isCalledFromSupportedCode($backtrace),
'calledWithNoticeSuppression' => Deprecation::$insideNoticeSuppression 'calledWithNoticeSuppression' => Deprecation::$insideNoticeSuppression
]; ];
} }
@ -360,6 +448,23 @@ class Deprecation
} }
} }
/**
* Shorthand method to create a suppressed notice for something with no immediate replacement.
* If $message is empty, then a standardised message will be used
*/
public static function noticeWithNoReplacment(
string $atVersion,
string $message = '',
int $scope = Deprecation::SCOPE_METHOD
): void {
if ($message === '') {
$message = 'Will be removed without equivalent functionality to replace it.';
}
Deprecation::withSuppressedNotice(
fn() => Deprecation::notice($atVersion, $message, $scope)
);
}
private static function varAsBoolean($val): bool private static function varAsBoolean($val): bool
{ {
if (is_string($val)) { if (is_string($val)) {

View File

@ -454,6 +454,13 @@ class GridFieldDetailForm_ItemRequest extends RequestHandler
$gridState = $this->gridField->getState(false); $gridState = $this->gridField->getState(false);
$actions->push(HiddenField::create($manager->getStateKey($this->gridField), null, $gridState)); $actions->push(HiddenField::create($manager->getStateKey($this->gridField), null, $gridState));
if (ClassInfo::hasMethod($manager, 'getStateRequestVar')) {
$stateRequestVar = $manager->getStateRequestVar();
$stateValue = $this->getRequest()->requestVar($stateRequestVar);
if ($stateValue) {
$actions->push(HiddenField::create($stateRequestVar, '', $stateValue));
}
}
$actions->push($this->getRightGroupField()); $actions->push($this->getRightGroupField());
} else { // adding new record } else { // adding new record

View File

@ -85,7 +85,7 @@ class GridState extends HiddenField
public function getData() public function getData()
{ {
if (!$this->data) { if (!$this->data) {
$this->data = new GridState_Data(); $this->data = new GridState_Data([], $this);
} }
return $this->data; return $this->data;
@ -99,6 +99,11 @@ class GridState extends HiddenField
return $this->grid->getList(); return $this->grid->getList();
} }
public function getGridField(): GridField
{
return $this->grid;
}
/** /**
* Returns a json encoded string representation of this state. * Returns a json encoded string representation of this state.
* *

View File

@ -2,6 +2,8 @@
namespace SilverStripe\Forms\GridField; namespace SilverStripe\Forms\GridField;
use SilverStripe\Core\ClassInfo;
/** /**
* Simple set of data, similar to stdClass, but without the notice-level * Simple set of data, similar to stdClass, but without the notice-level
* errors. * errors.
@ -10,29 +12,33 @@ namespace SilverStripe\Forms\GridField;
*/ */
class GridState_Data class GridState_Data
{ {
use GridFieldStateAware;
/** /**
* @var array * @var array
*/ */
protected $data; protected $data;
protected ?GridState $state;
protected $defaults = []; protected $defaults = [];
public function __construct($data = []) public function __construct($data = [], ?GridState $state = null)
{ {
$this->data = $data; $this->data = $data;
$this->state = $state;
} }
public function __get($name) public function __get($name)
{ {
return $this->getData($name, new GridState_Data()); return $this->getData($name, new GridState_Data([], $this->state));
} }
public function __call($name, $arguments) public function __call($name, $arguments)
{ {
// Assume first parameter is default value // Assume first parameter is default value
if (empty($arguments)) { if (empty($arguments)) {
$default = new GridState_Data(); $default = new GridState_Data([], $this->state);
} else { } else {
$default = $arguments[0]; $default = $arguments[0];
} }
@ -72,16 +78,25 @@ class GridState_Data
$this->data[$name] = $default; $this->data[$name] = $default;
} else { } else {
if (is_array($this->data[$name])) { if (is_array($this->data[$name])) {
$this->data[$name] = new GridState_Data($this->data[$name]); $this->data[$name] = new GridState_Data($this->data[$name], $this->state);
} }
} }
return $this->data[$name]; return $this->data[$name];
} }
public function storeData()
{
$stateManager = $this->getStateManager();
if (ClassInfo::hasMethod($stateManager, 'storeState') && $this->state) {
$stateManager->storeState($this->state->getGridField(), $this->state->Value());
}
}
public function __set($name, $value) public function __set($name, $value)
{ {
$this->data[$name] = $value; $this->data[$name] = $value;
$this->storeData();
} }
public function __isset($name) public function __isset($name)
@ -92,6 +107,7 @@ class GridState_Data
public function __unset($name) public function __unset($name)
{ {
unset($this->data[$name]); unset($this->data[$name]);
$this->storeData();
} }
public function __toString() public function __toString()

View File

@ -0,0 +1,101 @@
<?php
namespace SilverStripe\Forms\GridField;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
/**
* Creates a unique key for managing GridField states in user Session, for both storage and retrieval.
* Only stores states and generates a session key if a state is requested to be stored
* (i.e. the state is changed from the default).
* If a session state key is present in the request, it will always be used instead of generating a new one.
*/
class SessionGridFieldStateManager implements GridFieldStateManagerInterface
{
protected static $state_ids = [];
protected function getStateID(GridField $gridField, $create = false): ?string
{
$requestVar = $this->getStateRequestVar();
$sessionStateID = $gridField->getForm()?->getRequestHandler()->getRequest()->requestVar($requestVar);
if (!$sessionStateID) {
$sessionStateID = Controller::curr()->getRequest()->requestVar($requestVar);
}
if ($sessionStateID) {
return $sessionStateID;
}
$stateKey = $this->getStateKey($gridField);
if (isset(self::$state_ids[$stateKey])) {
$sessionStateID = self::$state_ids[$stateKey];
} elseif ($create) {
$sessionStateID = substr(md5(time()), 0, 8);
// we don't want session state id to be strictly numeric, since this is used as a session key,
// and session keys in php has to be usable as variable names
if (is_numeric($sessionStateID)) {
$sessionStateID .= 'a';
}
self::$state_ids[$stateKey] = $sessionStateID;
}
return $sessionStateID;
}
public function storeState(GridField $gridField, $value = null)
{
$sessionStateID = $this->getStateID($gridField, true);
$sessionState = Controller::curr()->getRequest()->getSession()->get($sessionStateID);
if (!$sessionState) {
$sessionState = [];
}
$stateKey = $this->getStateKey($gridField);
$sessionState[$stateKey] = $value ?? $gridField->getState(false)->Value();
Controller::curr()->getRequest()->getSession()->set($sessionStateID, $sessionState);
}
public function getStateRequestVar(): string
{
return 'gridSessionState';
}
/**
* @param GridField $gridField
* @return string
*/
public function getStateKey(GridField $gridField): string
{
$record = $gridField->getForm()?->getRecord();
return $gridField->getName() . '-' . ($record ? $record->ID : 0);
}
/**
* @param GridField $gridField
* @param string $url
* @return string
*/
public function addStateToURL(GridField $gridField, string $url): string
{
$sessionStateID = $this->getStateID($gridField);
if ($sessionStateID) {
return Controller::join_links($url, '?' . $this->getStateRequestVar() . '=' . $sessionStateID);
}
return $url;
}
/**
* @param GridField $gridField
* @param HTTPRequest $request
* @return string|null
*/
public function getStateFromRequest(GridField $gridField, HTTPRequest $request): ?string
{
$gridSessionStateID = $request->requestVar($this->getStateRequestVar());
if ($gridSessionStateID) {
$sessionState = $request->getSession()->get($gridSessionStateID);
$stateKey = $this->getStateKey($gridField);
if ($sessionState && isset($sessionState[$stateKey])) {
return $sessionState[$stateKey];
}
}
return null;
}
}

View File

@ -13,7 +13,8 @@ class DBBoolean extends DBField
{ {
public function __construct($name = null, $defaultVal = 0) public function __construct($name = null, $defaultVal = 0)
{ {
$this->defaultVal = ($defaultVal) ? 1 : 0; $defaultValue = $defaultVal ? 1 : 0;
$this->setDefaultValue($defaultValue);
parent::__construct($name); parent::__construct($name);
} }
@ -25,7 +26,7 @@ class DBBoolean extends DBField
'precision' => 1, 'precision' => 1,
'sign' => 'unsigned', 'sign' => 'unsigned',
'null' => 'not null', 'null' => 'not null',
'default' => $this->defaultVal, 'default' => $this->getDefaultValue(),
'arrayValue' => $this->arrayValue 'arrayValue' => $this->arrayValue
]; ];
$values = ['type' => 'boolean', 'parts' => $parts]; $values = ['type' => 'boolean', 'parts' => $parts];

View File

@ -122,6 +122,7 @@ abstract class DBField extends ViewableData implements DBIndexable
* @var $default mixed Default-value in the database. * @var $default mixed Default-value in the database.
* Might be overridden on DataObject-level, but still useful for setting defaults on * Might be overridden on DataObject-level, but still useful for setting defaults on
* already existing records after a db-build. * already existing records after a db-build.
* @deprecated 5.4.0 Use getDefaultValue() and setDefaultValue() instead
*/ */
protected $defaultVal; protected $defaultVal;

View File

@ -13,7 +13,8 @@ class DBFloat extends DBField
public function __construct($name = null, $defaultVal = 0) public function __construct($name = null, $defaultVal = 0)
{ {
$this->defaultVal = is_float($defaultVal) ? $defaultVal : (float) 0; $defaultValue = is_float($defaultVal) ? $defaultVal : (float) 0;
$this->setDefaultValue($defaultValue);
parent::__construct($name); parent::__construct($name);
} }
@ -23,7 +24,7 @@ class DBFloat extends DBField
$parts = [ $parts = [
'datatype' => 'float', 'datatype' => 'float',
'null' => 'not null', 'null' => 'not null',
'default' => $this->defaultVal, 'default' => $this->getDefaultValue(),
'arrayValue' => $this->arrayValue 'arrayValue' => $this->arrayValue
]; ];
$values = ['type' => 'float', 'parts' => $parts]; $values = ['type' => 'float', 'parts' => $parts];

View File

@ -15,7 +15,8 @@ class DBInt extends DBField
public function __construct($name = null, $defaultVal = 0) public function __construct($name = null, $defaultVal = 0)
{ {
$this->defaultVal = is_int($defaultVal) ? $defaultVal : 0; $defaultValue = is_int($defaultVal) ? $defaultVal : 0;
$this->setDefaultValue($defaultValue);
parent::__construct($name); parent::__construct($name);
} }
@ -43,7 +44,7 @@ class DBInt extends DBField
'datatype' => 'int', 'datatype' => 'int',
'precision' => 11, 'precision' => 11,
'null' => 'not null', 'null' => 'not null',
'default' => $this->defaultVal, 'default' => $this->getDefaultValue(),
'arrayValue' => $this->arrayValue 'arrayValue' => $this->arrayValue
]; ];
$values = ['type' => 'int', 'parts' => $parts]; $values = ['type' => 'int', 'parts' => $parts];

View File

@ -23,6 +23,8 @@ class DeprecationTest extends SapphireTest
private bool $noticesWereEnabled = false; private bool $noticesWereEnabled = false;
private bool $showSupportedNoticesWasEnabled = false;
protected function setup(): void protected function setup(): void
{ {
// Use custom error handler for two reasons: // Use custom error handler for two reasons:
@ -31,6 +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::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')) {
@ -46,6 +49,8 @@ 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 notice from instantiating DeprecationTestObject in TableBuilder::buildTables().
Deprecation::outputNotices();
} }
protected function tearDown(): void protected function tearDown(): void
@ -55,6 +60,7 @@ class DeprecationTest extends SapphireTest
} else { } else {
Deprecation::disable(); Deprecation::disable();
} }
Deprecation::setShowNoticesCalledFromSupportedCode($this->showSupportedNoticesWasEnabled);
restore_error_handler(); restore_error_handler();
$this->oldHandler = null; $this->oldHandler = null;
parent::tearDown(); parent::tearDown();
@ -66,6 +72,18 @@ class DeprecationTest extends SapphireTest
return 'abc'; return 'abc';
} }
private function myDeprecatedMethodNoReplacement(): string
{
Deprecation::noticeWithNoReplacment('1.2.3');
return 'abc';
}
private function enableDeprecationNotices(bool $showNoReplacementNotices = false): void
{
Deprecation::enable($showNoReplacementNotices);
Deprecation::setShowNoticesCalledFromSupportedCode(true);
}
public function testNotice() public function testNotice()
{ {
$message = implode(' ', [ $message = implode(' ', [
@ -75,7 +93,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
$ret = $this->myDeprecatedMethod(); $ret = $this->myDeprecatedMethod();
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);
// call outputNotices() directly because the regular shutdown function that emits // call outputNotices() directly because the regular shutdown function that emits
@ -83,6 +101,29 @@ class DeprecationTest extends SapphireTest
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
public function testNoticeNoReplacement()
{
$message = implode(' ', [
'SilverStripe\Dev\Tests\DeprecationTest->myDeprecatedMethodNoReplacement is deprecated.',
'Will be removed without equivalent functionality to replace it.',
'Called from SilverStripe\Dev\Tests\DeprecationTest->testNoticeNoReplacement.'
]);
$this->expectDeprecation();
$this->expectDeprecationMessage($message);
$this->enableDeprecationNotices(true);
$ret = $this->myDeprecatedMethodNoReplacement();
$this->assertSame('abc', $ret);
Deprecation::outputNotices();
}
public function testNoticeNoReplacementNoSupressed()
{
$this->enableDeprecationNotices();
$ret = $this->myDeprecatedMethodNoReplacement();
$this->assertSame('abc', $ret);
Deprecation::outputNotices();
}
public function testCallUserFunc() public function testCallUserFunc()
{ {
$message = implode(' ', [ $message = implode(' ', [
@ -92,7 +133,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
$ret = call_user_func([$this, 'myDeprecatedMethod']); $ret = call_user_func([$this, 'myDeprecatedMethod']);
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);
Deprecation::outputNotices(); Deprecation::outputNotices();
@ -107,7 +148,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
$ret = call_user_func_array([$this, 'myDeprecatedMethod'], []); $ret = call_user_func_array([$this, 'myDeprecatedMethod'], []);
$this->assertSame('abc', $ret); $this->assertSame('abc', $ret);
Deprecation::outputNotices(); Deprecation::outputNotices();
@ -115,7 +156,7 @@ class DeprecationTest extends SapphireTest
public function testwithSuppressedNoticeDefault() public function testwithSuppressedNoticeDefault()
{ {
Deprecation::enable(); $this->enableDeprecationNotices();
$ret = Deprecation::withSuppressedNotice(function () { $ret = Deprecation::withSuppressedNotice(function () {
return $this->myDeprecatedMethod(); return $this->myDeprecatedMethod();
}); });
@ -132,7 +173,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(true); $this->enableDeprecationNotices(true);
$ret = Deprecation::withSuppressedNotice(function () { $ret = Deprecation::withSuppressedNotice(function () {
return $this->myDeprecatedMethod(); return $this->myDeprecatedMethod();
}); });
@ -149,7 +190,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(true); $this->enableDeprecationNotices(true);
$ret = Deprecation::withSuppressedNotice(function () { $ret = Deprecation::withSuppressedNotice(function () {
return call_user_func([$this, 'myDeprecatedMethod']); return call_user_func([$this, 'myDeprecatedMethod']);
}); });
@ -166,7 +207,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(true); $this->enableDeprecationNotices(true);
Deprecation::withSuppressedNotice(function () { Deprecation::withSuppressedNotice(function () {
Deprecation::notice('123', 'My message.'); Deprecation::notice('123', 'My message.');
}); });
@ -182,7 +223,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(true); $this->enableDeprecationNotices(true);
// using this syntax because my IDE was complaining about DeprecationTestObject not existing // using this syntax because my IDE was complaining about DeprecationTestObject not existing
// when trying to use `new DeprecationTestObject();` // when trying to use `new DeprecationTestObject();`
$class = DeprecationTestObject::class; $class = DeprecationTestObject::class;
@ -199,7 +240,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(true); $this->enableDeprecationNotices(true);
Injector::inst()->get(DeprecationTestObject::class); Injector::inst()->get(DeprecationTestObject::class);
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -217,6 +258,50 @@ class DeprecationTest extends SapphireTest
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
public function testshowNoticesCalledFromSupportedCode()
{
$this->expectNotToPerformAssertions();
$this->enableDeprecationNotices(true);
// showNoticesCalledFromSupportedCode is set to true by default for these unit tests
// as it is testing code within vendor/silverstripe
// This test is to ensure that the method works as expected when we disable this
// and we should expect no exceptions to be thrown
//
// Note specifically NOT testing the following because it's counted as being called
// from phpunit itself, which is not considered supported code
// Deprecation::withSuppressedNotice(function () {
// Deprecation::notice('123', 'My message.');
// });
Deprecation::setShowNoticesCalledFromSupportedCode(false);
// notice()
$this->myDeprecatedMethod();
// noticeNoReplacement()
$this->myDeprecatedMethodNoReplacement();
// callUserFunc()
call_user_func([$this, 'myDeprecatedMethod']);
// callUserFuncArray()
call_user_func_array([$this, 'myDeprecatedMethod'], []);
// withSuppressedNotice()
Deprecation::withSuppressedNotice(
fn() => $this->myDeprecatedMethod()
);
// withSuppressedNoticeTrue()
Deprecation::withSuppressedNotice(function () {
$this->myDeprecatedMethod();
});
// withSuppressedNoticeTrueCallUserFunc()
Deprecation::withSuppressedNotice(function () {
call_user_func([$this, 'myDeprecatedMethod']);
});
// classWithSuppressedNotice()
$class = DeprecationTestObject::class;
new $class();
// classWithInjectorwithSuppressedNotice()
Injector::inst()->get(DeprecationTestObject::class);
// Output notices - there should be none
Deprecation::outputNotices();
}
// The following tests would be better to put in the silverstripe/config module, however this is not // The following tests would be better to put in the silverstripe/config module, however this is not
// possible to do in a clean way as the config for the DeprecationTestObject will not load if it // possible to do in a clean way as the config for the DeprecationTestObject will not load if it
// is inside the silverstripe/config directory, as there is no _config.php file or _config folder. // is inside the silverstripe/config directory, as there is no _config.php file or _config folder.
@ -231,7 +316,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
Config::inst()->get(DeprecationTestObject::class, 'first_config'); Config::inst()->get(DeprecationTestObject::class, 'first_config');
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -244,7 +329,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
Config::inst()->get(DeprecationTestObject::class, 'second_config'); Config::inst()->get(DeprecationTestObject::class, 'second_config');
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -254,7 +339,7 @@ class DeprecationTest extends SapphireTest
$message = 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.third_config is deprecated.'; $message = 'Config SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject.third_config is deprecated.';
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
Config::inst()->get(DeprecationTestObject::class, 'third_config'); Config::inst()->get(DeprecationTestObject::class, 'third_config');
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -267,7 +352,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
Config::modify()->set(DeprecationTestObject::class, 'first_config', 'abc'); Config::modify()->set(DeprecationTestObject::class, 'first_config', 'abc');
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -280,7 +365,7 @@ class DeprecationTest extends SapphireTest
]); ]);
$this->expectDeprecation(); $this->expectDeprecation();
$this->expectDeprecationMessage($message); $this->expectDeprecationMessage($message);
Deprecation::enable(); $this->enableDeprecationNotices();
Config::modify()->merge(DeprecationTestObject::class, 'array_config', ['abc']); Config::modify()->merge(DeprecationTestObject::class, 'array_config', ['abc']);
Deprecation::outputNotices(); Deprecation::outputNotices();
} }
@ -366,7 +451,7 @@ class DeprecationTest extends SapphireTest
switch ($varName) { switch ($varName) {
case 'SS_DEPRECATION_ENABLED': case 'SS_DEPRECATION_ENABLED':
if ($configVal) { if ($configVal) {
Deprecation::enable(); $this->enableDeprecationNotices();
} else { } else {
Deprecation::disable(); Deprecation::disable();
} }
@ -542,7 +627,7 @@ class DeprecationTest extends SapphireTest
private function setEnabledViaStatic(bool $enabled): void private function setEnabledViaStatic(bool $enabled): void
{ {
if ($enabled) { if ($enabled) {
Deprecation::enable(); $this->enableDeprecationNotices();
} else { } else {
Deprecation::disable(); Deprecation::disable();
} }

View File

@ -0,0 +1,140 @@
<?php
namespace SilverStripe\Forms\Tests\GridField;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\Session;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldStateManagerInterface;
use SilverStripe\Forms\GridField\SessionGridFieldStateManager;
use SilverStripe\Forms\Tests\GridField\GridFieldPrintButtonTest\TestObject;
class SessionGridFieldStateManagerTest extends SapphireTest
{
protected function setUp(): void
{
parent::setUp();
// configure the injector to use the session grid field state manager
Injector::inst()->registerService(new SessionGridFieldStateManager(), GridFieldStateManagerInterface::class);
}
public function testStateKey()
{
$manager = new SessionGridFieldStateManager();
$controller = new Controller();
$form1 = new Form($controller, 'form1', new FieldList(), new FieldList());
$testObject = new TestObject();
$testObject->ID = 1;
$form2 = new Form($controller, 'form2', new FieldList(), new FieldList());
$form2->loadDataFrom($testObject);
$grid1 = new GridField('A');
$grid2 = new GridField('B');
$grid1->setForm($form1);
$grid2->setForm($form2);
$this->assertEquals('A-0', $manager->getStateKey($grid1));
$this->assertEquals('B-1', $manager->getStateKey($grid2));
}
public function testAddStateToURL()
{
$manager = new SessionGridFieldStateManager();
$grid = new GridField('TestGrid');
$grid->getState()->testValue = 'foo';
$stateRequestVar = $manager->getStateRequestVar();
$link = '/link-to/something';
$this->assertTrue(
preg_match(
"|^$link\?{$stateRequestVar}=[a-zA-Z0-9]+$|",
$manager->addStateToURL($grid, $link)
) == 1
);
$link = '/link-to/something-else?someParam=somevalue';
$this->assertTrue(
preg_match(
"|^/link-to/something-else\?someParam=somevalue&{$stateRequestVar}=[a-zA-Z0-9]+$|",
$manager->addStateToURL($grid, $link)
) == 1
);
}
public function testGetStateFromRequest()
{
$manager = new SessionGridFieldStateManager();
$session = new Session([]);
$request = new HTTPRequest(
'GET',
'/link-to/something',
[
$manager->getStateRequestVar() => 'testGetStateFromRequest'
]
);
$request->setSession($session);
$controller = new Controller();
$controller->setRequest($request);
$controller->pushCurrent();
$form = new Form($controller, 'form1', new FieldList(), new FieldList());
$grid = new GridField('TestGrid');
$grid->setForm($form);
$grid->getState()->testValue = 'foo';
$state = $grid->getState(false)->Value() ?? '{}';
$result = $manager->getStateFromRequest($grid, $request);
$this->assertEquals($state, $result);
$controller->popCurrent();
}
public function testDefaultStateLeavesURLUnchanged()
{
$manager = new SessionGridFieldStateManager();
$grid = new GridField('DefaultStateGrid');
$grid->getState(false)->getData()->testValue->initDefaults(['foo' => 'bar']);
$link = '/link-to/something';
$this->assertEquals('{}', $grid->getState(false)->Value());
$this->assertEquals(
'/link-to/something',
$manager->addStateToURL($grid, $link)
);
}
public function testStoreState()
{
$manager = new SessionGridFieldStateManager();
$session = new Session([]);
$request = new HTTPRequest(
'GET',
'/link-to/something',
[
$manager->getStateRequestVar() => 'testStoreState'
]
);
$request->setSession($session);
$controller = new Controller();
$controller->setRequest($request);
$controller->pushCurrent();
$form = new Form($controller, 'form1', new FieldList(), new FieldList());
$grid = new GridField('TestGrid');
$grid->setForm($form);
$grid->getState()->testValue = 'foo';
$state = $grid->getState(false)->Value() ?? '{}';
$manager->storeState($grid);
$this->assertEquals($state, $session->get('testStoreState')['TestGrid-0']);
$controller->popCurrent();
}
}