Compare commits

..

6 Commits

Author SHA1 Message Date
Guy Sartorelli
985a3d3b5f
Merge 8a7c70133f into 82b0851a2a 2024-10-21 01:51:26 +00:00
Guy Sartorelli
8a7c70133f
API Deprecations for template layer 2024-10-21 14:51:18 +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
24 changed files with 349 additions and 214 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

@ -4,7 +4,6 @@ namespace SilverStripe\Control;
use SilverStripe\Core\ClassInfo; use SilverStripe\Core\ClassInfo;
use SilverStripe\Dev\Debug; use SilverStripe\Dev\Debug;
use SilverStripe\Dev\Deprecation;
use SilverStripe\ORM\FieldType\DBHTMLText; use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\Security\Member; use SilverStripe\Security\Member;
use SilverStripe\Security\Security; use SilverStripe\Security\Security;
@ -20,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.
* *
@ -456,8 +454,7 @@ class Controller extends RequestHandler implements TemplateGlobalProvider
$class = static::class; $class = static::class;
while ($class != 'SilverStripe\\Control\\RequestHandler') { while ($class != 'SilverStripe\\Control\\RequestHandler') {
$templateName = strtok($class ?? '', '_') . '_' . $action; $templateName = strtok($class ?? '', '_') . '_' . $action;
$templateExists = Deprecation::withSuppressedNotice(fn() => SSViewer::hasTemplate($templateName)); if (SSViewer::hasTemplate($templateName)) {
if ($templateExists) {
return $class; return $class;
} }
@ -489,7 +486,7 @@ class Controller extends RequestHandler implements TemplateGlobalProvider
$parentClass = get_parent_class($parentClass ?? ''); $parentClass = get_parent_class($parentClass ?? '');
} }
return Deprecation::withSuppressedNotice(fn() => SSViewer::hasTemplate($templates)); return SSViewer::hasTemplate($templates);
} }
/** /**

View File

@ -12,7 +12,6 @@ use SilverStripe\Core\Environment;
use SilverStripe\Core\Extensible; use SilverStripe\Core\Extensible;
use SilverStripe\Core\Injector\Injectable; use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Deprecation;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
use SilverStripe\View\Requirements; use SilverStripe\View\Requirements;
@ -403,11 +402,9 @@ class Email extends SymfonyEmail
return $this->HTMLTemplate; return $this->HTMLTemplate;
} }
return Deprecation::withSuppressedNotice( return ThemeResourceLoader::inst()->findTemplate(
fn() => ThemeResourceLoader::inst()->findTemplate( SSViewer::get_templates_by_class(static::class, '', Email::class),
SSViewer::get_templates_by_class(static::class, '', Email::class), SSViewer::get_themes()
SSViewer::get_themes()
)
); );
} }

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

@ -17,7 +17,6 @@ use SilverStripe\View\ArrayData;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use LogicException; use LogicException;
use SilverStripe\Control\HTTPResponse_Exception; use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Dev\Deprecation;
/** /**
* This class is is responsible for adding objects to another object's has_many * This class is is responsible for adding objects to another object's has_many
@ -284,7 +283,7 @@ class GridFieldAddExistingAutocompleter extends AbstractGridFieldComponent imple
$json = []; $json = [];
Config::nest(); Config::nest();
SSViewer::config()->set('source_file_comments', false); SSViewer::config()->set('source_file_comments', false);
$viewer = Deprecation::withSuppressedNotice(fn() => SSViewer::fromString($this->resultsFormat)); $viewer = SSViewer::fromString($this->resultsFormat);
foreach ($results as $result) { foreach ($results as $result) {
if (!$result->canView()) { if (!$result->canView()) {
continue; continue;

View File

@ -240,7 +240,7 @@ class GridFieldDataColumns extends AbstractGridFieldComponent implements GridFie
$methodName = $fieldNameParts[$idx]; $methodName = $fieldNameParts[$idx];
// Last mmethod call from $columnName return what that method is returning // Last mmethod call from $columnName return what that method is returning
if ($idx == sizeof($fieldNameParts ?? []) - 1) { if ($idx == sizeof($fieldNameParts ?? []) - 1) {
return Deprecation::withSuppressedNotice(fn() => $tmpItem->XML_val($methodName)); return $tmpItem->XML_val($methodName);
} }
// else get the object from this $methodName // else get the object from this $methodName
$tmpItem = $tmpItem->$methodName(); $tmpItem = $tmpItem->$methodName();

View File

@ -8,7 +8,6 @@ use SilverStripe\Forms\TextareaField;
use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataObjectInterface; use SilverStripe\ORM\DataObjectInterface;
use Exception; use Exception;
use SilverStripe\Dev\Deprecation;
use SilverStripe\View\Parsers\HTMLValue; use SilverStripe\View\Parsers\HTMLValue;
/** /**
@ -130,9 +129,7 @@ class HTMLEditorField extends TextareaField
*/ */
public function saveInto(DataObjectInterface $record) public function saveInto(DataObjectInterface $record)
{ {
if ($record->hasField($this->name) if ($record->hasField($this->name) && $record->escapeTypeForField($this->name) != 'xml') {
&& Deprecation::withSuppressedNotice(fn () => $record->escapeTypeForField($this->name)) != 'xml'
) {
throw new Exception( throw new Exception(
'HTMLEditorField->saveInto(): This field should save into a HTMLText or HTMLVarchar field.' 'HTMLEditorField->saveInto(): This field should save into a HTMLText or HTMLVarchar field.'
); );

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

@ -193,11 +193,11 @@ class SSViewer implements Flushable
public function __construct($templates, TemplateParser $parser = null) public function __construct($templates, TemplateParser $parser = null)
{ {
if ($parser) { if ($parser) {
Deprecation::notice('5.4.0', 'The $parser parameter is deprecated and will be removed'); Deprecation::noticeWithNoReplacment('5.4.0', 'The $parser parameter is deprecated and will be removed');
Deprecation::withSuppressedNotice(fn() => $this->setParser($parser)); $this->setParser($parser);
} }
Deprecation::withSuppressedNotice(fn() => $this->setTemplate($templates)); $this->setTemplate($templates);
if (!$this->chosen) { if (!$this->chosen) {
$message = 'None of the following templates could be found: '; $message = 'None of the following templates could be found: ';
@ -220,11 +220,9 @@ class SSViewer implements Flushable
*/ */
public static function flush() public static function flush()
{ {
Deprecation::withSuppressedNotice(function () { Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::flush()');
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::flush()'); SSViewer::flush_template_cache(true);
SSViewer::flush_template_cache(true); SSViewer::flush_cacheblock_cache(true);
SSViewer::flush_cacheblock_cache(true);
});
} }
/** /**
@ -237,8 +235,8 @@ class SSViewer implements Flushable
*/ */
public static function fromString($content, $cacheTemplate = null) public static function fromString($content, $cacheTemplate = null)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::renderString()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::renderString()');
$viewer = Deprecation::withSuppressedNotice(fn() => SSViewer_FromString::create($content)); $viewer = SSViewer_FromString::create($content);
if ($cacheTemplate !== null) { if ($cacheTemplate !== null) {
$viewer->setCacheTemplate($cacheTemplate); $viewer->setCacheTemplate($cacheTemplate);
} }
@ -344,7 +342,7 @@ class SSViewer implements Flushable
*/ */
public static function topLevel() public static function topLevel()
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it.'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it.');
if (SSViewer::$topLevel) { if (SSViewer::$topLevel) {
return SSViewer::$topLevel[sizeof(SSViewer::$topLevel)-1]; return SSViewer::$topLevel[sizeof(SSViewer::$topLevel)-1];
} }
@ -406,7 +404,7 @@ class SSViewer implements Flushable
*/ */
public function setTemplate($templates) public function setTemplate($templates)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::setTemplate()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::setTemplate()');
$this->templates = $templates; $this->templates = $templates;
$this->chosen = $this->chooseTemplate($templates); $this->chosen = $this->chooseTemplate($templates);
$this->subTemplates = []; $this->subTemplates = [];
@ -421,10 +419,8 @@ class SSViewer implements Flushable
*/ */
public static function chooseTemplate($templates) public static function chooseTemplate($templates)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
return Deprecation::withSuppressedNotice( return ThemeResourceLoader::inst()->findTemplate($templates, SSViewer::get_themes());
fn() => ThemeResourceLoader::inst()->findTemplate($templates, SSViewer::get_themes())
);
} }
/** /**
@ -435,7 +431,7 @@ class SSViewer implements Flushable
*/ */
public function setParser(TemplateParser $parser) public function setParser(TemplateParser $parser)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::setParser()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::setParser()');
$this->parser = $parser; $this->parser = $parser;
} }
@ -447,11 +443,9 @@ class SSViewer implements Flushable
*/ */
public function getParser() public function getParser()
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::getParser()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::getParser()');
if (!$this->parser) { if (!$this->parser) {
Deprecation::withSuppressedNotice( $this->setParser(Injector::inst()->get('SilverStripe\\View\\SSTemplateParser'));
fn() => $this->setParser(Injector::inst()->get('SilverStripe\\View\\SSTemplateParser'))
);
} }
return $this->parser; return $this->parser;
} }
@ -466,10 +460,8 @@ class SSViewer implements Flushable
*/ */
public static function hasTemplate($templates) public static function hasTemplate($templates)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::hasTemplate()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::hasTemplate()');
return Deprecation::withSuppressedNotice( return (bool)ThemeResourceLoader::inst()->findTemplate($templates, SSViewer::get_themes());
fn() => (bool)ThemeResourceLoader::inst()->findTemplate($templates, SSViewer::get_themes())
);
} }
/** /**
@ -489,7 +481,7 @@ class SSViewer implements Flushable
*/ */
public function exists() public function exists()
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
return $this->chosen; return $this->chosen;
} }
@ -501,10 +493,8 @@ class SSViewer implements Flushable
*/ */
public static function getTemplateFileByType($identifier, $type = null) public static function getTemplateFileByType($identifier, $type = null)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
return Deprecation::withSuppressedNotice( return ThemeResourceLoader::inst()->findTemplate(['type' => $type, $identifier], SSViewer::get_themes());
fn() => ThemeResourceLoader::inst()->findTemplate(['type' => $type, $identifier], SSViewer::get_themes())
);
} }
/** /**
@ -518,7 +508,7 @@ class SSViewer implements Flushable
*/ */
public static function flush_template_cache($force = false) public static function flush_template_cache($force = false)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::flushTemplateCache()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::flushTemplateCache()');
if (!SSViewer::$template_cache_flushed || $force) { if (!SSViewer::$template_cache_flushed || $force) {
$dir = dir(TEMP_PATH); $dir = dir(TEMP_PATH);
while (false !== ($file = $dir->read())) { while (false !== ($file = $dir->read())) {
@ -541,7 +531,7 @@ class SSViewer implements Flushable
*/ */
public static function flush_cacheblock_cache($force = false) public static function flush_cacheblock_cache($force = false)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::flushCacheBlockCache()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::flushCacheBlockCache()');
if (!SSViewer::$cacheblock_cache_flushed || $force) { if (!SSViewer::$cacheblock_cache_flushed || $force) {
$cache = Injector::inst()->get(CacheInterface::class . '.cacheblock'); $cache = Injector::inst()->get(CacheInterface::class . '.cacheblock');
$cache->clear(); $cache->clear();
@ -559,7 +549,7 @@ class SSViewer implements Flushable
*/ */
public function setPartialCacheStore($cache) public function setPartialCacheStore($cache)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::setPartialCacheStore()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::setPartialCacheStore()');
$this->partialCacheStore = $cache; $this->partialCacheStore = $cache;
} }
@ -571,7 +561,7 @@ class SSViewer implements Flushable
*/ */
public function getPartialCacheStore() public function getPartialCacheStore()
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::getPartialCacheStore()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::getPartialCacheStore()');
if ($this->partialCacheStore) { if ($this->partialCacheStore) {
return $this->partialCacheStore; return $this->partialCacheStore;
} }
@ -605,7 +595,7 @@ class SSViewer implements Flushable
*/ */
protected function includeGeneratedTemplate($cacheFile, $item, $overlay, $underlay, $inheritedScope = null) protected function includeGeneratedTemplate($cacheFile, $item, $overlay, $underlay, $inheritedScope = null)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::includeGeneratedTemplate()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::includeGeneratedTemplate()');
if (isset($_GET['showtemplate']) && $_GET['showtemplate'] && Permission::check('ADMIN')) { if (isset($_GET['showtemplate']) && $_GET['showtemplate'] && Permission::check('ADMIN')) {
$lines = file($cacheFile ?? ''); $lines = file($cacheFile ?? '');
echo "<h2>Template: $cacheFile</h2>"; echo "<h2>Template: $cacheFile</h2>";
@ -616,10 +606,8 @@ class SSViewer implements Flushable
echo "</pre>"; echo "</pre>";
} }
$cache = Deprecation::withSuppressedNotice(fn() => $this->getPartialCacheStore()); $cache = $this->getPartialCacheStore();
$scope = Deprecation::withSuppressedNotice( $scope = new SSViewer_DataPresenter($item, $overlay, $underlay, $inheritedScope);
fn() => new SSViewer_DataPresenter($item, $overlay, $underlay, $inheritedScope)
);
$val = ''; $val = '';
// Placeholder for values exposed to $cacheFile // Placeholder for values exposed to $cacheFile
@ -648,9 +636,7 @@ class SSViewer implements Flushable
public function process($item, $arguments = null, $inheritedScope = null) public function process($item, $arguments = null, $inheritedScope = null)
{ {
if ($inheritedScope !== null) { if ($inheritedScope !== null) {
Deprecation::withSuppressedNotice( Deprecation::noticeWithNoReplacment('5.4.0', 'The $inheritedScope parameter is deprecated and will be removed');
fn() => Deprecation::notice('5.4.0', 'The $inheritedScope parameter is deprecated and will be removed')
);
} }
// Set hashlinks and temporarily modify global state // Set hashlinks and temporarily modify global state
$rewrite = $this->getRewriteHashLinks(); $rewrite = $this->getRewriteHashLinks();
@ -667,7 +653,7 @@ class SSViewer implements Flushable
if (!file_exists($cacheFile ?? '') || filemtime($cacheFile ?? '') < $lastEdited) { if (!file_exists($cacheFile ?? '') || filemtime($cacheFile ?? '') < $lastEdited) {
$content = file_get_contents($template ?? ''); $content = file_get_contents($template ?? '');
$content = Deprecation::withSuppressedNotice(fn() => $this->parseTemplateContent($content, $template)); $content = $this->parseTemplateContent($content, $template);
$fh = fopen($cacheFile ?? '', 'w'); $fh = fopen($cacheFile ?? '', 'w');
fwrite($fh, $content ?? ''); fwrite($fh, $content ?? '');
@ -680,7 +666,7 @@ class SSViewer implements Flushable
// through $Content and $Layout placeholders. // through $Content and $Layout placeholders.
foreach (['Content', 'Layout'] as $subtemplate) { foreach (['Content', 'Layout'] as $subtemplate) {
// Detect sub-template to use // Detect sub-template to use
$sub = Deprecation::withSuppressedNotice(fn() => $this->getSubtemplateFor($subtemplate)); $sub = $this->getSubtemplateFor($subtemplate);
if (!$sub) { if (!$sub) {
continue; continue;
} }
@ -691,19 +677,17 @@ class SSViewer implements Flushable
// Disable requirements - this will be handled by the parent template // Disable requirements - this will be handled by the parent template
$subtemplateViewer->includeRequirements(false); $subtemplateViewer->includeRequirements(false);
// Select the right template // Select the right template
Deprecation::withSuppressedNotice(fn() => $subtemplateViewer->setTemplate($sub)); $subtemplateViewer->setTemplate($sub);
// Render if available // Render if available
if (Deprecation::withSuppressedNotice(fn() => $subtemplateViewer->exists())) { if ($subtemplateViewer->exists()) {
return $subtemplateViewer->process($item, $arguments); return $subtemplateViewer->process($item, $arguments);
} }
return null; return null;
}; };
} }
$output = Deprecation::withSuppressedNotice( $output = $this->includeGeneratedTemplate($cacheFile, $item, $arguments, $underlay, $inheritedScope);
fn() => $this->includeGeneratedTemplate($cacheFile, $item, $arguments, $underlay, $inheritedScope)
);
if ($this->includeRequirements) { if ($this->includeRequirements) {
$output = Requirements::includeInHTML($output); $output = Requirements::includeInHTML($output);
@ -744,7 +728,7 @@ PHP;
*/ */
protected function getSubtemplateFor($subtemplate) protected function getSubtemplateFor($subtemplate)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::getSubtemplateFor()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::getSubtemplateFor()');
// Get explicit subtemplate name // Get explicit subtemplate name
if (isset($this->subTemplates[$subtemplate])) { if (isset($this->subTemplates[$subtemplate])) {
return $this->subTemplates[$subtemplate]; return $this->subTemplates[$subtemplate];
@ -786,10 +770,10 @@ PHP;
*/ */
public static function execute_template($template, $data, $arguments = null, $scope = null, $globalRequirements = false) public static function execute_template($template, $data, $arguments = null, $scope = null, $globalRequirements = false)
{ {
Deprecation::withSuppressedNotice(fn() => Deprecation::notice( Deprecation::noticeWithNoReplacment(
'5.4.0', '5.4.0',
'Will be replaced with SilverStripe\View\SSTemplateEngine::execute_template()' 'Will be replaced with SilverStripe\View\SSTemplateEngine::execute_template()'
)); );
$v = SSViewer::create($template); $v = SSViewer::create($template);
if ($globalRequirements) { if ($globalRequirements) {
@ -823,8 +807,8 @@ PHP;
*/ */
public static function execute_string($content, $data, $arguments = null, $globalRequirements = false) public static function execute_string($content, $data, $arguments = null, $globalRequirements = false)
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::renderString()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::renderString()');
$v = Deprecation::withSuppressedNotice(fn() => SSViewer::fromString($content)); $v = SSViewer::fromString($content);
if ($globalRequirements) { if ($globalRequirements) {
$v->includeRequirements(false); $v->includeRequirements(false);
@ -852,7 +836,7 @@ PHP;
*/ */
public function parseTemplateContent($content, $template = "") public function parseTemplateContent($content, $template = "")
{ {
Deprecation::notice('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::parseTemplateContent()'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be replaced with SilverStripe\View\SSTemplateEngine::parseTemplateContent()');
return $this->getParser()->compileString( return $this->getParser()->compileString(
$content, $content,
$template, $template,
@ -869,7 +853,7 @@ PHP;
*/ */
public function templates() public function templates()
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
return array_merge(['main' => $this->chosen], $this->subTemplates); return array_merge(['main' => $this->chosen], $this->subTemplates);
} }
@ -880,7 +864,7 @@ PHP;
*/ */
public function setTemplateFile($type, $file) public function setTemplateFile($type, $file)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
if (!$type || $type == 'main') { if (!$type || $type == 'main') {
$this->chosen = $file; $this->chosen = $file;
} else { } else {
@ -899,7 +883,7 @@ PHP;
*/ */
public static function get_base_tag($contentGeneratedSoFar) public static function get_base_tag($contentGeneratedSoFar)
{ {
Deprecation::withSuppressedNotice(fn() => Deprecation::notice('5.4.0', 'Use getBaseTag() instead')); Deprecation::notice('5.4.0', 'Use getBaseTag() instead');
// Is the document XHTML? // Is the document XHTML?
$isXhtml = preg_match('/<!DOCTYPE[^>]+xhtml/i', $contentGeneratedSoFar ?? ''); $isXhtml = preg_match('/<!DOCTYPE[^>]+xhtml/i', $contentGeneratedSoFar ?? '');
return static::getBaseTag($isXhtml); return static::getBaseTag($isXhtml);

View File

@ -66,7 +66,7 @@ class SSViewer_DataPresenter extends SSViewer_Scope
array $underlay = null, array $underlay = null,
SSViewer_Scope $inheritedScope = null SSViewer_Scope $inheritedScope = null
) { ) {
Deprecation::notice('5.4.0', 'Will be merged into ' . SSViewer_Scope::class, Deprecation::SCOPE_CLASS); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be merged into ' . SSViewer_Scope::class, Deprecation::SCOPE_CLASS);
parent::__construct($item, $inheritedScope); parent::__construct($item, $inheritedScope);
$this->overlay = $overlay ?: []; $this->overlay = $overlay ?: [];

View File

@ -39,13 +39,13 @@ class SSViewer_FromString extends SSViewer
*/ */
public function __construct($content, TemplateParser $parser = null) public function __construct($content, TemplateParser $parser = null)
{ {
Deprecation::notice( Deprecation::noticeWithNoReplacment(
'5.4.0', '5.4.0',
'Will be replaced with SilverStripe\View\SSTemplateEngine::renderString()', 'Will be replaced with SilverStripe\View\SSTemplateEngine::renderString()',
Deprecation::SCOPE_CLASS Deprecation::SCOPE_CLASS
); );
if ($parser) { if ($parser) {
Deprecation::withSuppressedNotice(fn() => $this->setParser($parser)); $this->setParser($parser);
} }
$this->content = $content; $this->content = $content;
@ -60,17 +60,13 @@ class SSViewer_FromString extends SSViewer
$cacheFile = TEMP_PATH . DIRECTORY_SEPARATOR . ".cache.$hash"; $cacheFile = TEMP_PATH . DIRECTORY_SEPARATOR . ".cache.$hash";
if (!file_exists($cacheFile ?? '') || isset($_GET['flush'])) { if (!file_exists($cacheFile ?? '') || isset($_GET['flush'])) {
$content = Deprecation::withSuppressedNotice( $content = $this->parseTemplateContent($this->content, "string sha1=$hash");
fn() => $this->parseTemplateContent($this->content, "string sha1=$hash")
);
$fh = fopen($cacheFile ?? '', 'w'); $fh = fopen($cacheFile ?? '', 'w');
fwrite($fh, $content ?? ''); fwrite($fh, $content ?? '');
fclose($fh); fclose($fh);
} }
$val = Deprecation::withSuppressedNotice( $val = $this->includeGeneratedTemplate($cacheFile, $item, $arguments, null, $scope);
fn() => $this->includeGeneratedTemplate($cacheFile, $item, $arguments, null, $scope)
);
if ($this->cacheTemplate !== null) { if ($this->cacheTemplate !== null) {
$cacheTemplate = $this->cacheTemplate; $cacheTemplate = $this->cacheTemplate;

View File

@ -138,7 +138,7 @@ class SSViewer_Scope
public function getCurrentItem() public function getCurrentItem()
{ {
return Deprecation::withSuppressedNotice(fn() => $this->getItem()); return $this->getItem();
} }
/** /**
@ -210,9 +210,7 @@ class SSViewer_Scope
*/ */
public function obj($name, $arguments = [], $cache = false, $cacheName = null) public function obj($name, $arguments = [], $cache = false, $cacheName = null)
{ {
Deprecation::withSuppressedNotice( Deprecation::noticeWithNoReplacment('5.4.0', 'Will be renamed scopeToIntermediateValue()');
fn() => Deprecation::notice('5.4.0', 'Will be renamed scopeToIntermediateValue()')
);
switch ($name) { switch ($name) {
case 'Up': case 'Up':
if ($this->upIndex === null) { if ($this->upIndex === null) {
@ -364,7 +362,7 @@ class SSViewer_Scope
{ {
$on = $this->getCurrentItem(); $on = $this->getCurrentItem();
if ($on instanceof ViewableData && $name === 'XML_val') { if ($on instanceof ViewableData && $name === 'XML_val') {
$retval = Deprecation::withSuppressedNotice(fn() => $on->XML_val(...$arguments)); $retval = $on->XML_val(...$arguments);
} else { } else {
$retval = $on ? $on->$name(...$arguments) : null; $retval = $on ? $on->$name(...$arguments) : null;
} }

View File

@ -187,7 +187,7 @@ class ThemeResourceLoader implements Flushable, TemplateGlobalProvider
*/ */
public function findTemplate($template, $themes = null) public function findTemplate($template, $themes = null)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it.'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it.');
if ($themes === null) { if ($themes === null) {
$themes = SSViewer::get_themes(); $themes = SSViewer::get_themes();
} }
@ -214,7 +214,7 @@ class ThemeResourceLoader implements Flushable, TemplateGlobalProvider
foreach ($templateList as $i => $template) { foreach ($templateList as $i => $template) {
// Check if passed list of templates in array format // Check if passed list of templates in array format
if (is_array($template)) { if (is_array($template)) {
$path = Deprecation::withSuppressedNotice(fn() => $this->findTemplate($template, $themes)); $path = $this->findTemplate($template, $themes);
if ($path) { if ($path) {
$this->getCache()->set($cacheKey, $path); $this->getCache()->set($cacheKey, $path);
return $path; return $path;

View File

@ -430,7 +430,7 @@ class ViewableData implements IteratorAggregate
*/ */
public function castingClass($field) public function castingClass($field)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it.'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it.');
// Strip arguments // Strip arguments
$spec = $this->castingHelper($field); $spec = $this->castingHelper($field);
return trim(strtok($spec ?? '', '(') ?? ''); return trim(strtok($spec ?? '', '(') ?? '');
@ -445,9 +445,8 @@ class ViewableData implements IteratorAggregate
*/ */
public function escapeTypeForField($field) public function escapeTypeForField($field)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it.'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it.');
$class = Deprecation::withSuppressedNotice(fn() => $this->castingClass($field)) $class = $this->castingClass($field) ?: $this->config()->get('default_cast');
?: $this->config()->get('default_cast');
/** @var DBField $type */ /** @var DBField $type */
$type = Injector::inst()->get($class, true); $type = Injector::inst()->get($class, true);
@ -497,7 +496,7 @@ class ViewableData implements IteratorAggregate
*/ */
protected function objCacheName($fieldName, $arguments) protected function objCacheName($fieldName, $arguments)
{ {
Deprecation::notice('5.4.0', 'Will be made private'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be made private');
return $arguments return $arguments
? $fieldName . ":" . var_export($arguments, true) ? $fieldName . ":" . var_export($arguments, true)
: $fieldName; : $fieldName;
@ -554,10 +553,10 @@ class ViewableData implements IteratorAggregate
public function obj($fieldName, $arguments = [], $cache = false, $cacheName = null) public function obj($fieldName, $arguments = [], $cache = false, $cacheName = null)
{ {
if ($cacheName !== null) { if ($cacheName !== null) {
Deprecation::notice('5.4.0', 'The $cacheName parameter has been deprecated and will be removed'); Deprecation::noticeWithNoReplacment('5.4.0', 'The $cacheName parameter has been deprecated and will be removed');
} }
if (!$cacheName && $cache) { if (!$cacheName && $cache) {
$cacheName = Deprecation::withSuppressedNotice(fn() => $this->objCacheName($fieldName, $arguments)); $cacheName = $this->objCacheName($fieldName, $arguments);
} }
// Check pre-cached value // Check pre-cached value
@ -633,7 +632,7 @@ class ViewableData implements IteratorAggregate
*/ */
public function XML_val($field, $arguments = [], $cache = false) public function XML_val($field, $arguments = [], $cache = false)
{ {
Deprecation::notice('5.4.0', 'Will be removed without equivalent functionality to replace it'); Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
$result = $this->obj($field, $arguments, $cache); $result = $this->obj($field, $arguments, $cache);
// Might contain additional formatting over ->XML(). E.g. parse shortcodes, nl2br() // Might contain additional formatting over ->XML(). E.g. parse shortcodes, nl2br()
return $result->forTemplate(); return $result->forTemplate();
@ -648,10 +647,11 @@ class ViewableData implements IteratorAggregate
*/ */
public function getXMLValues($fields) public function getXMLValues($fields)
{ {
Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it');
$result = []; $result = [];
foreach ($fields as $field) { foreach ($fields as $field) {
$result[$field] = Deprecation::withSuppressedNotice(fn() => $this->XML_val($field)); $result[$field] = $this->XML_val($field);
} }
return $result; return $result;

View File

@ -9,7 +9,6 @@ use SilverStripe\View\ThemeResourceLoader;
use SilverStripe\View\ThemeManifest; use SilverStripe\View\ThemeManifest;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Core\Manifest\ModuleManifest; use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Dev\Deprecation;
/** /**
* Tests for the {@link TemplateLoader} class. * Tests for the {@link TemplateLoader} class.
@ -74,46 +73,41 @@ class ThemeResourceLoaderTest extends SapphireTest
{ {
$this->assertEquals( $this->assertEquals(
"$this->base/module/templates/Page.ss", "$this->base/module/templates/Page.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate('Page', ['$default'])) $this->loader->findTemplate('Page', ['$default'])
); );
$this->assertEquals( $this->assertEquals(
"$this->base/module/templates/Layout/Page.ss", "$this->base/module/templates/Layout/Page.ss",
Deprecation::withSuppressedNotice( $this->loader->findTemplate(['type' => 'Layout', 'Page'], ['$default'])
fn() => $this->loader->findTemplate(['type' => 'Layout', 'Page'], ['$default'])
)
); );
} }
public function testFindNestedThemeTemplates() public function testFindNestedThemeTemplates()
{ {
// Without including the theme this template cannot be found // Without including the theme this template cannot be found
$this->assertEquals( $this->assertEquals(null, $this->loader->findTemplate('NestedThemePage', ['$default']));
null,
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate('NestedThemePage', ['$default']))
);
// With a nested theme available then it is available // With a nested theme available then it is available
$this->assertEquals( $this->assertEquals(
"{$this->base}/module/themes/subtheme/templates/NestedThemePage.ss", "{$this->base}/module/themes/subtheme/templates/NestedThemePage.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate( $this->loader->findTemplate(
'NestedThemePage', 'NestedThemePage',
[ [
'silverstripe/module:subtheme', 'silverstripe/module:subtheme',
'$default' '$default'
] ]
)) )
); );
// Can also be found if excluding $default theme // Can also be found if excluding $default theme
$this->assertEquals( $this->assertEquals(
"{$this->base}/module/themes/subtheme/templates/NestedThemePage.ss", "{$this->base}/module/themes/subtheme/templates/NestedThemePage.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate( $this->loader->findTemplate(
'NestedThemePage', 'NestedThemePage',
[ [
'silverstripe/module:subtheme', 'silverstripe/module:subtheme',
] ]
)) )
); );
} }
@ -122,7 +116,7 @@ class ThemeResourceLoaderTest extends SapphireTest
// Test that "type" is respected properly // Test that "type" is respected properly
$this->assertEquals( $this->assertEquals(
"{$this->base}/module/templates/MyNamespace/Layout/MyClass.ss", "{$this->base}/module/templates/MyNamespace/Layout/MyClass.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate( $this->loader->findTemplate(
[ [
[ [
'type' => 'Layout', 'type' => 'Layout',
@ -139,13 +133,13 @@ class ThemeResourceLoaderTest extends SapphireTest
'theme', 'theme',
'$default', '$default',
] ]
)) )
); );
// Non-typed template can be found even if looking for typed theme at a lower priority // Non-typed template can be found even if looking for typed theme at a lower priority
$this->assertEquals( $this->assertEquals(
"{$this->base}/module/templates/MyNamespace/MyClass.ss", "{$this->base}/module/templates/MyNamespace/MyClass.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate( $this->loader->findTemplate(
[ [
[ [
'type' => 'Layout', 'type' => 'Layout',
@ -162,7 +156,7 @@ class ThemeResourceLoaderTest extends SapphireTest
'theme', 'theme',
'$default', '$default',
] ]
)) )
); );
} }
@ -171,32 +165,30 @@ class ThemeResourceLoaderTest extends SapphireTest
// Items given as full paths are returned directly // Items given as full paths are returned directly
$this->assertEquals( $this->assertEquals(
"$this->base/themes/theme/templates/Page.ss", "$this->base/themes/theme/templates/Page.ss",
Deprecation::withSuppressedNotice( $this->loader->findTemplate("$this->base/themes/theme/templates/Page.ss", ['theme'])
fn() => $this->loader->findTemplate("$this->base/themes/theme/templates/Page.ss", ['theme'])
)
); );
$this->assertEquals( $this->assertEquals(
"$this->base/themes/theme/templates/Page.ss", "$this->base/themes/theme/templates/Page.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate( $this->loader->findTemplate(
[ [
"$this->base/themes/theme/templates/Page.ss", "$this->base/themes/theme/templates/Page.ss",
"Page" "Page"
], ],
['theme'] ['theme']
)) )
); );
// Ensure checks for file_exists // Ensure checks for file_exists
$this->assertEquals( $this->assertEquals(
"$this->base/themes/theme/templates/Page.ss", "$this->base/themes/theme/templates/Page.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate( $this->loader->findTemplate(
[ [
"$this->base/themes/theme/templates/NotAPage.ss", "$this->base/themes/theme/templates/NotAPage.ss",
"$this->base/themes/theme/templates/Page.ss", "$this->base/themes/theme/templates/Page.ss",
], ],
['theme'] ['theme']
)) )
); );
} }
@ -207,14 +199,12 @@ class ThemeResourceLoaderTest extends SapphireTest
{ {
$this->assertEquals( $this->assertEquals(
"$this->base/themes/theme/templates/Page.ss", "$this->base/themes/theme/templates/Page.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate('Page', ['theme'])) $this->loader->findTemplate('Page', ['theme'])
); );
$this->assertEquals( $this->assertEquals(
"$this->base/themes/theme/templates/Layout/Page.ss", "$this->base/themes/theme/templates/Layout/Page.ss",
Deprecation::withSuppressedNotice( $this->loader->findTemplate(['type' => 'Layout', 'Page'], ['theme'])
fn() => $this->loader->findTemplate(['type' => 'Layout', 'Page'], ['theme'])
)
); );
} }
@ -231,14 +221,12 @@ class ThemeResourceLoaderTest extends SapphireTest
$this->assertEquals( $this->assertEquals(
"$this->base/myproject/templates/Page.ss", "$this->base/myproject/templates/Page.ss",
Deprecation::withSuppressedNotice(fn() => $this->loader->findTemplate('Page', ['$default'])) $this->loader->findTemplate('Page', ['$default'])
); );
$this->assertEquals( $this->assertEquals(
"$this->base/myproject/templates/Layout/Page.ss", "$this->base/myproject/templates/Layout/Page.ss",
Deprecation::withSuppressedNotice( $this->loader->findTemplate(['type' => 'Layout', 'Page'], ['$default'])
fn() => $this->loader->findTemplate(['type' => 'Layout', 'Page'], ['$default'])
)
); );
$this->removeTestTemplates($templates); $this->removeTestTemplates($templates);
@ -251,16 +239,12 @@ class ThemeResourceLoaderTest extends SapphireTest
{ {
$this->assertEquals( $this->assertEquals(
"$this->base/themes/theme/templates/CustomThemePage.ss", "$this->base/themes/theme/templates/CustomThemePage.ss",
Deprecation::withSuppressedNotice( $this->loader->findTemplate('CustomThemePage', ['theme', '$default'])
fn() => $this->loader->findTemplate('CustomThemePage', ['theme', '$default'])
)
); );
$this->assertEquals( $this->assertEquals(
"$this->base/module/templates/Layout/CustomThemePage.ss", "$this->base/module/templates/Layout/CustomThemePage.ss",
Deprecation::withSuppressedNotice( $this->loader->findTemplate(['type' => 'Layout', 'CustomThemePage'], ['theme', '$default'])
fn() => $this->loader->findTemplate(['type' => 'Layout', 'CustomThemePage'], ['theme', '$default'])
)
); );
} }
@ -406,7 +390,7 @@ class ThemeResourceLoaderTest extends SapphireTest
$loader = new ThemeResourceLoader(); $loader = new ThemeResourceLoader();
$loader->setCache($mockCache); $loader->setCache($mockCache);
Deprecation::withSuppressedNotice(fn() => $loader->findTemplate('Page', ['$default'])); $loader->findTemplate('Page', ['$default']);
} }
public function testFindTemplateWithCacheHit() public function testFindTemplateWithCacheHit()
@ -418,9 +402,6 @@ class ThemeResourceLoaderTest extends SapphireTest
$loader = new ThemeResourceLoader(); $loader = new ThemeResourceLoader();
$loader->setCache($mockCache); $loader->setCache($mockCache);
$this->assertSame( $this->assertSame('mock_template.ss', $loader->findTemplate('Page', ['$default']));
'mock_template.ss',
Deprecation::withSuppressedNotice(fn() => $loader->findTemplate('Page', ['$default']))
);
} }
} }

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

@ -5,7 +5,6 @@ namespace SilverStripe\View\Tests;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Control\ContentNegotiator; use SilverStripe\Control\ContentNegotiator;
use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\HTTPResponse;
use SilverStripe\Dev\Deprecation;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use SilverStripe\View\Tests\SSViewerTest\TestFixture; use SilverStripe\View\Tests\SSViewerTest\TestFixture;
@ -18,7 +17,7 @@ class ContentNegotiatorTest extends SapphireTest
*/ */
private function render($templateString, $data = null) private function render($templateString, $data = null)
{ {
$t = Deprecation::withSuppressedNotice(fn() => SSViewer::fromString($templateString)); $t = SSViewer::fromString($templateString);
if (!$data) { if (!$data) {
$data = new TestFixture(); $data = new TestFixture();
} }

View File

@ -9,7 +9,6 @@ use SilverStripe\Versioned\Versioned;
use Psr\SimpleCache\CacheInterface; use Psr\SimpleCache\CacheInterface;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\Control\Director; use SilverStripe\Control\Director;
use SilverStripe\Dev\Deprecation;
use SilverStripe\View\SSTemplateParseException; use SilverStripe\View\SSTemplateParseException;
use SilverStripe\View\SSViewer; use SilverStripe\View\SSViewer;
use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter;
@ -65,7 +64,7 @@ class SSViewerCacheBlockTest extends SapphireTest
$data = $this->data->customise($data); $data = $this->data->customise($data);
} }
return Deprecation::withSuppressedNotice(fn() => SSViewer::execute_string($template, $data)); return SSViewer::execute_string($template, $data);
} }
public function testParsing() public function testParsing()
@ -178,13 +177,13 @@ class SSViewerCacheBlockTest extends SapphireTest
$data->setEntropy('default'); $data->setEntropy('default');
$this->assertEquals( $this->assertEquals(
'default Stage.Stage', 'default Stage.Stage',
Deprecation::withSuppressedNotice(fn() => SSViewer::execute_string('<% cached %>$Inspect<% end_cached %>', $data)) SSViewer::execute_string('<% cached %>$Inspect<% end_cached %>', $data)
); );
$data = new SSViewerCacheBlockTest\VersionedModel(); $data = new SSViewerCacheBlockTest\VersionedModel();
$data->setEntropy('first'); $data->setEntropy('first');
$this->assertEquals( $this->assertEquals(
'first Stage.Stage', 'first Stage.Stage',
Deprecation::withSuppressedNotice(fn() => SSViewer::execute_string('<% cached %>$Inspect<% end_cached %>', $data)) SSViewer::execute_string('<% cached %>$Inspect<% end_cached %>', $data)
); );
// Run without caching in live to prove data is uncached // Run without caching in live to prove data is uncached

View File

@ -13,7 +13,6 @@ use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Convert; use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Injector\Injector;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;
use SilverStripe\ORM\ArrayList; use SilverStripe\ORM\ArrayList;
@ -197,7 +196,7 @@ class SSViewerTest extends SapphireTest
*/ */
public function render($templateString, $data = null, $cacheTemplate = false) public function render($templateString, $data = null, $cacheTemplate = false)
{ {
$t = Deprecation::withSuppressedNotice(fn() => SSViewer::fromString($templateString, $cacheTemplate)); $t = SSViewer::fromString($templateString, $cacheTemplate);
if (!$data) { if (!$data) {
$data = new SSViewerTest\TestFixture(); $data = new SSViewerTest\TestFixture();
} }
@ -1305,29 +1304,29 @@ after'
// Value casted as "Text" // Value casted as "Text"
$this->assertEquals( $this->assertEquals(
'&lt;b&gt;html&lt;/b&gt;', '&lt;b&gt;html&lt;/b&gt;',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$TextValue'))->process($vd) $t = SSViewer::fromString('$TextValue')->process($vd)
); );
$this->assertEquals( $this->assertEquals(
'<b>html</b>', '<b>html</b>',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$TextValue.RAW'))->process($vd) $t = SSViewer::fromString('$TextValue.RAW')->process($vd)
); );
$this->assertEquals( $this->assertEquals(
'&lt;b&gt;html&lt;/b&gt;', '&lt;b&gt;html&lt;/b&gt;',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$TextValue.XML'))->process($vd) $t = SSViewer::fromString('$TextValue.XML')->process($vd)
); );
// Value casted as "HTMLText" // Value casted as "HTMLText"
$this->assertEquals( $this->assertEquals(
'<b>html</b>', '<b>html</b>',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$HTMLValue'))->process($vd) $t = SSViewer::fromString('$HTMLValue')->process($vd)
); );
$this->assertEquals( $this->assertEquals(
'<b>html</b>', '<b>html</b>',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$HTMLValue.RAW'))->process($vd) $t = SSViewer::fromString('$HTMLValue.RAW')->process($vd)
); );
$this->assertEquals( $this->assertEquals(
'&lt;b&gt;html&lt;/b&gt;', '&lt;b&gt;html&lt;/b&gt;',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$HTMLValue.XML'))->process($vd) $t = SSViewer::fromString('$HTMLValue.XML')->process($vd)
); );
// Uncasted value (falls back to ViewableData::$default_cast="Text") // Uncasted value (falls back to ViewableData::$default_cast="Text")
@ -1335,15 +1334,15 @@ after'
$vd->UncastedValue = '<b>html</b>'; $vd->UncastedValue = '<b>html</b>';
$this->assertEquals( $this->assertEquals(
'&lt;b&gt;html&lt;/b&gt;', '&lt;b&gt;html&lt;/b&gt;',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$UncastedValue'))->process($vd) $t = SSViewer::fromString('$UncastedValue')->process($vd)
); );
$this->assertEquals( $this->assertEquals(
'<b>html</b>', '<b>html</b>',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$UncastedValue.RAW'))->process($vd) $t = SSViewer::fromString('$UncastedValue.RAW')->process($vd)
); );
$this->assertEquals( $this->assertEquals(
'&lt;b&gt;html&lt;/b&gt;', '&lt;b&gt;html&lt;/b&gt;',
Deprecation::withSuppressedNotice(fn() => SSViewer::fromString('$UncastedValue.XML'))->process($vd) $t = SSViewer::fromString('$UncastedValue.XML')->process($vd)
); );
} }
@ -2040,9 +2039,7 @@ EOC;
public function testLoopIteratorIterator() public function testLoopIteratorIterator()
{ {
$list = new PaginatedList(new ArrayList()); $list = new PaginatedList(new ArrayList());
$viewer = Deprecation::withSuppressedNotice( $viewer = new SSViewer_FromString('<% loop List %>$ID - $FirstName<br /><% end_loop %>');
fn() => new SSViewer_FromString('<% loop List %>$ID - $FirstName<br /><% end_loop %>')
);
$result = $viewer->process(new ArrayData(['List' => $list])); $result = $viewer->process(new ArrayData(['List' => $list]));
$this->assertEquals($result, ''); $this->assertEquals($result, '');
} }
@ -2185,9 +2182,7 @@ EOC;
} }
); );
$template = Deprecation::withSuppressedNotice( $template = new SSViewer_FromString("<% test %><% end_test %>", $parser);
fn() => new SSViewer_FromString("<% test %><% end_test %>", $parser)
);
$template->process(new SSViewerTest\TestFixture()); $template->process(new SSViewerTest\TestFixture());
$this->assertEquals(1, $count); $this->assertEquals(1, $count);
@ -2204,7 +2199,7 @@ EOC;
} }
); );
$template = Deprecation::withSuppressedNotice(fn() => new SSViewer_FromString("<% test %>", $parser)); $template = new SSViewer_FromString("<% test %>", $parser);
$template->process(new SSViewerTest\TestFixture()); $template->process(new SSViewerTest\TestFixture());
$this->assertEquals(1, $count); $this->assertEquals(1, $count);

View File

@ -3,7 +3,6 @@
namespace SilverStripe\View\Tests; namespace SilverStripe\View\Tests;
use ReflectionMethod; use ReflectionMethod;
use SilverStripe\Dev\Deprecation;
use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\SapphireTest;
use SilverStripe\View\ArrayData; use SilverStripe\View\ArrayData;
@ -78,12 +77,12 @@ class ViewableDataTest extends SapphireTest
{ {
$caster = new ViewableDataTest\Castable(); $caster = new ViewableDataTest\Castable();
$this->assertEquals('casted', Deprecation::withSuppressedNotice(fn() => $caster->XML_val('alwaysCasted'))); $this->assertEquals('casted', $caster->XML_val('alwaysCasted'));
$this->assertEquals('casted', Deprecation::withSuppressedNotice(fn() => $caster->XML_val('noCastingInformation'))); $this->assertEquals('casted', $caster->XML_val('noCastingInformation'));
// Test automatic escaping is applied even to fields with no 'casting' // Test automatic escaping is applied even to fields with no 'casting'
$this->assertEquals('casted', Deprecation::withSuppressedNotice(fn() => $caster->XML_val('unsafeXML'))); $this->assertEquals('casted', $caster->XML_val('unsafeXML'));
$this->assertEquals('&lt;foo&gt;', Deprecation::withSuppressedNotice(fn() => $caster->XML_val('castedUnsafeXML'))); $this->assertEquals('&lt;foo&gt;', $caster->XML_val('castedUnsafeXML'));
} }
public function testArrayCustomise() public function testArrayCustomise()
@ -96,11 +95,11 @@ class ViewableDataTest extends SapphireTest
] ]
); );
$this->assertEquals('test', Deprecation::withSuppressedNotice(fn() => $viewableData->XML_val('test'))); $this->assertEquals('test', $viewableData->XML_val('test'));
$this->assertEquals('casted', Deprecation::withSuppressedNotice(fn() => $viewableData->XML_val('alwaysCasted'))); $this->assertEquals('casted', $viewableData->XML_val('alwaysCasted'));
$this->assertEquals('overwritten', Deprecation::withSuppressedNotice(fn() => $newViewableData->XML_val('test'))); $this->assertEquals('overwritten', $newViewableData->XML_val('test'));
$this->assertEquals('overwritten', Deprecation::withSuppressedNotice(fn() => $newViewableData->XML_val('alwaysCasted'))); $this->assertEquals('overwritten', $newViewableData->XML_val('alwaysCasted'));
$this->assertEquals('castable', $viewableData->forTemplate()); $this->assertEquals('castable', $viewableData->forTemplate());
$this->assertEquals('castable', $newViewableData->forTemplate()); $this->assertEquals('castable', $newViewableData->forTemplate());
@ -111,11 +110,11 @@ class ViewableDataTest extends SapphireTest
$viewableData = new ViewableDataTest\Castable(); $viewableData = new ViewableDataTest\Castable();
$newViewableData = $viewableData->customise(new ViewableDataTest\RequiresCasting()); $newViewableData = $viewableData->customise(new ViewableDataTest\RequiresCasting());
$this->assertEquals('test', Deprecation::withSuppressedNotice(fn() => $viewableData->XML_val('test'))); $this->assertEquals('test', $viewableData->XML_val('test'));
$this->assertEquals('casted', Deprecation::withSuppressedNotice(fn() => $viewableData->XML_val('alwaysCasted'))); $this->assertEquals('casted', $viewableData->XML_val('alwaysCasted'));
$this->assertEquals('overwritten', Deprecation::withSuppressedNotice(fn() => $newViewableData->XML_val('test'))); $this->assertEquals('overwritten', $newViewableData->XML_val('test'));
$this->assertEquals('casted', Deprecation::withSuppressedNotice(fn() => $newViewableData->XML_val('alwaysCasted'))); $this->assertEquals('casted', $newViewableData->XML_val('alwaysCasted'));
$this->assertEquals('castable', $viewableData->forTemplate()); $this->assertEquals('castable', $viewableData->forTemplate());
$this->assertEquals('casted', $newViewableData->forTemplate()); $this->assertEquals('casted', $newViewableData->forTemplate());
@ -148,7 +147,7 @@ class ViewableDataTest extends SapphireTest
foreach ($expected as $field => $class) { foreach ($expected as $field => $class) {
$this->assertEquals( $this->assertEquals(
$class, $class,
Deprecation::withSuppressedNotice(fn() => $obj->castingClass($field)), $obj->castingClass($field),
"castingClass() returns correct results for ::\$$field" "castingClass() returns correct results for ::\$$field"
); );
} }
@ -160,7 +159,7 @@ class ViewableDataTest extends SapphireTest
// Save a literal string into cache // Save a literal string into cache
$cache = true; $cache = true;
$uncastedData = $obj->obj('noCastingInformation', null, $cache); $uncastedData = $obj->obj('noCastingInformation', null, false, $cache);
// Fetch the cached string as an object // Fetch the cached string as an object
$forceReturnedObject = true; $forceReturnedObject = true;
@ -185,15 +184,15 @@ class ViewableDataTest extends SapphireTest
$objCached->Test = 'AAA'; $objCached->Test = 'AAA';
$objNotCached->Test = 'AAA'; $objNotCached->Test = 'AAA';
$this->assertEquals('AAA', $objCached->obj('Test', null, true)); $this->assertEquals('AAA', $objCached->obj('Test', null, true, true));
$this->assertEquals('AAA', $objNotCached->obj('Test', null, true)); $this->assertEquals('AAA', $objNotCached->obj('Test', null, true, true));
$objCached->Test = 'BBB'; $objCached->Test = 'BBB';
$objNotCached->Test = 'BBB'; $objNotCached->Test = 'BBB';
// Cached data must be always the same // Cached data must be always the same
$this->assertEquals('AAA', $objCached->obj('Test', null, true)); $this->assertEquals('AAA', $objCached->obj('Test', null, true, true));
$this->assertEquals('BBB', $objNotCached->obj('Test', null, true)); $this->assertEquals('BBB', $objNotCached->obj('Test', null, true, true));
} }
public function testSetFailover() public function testSetFailover()

View File

@ -8,7 +8,6 @@ use SilverStripe\Core\Manifest\ClassManifest;
use SilverStripe\Core\Manifest\ClassLoader; use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleManifest; use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Dev\Deprecation;
use SilverStripe\i18n\i18n; use SilverStripe\i18n\i18n;
use SilverStripe\i18n\Messages\MessageProvider; use SilverStripe\i18n\Messages\MessageProvider;
use SilverStripe\i18n\Messages\Symfony\ModuleYamlLoader; use SilverStripe\i18n\Messages\Symfony\ModuleYamlLoader;
@ -74,7 +73,7 @@ trait i18nTestManifest
{ {
// force SSViewer_DataPresenter to cache global template vars before we switch to the // force SSViewer_DataPresenter to cache global template vars before we switch to the
// test-project class manifest (since it will lose visibility of core classes) // test-project class manifest (since it will lose visibility of core classes)
$presenter = Deprecation::withSuppressedNotice(fn() => new SSViewer_DataPresenter(new ViewableData())); $presenter = new SSViewer_DataPresenter(new ViewableData());
unset($presenter); unset($presenter);
// Switch to test manifest // Switch to test manifest