From 137ebcebec0701818e55a6edc3b6f637c6121cbd Mon Sep 17 00:00:00 2001 From: Steve Boyd Date: Tue, 15 Nov 2022 18:20:54 +1300 Subject: [PATCH] API Stop using deprecated API --- _config.php | 4 - _config/i18n.yml | 4 +- src/Control/CookieJar.php | 3 - src/Control/Director.php | 2 +- src/Control/Email/Email.php | 359 ++++++++++-------- src/Control/Email/SwiftMailer.php | 4 +- src/Control/Email/SwiftPlugin.php | 4 +- src/Control/HTTP.php | 36 +- src/Control/Middleware/FlushMiddleware.php | 8 +- .../Middleware/HTTPCacheControlMiddleware.php | 5 +- .../URLSpecialsMiddleware/FlushScheduler.php | 7 +- src/Control/RSS/RSSFeed.php | 4 +- src/Control/RequestProcessor.php | 4 +- src/Control/Session.php | 2 - src/Control/SimpleResourceURLGenerator.php | 5 +- src/Core/BaseKernel.php | 46 +-- src/Core/Convert.php | 2 +- src/Core/Manifest/ClassLoader.php | 4 +- src/Core/Manifest/ClassManifest.php | 4 +- src/Core/Manifest/ManifestFileFinder.php | 5 +- src/Dev/Deprecation.php | 177 ++++++--- src/Dev/FunctionalTest.php | 21 +- src/Dev/SapphireTest.php | 16 +- src/Dev/Tasks/MigrateFileTask.php | 9 + .../GridFieldAddExistingAutocompleter.php | 2 +- src/Forms/GridField/GridFieldExportButton.php | 2 + src/Forms/GridField/GridFieldFilterHeader.php | 9 +- src/Forms/TreeDropdownField.php | 5 - src/Forms/UploadReceiver.php | 5 +- src/ORM/ArrayList.php | 8 +- src/ORM/Connect/DBSchemaManager.php | 4 - src/ORM/Connect/MySQLTransactionManager.php | 7 - src/ORM/DataObject.php | 5 - src/Security/CMSSecurity.php | 2 +- src/View/SSViewer.php | 7 +- src/i18n/i18n.php | 1 - .../Forms/GridField/GridField_Item.ss | 2 +- tests/php/Control/ControllerTest.php | 2 +- tests/php/Control/DirectorTest.php | 4 + tests/php/Control/Email/EmailTest.php | 4 +- tests/php/Control/Email/SwiftMailerTest.php | 2 +- tests/php/Control/Email/SwiftPluginTest.php | 8 +- tests/php/Control/HTTPRequestTest.php | 7 + tests/php/Control/HTTPTest.php | 13 + tests/php/Control/SessionTest.php | 4 +- tests/php/Core/ConvertTest.php | 18 +- tests/php/Core/Manifest/ModuleTest.php | 4 + tests/php/Core/ObjectTest.php | 13 + tests/php/Dev/BacktraceTest.php | 4 +- tests/php/Dev/DeprecationTest.php | 141 ++++++- .../DeprecationTest/DeprecationTestObject.php | 13 + tests/php/Dev/DevAdminControllerTest.php | 2 +- .../php/Forms/ConfirmedPasswordFieldTest.php | 10 +- tests/php/Forms/CurrencyFieldDisabledTest.php | 2 +- tests/php/Forms/CurrencyFieldReadonlyTest.php | 4 +- tests/php/Forms/CurrencyFieldTest.php | 13 +- tests/php/Forms/FormFieldTest.php | 8 +- tests/php/Forms/FormTest.php | 6 +- tests/php/Logging/MonologErrorHandlerTest.php | 7 +- tests/php/ORM/ArrayListTest.php | 15 + .../ORM/DataObjectSchemaGenerationTest.php | 16 +- tests/php/ORM/HierarchyCachingTest.php | 2 +- tests/php/ORM/HierarchyTest.php | 2 +- tests/php/ORM/ManyManyListTest.php | 4 +- tests/php/ORM/ManyManyThroughListTest.php | 4 +- tests/php/ORM/MySQLPDOConnectorTest.php | 13 + tests/php/ORM/SQLSelectTest.php | 13 - tests/php/ORM/TransactionTest.php | 16 - .../SessionAuthenticationHandlerTest.php | 11 +- .../php/Security/MemberCsvBulkLoaderTest.php | 4 +- tests/php/Security/MemberTest.php | 14 +- tests/php/Security/RandomGeneratorTest.php | 4 + tests/php/View/ArrayDataTest.php | 6 - tests/php/View/RequirementsTest.php | 2 +- tests/php/View/SSViewerTest.php | 34 +- ...iewerTestIncludeScopeInheritanceInclude.ss | 2 +- ...stIncludeScopeInheritanceWithArgsInLoop.ss | 2 +- tests/php/View/ViewableDataTest.php | 4 + tests/php/i18n/i18nTest.php | 6 +- tests/php/i18n/i18nTestManifest.php | 2 +- tests/php/i18n/i18nTextCollectorTest.php | 4 +- 81 files changed, 798 insertions(+), 465 deletions(-) diff --git a/_config.php b/_config.php index 6cc0e44db..27dcd372a 100644 --- a/_config.php +++ b/_config.php @@ -1,6 +1,5 @@ register('embed', [EmbedShortcodeProvider::class, 'handle_shortcode']); - -// Set to 5.0.0 to show APIs marked for removal at that version -Deprecation::notification_version('4.0.0'); diff --git a/_config/i18n.yml b/_config/i18n.yml index a219828b8..e900f46f5 100644 --- a/_config/i18n.yml +++ b/_config/i18n.yml @@ -2,14 +2,14 @@ Name: basei18n Before: '#defaulti18n' --- -SilverStripe\i18n\Data\Sources: +SilverStripe\Core\Manifest\ModuleManifest: module_priority: - silverstripe\admin - silverstripe\framework --- Name: defaulti18n --- -SilverStripe\i18n\Data\Sources: +SilverStripe\Core\Manifest\ModuleManifest: module_priority: - other_modules --- diff --git a/src/Control/CookieJar.php b/src/Control/CookieJar.php index 73467526c..6c3b0a26c 100644 --- a/src/Control/CookieJar.php +++ b/src/Control/CookieJar.php @@ -200,12 +200,9 @@ class CookieJar implements Cookie_Backend /** * Get the correct samesite value - Session cookies use a different configuration variable. - * - * @deprecated 4.12.0 The relevant methods will include a `$sameSite` parameter instead. */ private function getSameSite(string $name): string { - Deprecation::notice('4.12.0', 'The relevant methods will include a `$sameSite` parameter instead.'); if ($name === session_name()) { return Session::config()->get('cookie_samesite'); } diff --git a/src/Control/Director.php b/src/Control/Director.php index 91023b7a7..880561253 100644 --- a/src/Control/Director.php +++ b/src/Control/Director.php @@ -228,7 +228,7 @@ class Director implements TemplateGlobalProvider ? $cookies : Injector::inst()->createWithArgs(Cookie_Backend::class, [$cookies ?: []]); $newVars['_COOKIE'] = $cookieJar->getAll(false); - Cookie::config()->update('report_errors', false); + Cookie::config()->set('report_errors', false); Injector::inst()->registerService($cookieJar, Cookie_Backend::class); // Backup requirements diff --git a/src/Control/Email/Email.php b/src/Control/Email/Email.php index 0cb60a8ac..766bf8f7c 100644 --- a/src/Control/Email/Email.php +++ b/src/Control/Email/Email.php @@ -268,7 +268,9 @@ class Email extends ViewableData $message = new Swift_Message(null, null, 'text/html', 'utf-8'); // Set priority to fix PHP 8.1 SimpleMessage::getPriority() sscanf() null parameter $message->setPriority(Swift_Mime_SimpleMessage::PRIORITY_NORMAL); - $this->setSwiftMessage($message); + Deprecation::withNoReplacement(function () use ($message) { + $this->setSwiftMessage($message); + }); } return $this->swiftMessage; @@ -328,7 +330,9 @@ class Email extends ViewableData */ public function getFrom() { - return $this->getSwiftMessage()->getFrom(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getFrom(); + }); } /** @@ -351,8 +355,9 @@ class Email extends ViewableData public function setFrom($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setFrom($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->setFrom($address, $name); + }); return $this; } @@ -364,8 +369,9 @@ class Email extends ViewableData public function addFrom($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->addFrom($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->addFrom($address, $name); + }); return $this; } @@ -374,7 +380,9 @@ class Email extends ViewableData */ public function getSender() { - return $this->getSwiftMessage()->getSender(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getSender(); + }); } /** @@ -385,8 +393,9 @@ class Email extends ViewableData public function setSender($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setSender($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->setSender($address, $name); + }); return $this; } @@ -395,7 +404,9 @@ class Email extends ViewableData */ public function getReturnPath() { - return $this->getSwiftMessage()->getReturnPath(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getReturnPath(); + }); } /** @@ -407,7 +418,9 @@ class Email extends ViewableData public function setReturnPath($address) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setReturnPath($address); + Deprecation::withNoReplacement(function () use ($address) { + $this->getSwiftMessage()->setReturnPath($address); + }); return $this; } @@ -416,7 +429,9 @@ class Email extends ViewableData */ public function getTo() { - return $this->getSwiftMessage()->getTo(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getTo(); + }); } /** @@ -432,8 +447,9 @@ class Email extends ViewableData public function setTo($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setTo($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->setTo($address, $name); + }); return $this; } @@ -445,8 +461,9 @@ class Email extends ViewableData public function addTo($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->addTo($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->addTo($address, $name); + }); return $this; } @@ -455,7 +472,9 @@ class Email extends ViewableData */ public function getCC() { - return $this->getSwiftMessage()->getCc(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getCc(); + }); } /** @@ -466,8 +485,9 @@ class Email extends ViewableData public function setCC($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setCc($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->setCc($address, $name); + }); return $this; } @@ -479,8 +499,9 @@ class Email extends ViewableData public function addCC($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->addCc($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->addCc($address, $name); + }); return $this; } @@ -489,7 +510,9 @@ class Email extends ViewableData */ public function getBCC() { - return $this->getSwiftMessage()->getBcc(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getBcc(); + }); } /** @@ -500,8 +523,9 @@ class Email extends ViewableData public function setBCC($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setBcc($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->setBcc($address, $name); + }); return $this; } @@ -513,8 +537,9 @@ class Email extends ViewableData public function addBCC($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->addBcc($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->addBcc($address, $name); + }); return $this; } @@ -523,7 +548,9 @@ class Email extends ViewableData */ public function getReplyTo() { - return $this->getSwiftMessage()->getReplyTo(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getReplyTo(); + }); } /** @@ -534,8 +561,9 @@ class Email extends ViewableData public function setReplyTo($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->setReplyTo($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->setReplyTo($address, $name); + }); return $this; } @@ -547,8 +575,9 @@ class Email extends ViewableData public function addReplyTo($address, $name = null) { $address = $this->sanitiseAddress($address); - $this->getSwiftMessage()->addReplyTo($address, $name); - + Deprecation::withNoReplacement(function () use ($address, $name) { + $this->getSwiftMessage()->addReplyTo($address, $name); + }); return $this; } @@ -557,7 +586,9 @@ class Email extends ViewableData */ public function getSubject() { - return $this->getSwiftMessage()->getSubject(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getSubject(); + }); } /** @@ -566,8 +597,9 @@ class Email extends ViewableData */ public function setSubject($subject) { - $this->getSwiftMessage()->setSubject($subject); - + Deprecation::withNoReplacement(function () use ($subject) { + $this->getSwiftMessage()->setSubject($subject); + }); return $this; } @@ -576,7 +608,9 @@ class Email extends ViewableData */ public function getPriority() { - return $this->getSwiftMessage()->getPriority(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getPriority(); + }); } /** @@ -585,8 +619,9 @@ class Email extends ViewableData */ public function setPriority($priority) { - $this->getSwiftMessage()->setPriority($priority); - + Deprecation::withNoReplacement(function () use ($priority) { + $this->getSwiftMessage()->setPriority($priority); + }); return $this; } @@ -622,8 +657,9 @@ class Email extends ViewableData if ($mime) { $attachment->setContentType($mime); } - $this->getSwiftMessage()->attach($attachment); - + Deprecation::withNoReplacement(function () use ($attachment) { + $this->getSwiftMessage()->attach($attachment); + }); return $this; } @@ -642,8 +678,9 @@ class Email extends ViewableData public function setData($data) { $this->data = $data; - $this->invalidateBody(); - + Deprecation::withNoReplacement(function () { + $this->invalidateBody(); + }); return $this; } @@ -661,9 +698,9 @@ class Email extends ViewableData } else { $this->data->$name = $value; } - - $this->invalidateBody(); - + Deprecation::withNoReplacement(function () { + $this->invalidateBody(); + }); return $this; } @@ -680,9 +717,9 @@ class Email extends ViewableData } else { $this->data->$name = null; } - - $this->invalidateBody(); - + Deprecation::withNoReplacement(function () { + $this->invalidateBody(); + }); return $this; } @@ -691,7 +728,9 @@ class Email extends ViewableData */ public function getBody() { - return $this->getSwiftMessage()->getBody(); + return Deprecation::withNoReplacement(function () { + return $this->getSwiftMessage()->getBody(); + }); } /** @@ -700,15 +739,16 @@ class Email extends ViewableData */ public function setBody($body) { - $plainPart = $this->findPlainPart(); - if ($plainPart) { - $this->getSwiftMessage()->detach($plainPart); - } - unset($plainPart); - - $body = HTTP::absoluteURLs($body); - $this->getSwiftMessage()->setBody($body); - + Deprecation::withNoReplacement(function () use ($body) { + $plainPart = $this->findPlainPart(); + if ($plainPart) { + $this->getSwiftMessage()->detach($plainPart); + } + unset($plainPart); + + $body = HTTP::absoluteURLs($body); + $this->getSwiftMessage()->setBody($body); + }); return $this; } @@ -746,10 +786,11 @@ class Email extends ViewableData public function debug() { Deprecation::notice('4.12.0', 'Will be removed without equivalent functionality to replace it'); - $this->render(); - - $class = static::class; - return "

Email template {$class}:

\n" . '
' . $this->getSwiftMessage()->toString() . '
'; + return Deprecation::withNoReplacement(function () { + $this->render(); + $class = static::class; + return "

Email template {$class}:

\n" . '
' . $this->getSwiftMessage()->toString() . '
'; + }); } /** @@ -854,13 +895,15 @@ class Email extends ViewableData */ public function send() { - if (!$this->getBody()) { - $this->render(); - } - if (!$this->hasPlainPart()) { - $this->generatePlainPartFromBody(); - } - return Injector::inst()->get(Mailer::class)->send($this); + return Deprecation::withNoReplacement(function () { + if (!$this->getBody()) { + $this->render(); + } + if (!$this->hasPlainPart()) { + $this->generatePlainPartFromBody(); + } + return Injector::inst()->get(Mailer::class)->send($this); + }); } /** @@ -868,10 +911,12 @@ class Email extends ViewableData */ public function sendPlain() { - if (!$this->hasPlainPart()) { - $this->render(true); - } - return Injector::inst()->get(Mailer::class)->send($this); + return Deprecation::withNoReplacement(function () { + if (!$this->hasPlainPart()) { + $this->render(true); + } + return Injector::inst()->get(Mailer::class)->send($this); + }); } /** @@ -884,68 +929,71 @@ class Email extends ViewableData public function render($plainOnly = false) { Deprecation::notice('4.12.0', 'Will be removed without equivalent functionality to replace it'); - - if ($existingPlainPart = $this->findPlainPart()) { - $this->getSwiftMessage()->detach($existingPlainPart); - } - unset($existingPlainPart); - - // Respect explicitly set body - $htmlPart = $plainOnly ? null : $this->getBody(); - $plainPart = $plainOnly ? $this->getBody() : null; - - // Ensure we can at least render something - $htmlTemplate = $this->getHTMLTemplate(); - $plainTemplate = $this->getPlainTemplate(); - if (!$htmlTemplate && !$plainTemplate && !$plainPart && !$htmlPart) { - return $this; - } - - // Do not interfere with emails styles - Requirements::clear(); - - // Render plain part - if ($plainTemplate && !$plainPart) { - $plainPart = $this->renderWith($plainTemplate, $this->getData())->Plain(); - } - - // Render HTML part, either if sending html email, or a plain part is lacking - if (!$htmlPart && $htmlTemplate && (!$plainOnly || empty($plainPart))) { - $htmlPart = $this->renderWith($htmlTemplate, $this->getData()); - } - - // Plain part fails over to generated from html - if (!$plainPart && $htmlPart) { - /** @var DBHTMLText $htmlPartObject */ - $htmlPartObject = DBField::create_field('HTMLFragment', $htmlPart); - $plainPart = $htmlPartObject->Plain(); - } - - // Rendering is finished - Requirements::restore(); - - // Fail if no email to send - if (!$plainPart && !$htmlPart) { - return $this; - } - - // Build HTML / Plain components - if ($htmlPart && !$plainOnly) { - $this->setBody($htmlPart); - $this->getSwiftMessage()->setContentType('text/html'); - $this->getSwiftMessage()->setCharset('utf-8'); - if ($plainPart) { - $this->getSwiftMessage()->addPart($plainPart, 'text/plain', 'utf-8'); + return Deprecation::withNoReplacement(function () use ($plainOnly) { + $existingPlainPart = Deprecation::withNoReplacement(function () { + return $this->findPlainPart(); + }); + if ($existingPlainPart) { + $this->getSwiftMessage()->detach($existingPlainPart); } - } else { - if ($plainPart) { - $this->setBody($plainPart); - } - $this->getSwiftMessage()->setContentType('text/plain'); - $this->getSwiftMessage()->setCharset('utf-8'); - } + unset($existingPlainPart); - return $this; + // Respect explicitly set body + $htmlPart = $plainOnly ? null : $this->getBody(); + $plainPart = $plainOnly ? $this->getBody() : null; + + // Ensure we can at least render something + $htmlTemplate = $this->getHTMLTemplate(); + $plainTemplate = $this->getPlainTemplate(); + if (!$htmlTemplate && !$plainTemplate && !$plainPart && !$htmlPart) { + return $this; + } + + // Do not interfere with emails styles + Requirements::clear(); + + // Render plain part + if ($plainTemplate && !$plainPart) { + $plainPart = $this->renderWith($plainTemplate, $this->getData())->Plain(); + } + + // Render HTML part, either if sending html email, or a plain part is lacking + if (!$htmlPart && $htmlTemplate && (!$plainOnly || empty($plainPart))) { + $htmlPart = $this->renderWith($htmlTemplate, $this->getData()); + } + + // Plain part fails over to generated from html + if (!$plainPart && $htmlPart) { + /** @var DBHTMLText $htmlPartObject */ + $htmlPartObject = DBField::create_field('HTMLFragment', $htmlPart); + $plainPart = $htmlPartObject->Plain(); + } + + // Rendering is finished + Requirements::restore(); + + // Fail if no email to send + if (!$plainPart && !$htmlPart) { + return $this; + } + + // Build HTML / Plain components + if ($htmlPart && !$plainOnly) { + $this->setBody($htmlPart); + $this->getSwiftMessage()->setContentType('text/html'); + $this->getSwiftMessage()->setCharset('utf-8'); + if ($plainPart) { + $this->getSwiftMessage()->addPart($plainPart, 'text/plain', 'utf-8'); + } + } else { + if ($plainPart) { + $this->setBody($plainPart); + } + $this->getSwiftMessage()->setContentType('text/plain'); + $this->getSwiftMessage()->setCharset('utf-8'); + } + return $this; + }); } /** @@ -956,12 +1004,14 @@ class Email extends ViewableData public function findPlainPart() { Deprecation::notice('4.12.0', 'Will be removed without equivalent functionality to replace it'); - foreach ($this->getSwiftMessage()->getChildren() as $child) { - if ($child instanceof Swift_MimePart && $child->getContentType() == 'text/plain') { - return $child; + return Deprecation::withNoReplacement(function () { + foreach ($this->getSwiftMessage()->getChildren() as $child) { + if ($child instanceof Swift_MimePart && $child->getContentType() == 'text/plain') { + return $child; + } } - } - return false; + return false; + }); } /** @@ -972,10 +1022,12 @@ class Email extends ViewableData public function hasPlainPart() { Deprecation::notice('4.12.0', 'Will be removed without equivalent functionality to replace it'); - if ($this->getSwiftMessage()->getContentType() === 'text/plain') { - return true; - } - return (bool) $this->findPlainPart(); + return Deprecation::withNoReplacement(function () { + if ($this->getSwiftMessage()->getContentType() === 'text/plain') { + return true; + } + return (bool) $this->findPlainPart(); + }); } /** @@ -988,18 +1040,19 @@ class Email extends ViewableData public function generatePlainPartFromBody() { Deprecation::notice('4.12.0', 'Will be removed without equivalent functionality to replace it'); - $plainPart = $this->findPlainPart(); - if ($plainPart) { - $this->getSwiftMessage()->detach($plainPart); - } - unset($plainPart); + return Deprecation::withNoReplacement(function () { + $plainPart = $this->findPlainPart(); + if ($plainPart) { + $this->getSwiftMessage()->detach($plainPart); + } + unset($plainPart); - $this->getSwiftMessage()->addPart( - Convert::xml2raw($this->getBody()), - 'text/plain', - 'utf-8' - ); - - return $this; + $this->getSwiftMessage()->addPart( + Convert::xml2raw($this->getBody()), + 'text/plain', + 'utf-8' + ); + return $this; + }); } } diff --git a/src/Control/Email/SwiftMailer.php b/src/Control/Email/SwiftMailer.php index 33371acdc..3afca409b 100644 --- a/src/Control/Email/SwiftMailer.php +++ b/src/Control/Email/SwiftMailer.php @@ -40,7 +40,9 @@ class SwiftMailer implements Mailer */ public function __construct() { - Deprecation::notice('4.12.0', 'Will be replaced with symfony/mailer', Deprecation::SCOPE_CLASS); + Deprecation::withNoReplacement(function () { + Deprecation::notice('4.12.0', 'Will be replaced with symfony/mailer', Deprecation::SCOPE_CLASS); + }); } public function send($message) diff --git a/src/Control/Email/SwiftPlugin.php b/src/Control/Email/SwiftPlugin.php index 277c4f18b..5e53e8a3e 100644 --- a/src/Control/Email/SwiftPlugin.php +++ b/src/Control/Email/SwiftPlugin.php @@ -11,7 +11,9 @@ class SwiftPlugin implements \Swift_Events_SendListener { public function __construct() { - Deprecation::notice('4.12.0', 'Will be replaced with symfony/mailer', Deprecation::SCOPE_CLASS); + Deprecation::withNoReplacement(function () { + Deprecation::notice('4.12.0', 'Will be replaced with symfony/mailer', Deprecation::SCOPE_CLASS); + }); } /** diff --git a/src/Control/HTTP.php b/src/Control/HTTP.php index 84fce924d..cce77aec4 100644 --- a/src/Control/HTTP.php +++ b/src/Control/HTTP.php @@ -126,7 +126,7 @@ class HTTP if (preg_match('/^\w+:/', $url ?? '')) { return $url; } - return Director::absoluteURL($url, true); + return Director::absoluteURL($url); }); } @@ -474,6 +474,8 @@ class HTTP * Ensure that all deprecated HTTP cache settings are respected * * @deprecated 4.2.0 Use HTTPCacheControlMiddleware instead + * Simply delete this method in CMS 5 and the calls to it from HTTPCacheControlMiddleware + * * @throws \LogicException * @param HTTPRequest $request * @param HTTPResponse $response @@ -491,32 +493,32 @@ class HTTP // if http caching is disabled by config, disable it - used on dev environments due to frequently changing // templates and other data. will be overridden by forced publicCache(true) or privateCache(true) calls - if ($config->get('disable_http_cache')) { - Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultState/.defaultForcingLevel instead'); - $cacheControlMiddleware->disableCache(); - } + Deprecation::withNoReplacement(function () use ($config, $cacheControlMiddleware) { + if ($config->get('disable_http_cache')) { + $cacheControlMiddleware->disableCache(); + } + }); // if no caching ajax requests, disable ajax if is ajax request - if (!$config->get('cache_ajax_requests') && Director::is_ajax()) { - Deprecation::notice( - '5.0', - 'HTTP.cache_ajax_requests config is deprecated. Use HTTPCacheControlMiddleware::disableCache() instead' - ); - $cacheControlMiddleware->disableCache(); - } + Deprecation::withNoReplacement(function () use ($config, $cacheControlMiddleware) { + if (!$config->get('cache_ajax_requests') && Director::is_ajax()) { + $cacheControlMiddleware->disableCache(); + } + }); // Pass vary to middleware - $configVary = $config->get('vary'); + $configVary = Deprecation::withNoReplacement(function () use ($config) { + return $config->get('vary'); + }); if ($configVary) { - Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultVary instead'); $cacheControlMiddleware->addVary($configVary); } // Pass cache_control to middleware - $configCacheControl = $config->get('cache_control'); + $configCacheControl = Deprecation::withNoReplacement(function () use ($config) { + return $config->get('cache_control'); + }); if ($configCacheControl) { - Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware API instead'); - $supportedDirectives = ['max-age', 'no-cache', 'no-store', 'must-revalidate']; if ($foundUnsupported = array_diff(array_keys($configCacheControl ?? []), $supportedDirectives)) { throw new \LogicException( diff --git a/src/Control/Middleware/FlushMiddleware.php b/src/Control/Middleware/FlushMiddleware.php index e3bd61fbe..98b49423b 100644 --- a/src/Control/Middleware/FlushMiddleware.php +++ b/src/Control/Middleware/FlushMiddleware.php @@ -2,10 +2,12 @@ namespace SilverStripe\Control\Middleware; -use SilverStripe\Control\Director; use SilverStripe\Control\HTTPRequest; +use SilverStripe\Core\BaseKernel; use SilverStripe\Core\ClassInfo; use SilverStripe\Core\Flushable; +use SilverStripe\Core\Injector\Injector; +use SilverStripe\Core\Kernel; /** * Triggers a call to flush() on all implementors of Flushable. @@ -14,7 +16,9 @@ class FlushMiddleware implements HTTPMiddleware { public function process(HTTPRequest $request, callable $delegate) { - if (Director::isManifestFlushed()) { + /** @var BaseKernel $kernel */ + $kernel = Injector::inst()->get(Kernel::class); + if ((method_exists($kernel, 'isFlushed') && $kernel->isFlushed())) { // Disable cache when flushing HTTPCacheControlMiddleware::singleton()->disableCache(true); diff --git a/src/Control/Middleware/HTTPCacheControlMiddleware.php b/src/Control/Middleware/HTTPCacheControlMiddleware.php index 4f7aa49c6..1a64b4b54 100644 --- a/src/Control/Middleware/HTTPCacheControlMiddleware.php +++ b/src/Control/Middleware/HTTPCacheControlMiddleware.php @@ -12,6 +12,7 @@ use SilverStripe\Core\Injector\Injectable; use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Resettable; use SilverStripe\ORM\FieldType\DBDatetime; +use SilverStripe\Dev\Deprecation; class HTTPCacheControlMiddleware implements HTTPMiddleware, Resettable { @@ -51,7 +52,9 @@ class HTTPCacheControlMiddleware implements HTTPMiddleware, Resettable $this->augmentState($request, $response); // Update state based on deprecated HTTP settings - HTTP::augmentState($request, $response); + Deprecation::withNoReplacement(function () use ($request, $response) { + HTTP::augmentState($request, $response); + }); // Add all headers to this response object $this->applyToResponse($response); diff --git a/src/Control/Middleware/URLSpecialsMiddleware/FlushScheduler.php b/src/Control/Middleware/URLSpecialsMiddleware/FlushScheduler.php index 6f189286e..f2b62d0c2 100644 --- a/src/Control/Middleware/URLSpecialsMiddleware/FlushScheduler.php +++ b/src/Control/Middleware/URLSpecialsMiddleware/FlushScheduler.php @@ -2,10 +2,10 @@ namespace SilverStripe\Control\Middleware\URLSpecialsMiddleware; +use SilverStripe\Core\BaseKernel; use SilverStripe\Core\Kernel; use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Startup\ScheduledFlushDiscoverer; -use SilverStripe\Control\Director; use SilverStripe\Control\HTTPRequest; /** @@ -30,11 +30,12 @@ trait FlushScheduler { $flush = array_key_exists('flush', $request->getVars() ?? []) || ($request->getURL() === 'dev/build'); - if (!$flush || Director::isManifestFlushed()) { + /** @var BaseKernel $kernel */ + $kernel = Injector::inst()->get(Kernel::class); + if (!$flush || (method_exists($kernel, 'isFlushed') && $kernel->isFlushed())) { return false; } - $kernel = Injector::inst()->get(Kernel::class); ScheduledFlushDiscoverer::scheduleFlush($kernel); return true; diff --git a/src/Control/RSS/RSSFeed.php b/src/Control/RSS/RSSFeed.php index fd35b617e..5ab5eae9b 100644 --- a/src/Control/RSS/RSSFeed.php +++ b/src/Control/RSS/RSSFeed.php @@ -222,7 +222,7 @@ class RSSFeed extends ViewableData public function outputToBrowser() { $prevState = SSViewer::config()->uninherited('source_file_comments'); - SSViewer::config()->update('source_file_comments', false); + SSViewer::config()->set('source_file_comments', false); $response = Controller::curr()->getResponse(); @@ -236,7 +236,7 @@ class RSSFeed extends ViewableData $response->addHeader("Content-Type", "application/rss+xml; charset=utf-8"); - SSViewer::config()->update('source_file_comments', $prevState); + SSViewer::config()->set('source_file_comments', $prevState); return $this->renderWith($this->getTemplates()); } diff --git a/src/Control/RequestProcessor.php b/src/Control/RequestProcessor.php index 0661fcdda..f8ef07623 100644 --- a/src/Control/RequestProcessor.php +++ b/src/Control/RequestProcessor.php @@ -29,7 +29,9 @@ class RequestProcessor implements HTTPMiddleware */ public function __construct($filters = []) { - Deprecation::notice('4.0.1', 'Use HTTPMiddleware directly instead.', Deprecation::SCOPE_CLASS); + Deprecation::withNoReplacement(function () { + Deprecation::notice('4.0.1', 'Use HTTPMiddleware directly instead.', Deprecation::SCOPE_CLASS); + }); $this->filters = $filters; } diff --git a/src/Control/Session.php b/src/Control/Session.php index 01623d87f..5d49b92b3 100644 --- a/src/Control/Session.php +++ b/src/Control/Session.php @@ -586,13 +586,11 @@ class Session * Recursively apply the changes represented in $data to $dest. * Used to update $_SESSION * - * @deprecated 4.1.0 Use recursivelyApplyChanges() instead * @param array $data * @param array $dest */ protected function recursivelyApply($data, &$dest) { - Deprecation::notice('4.1.0', 'Use recursivelyApplyChanges() instead'); foreach ($data as $k => $v) { if (is_array($v)) { if (!isset($dest[$k]) || !is_array($dest[$k])) { diff --git a/src/Control/SimpleResourceURLGenerator.php b/src/Control/SimpleResourceURLGenerator.php index e6ea62175..40bd6189d 100644 --- a/src/Control/SimpleResourceURLGenerator.php +++ b/src/Control/SimpleResourceURLGenerator.php @@ -82,7 +82,10 @@ class SimpleResourceURLGenerator implements ResourceURLGenerator // Determine lookup mechanism based on existence of public/ folder. // From 5.0 onwards only resolvePublicResource() will be used. if (!Director::publicDir()) { - list($exists, $absolutePath, $relativePath) = $this->resolveUnsecuredResource($relativePath); + $ret = Deprecation::withNoReplacement(function () use ($relativePath) { + return $this->resolveUnsecuredResource($relativePath); + }); + list($exists, $absolutePath, $relativePath) = $ret; } else { list($exists, $absolutePath, $relativePath) = $this->resolvePublicResource($relativePath); } diff --git a/src/Core/BaseKernel.php b/src/Core/BaseKernel.php index ee3370d54..3706f94d6 100644 --- a/src/Core/BaseKernel.php +++ b/src/Core/BaseKernel.php @@ -180,18 +180,24 @@ abstract class BaseKernel implements Kernel protected function bootManifests($flush) { // Setup autoloader - $this->getClassLoader()->init( - $this->getIncludeTests(), - $flush, - $this->getIgnoredCIConfigs() - ); + $ignoredCIConfigs = Deprecation::withNoReplacement(function () { + return $this->getIgnoredCIConfigs(); + }); - // Find modules - $this->getModuleLoader()->init( - $this->getIncludeTests(), - $flush, - $this->getIgnoredCIConfigs() - ); + Deprecation::withNoReplacement(function () use ($flush, $ignoredCIConfigs) { + $this->getClassLoader()->init( + $this->getIncludeTests(), + $flush, + $ignoredCIConfigs + ); + + // Find modules + $this->getModuleLoader()->init( + $this->getIncludeTests(), + $flush, + $ignoredCIConfigs + ); + }); // Flush config if ($flush) { @@ -209,11 +215,13 @@ abstract class BaseKernel implements Kernel $defaultSet->setProject( ModuleManifest::config()->get('project') ); - $defaultSet->init( - $this->getIncludeTests(), - $flush, - $this->getIgnoredCIConfigs() - ); + Deprecation::withNoReplacement(function () use ($defaultSet, $flush, $ignoredCIConfigs) { + $defaultSet->init( + $this->getIncludeTests(), + $flush, + $ignoredCIConfigs + ); + }); } } @@ -259,12 +267,9 @@ abstract class BaseKernel implements Kernel * Get the environment type * * @return string - * - * @deprecated 4.12.0 Use Director::get_environment_type() instead */ public function getEnvironment() { - Deprecation::notice('4.12.0', 'Use Director::get_environment_type() instead'); // Check set if ($this->enviroment) { return $this->enviroment; @@ -288,12 +293,9 @@ abstract class BaseKernel implements Kernel * Check or update any temporary environment specified in the session. * * @return null|string - * - * @deprecated 4.12.0 Use Director::get_session_environment_type() instead */ protected function sessionEnvironment() { - Deprecation::notice('4.12.0', 'Use Director::get_session_environment_type() instead'); if (!$this->booted) { // session is not initialyzed yet, neither is manifest return null; diff --git a/src/Core/Convert.php b/src/Core/Convert.php index 0fb4293c1..2021e8446 100644 --- a/src/Core/Convert.php +++ b/src/Core/Convert.php @@ -275,7 +275,7 @@ class Convert /** * Convert a JSON string into an array. * - * @deprecated 4.4.0 Use json_decode() instead + * @deprecated 4.4.0 Use json_decode($val, true) instead * @param string $val JSON string to convert * @return array|boolean */ diff --git a/src/Core/Manifest/ClassLoader.php b/src/Core/Manifest/ClassLoader.php index 238fa647f..ac562dcd2 100644 --- a/src/Core/Manifest/ClassLoader.php +++ b/src/Core/Manifest/ClassLoader.php @@ -131,7 +131,9 @@ class ClassLoader foreach ($this->manifests as $manifest) { /** @var ClassManifest $instance */ $instance = $manifest['instance']; - $instance->init($includeTests, $forceRegen, $ignoredCIConfigs); + Deprecation::withNoReplacement(function () use ($instance, $includeTests, $forceRegen, $ignoredCIConfigs) { + $instance->init($includeTests, $forceRegen, $ignoredCIConfigs); + }); } $this->registerAutoloader(); diff --git a/src/Core/Manifest/ClassManifest.php b/src/Core/Manifest/ClassManifest.php index 7ebdc0dfe..7bd407304 100644 --- a/src/Core/Manifest/ClassManifest.php +++ b/src/Core/Manifest/ClassManifest.php @@ -297,7 +297,9 @@ class ClassManifest } // Build - $this->regenerate($includeTests, $ignoredCIConfigs); + Deprecation::withNoReplacement(function () use ($includeTests, $ignoredCIConfigs) { + $this->regenerate($includeTests, $ignoredCIConfigs); + }); } /** diff --git a/src/Core/Manifest/ManifestFileFinder.php b/src/Core/Manifest/ManifestFileFinder.php index 75763e4ed..9011a51e8 100644 --- a/src/Core/Manifest/ManifestFileFinder.php +++ b/src/Core/Manifest/ManifestFileFinder.php @@ -4,6 +4,7 @@ namespace SilverStripe\Core\Manifest; use RuntimeException; use SilverStripe\Assets\FileFinder; +use SilverStripe\Dev\Deprecation; /** * An extension to the default file finder with some extra filters to facilitate @@ -285,7 +286,9 @@ class ManifestFileFinder extends FileFinder if ($this->isDirectoryModule($newBasename, $newPathname, $newDepth)) { // We've reached the root of the module folder, we can read the PHP CI config now $module = new Module($newPathname, $this->upLevels($newPathname, $newDepth)); - $config = $module->getCIConfig(); + $config = Deprecation::withNoReplacement(function () use ($module) { + return $module->getCIConfig(); + }); if (empty($config['PHP'])) { // This should never happen diff --git a/src/Dev/Deprecation.php b/src/Dev/Deprecation.php index 5bd17cda6..3ca6a0d3b 100644 --- a/src/Dev/Deprecation.php +++ b/src/Dev/Deprecation.php @@ -5,6 +5,7 @@ namespace SilverStripe\Dev; use BadMethodCallException; use SilverStripe\Control\Director; use SilverStripe\Core\Environment; +use SilverStripe\Core\Injector\InjectionCreator; use SilverStripe\Core\Injector\InjectorLoader; use SilverStripe\Core\Manifest\Module; @@ -21,19 +22,7 @@ use SilverStripe\Core\Manifest\Module; * * This class abstracts the above pattern and adds a way to do that. * - * Each call to notice passes a version that the notice will be valid from. Additionally this class has a notion of the - * version it should use when deciding whether to raise the notice. If that version is equal to or greater than the - * notices version (and SilverStripe is in dev mode) a deprecation message will be raised. - * - * Normally the checking version will be the release version of SilverStripe, but a developer can choose to set it to a - * future version, to see how their code will behave in future versions. - * - * Modules can also set the version for calls they make - either setting it to a future version in order to ensure - * forwards compatibility or setting it backwards if a module has not yet removed references to deprecated methods. - * - * When set per-module, only direct calls to deprecated methods from those modules are considered - if the module - * calls a non-module method which then calls a deprecated method, that call will use the global check version, not - * the module specific check version. + * Each call to notice passes a version that the notice will be valid from. */ class Deprecation { @@ -58,10 +47,22 @@ class Deprecation * must be available before this to avoid infinite loops. * * @var boolean|null - * @deprecated 4.12.0 Use $is_enabled instead + * @deprecated 4.12.0 Use $currentlyEnabled instead */ protected static $enabled = null; + /** + * @var array + * @deprecated 4.12.0 Will be removed without equivalent functionality to replace it + */ + protected static $module_version_overrides = []; + + /** + * @var array + * @deprecated 4.12.0 Will be removed without equivalent functionality to replace it + */ + public static $notice_level = E_USER_DEPRECATED; + /** * Must be configured outside of the config API, as deprecation API * must be available before this to avoid infinite loops. @@ -70,48 +71,64 @@ class Deprecation * * @internal - Marked as internal so this and other private static's are not treated as config */ - private static bool $is_enabled = false; - - /** - * @var array - * @deprecated 4.12.0 Will be removed without equivalent functionality to replace it - */ - protected static $module_version_overrides = []; + private static bool $currentlyEnabled = false; /** * @internal */ - private static bool $inside_notice = false; + private static bool $insideNotice = false; /** - * @var array - * @deprecated 4.12.0 Will be removed without equivalent functionality to replace it + * @internal */ - public static $notice_level = E_USER_DEPRECATED; + private static bool $insideWithNoReplacement = false; /** - * Buffer of user_errors to be raised when enabled() is called - * - * This is used when setting deprecated config via yaml, before Deprecation::enable() has been called in _config.php - * Deprecated config set via yaml will only be shown in the browser when using ?flush=1 - * It will not show in CLI when running dev/build flush=1 + * Buffer of user_errors to be raised * * @internal */ - private static array $user_error_message_buffer = []; + private static array $userErrorMessageBuffer = []; - public static function enable(): void + /** + * @internal + */ + private static bool $haveSetShutdownFunction = false; + + /** + * @internal + */ + private static bool $showNoReplacementNotices = false; + + public static function enable(bool $showNoReplacementNotices = false): void { - static::$is_enabled = true; - foreach (self::$user_error_message_buffer as $message) { - user_error($message, E_USER_DEPRECATED); - } - self::$user_error_message_buffer = []; + static::$currentlyEnabled = true; + static::$showNoReplacementNotices = $showNoReplacementNotices; } public static function disable(): void { - static::$is_enabled = false; + static::$currentlyEnabled = false; + } + + /** + * Used to wrap deprecated methods and deprecated config get()/set() that will be removed + * in the next major version with no replacement. This is done to surpress deprecation notices + * by for calls from the vendor dir to deprecated code that projects have no ability to change + * + * @return mixed + */ + public static function withNoReplacement(callable $func) + { + if (self::$insideWithNoReplacement) { + return $func(); + } + self::$insideWithNoReplacement = true; + try { + return $func(); + } finally { + self::$insideWithNoReplacement = false; + } } /** @@ -159,12 +176,19 @@ class Deprecation if (!$level) { $level = 1; } - $called = $backtrace ? $backtrace[$level] : []; - - if (isset($called['class'])) { - return $called['class'] . $called['type'] . $called['function']; + $newLevel = $level; + // handle call_user_func + if ($level === 4 && strpos($backtrace[2]['function'] ?? '', 'call_user_func') !== false) { + $newLevel = 5; + } elseif (strpos($backtrace[$level]['function'] ?? '', 'call_user_func') !== false) { + $newLevel = $level + 1; } - return $called['function'] ?? ''; + // handle InjectionCreator + if ($level == 4 && ($backtrace[$newLevel]['class'] ?? '') === InjectionCreator::class) { + $newLevel = $newLevel + 4; + } + $called = $backtrace[$newLevel] ?? []; + return ($called['class'] ?? '') . ($called['type'] ?? '') . ($called['function'] ?? ''); } /** @@ -179,12 +203,12 @@ class Deprecation // noop } - private static function get_is_enabled(): bool + public static function isEnabled(): bool { if (!Director::isDev()) { return false; } - return static::$is_enabled || Environment::getEnv('SS_DEPRECATION_ENABLED'); + return static::$currentlyEnabled || Environment::getEnv('SS_DEPRECATION_ENABLED'); } /** @@ -199,6 +223,24 @@ class Deprecation // noop } + public static function outputNotices(): void + { + if (!self::isEnabled()) { + return; + } + // using a while loop with array_shift() to ensure that self::$userErrorMessageBuffer will have + // have values removed from it before calling user_error() + while (count(self::$userErrorMessageBuffer)) { + $arr = array_shift(self::$userErrorMessageBuffer); + $message = $arr['message']; + $calledInsideWithNoReplacement = $arr['calledInsideWithNoReplacement']; + if ($calledInsideWithNoReplacement && !self::$showNoReplacementNotices) { + continue; + } + user_error($message, E_USER_DEPRECATED); + } + } + /** * Raise a notice indicating the method is deprecated if the version passed as the second argument is greater * than or equal to the check version set via ::notification_version @@ -209,22 +251,23 @@ class Deprecation */ public static function notice($atVersion, $string = '', $scope = Deprecation::SCOPE_METHOD) { - if (static::$inside_notice) { + if (static::$insideNotice) { return; } - static::$inside_notice = true; + static::$insideNotice = true; // try block needs to wrap all code in case anything inside the try block // calls something else that calls Deprecation::notice() try { if ($scope === self::SCOPE_CONFIG) { - if (self::get_is_enabled()) { - user_error($string, E_USER_DEPRECATED); - } else { - self::$user_error_message_buffer[] = $string; - } + // Deprecated config set via yaml will only be shown in the browser when using ?flush=1 + // It will not show in CLI when running dev/build flush=1 + self::$userErrorMessageBuffer[] = [ + 'message' => $string, + 'calledInsideWithNoReplacement' => self::$insideWithNoReplacement + ]; } else { - if (!self::get_is_enabled()) { - // Do not add to self::$user_error_message_buffer, as the backtrace is too expensive + if (!self::isEnabled()) { + // Do not add to self::$userErrorMessageBuffer, as the backtrace is too expensive return; } @@ -234,7 +277,7 @@ class Deprecation // Get the calling scope if ($scope == Deprecation::SCOPE_METHOD) { $backtrace = debug_backtrace(0); - $caller = self::get_called_method_from_trace($backtrace); + $caller = self::get_called_method_from_trace($backtrace, 1); } elseif ($scope == Deprecation::SCOPE_CLASS) { $backtrace = debug_backtrace(0); $caller = isset($backtrace[1]['class']) ? $backtrace[1]['class'] : '(unknown)'; @@ -242,18 +285,30 @@ class Deprecation $caller = false; } - // Then raise the notice if (substr($string, -1) != '.') { $string .= "."; } - $string .= " Called from " . self::get_called_method_from_trace($backtrace, 2) . '.'; + $level = self::$insideWithNoReplacement ? 4 : 2; + $string .= " Called from " . self::get_called_method_from_trace($backtrace, $level) . '.'; if ($caller) { - user_error($caller . ' is deprecated.' . ($string ? ' ' . $string : ''), E_USER_DEPRECATED); - } else { - user_error($string, E_USER_DEPRECATED); + $string = $caller . ' is deprecated.' . ($string ? ' ' . $string : ''); } + self::$userErrorMessageBuffer[] = [ + 'message' => $string, + 'calledInsideWithNoReplacement' => self::$insideWithNoReplacement + ]; + } + if (!self::$haveSetShutdownFunction && self::isEnabled()) { + // Use a shutdown function rather than immediately calling user_error() so that notices + // do not interfere with setting session varibles i.e. headers already sent error + // it also means the deprecation notices appear below all phpunit output in CI + // which is far nicer than having it spliced between phpunit output + register_shutdown_function(function () { + self::outputNotices(); + }); + self::$haveSetShutdownFunction = true; } } catch (BadMethodCallException $e) { if ($e->getMessage() === InjectorLoader::NO_MANIFESTS_AVAILABLE) { @@ -264,7 +319,7 @@ class Deprecation throw $e; } } finally { - static::$inside_notice = false; + static::$insideNotice = false; } } diff --git a/src/Dev/FunctionalTest.php b/src/Dev/FunctionalTest.php index c0329c355..97025c291 100644 --- a/src/Dev/FunctionalTest.php +++ b/src/Dev/FunctionalTest.php @@ -14,6 +14,7 @@ use SilverStripe\Security\BasicAuth; use SilverStripe\Security\SecurityToken; use SilverStripe\View\SSViewer; use SimpleXMLElement; +use SilverStripe\Dev\Deprecation; /* ------------------------------------------------- * @@ -115,7 +116,7 @@ if (class_exists(IsEqualCanonicalizing::class)) { // Disable theme, if necessary if (static::get_disable_themes()) { - SSViewer::config()->update('theme_enabled', false); + SSViewer::config()->set('theme_enabled', false); } // Flush user @@ -123,9 +124,11 @@ if (class_exists(IsEqualCanonicalizing::class)) { // Switch to draft site, if necessary // If you rely on this you should be crafting stage-specific urls instead though. - if (static::get_use_draft_site()) { - $this->useDraftSite(); - } + Deprecation::withNoReplacement(function () { + if (static::get_use_draft_site()) { + $this->useDraftSite(); + } + }); // Unprotect the site, tests are running with the assumption it's off. They will enable it on a case-by-case // basis. @@ -560,7 +563,7 @@ class FunctionalTest extends SapphireTest implements TestOnly // Disable theme, if necessary if (static::get_disable_themes()) { - SSViewer::config()->update('theme_enabled', false); + SSViewer::config()->set('theme_enabled', false); } // Flush user @@ -568,9 +571,11 @@ class FunctionalTest extends SapphireTest implements TestOnly // Switch to draft site, if necessary // If you rely on this you should be crafting stage-specific urls instead though. - if (static::get_use_draft_site()) { - $this->useDraftSite(); - } + Deprecation::withNoReplacement(function () { + if (static::get_use_draft_site()) { + $this->useDraftSite(); + } + }); // Unprotect the site, tests are running with the assumption it's off. They will enable it on a case-by-case // basis. diff --git a/src/Dev/SapphireTest.php b/src/Dev/SapphireTest.php index d7b08afc9..4440a00c0 100644 --- a/src/Dev/SapphireTest.php +++ b/src/Dev/SapphireTest.php @@ -329,7 +329,7 @@ if (class_exists(IsEqualCanonicalizing::class)) { } if (class_exists(Cookie::class)) { - Cookie::config()->update('report_errors', false); + Cookie::config()->set('report_errors', false); } if (class_exists(RootURLController::class)) { @@ -347,16 +347,12 @@ if (class_exists(IsEqualCanonicalizing::class)) { if ($this->shouldSetupDatabaseForCurrentTest($fixtureFiles)) { // Assign fixture factory to deprecated prop in case old tests use it over the getter - /** @var FixtureTestState $fixtureState */ - $fixtureState = static::$state->getStateByName('fixtures'); - $this->fixtureFactory = $fixtureState->getFixtureFactory(static::class); - $this->logInWithPermission('ADMIN'); } // turn off template debugging if (class_exists(SSViewer::class)) { - SSViewer::config()->update('source_file_comments', false); + SSViewer::config()->set('source_file_comments', false); } // Set up the test mailer @@ -1206,7 +1202,7 @@ if (class_exists(IsEqualCanonicalizing::class)) { if (strpos($themeBaseDir ?? '', BASE_PATH) === 0) { $themeBaseDir = substr($themeBaseDir ?? '', strlen(BASE_PATH)); } - SSViewer::config()->update('theme_enabled', true); + SSViewer::config()->set('theme_enabled', true); SSViewer::set_themes([$themeBaseDir . '/themes/' . $theme, '$default']); try { @@ -1649,7 +1645,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly } if (class_exists(Cookie::class)) { - Cookie::config()->update('report_errors', false); + Cookie::config()->set('report_errors', false); } if (class_exists(RootURLController::class)) { @@ -1676,7 +1672,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly // turn off template debugging if (class_exists(SSViewer::class)) { - SSViewer::config()->update('source_file_comments', false); + SSViewer::config()->set('source_file_comments', false); } // Set up the test mailer @@ -2556,7 +2552,7 @@ class SapphireTest extends PHPUnit_Framework_TestCase implements TestOnly if (strpos($themeBaseDir ?? '', BASE_PATH) === 0) { $themeBaseDir = substr($themeBaseDir ?? '', strlen(BASE_PATH)); } - SSViewer::config()->update('theme_enabled', true); + SSViewer::config()->set('theme_enabled', true); SSViewer::set_themes([$themeBaseDir . '/themes/' . $theme, '$default']); try { diff --git a/src/Dev/Tasks/MigrateFileTask.php b/src/Dev/Tasks/MigrateFileTask.php index 14f2c214b..797e58ec3 100644 --- a/src/Dev/Tasks/MigrateFileTask.php +++ b/src/Dev/Tasks/MigrateFileTask.php @@ -21,9 +21,12 @@ use SilverStripe\Dev\BuildTask; use SilverStripe\Assets\Dev\Tasks\SecureAssetsMigrationHelper; use SilverStripe\UserForms\Task\RecoverUploadLocationsHelper; use \Bramus\Monolog\Formatter\ColoredLineFormatter; +use SilverStripe\Dev\Deprecation; /** * Migrates all 3.x file dataobjects to use the new DBFile field. + * + * @deprected 4.12.0 Will be removed without equivalent functionality to replace it */ class MigrateFileTask extends BuildTask { @@ -52,6 +55,12 @@ class MigrateFileTask extends BuildTask /** @var Logger */ private $logger; + public function __construct() + { + Deprecation::notice('4.12.0', 'Will be removed without equivalent functionality to replace it', Deprecation::SCOPE_CLASS); + parent::__construct(); + } + public function run($request) { $this->addLogHandlers(); diff --git a/src/Forms/GridField/GridFieldAddExistingAutocompleter.php b/src/Forms/GridField/GridFieldAddExistingAutocompleter.php index d8efa5903..ff6176d92 100644 --- a/src/Forms/GridField/GridFieldAddExistingAutocompleter.php +++ b/src/Forms/GridField/GridFieldAddExistingAutocompleter.php @@ -262,7 +262,7 @@ class GridFieldAddExistingAutocompleter extends AbstractGridFieldComponent imple $json = []; Config::nest(); - SSViewer::config()->update('source_file_comments', false); + SSViewer::config()->set('source_file_comments', false); $viewer = SSViewer::fromString($this->resultsFormat); foreach ($results as $result) { $title = Convert::html2raw($viewer->process($result)); diff --git a/src/Forms/GridField/GridFieldExportButton.php b/src/Forms/GridField/GridFieldExportButton.php index 9e56b76aa..904219ef2 100644 --- a/src/Forms/GridField/GridFieldExportButton.php +++ b/src/Forms/GridField/GridFieldExportButton.php @@ -8,6 +8,7 @@ use SilverStripe\Control\HTTPResponse; use SilverStripe\Core\Config\Config; use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataObject; +use SilverStripe\ORM\ArrayList; /** * Adds an "Export list" button to the bottom of a {@link GridField}. @@ -221,6 +222,7 @@ class GridFieldExportButton extends AbstractGridFieldComponent implements GridFi ? $gridFieldColumnsComponent->getColumnsHandled($gridField) : []; + /** @var ArrayList|DataList $items */ // Remove limit as the list may be paginated, we want the full list for the export $items = $items->limit(null); // Use Generator in applicable cases to reduce memory consumption diff --git a/src/Forms/GridField/GridFieldFilterHeader.php b/src/Forms/GridField/GridFieldFilterHeader.php index 6cd457e4c..58599b2fe 100755 --- a/src/Forms/GridField/GridFieldFilterHeader.php +++ b/src/Forms/GridField/GridFieldFilterHeader.php @@ -102,7 +102,10 @@ class GridFieldFilterHeader extends AbstractGridFieldComponent implements GridFi callable $updateSearchContext = null, callable $updateSearchForm = null ) { - $this->useLegacyFilterHeader = Config::inst()->get(self::class, 'force_legacy') || $useLegacy; + $forceLegacy = Deprecation::withNoReplacement(function () { + return Config::inst()->get(self::class, 'force_legacy'); + }); + $this->useLegacyFilterHeader = $forceLegacy || $useLegacy; $this->updateSearchContextCallback = $updateSearchContext; $this->updateSearchFormCallback = $updateSearchForm; } @@ -523,7 +526,9 @@ class GridFieldFilterHeader extends AbstractGridFieldComponent implements GridFi } if ($this->useLegacyFilterHeader) { - $fieldsList = $this->getLegacyFilterHeader($gridField); + $fieldsList = Deprecation::withNoReplacement(function () use ($gridField) { + return $this->getLegacyFilterHeader($gridField); + }); $forTemplate->Fields = $fieldsList; $filterTemplates = SSViewer::get_templates_by_class($this, '_Row', __CLASS__); return ['header' => $forTemplate->renderWith($filterTemplates)]; diff --git a/src/Forms/TreeDropdownField.php b/src/Forms/TreeDropdownField.php index 69201889f..9ea404844 100644 --- a/src/Forms/TreeDropdownField.php +++ b/src/Forms/TreeDropdownField.php @@ -2,7 +2,6 @@ namespace SilverStripe\Forms; -use SilverStripe\Dev\Deprecation; use Exception; use InvalidArgumentException; use SilverStripe\Assets\Folder; @@ -622,13 +621,11 @@ class TreeDropdownField extends FormField /** * HTML-encoded label for this node, including css classes and other markup. * - * @deprecated 4.0.1 Use setTitleField() instead * @param string $field * @return $this */ public function setLabelField($field) { - Deprecation::notice('4.0.1', 'Use setTitleField() instead'); $this->labelField = $field; return $this; } @@ -636,12 +633,10 @@ class TreeDropdownField extends FormField /** * HTML-encoded label for this node, including css classes and other markup. * - * @deprecated 4.0.1 Use getTitleField() instead * @return string */ public function getLabelField() { - Deprecation::notice('4.0.1', 'Use getTitleField() instead'); return $this->labelField; } diff --git a/src/Forms/UploadReceiver.php b/src/Forms/UploadReceiver.php index fda6a617d..9d745b0d4 100644 --- a/src/Forms/UploadReceiver.php +++ b/src/Forms/UploadReceiver.php @@ -6,6 +6,7 @@ namespace SilverStripe\Forms; use SilverStripe\Assets\File; use SilverStripe\Assets\Upload; use SilverStripe\Assets\Upload_Validator; +use SilverStripe\Core\Convert; /** * Represents a form field which has an Upload() instance and can upload to a folder @@ -47,8 +48,8 @@ trait UploadReceiver ); // get the lower max size - $maxUpload = File::ini2bytes(ini_get('upload_max_filesize')); - $maxPost = File::ini2bytes(ini_get('post_max_size')); + $maxUpload = Convert::memstring2bytes(ini_get('upload_max_filesize')); + $maxPost = Convert::memstring2bytes(ini_get('post_max_size')); $this->getValidator()->setAllowedMaxFileSize(min($maxUpload, $maxPost)); } diff --git a/src/ORM/ArrayList.php b/src/ORM/ArrayList.php index 74a7cd600..83e448b93 100644 --- a/src/ORM/ArrayList.php +++ b/src/ORM/ArrayList.php @@ -178,18 +178,20 @@ class ArrayList extends ViewableData implements SS_List, Filterable, Sortable, L /** * Get a sub-range of this dataobjectset as an array + * Pass null to "remove the limit" - this is for consistency with DataList::limit(null) which itself will + * call SQLSelect::setLimit(null) * - * @param int $length + * @param int|null $length * @param int $offset * @return static */ public function limit($length, $offset = 0) { // Type checking: designed for consistency with DataList::limit() - if (!is_numeric($length) || !is_numeric($offset)) { + if ((!is_numeric($length) || !is_numeric($offset)) && !is_null($length)) { Deprecation::notice( '4.3', - 'Arguments to ArrayList::limit() should be numeric' + 'Arguments to ArrayList::limit() should be numeric or null' ); } diff --git a/src/ORM/Connect/DBSchemaManager.php b/src/ORM/Connect/DBSchemaManager.php index 698f17cd5..4a8936228 100644 --- a/src/ORM/Connect/DBSchemaManager.php +++ b/src/ORM/Connect/DBSchemaManager.php @@ -2,7 +2,6 @@ namespace SilverStripe\ORM\Connect; -use SilverStripe\Dev\Deprecation; use Exception; use SilverStripe\Control\Director; use SilverStripe\Core\Config\Config; @@ -60,12 +59,9 @@ abstract class DBSchemaManager /** * @param string $table * @param string $class - * - * @deprecated 4.0.1 Will be removed without equivalent functionality */ public static function showTableNameWarning($table, $class) { - Deprecation::notice('4.0.1', 'Will be removed without equivalent functionality'); static::$table_name_warnings[$table] = $class; } diff --git a/src/ORM/Connect/MySQLTransactionManager.php b/src/ORM/Connect/MySQLTransactionManager.php index 452ce334a..b4d9d1a62 100644 --- a/src/ORM/Connect/MySQLTransactionManager.php +++ b/src/ORM/Connect/MySQLTransactionManager.php @@ -20,13 +20,6 @@ class MySQLTransactionManager implements TransactionManager public function transactionStart($transactionMode = false, $sessionCharacteristics = false) { - if ($transactionMode || $sessionCharacteristics) { - Deprecation::notice( - '4.4', - '$transactionMode and $sessionCharacteristics are deprecated and will be removed in SS5' - ); - } - if ($this->inTransaction) { throw new DatabaseException( "Already in transaction, can't start another. Consider decorating with NestedTransactionManager." diff --git a/src/ORM/DataObject.php b/src/ORM/DataObject.php index aac5f79cb..9d92c4086 100644 --- a/src/ORM/DataObject.php +++ b/src/ORM/DataObject.php @@ -2604,11 +2604,6 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity // Support for the old method during the deprecation period if ($this->hasMethod('getCMSValidator')) { - Deprecation::notice( - '4.6', - 'getCMSValidator() is removed in 5.0 in favour of getCMSCompositeValidator()' - ); - $compositeValidator->addValidator($this->getCMSValidator()); } diff --git a/src/Security/CMSSecurity.php b/src/Security/CMSSecurity.php index eadd22e12..1aedbcf69 100644 --- a/src/Security/CMSSecurity.php +++ b/src/Security/CMSSecurity.php @@ -187,7 +187,7 @@ PHP $backURLs = [ $this->getRequest()->requestVar('BackURL'), $this->getRequest()->getSession()->get('BackURL'), - Director::absoluteURL(AdminRootController::config()->get('url_base'), true), + Director::absoluteURL(AdminRootController::config()->get('url_base')), ]; $backURL = null; foreach ($backURLs as $backURL) { diff --git a/src/View/SSViewer.php b/src/View/SSViewer.php index 6dafb12f4..2057f5974 100644 --- a/src/View/SSViewer.php +++ b/src/View/SSViewer.php @@ -287,8 +287,11 @@ class SSViewer implements Flushable return $themes; } - // Support legacy behaviour - if ($theme = SSViewer::config()->uninherited('theme')) { + // Support @deprecated legacy behaviour + $theme = Deprecation::withNoReplacement(function () { + return SSViewer::config()->uninherited('theme'); + }); + if ($theme) { return [self::PUBLIC_THEME, $theme, self::DEFAULT_THEME]; } diff --git a/src/i18n/i18n.php b/src/i18n/i18n.php index 597a7ecec..b7357b802 100644 --- a/src/i18n/i18n.php +++ b/src/i18n/i18n.php @@ -178,7 +178,6 @@ class i18n implements TemplateGlobalProvider // inject the variables from injectionArray (if present) $sprintfArgs = []; if ($default && !preg_match('/\{[\w\d]*\}/i', $default ?? '') && preg_match('/%[s,d]/', $default ?? '')) { - Deprecation::notice('5.0', 'sprintf style localisation variables are deprecated'); $sprintfArgs = array_values($injection ?? []); $injection = []; } diff --git a/templates/SilverStripe/Forms/GridField/GridField_Item.ss b/templates/SilverStripe/Forms/GridField/GridField_Item.ss index ed5a5fe15..c57cd94df 100644 --- a/templates/SilverStripe/Forms/GridField/GridField_Item.ss +++ b/templates/SilverStripe/Forms/GridField/GridField_Item.ss @@ -6,7 +6,7 @@ <% else %> <% loop $Fields %> - class="ss-gridfield-{$FirstLast}"<% end_if %>>$Value + class="ss-gridfield-{$FirstLast}"<% end_if %>>$Value <% end_loop %> <% end_if %> diff --git a/tests/php/Control/ControllerTest.php b/tests/php/Control/ControllerTest.php index def255c6b..34559386e 100644 --- a/tests/php/Control/ControllerTest.php +++ b/tests/php/Control/ControllerTest.php @@ -45,7 +45,7 @@ class ControllerTest extends FunctionalTest protected function setUp(): void { parent::setUp(); - Director::config()->update('alternate_base_url', '/'); + Director::config()->set('alternate_base_url', '/'); // Add test theme $themeDir = substr(__DIR__, strlen(FRAMEWORK_DIR)) . '/ControllerTest/'; diff --git a/tests/php/Control/DirectorTest.php b/tests/php/Control/DirectorTest.php index 05e24046b..44c9e1980 100644 --- a/tests/php/Control/DirectorTest.php +++ b/tests/php/Control/DirectorTest.php @@ -16,6 +16,7 @@ use SilverStripe\Core\Config\Config; use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Environment; use SilverStripe\Core\Kernel; +use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; /** @@ -856,6 +857,9 @@ class DirectorTest extends SapphireTest public function testRequestFilterInDirectorTest() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $filter = new DirectorTest\TestRequestFilter; $processor = new RequestProcessor([$filter]); diff --git a/tests/php/Control/Email/EmailTest.php b/tests/php/Control/Email/EmailTest.php index daa69ae41..462d51f1b 100644 --- a/tests/php/Control/Email/EmailTest.php +++ b/tests/php/Control/Email/EmailTest.php @@ -271,7 +271,7 @@ class EmailTest extends SapphireTest public function testSetSwiftMessage() { - Email::config()->update('admin_email', 'admin@example.com'); + Email::config()->set('admin_email', 'admin@example.com'); DBDatetime::set_mock_now('2017-01-01 07:00:00'); $email = new Email(); $swiftMessage = new Swift_Message(); @@ -294,7 +294,7 @@ class EmailTest extends SapphireTest public function testAdminEmailApplied() { - Email::config()->update('admin_email', 'admin@example.com'); + Email::config()->set('admin_email', 'admin@example.com'); $email = new Email(); $this->assertCount(1, $email->getFrom()); diff --git a/tests/php/Control/Email/SwiftMailerTest.php b/tests/php/Control/Email/SwiftMailerTest.php index 43a7f98d1..51161a52b 100644 --- a/tests/php/Control/Email/SwiftMailerTest.php +++ b/tests/php/Control/Email/SwiftMailerTest.php @@ -21,7 +21,7 @@ class SwiftMailerTest extends SapphireTest $this->assertEquals($swift, $mailer->getSwiftMailer()); SwiftMailer::config()->remove('swift_plugins'); - SwiftMailer::config()->update('swift_plugins', [Swift_Plugins_AntiFloodPlugin::class]); + SwiftMailer::config()->merge('swift_plugins', [Swift_Plugins_AntiFloodPlugin::class]); /** @var Swift_MailTransport $transport */ $transport = $this->getMockBuilder(Swift_MailTransport::class)->getMock(); diff --git a/tests/php/Control/Email/SwiftPluginTest.php b/tests/php/Control/Email/SwiftPluginTest.php index 5ca702d8e..231e6a523 100644 --- a/tests/php/Control/Email/SwiftPluginTest.php +++ b/tests/php/Control/Email/SwiftPluginTest.php @@ -39,7 +39,7 @@ class SwiftPluginTest extends SapphireTest public function testSendAllEmailsTo() { - Email::config()->update('send_all_emails_to', 'to@example.com'); + Email::config()->set('send_all_emails_to', 'to@example.com'); $email = $this->getEmail(); $this->getMailer()->send($email->getSwiftMessage()); $headers = $email->getSwiftMessage()->getHeaders(); @@ -68,7 +68,7 @@ class SwiftPluginTest extends SapphireTest public function testSendAllEmailsFrom() { - Email::config()->update('send_all_emails_from', 'from@example.com'); + Email::config()->set('send_all_emails_from', 'from@example.com'); $email = $this->getEmail(); $this->getMailer()->send($email->getSwiftMessage()); @@ -88,7 +88,7 @@ class SwiftPluginTest extends SapphireTest public function testCCAllEmailsTo() { - Email::config()->update('cc_all_emails_to', 'cc@example.com'); + Email::config()->set('cc_all_emails_to', 'cc@example.com'); $email = $this->getEmail(); $this->getMailer()->send($email->getSwiftMessage()); @@ -99,7 +99,7 @@ class SwiftPluginTest extends SapphireTest public function testBCCAllEmailsTo() { - Email::config()->update('bcc_all_emails_to', 'bcc@example.com'); + Email::config()->set('bcc_all_emails_to', 'bcc@example.com'); $email = $this->getEmail(); $this->getMailer()->send($email->getSwiftMessage()); diff --git a/tests/php/Control/HTTPRequestTest.php b/tests/php/Control/HTTPRequestTest.php index cf0acc0ca..8f39efbc2 100644 --- a/tests/php/Control/HTTPRequestTest.php +++ b/tests/php/Control/HTTPRequestTest.php @@ -6,6 +6,7 @@ use ReflectionMethod; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\Middleware\TrustedProxyMiddleware; use SilverStripe\Control\Session; +use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; class HTTPRequestTest extends SapphireTest @@ -155,12 +156,18 @@ class HTTPRequestTest extends SapphireTest */ public function testDetectMethod($realMethod, $post, $expected) { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $actual = HTTPRequest::detect_method($realMethod, $post); $this->assertEquals($expected, $actual); } public function testBadDetectMethod() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $this->expectException(\InvalidArgumentException::class); HTTPRequest::detect_method('POST', ['_method' => 'Boom']); } diff --git a/tests/php/Control/HTTPTest.php b/tests/php/Control/HTTPTest.php index 4d43f16b9..b7ea02e9d 100644 --- a/tests/php/Control/HTTPTest.php +++ b/tests/php/Control/HTTPTest.php @@ -11,6 +11,7 @@ use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware; use SilverStripe\Control\Session; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\FunctionalTest; +use SilverStripe\Dev\Deprecation; /** * Tests the {@link HTTP} class @@ -115,6 +116,9 @@ class HTTPTest extends FunctionalTest public function testDeprecatedVaryHandling() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } /** @var Config */ Config::modify()->set( HTTP::class, @@ -129,6 +133,9 @@ class HTTPTest extends FunctionalTest public function testDeprecatedCacheControlHandling() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } HTTPCacheControlMiddleware::singleton()->publicCache(); /** @var Config */ @@ -149,6 +156,9 @@ class HTTPTest extends FunctionalTest public function testDeprecatedCacheControlHandlingOnMaxAge() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } HTTPCacheControlMiddleware::singleton()->publicCache(); /** @var Config */ @@ -169,6 +179,9 @@ class HTTPTest extends FunctionalTest public function testDeprecatedCacheControlHandlingThrowsWithUnknownDirectives() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $this->expectException(\LogicException::class); $this->expectExceptionMessageMatches('/Found unsupported legacy directives in HTTP\.cache_control: unknown/'); /** @var Config */ diff --git a/tests/php/Control/SessionTest.php b/tests/php/Control/SessionTest.php index e37396448..e0b4d4c49 100644 --- a/tests/php/Control/SessionTest.php +++ b/tests/php/Control/SessionTest.php @@ -107,7 +107,7 @@ class SessionTest extends SapphireTest ->setScheme('https'); Cookie::set(session_name(), '1234'); $session = new Session(null); // unstarted session - $session->config()->update('cookie_secure', true); + $session->config()->set('cookie_secure', true); $session->start($req); $this->assertEquals(session_name(), $session->config()->get('cookie_name_secure')); } @@ -270,7 +270,7 @@ class SessionTest extends SapphireTest ->setScheme('https'); $session = new Session(null); // unstarted session Cookie::set($session->config()->get('cookie_name_secure'), '1234'); - $session->config()->update('cookie_secure', true); + $session->config()->set('cookie_secure', true); $this->assertTrue($session->requestContainsSessionId($req)); } diff --git a/tests/php/Core/ConvertTest.php b/tests/php/Core/ConvertTest.php index 6522fb39e..1c846f974 100644 --- a/tests/php/Core/ConvertTest.php +++ b/tests/php/Core/ConvertTest.php @@ -5,6 +5,7 @@ namespace SilverStripe\Core\Tests; use Exception; use InvalidArgumentException; use SilverStripe\Core\Convert; +use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; use SilverStripe\View\Parsers\URLSegmentFilter; use stdClass; @@ -217,6 +218,9 @@ PHP */ public function testArray2JSON() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $val = [ 'Joe' => 'Bloggs', 'Tom' => 'Jones', @@ -237,6 +241,9 @@ PHP */ public function testJSON2Array() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $val = '{"Joe":"Bloggs","Tom":"Jones","My":{"Complicated":"Structure"}}'; $decoded = Convert::json2array($val); $this->assertEquals(3, count($decoded ?? []), '3 items in the decoded array'); @@ -250,6 +257,9 @@ PHP */ public function testJSON2Obj() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $val = '{"Joe":"Bloggs","Tom":"Jones","My":{"Complicated":"Structure"}}'; $obj = Convert::json2obj($val); $this->assertEquals('Bloggs', $obj->Joe); @@ -264,7 +274,7 @@ PHP */ public function testRaw2URL() { - URLSegmentFilter::config()->update('default_allow_multibyte', false); + URLSegmentFilter::config()->set('default_allow_multibyte', false); $this->assertEquals('foo', Convert::raw2url('foo')); $this->assertEquals('foo-and-bar', Convert::raw2url('foo & bar')); $this->assertEquals('foo-and-bar', Convert::raw2url('foo & bar!')); @@ -359,6 +369,9 @@ PHP */ public function testRaw2JSON() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } // Test object $input = new stdClass(); @@ -390,6 +403,9 @@ PHP */ public function testRaw2JsonWithContext() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $data = ['foo' => 'b"ar']; $expected = '{"foo":"b\u0022ar"}'; $result = Convert::raw2json($data, JSON_HEX_QUOT); diff --git a/tests/php/Core/Manifest/ModuleTest.php b/tests/php/Core/Manifest/ModuleTest.php index f4ea2db5a..a0e9f6a0f 100644 --- a/tests/php/Core/Manifest/ModuleTest.php +++ b/tests/php/Core/Manifest/ModuleTest.php @@ -5,6 +5,7 @@ namespace SilverStripe\Core\Tests\Manifest; use SilverStripe\Control\Director; use SilverStripe\Core\Manifest\Module; use SilverStripe\Dev\SapphireTest; +use SilverStripe\Dev\Deprecation; class ModuleTest extends SapphireTest { @@ -29,6 +30,9 @@ class ModuleTest extends SapphireTest */ public function testGetCIConfig($fixture, $expectedPhpConfig) { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $path = __DIR__ . '/fixtures/phpunit-detection/' . $fixture; $module = new Module($path, $path); $this->assertEquals( diff --git a/tests/php/Core/ObjectTest.php b/tests/php/Core/ObjectTest.php index 969fdaf7a..66562315a 100644 --- a/tests/php/Core/ObjectTest.php +++ b/tests/php/Core/ObjectTest.php @@ -19,6 +19,7 @@ use SilverStripe\Core\Tests\ObjectTest\ExtensionTest3; use SilverStripe\Core\Tests\ObjectTest\MyObject; use SilverStripe\Core\Tests\ObjectTest\MySubObject; use SilverStripe\Core\Tests\ObjectTest\TestExtension; +use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; use SilverStripe\Versioned\Versioned; @@ -110,6 +111,9 @@ class ObjectTest extends SapphireTest public function testStaticGetterMethod() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $obj = singleton(MyObject::class); $this->assertEquals( 'MyObject', @@ -120,6 +124,9 @@ class ObjectTest extends SapphireTest public function testStaticInheritanceGetters() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $subObj = singleton(MyObject::class); $this->assertEquals( $subObj->stat('mystaticProperty'), @@ -130,6 +137,9 @@ class ObjectTest extends SapphireTest public function testStaticSettingOnSingletons() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $singleton1 = singleton(MyObject::class); $singleton2 = singleton(MyObject::class); $singleton1->set_stat('mystaticProperty', 'changed'); @@ -142,6 +152,9 @@ class ObjectTest extends SapphireTest public function testStaticSettingOnInstances() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $instance1 = new ObjectTest\MyObject(); $instance2 = new ObjectTest\MyObject(); $instance1->set_stat('mystaticProperty', 'changed'); diff --git a/tests/php/Dev/BacktraceTest.php b/tests/php/Dev/BacktraceTest.php index de44410d1..d1f5fe98d 100644 --- a/tests/php/Dev/BacktraceTest.php +++ b/tests/php/Dev/BacktraceTest.php @@ -59,7 +59,7 @@ class BacktraceTest extends SapphireTest 'args' => ['myarg' => 'myval'] ] ]; - Backtrace::config()->update( + Backtrace::config()->merge( 'ignore_function_args', [ ['MyClass', 'myIgnoredClassFunction'], @@ -101,7 +101,7 @@ class BacktraceTest extends SapphireTest 'args' => ['myarg' => 'myval'] ] ]; - Backtrace::config()->update( + Backtrace::config()->merge( 'ignore_function_args', [ ['*', 'myIgnoredClassFunction'], diff --git a/tests/php/Dev/DeprecationTest.php b/tests/php/Dev/DeprecationTest.php index b447866a0..fac1ad726 100644 --- a/tests/php/Dev/DeprecationTest.php +++ b/tests/php/Dev/DeprecationTest.php @@ -7,6 +7,7 @@ use SilverStripe\Core\Config\Config; use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; use SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject; +use SilverStripe\Core\Injector\Injector; class DeprecationTest extends SapphireTest { @@ -16,6 +17,8 @@ class DeprecationTest extends SapphireTest private $oldHandler = null; + private bool $noticesWereEnabled = false; + protected function setup(): void { // Use custom error handler for two reasons: @@ -23,6 +26,7 @@ class DeprecationTest extends SapphireTest // - Allow the use of expectDeprecation(), which doesn't work with E_USER_DEPRECATION by default // https://github.com/laminas/laminas-di/pull/30#issuecomment-927585210 parent::setup(); + $this->noticesWereEnabled = Deprecation::isEnabled(); $this->oldHandler = set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) { if ($errno === E_USER_DEPRECATED) { if (str_contains($errstr, 'SilverStripe\\Dev\\Tests\\DeprecationTest')) { @@ -42,23 +46,140 @@ class DeprecationTest extends SapphireTest protected function tearDown(): void { - Deprecation::disable(); + if (!$this->noticesWereEnabled) { + Deprecation::disable(); + } restore_error_handler(); $this->oldHandler = null; parent::tearDown(); } + private function myDeprecatedMethod(): string + { + Deprecation::notice('1.2.3', 'My message'); + return 'abc'; + } + public function testNotice() { $message = implode(' ', [ - 'SilverStripe\Dev\Tests\DeprecationTest->testNotice is deprecated.', + 'SilverStripe\Dev\Tests\DeprecationTest->myDeprecatedMethod is deprecated.', 'My message.', - 'Called from PHPUnit\Framework\TestCase->runTest.' + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testNotice.' ]); $this->expectDeprecation(); $this->expectDeprecationMessage($message); Deprecation::enable(); - Deprecation::notice('1.2.3', 'My message'); + $ret = $this->myDeprecatedMethod(); + $this->assertSame('abc', $ret); + // call outputNotices() directly because the regular shutdown function that emits + // the notices within Deprecation won't be called until after this unit-test has finished + Deprecation::outputNotices(); + } + + public function testCallUserFunc() + { + $message = implode(' ', [ + 'SilverStripe\Dev\Tests\DeprecationTest->myDeprecatedMethod is deprecated.', + 'My message.', + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testCallUserFunc.' + ]); + $this->expectDeprecation(); + $this->expectDeprecationMessage($message); + Deprecation::enable(); + $ret = call_user_func([$this, 'myDeprecatedMethod']); + $this->assertSame('abc', $ret); + Deprecation::outputNotices(); + } + + public function testCallUserFuncArray() + { + $message = implode(' ', [ + 'SilverStripe\Dev\Tests\DeprecationTest->myDeprecatedMethod is deprecated.', + 'My message.', + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testCallUserFuncArray.' + ]); + $this->expectDeprecation(); + $this->expectDeprecationMessage($message); + Deprecation::enable(); + $ret = call_user_func_array([$this, 'myDeprecatedMethod'], []); + $this->assertSame('abc', $ret); + Deprecation::outputNotices(); + } + + public function testWithNoReplacementDefault() + { + Deprecation::enable(); + $ret = Deprecation::withNoReplacement(function () { + return $this->myDeprecatedMethod(); + }); + $this->assertSame('abc', $ret); + Deprecation::outputNotices(); + } + + public function testWithNoReplacementTrue() + { + $message = implode(' ', [ + 'SilverStripe\Dev\Tests\DeprecationTest->myDeprecatedMethod is deprecated.', + 'My message.', + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testWithNoReplacementTrue.' + ]); + $this->expectDeprecation(); + $this->expectDeprecationMessage($message); + Deprecation::enable(true); + $ret = Deprecation::withNoReplacement(function () { + return $this->myDeprecatedMethod(); + }); + $this->assertSame('abc', $ret); + Deprecation::outputNotices(); + } + + public function testWithNoReplacementTrueCallUserFunc() + { + $message = implode(' ', [ + 'SilverStripe\Dev\Tests\DeprecationTest->myDeprecatedMethod is deprecated.', + 'My message.', + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testWithNoReplacementTrueCallUserFunc.' + ]); + $this->expectDeprecation(); + $this->expectDeprecationMessage($message); + Deprecation::enable(true); + $ret = Deprecation::withNoReplacement(function () { + return call_user_func([$this, 'myDeprecatedMethod']); + }); + $this->assertSame('abc', $ret); + Deprecation::outputNotices(); + } + + public function testClassWithNoReplacement() + { + $message = implode(' ', [ + 'SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject is deprecated.', + 'Some class message.', + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testClassWithNoReplacement.' + ]); + $this->expectDeprecation(); + $this->expectDeprecationMessage($message); + Deprecation::enable(true); + // using this syntax because my IDE was complaining about DeprecationTestObject not existing + // when trying to use `new DeprecationTestObject();` + $class = DeprecationTestObject::class; + new $class(); + Deprecation::outputNotices(); + } + + public function testClassWithInjectorWithNoReplacement() + { + $message = implode(' ', [ + 'SilverStripe\Dev\Tests\DeprecationTest\DeprecationTestObject is deprecated.', + 'Some class message.', + 'Called from SilverStripe\Dev\Tests\DeprecationTest->testClassWithInjectorWithNoReplacement.' + ]); + $this->expectDeprecation(); + $this->expectDeprecationMessage($message); + Deprecation::enable(true); + Injector::inst()->get(DeprecationTestObject::class); + Deprecation::outputNotices(); } /** @@ -66,8 +187,12 @@ class DeprecationTest extends SapphireTest */ public function testDisabled() { + if ($this->noticesWereEnabled) { + $this->markTestSkipped('Notices are enabled for this project outside of this unit test'); + } // test that no error error is raised because by default Deprecation is disabled - Deprecation::notice('4.5.6', 'My message'); + $this->myDeprecatedMethod(); + Deprecation::outputNotices(); } // The following tests would be better to put in the silverstripe/config module, however this is not @@ -76,7 +201,6 @@ class DeprecationTest extends SapphireTest // Adding a _config.php file will break existing unit-tests within silverstripe/config // It is possible to put DeprecationTestObject in framework and the unit tests in config, however // that's probably messier then just having everything within framework - public function testConfigGetFirst() { $message = implode(' ', [ @@ -87,6 +211,7 @@ class DeprecationTest extends SapphireTest $this->expectDeprecationMessage($message); Deprecation::enable(); Config::inst()->get(DeprecationTestObject::class, 'first_config'); + Deprecation::outputNotices(); } public function testConfigGetSecond() @@ -99,6 +224,7 @@ class DeprecationTest extends SapphireTest $this->expectDeprecationMessage($message); Deprecation::enable(); Config::inst()->get(DeprecationTestObject::class, 'second_config'); + Deprecation::outputNotices(); } public function testConfigGetThird() @@ -108,6 +234,7 @@ class DeprecationTest extends SapphireTest $this->expectDeprecationMessage($message); Deprecation::enable(); Config::inst()->get(DeprecationTestObject::class, 'third_config'); + Deprecation::outputNotices(); } public function testConfigSet() @@ -120,6 +247,7 @@ class DeprecationTest extends SapphireTest $this->expectDeprecationMessage($message); Deprecation::enable(); Config::modify()->set(DeprecationTestObject::class, 'first_config', 'abc'); + Deprecation::outputNotices(); } public function testConfigMerge() @@ -132,5 +260,6 @@ class DeprecationTest extends SapphireTest $this->expectDeprecationMessage($message); Deprecation::enable(); Config::modify()->merge(DeprecationTestObject::class, 'array_config', ['abc']); + Deprecation::outputNotices(); } } diff --git a/tests/php/Dev/DeprecationTest/DeprecationTestObject.php b/tests/php/Dev/DeprecationTest/DeprecationTestObject.php index c16a83710..60a725458 100644 --- a/tests/php/Dev/DeprecationTest/DeprecationTestObject.php +++ b/tests/php/Dev/DeprecationTest/DeprecationTestObject.php @@ -4,9 +4,22 @@ namespace SilverStripe\Dev\Tests\DeprecationTest; use SilverStripe\Dev\TestOnly; use SilverStripe\ORM\DataObject; +use SilverStripe\Dev\Deprecation; class DeprecationTestObject extends DataObject implements TestOnly { + public function __construct() + { + parent::__construct(); + Deprecation::withNoReplacement(function () { + Deprecation::notice( + '1.2.3', + 'Some class message', + Deprecation::SCOPE_CLASS + ); + }); + } + private static $db = [ "Name" => "Varchar" ]; diff --git a/tests/php/Dev/DevAdminControllerTest.php b/tests/php/Dev/DevAdminControllerTest.php index 8a64b3f71..60e93fed0 100644 --- a/tests/php/Dev/DevAdminControllerTest.php +++ b/tests/php/Dev/DevAdminControllerTest.php @@ -18,7 +18,7 @@ class DevAdminControllerTest extends FunctionalTest { parent::setUp(); - DevelopmentAdmin::config()->update( + DevelopmentAdmin::config()->merge( 'registered_controllers', [ 'x1' => [ diff --git a/tests/php/Forms/ConfirmedPasswordFieldTest.php b/tests/php/Forms/ConfirmedPasswordFieldTest.php index 20be81893..990402db0 100644 --- a/tests/php/Forms/ConfirmedPasswordFieldTest.php +++ b/tests/php/Forms/ConfirmedPasswordFieldTest.php @@ -200,7 +200,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest $this->assertSame($expectValid, $result, 'Validate method should return its result'); $this->assertSame($expectValid, $validator->getResult()->isValid()); if ($expectedMessage) { - $this->assertStringContainsString($expectedMessage, $validator->getResult()->serialize()); + $this->assertStringContainsString($expectedMessage, json_encode($validator->getResult()->__serialize())); } } @@ -235,7 +235,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest $this->assertFalse($validator->getResult()->isValid()); $this->assertStringContainsString( 'Passwords must have at least one digit and one alphanumeric character', - $validator->getResult()->serialize() + json_encode($validator->getResult()->__serialize()) ); } @@ -254,7 +254,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest $this->assertFalse($validator->getResult()->isValid()); $this->assertStringContainsString( 'You must enter your current password', - $validator->getResult()->serialize() + json_encode($validator->getResult()->__serialize()) ); } @@ -276,7 +276,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest $this->assertFalse($validator->getResult()->isValid()); $this->assertStringContainsString( 'You must be logged in to change your password', - $validator->getResult()->serialize() + json_encode($validator->getResult()->__serialize()) ); } @@ -302,7 +302,7 @@ class ConfirmedPasswordFieldTest extends SapphireTest $this->assertFalse($validator->getResult()->isValid()); $this->assertStringContainsString( 'The current password you have entered is not correct', - $validator->getResult()->serialize() + json_encode($validator->getResult()->__serialize()) ); } diff --git a/tests/php/Forms/CurrencyFieldDisabledTest.php b/tests/php/Forms/CurrencyFieldDisabledTest.php index 6f1cc0c70..d02e1375a 100644 --- a/tests/php/Forms/CurrencyFieldDisabledTest.php +++ b/tests/php/Forms/CurrencyFieldDisabledTest.php @@ -23,7 +23,7 @@ class CurrencyFieldDisabledTest extends SapphireTest */ public function testFieldWithCustomisedCurrencySymbol() { - DBCurrency::config()->update('currency_symbol', '€'); + DBCurrency::config()->set('currency_symbol', '€'); $field = new CurrencyField_Disabled('Test', '', '€5.00'); $result = $field->Field(); diff --git a/tests/php/Forms/CurrencyFieldReadonlyTest.php b/tests/php/Forms/CurrencyFieldReadonlyTest.php index 0c998a8ef..352b97f82 100644 --- a/tests/php/Forms/CurrencyFieldReadonlyTest.php +++ b/tests/php/Forms/CurrencyFieldReadonlyTest.php @@ -28,7 +28,7 @@ class CurrencyFieldReadonlyTest extends SapphireTest public function testFieldWithOutValue() { - DBCurrency::config()->update('currency_symbol', 'AUD'); + DBCurrency::config()->set('currency_symbol', 'AUD'); $field = new CurrencyField_Readonly('Test', '', null); $result = $field->Field(); @@ -42,7 +42,7 @@ class CurrencyFieldReadonlyTest extends SapphireTest */ public function testFieldWithCustomisedCurrencySymbol() { - DBCurrency::config()->update('currency_symbol', '€'); + DBCurrency::config()->set('currency_symbol', '€'); $field = new CurrencyField_Readonly('Test', '', '€5.00'); $result = $field->Field(); diff --git a/tests/php/Forms/CurrencyFieldTest.php b/tests/php/Forms/CurrencyFieldTest.php index 02c4114e4..2ca244dd2 100644 --- a/tests/php/Forms/CurrencyFieldTest.php +++ b/tests/php/Forms/CurrencyFieldTest.php @@ -67,7 +67,7 @@ class CurrencyFieldTest extends SapphireTest ); //tests with updated currency symbol setting - DBCurrency::config()->update('currency_symbol', '€'); + DBCurrency::config()->set('currency_symbol', '€'); $f->setValue('123.45'); $this->assertTrue( @@ -180,7 +180,7 @@ class CurrencyFieldTest extends SapphireTest ); //update currency symbol via config - DBCurrency::config()->update('currency_symbol', '€'); + DBCurrency::config()->set('currency_symbol', '€'); $f->setValue('123.45'); $this->assertEquals( @@ -263,7 +263,7 @@ class CurrencyFieldTest extends SapphireTest ); //tests with updated currency symbol setting - DBCurrency::config()->update('currency_symbol', '€'); + DBCurrency::config()->set('currency_symbol', '€'); $f->setValue('€123.45'); $this->assertEquals( @@ -302,11 +302,14 @@ class CurrencyFieldTest extends SapphireTest $field = new CurrencyField('Test', '', '$5.00'); $validator = new RequiredFields(); - DBCurrency::config()->update('currency_symbol', '€'); + DBCurrency::config()->set('currency_symbol', '€'); $result = $field->validate($validator); $this->assertFalse($result, 'Validation should fail since wrong currency was used'); $this->assertFalse($validator->getResult()->isValid(), 'Validator should receive failed state'); - $this->assertStringContainsString('Please enter a valid currency', $validator->getResult()->serialize()); + $this->assertStringContainsString( + 'Please enter a valid currency', + json_encode($validator->getResult()->__serialize()) + ); } } diff --git a/tests/php/Forms/FormFieldTest.php b/tests/php/Forms/FormFieldTest.php index f633e6792..47a3ff946 100644 --- a/tests/php/Forms/FormFieldTest.php +++ b/tests/php/Forms/FormFieldTest.php @@ -31,7 +31,7 @@ class FormFieldTest extends SapphireTest { Config::nest(); - FormField::config()->update( + FormField::config()->merge( 'default_classes', [ 'class1', @@ -42,7 +42,7 @@ class FormFieldTest extends SapphireTest $this->assertStringContainsString('class1', $field->extraClass(), 'Class list does not contain expected class'); - FormField::config()->update( + FormField::config()->merge( 'default_classes', [ 'class1', @@ -54,7 +54,7 @@ class FormFieldTest extends SapphireTest $this->assertStringContainsString('class1 class2', $field->extraClass(), 'Class list does not contain expected class'); - FormField::config()->update( + FormField::config()->merge( 'default_classes', [ 'class3', @@ -69,7 +69,7 @@ class FormFieldTest extends SapphireTest $this->assertStringNotContainsString('class3', $field->extraClass(), 'Class list contains unexpected class'); - TextField::config()->update( + TextField::config()->merge( 'default_classes', [ 'textfield-class', diff --git a/tests/php/Forms/FormTest.php b/tests/php/Forms/FormTest.php index 140db87fb..34689f487 100644 --- a/tests/php/Forms/FormTest.php +++ b/tests/php/Forms/FormTest.php @@ -792,7 +792,7 @@ class FormTest extends FunctionalTest public function testDefaultClasses() { - Form::config()->update( + Form::config()->merge( 'default_classes', [ 'class1', @@ -803,7 +803,7 @@ class FormTest extends FunctionalTest $this->assertStringContainsString('class1', $form->extraClass(), 'Class list does not contain expected class'); - Form::config()->update( + Form::config()->merge( 'default_classes', [ 'class1', @@ -815,7 +815,7 @@ class FormTest extends FunctionalTest $this->assertStringContainsString('class1 class2', $form->extraClass(), 'Class list does not contain expected class'); - Form::config()->update( + Form::config()->merge( 'default_classes', [ 'class3', diff --git a/tests/php/Logging/MonologErrorHandlerTest.php b/tests/php/Logging/MonologErrorHandlerTest.php index 6bbe37b03..b31251e91 100644 --- a/tests/php/Logging/MonologErrorHandlerTest.php +++ b/tests/php/Logging/MonologErrorHandlerTest.php @@ -4,6 +4,7 @@ namespace SilverStripe\Logging\Tests; use InvalidArgumentException; use Psr\Log\LoggerInterface; +use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; use SilverStripe\Logging\MonologErrorHandler; @@ -26,8 +27,10 @@ class MonologErrorHandlerTest extends SapphireTest $handler->pushLogger($logger)->pushLogger($logger); $this->assertCount(2, $handler->getLoggers(), 'Loggers are pushed to the stack'); - $handler->setLogger($logger); - $this->assertCount(1, $handler->getLoggers(), 'setLogger resets stack and pushes'); + if (!Deprecation::isEnabled()) { + $handler->setLogger($logger); + $this->assertCount(1, $handler->getLoggers(), 'setLogger resets stack and pushes'); + } $handler->setLoggers([]); $this->assertCount(0, $handler->getLoggers(), 'setLoggers overwrites all configured loggers'); diff --git a/tests/php/ORM/ArrayListTest.php b/tests/php/ORM/ArrayListTest.php index d2e57447d..9cb606030 100644 --- a/tests/php/ORM/ArrayListTest.php +++ b/tests/php/ORM/ArrayListTest.php @@ -133,6 +133,21 @@ class ArrayListTest extends SapphireTest ); } + public function testLimitNull() + { + $list = new ArrayList( + [ + ['Key' => 1], ['Key' => 2], ['Key' => 3] + ] + ); + $this->assertEquals( + $list->limit(null, 0)->toArray(), + [ + ['Key' => 1], ['Key' => 2], ['Key' => 3] + ] + ); + } + public function testAddRemove() { $list = new ArrayList( diff --git a/tests/php/ORM/DataObjectSchemaGenerationTest.php b/tests/php/ORM/DataObjectSchemaGenerationTest.php index 95e0aa98a..b8a3d30bc 100644 --- a/tests/php/ORM/DataObjectSchemaGenerationTest.php +++ b/tests/php/ORM/DataObjectSchemaGenerationTest.php @@ -101,7 +101,7 @@ class DataObjectSchemaGenerationTest extends SapphireTest // Table will have been initially created by the $extraDataObjects setting // Let's insert a new field here - TestObject::config()->update( + TestObject::config()->merge( 'db', [ 'SecretField' => 'Varchar(100)' @@ -170,7 +170,7 @@ class DataObjectSchemaGenerationTest extends SapphireTest // Table will have been initially created by the $extraDataObjects setting // Update the SearchFields index here - TestIndexObject::config()->update( + TestIndexObject::config()->merge( 'indexes', [ 'SearchFields' => [ @@ -265,35 +265,35 @@ class DataObjectSchemaGenerationTest extends SapphireTest 'columns' => ['Sort'], ], $indexes); DataObject::getSchema()->reset(); - Config::inst()->update(SortedObject::class, 'default_sort', 'Sort ASC'); + Config::inst()->set(SortedObject::class, 'default_sort', 'Sort ASC'); $indexes = DataObject::getSchema()->databaseIndexes(SortedObject::class); $this->assertContains([ 'type' => 'index', 'columns' => ['Sort'], ], $indexes); DataObject::getSchema()->reset(); - Config::inst()->update(SortedObject::class, 'default_sort', 'Sort DESC'); + Config::inst()->set(SortedObject::class, 'default_sort', 'Sort DESC'); $indexes = DataObject::getSchema()->databaseIndexes(SortedObject::class); $this->assertContains([ 'type' => 'index', 'columns' => ['Sort'], ], $indexes); DataObject::getSchema()->reset(); - Config::inst()->update(SortedObject::class, 'default_sort', '"Sort" DESC'); + Config::inst()->set(SortedObject::class, 'default_sort', '"Sort" DESC'); $indexes = DataObject::getSchema()->databaseIndexes(SortedObject::class); $this->assertContains([ 'type' => 'index', 'columns' => ['Sort'], ], $indexes); DataObject::getSchema()->reset(); - Config::inst()->update(SortedObject::class, 'default_sort', '"DataObjectSchemaGenerationTest_SortedObject"."Sort" ASC'); + Config::inst()->set(SortedObject::class, 'default_sort', '"DataObjectSchemaGenerationTest_SortedObject"."Sort" ASC'); $indexes = DataObject::getSchema()->databaseIndexes(SortedObject::class); $this->assertContains([ 'type' => 'index', 'columns' => ['Sort'], ], $indexes); DataObject::getSchema()->reset(); - Config::inst()->update(SortedObject::class, 'default_sort', '"Sort" DESC, "Title" ASC'); + Config::inst()->set(SortedObject::class, 'default_sort', '"Sort" DESC, "Title" ASC'); $indexes = DataObject::getSchema()->databaseIndexes(SortedObject::class); $this->assertContains([ 'type' => 'index', @@ -305,7 +305,7 @@ class DataObjectSchemaGenerationTest extends SapphireTest ], $indexes); DataObject::getSchema()->reset(); // make sure that specific indexes aren't overwritten - Config::inst()->update(SortedObject::class, 'indexes', [ + Config::inst()->merge(SortedObject::class, 'indexes', [ 'Sort' => [ 'type' => 'unique', 'columns' => ['Sort'], diff --git a/tests/php/ORM/HierarchyCachingTest.php b/tests/php/ORM/HierarchyCachingTest.php index afbd488c2..8070fbe26 100644 --- a/tests/php/ORM/HierarchyCachingTest.php +++ b/tests/php/ORM/HierarchyCachingTest.php @@ -37,7 +37,7 @@ class HierachyCacheTest extends SapphireTest public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); - HideTestObject::config()->update( + HideTestObject::config()->merge( 'hide_from_hierarchy', [ HideTestSubObject::class ] ); diff --git a/tests/php/ORM/HierarchyTest.php b/tests/php/ORM/HierarchyTest.php index 697fc7c2f..c3d2e0b12 100644 --- a/tests/php/ORM/HierarchyTest.php +++ b/tests/php/ORM/HierarchyTest.php @@ -273,7 +273,7 @@ class HierarchyTest extends SapphireTest public function testHideFromHierarchy() { - HierarchyTest\HideTestObject::config()->update( + HierarchyTest\HideTestObject::config()->merge( 'hide_from_hierarchy', [ HierarchyTest\HideTestSubObject::class ] ); diff --git a/tests/php/ORM/ManyManyListTest.php b/tests/php/ORM/ManyManyListTest.php index f7b4dd5b5..2dd852b62 100644 --- a/tests/php/ORM/ManyManyListTest.php +++ b/tests/php/ORM/ManyManyListTest.php @@ -423,7 +423,7 @@ class ManyManyListTest extends SapphireTest $obj->Clients()->add($obj2, ['Worth' => $money, 'Reference' => 'B']); // Set the default sort for this relation - Config::inst()->update('ManyManyListTest_ExtraFields_Clients', 'default_sort', 'Reference ASC'); + Config::inst()->set('ManyManyListTest_ExtraFields_Clients', 'default_sort', 'Reference ASC'); $clients = $obj->Clients(); $this->assertCount(2, $clients); @@ -432,7 +432,7 @@ class ManyManyListTest extends SapphireTest $this->assertEquals('B', $second->Reference); // Now we ensure the default sort is being respected by reversing its order - Config::inst()->update('ManyManyListTest_ExtraFields_Clients', 'default_sort', 'Reference DESC'); + Config::inst()->set('ManyManyListTest_ExtraFields_Clients', 'default_sort', 'Reference DESC'); $reverseClients = $obj->Clients(); $this->assertCount(2, $reverseClients); diff --git a/tests/php/ORM/ManyManyThroughListTest.php b/tests/php/ORM/ManyManyThroughListTest.php index 2d9cb8908..26211d7c2 100644 --- a/tests/php/ORM/ManyManyThroughListTest.php +++ b/tests/php/ORM/ManyManyThroughListTest.php @@ -268,7 +268,7 @@ class ManyManyThroughListTest extends SapphireTest { $this->expectException(\InvalidArgumentException::class); DataObject::reset(); - ManyManyThroughListTest\Item::config()->update( + ManyManyThroughListTest\Item::config()->merge( 'db', [ ManyManyThroughListTest\JoinObject::class => 'Text' @@ -416,7 +416,7 @@ class ManyManyThroughListTest extends SapphireTest $this->assertSame('International', $second->Title); // Ensure that we're respecting the default sort by reversing it - Config::inst()->update(FallbackLocale::class, 'default_sort', '"ManyManyThroughTest_FallbackLocale"."Sort" DESC'); + Config::inst()->set(FallbackLocale::class, 'default_sort', '"ManyManyThroughTest_FallbackLocale"."Sort" DESC'); $reverse = $mexico->Fallbacks(); list($firstReverse, $secondReverse) = $reverse; diff --git a/tests/php/ORM/MySQLPDOConnectorTest.php b/tests/php/ORM/MySQLPDOConnectorTest.php index 473d71eb9..7a122c3a0 100644 --- a/tests/php/ORM/MySQLPDOConnectorTest.php +++ b/tests/php/ORM/MySQLPDOConnectorTest.php @@ -10,6 +10,7 @@ use SilverStripe\Dev\TestOnly; use SilverStripe\ORM\Tests\MySQLPDOConnectorTest\PDOConnector; use SilverStripe\ORM\DB; use SilverStripe\Tests\ORM\Utf8\Utf8TestHelper; +use SilverStripe\Dev\Deprecation; /** * @requires extension PDO @@ -22,6 +23,9 @@ class MySQLPDOConnectorTest extends SapphireTest implements TestOnly */ public function testConnectionCharsetControl($charset, $defaultCollation) { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $config = DB::getConfig(); $config['driver'] = 'mysql'; $config['charset'] = $charset; @@ -51,6 +55,9 @@ class MySQLPDOConnectorTest extends SapphireTest implements TestOnly */ public function testConnectionCollationControl($charset, $defaultCollation, $customCollation) { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $config = DB::getConfig(); $config['charset'] = $charset; $config['driver'] = 'mysql'; @@ -86,6 +93,9 @@ class MySQLPDOConnectorTest extends SapphireTest implements TestOnly public function testUtf8mb4GeneralCollation() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $charset = 'utf8mb4'; $collation = 'utf8mb4_general_ci'; @@ -113,6 +123,9 @@ class MySQLPDOConnectorTest extends SapphireTest implements TestOnly public function testUtf8mb4UnicodeCollation() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $charset = 'utf8mb4'; $collation = 'utf8mb4_unicode_ci'; diff --git a/tests/php/ORM/SQLSelectTest.php b/tests/php/ORM/SQLSelectTest.php index f3618ebe0..54b29209a 100755 --- a/tests/php/ORM/SQLSelectTest.php +++ b/tests/php/ORM/SQLSelectTest.php @@ -8,7 +8,6 @@ use SilverStripe\ORM\Connect\MySQLDatabase; use SilverStripe\ORM\Queries\SQLSelect; use SilverStripe\SQLite\SQLite3Database; use SilverStripe\PostgreSQL\PostgreSQLDatabase; -use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; class SQLSelectTest extends SapphireTest @@ -24,18 +23,6 @@ class SQLSelectTest extends SapphireTest protected $oldDeprecation = null; - protected function setUp(): void - { - parent::setUp(); - $this->oldDeprecation = Deprecation::dump_settings(); - } - - protected function tearDown(): void - { - Deprecation::restore_settings($this->oldDeprecation); - parent::tearDown(); - } - public function testCount() { diff --git a/tests/php/ORM/TransactionTest.php b/tests/php/ORM/TransactionTest.php index 8c524e78c..6a27bdc69 100644 --- a/tests/php/ORM/TransactionTest.php +++ b/tests/php/ORM/TransactionTest.php @@ -5,7 +5,6 @@ namespace SilverStripe\ORM\Tests; use SilverStripe\ORM\DB; use SilverStripe\ORM\DataObject; use SilverStripe\Dev\SapphireTest; -use SilverStripe\Dev\Deprecation; use SilverStripe\ORM\Tests\TransactionTest\TestObject; class TransactionTest extends SapphireTest @@ -20,18 +19,6 @@ class TransactionTest extends SapphireTest private static $originalVersionInfo; - protected function setUp(): void - { - parent::setUp(); - self::$originalVersionInfo = Deprecation::dump_settings(); - } - - protected function tearDown(): void - { - Deprecation::restore_settings(self::$originalVersionInfo); - parent::tearDown(); - } - public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); @@ -166,9 +153,6 @@ class TransactionTest extends SapphireTest return; } - // This feature is deprecated in 4.4, but we're still testing it. - Deprecation::notification_version('4.3.0'); - $page = new TestObject(); $page->Title = 'Read only success'; $page->write(); diff --git a/tests/php/Security/MemberAuthenticator/SessionAuthenticationHandlerTest.php b/tests/php/Security/MemberAuthenticator/SessionAuthenticationHandlerTest.php index def203040..87276e3e5 100644 --- a/tests/php/Security/MemberAuthenticator/SessionAuthenticationHandlerTest.php +++ b/tests/php/Security/MemberAuthenticator/SessionAuthenticationHandlerTest.php @@ -15,10 +15,6 @@ class SessionAuthenticationHandlerTest extends SapphireTest protected $usesDatabase = true; - /** - * @runInSeparateProcess - * @preserveGlobalState disabled - */ public function testAuthenticateRequestDefersSessionStartWithoutSessionIdentifier() { $member = new Member(['Email' => 'test@example.com']); @@ -36,10 +32,6 @@ class SessionAuthenticationHandlerTest extends SapphireTest $this->assertNull($matchedMember); } - /** - * @runInSeparateProcess - * @preserveGlobalState disabled - */ public function testAuthenticateRequestStartsSessionWithSessionIdentifier() { $member = new Member(['Email' => 'test@example.com']); @@ -49,12 +41,13 @@ class SessionAuthenticationHandlerTest extends SapphireTest $session = new Session(null); // unstarted $session->set($handler->getSessionVariable(), $member->ID); + $session = new Session($session); // started $req = new HTTPRequest('GET', '/'); $req->setSession($session); + // simulate detection of session cookie Cookie::set(session_name(), '1234'); - $session->start($req); // simulate detection of session cookie $matchedMember = $handler->authenticateRequest($req); $this->assertNotNull($matchedMember); diff --git a/tests/php/Security/MemberCsvBulkLoaderTest.php b/tests/php/Security/MemberCsvBulkLoaderTest.php index 0b3d18363..723adcd46 100644 --- a/tests/php/Security/MemberCsvBulkLoaderTest.php +++ b/tests/php/Security/MemberCsvBulkLoaderTest.php @@ -9,6 +9,7 @@ use SilverStripe\Security\Member; use SilverStripe\Security\PasswordValidator; use SilverStripe\Security\Security; use SilverStripe\Dev\SapphireTest; +use SilverStripe\Security\MemberAuthenticator\MemberAuthenticator; class MemberCsvBulkLoaderTest extends SapphireTest { @@ -105,7 +106,8 @@ class MemberCsvBulkLoaderTest extends SapphireTest // TODO Direct getter doesn't work, wtf! $this->assertEquals(Security::config()->password_encryption_algorithm, $member->getField('PasswordEncryption')); - $result = $member->checkPassword('mypassword'); + $auth = new MemberAuthenticator(); + $result = $auth->checkPassword($member, 'mypassword'); $this->assertTrue($result->isValid()); } } diff --git a/tests/php/Security/MemberTest.php b/tests/php/Security/MemberTest.php index 62454b56d..53e1875b4 100644 --- a/tests/php/Security/MemberTest.php +++ b/tests/php/Security/MemberTest.php @@ -219,7 +219,7 @@ class MemberTest extends FunctionalTest */ public function testChangedPasswordEmaling() { - Member::config()->update('notify_password_change', true); + Member::config()->set('notify_password_change', true); $this->clearEmails(); @@ -1187,7 +1187,7 @@ class MemberTest extends FunctionalTest $this->assertStringContainsString($message, $response->getBody()); // Logging out from the second device - only one device being logged out - RememberLoginHash::config()->update('logout_across_devices', false); + RememberLoginHash::config()->set('logout_across_devices', false); $this->get( 'Security/logout', $this->session(), @@ -1205,7 +1205,7 @@ class MemberTest extends FunctionalTest // If session-manager module is installed then logout_across_devices is modified so skip if (!class_exists(LoginSession::class)) { // Logging out from any device when all login hashes should be removed - RememberLoginHash::config()->update('logout_across_devices', true); + RememberLoginHash::config()->set('logout_across_devices', true); Injector::inst()->get(IdentityStore::class)->logIn($m1, true); $this->get('Security/logout', $this->session()); $this->assertEquals( @@ -1248,7 +1248,7 @@ class MemberTest extends FunctionalTest { $maxFailedLoginsAllowed = 3; //set up the config variables to enable login lockouts - Member::config()->update('lock_out_after_incorrect_logins', $maxFailedLoginsAllowed); + Member::config()->set('lock_out_after_incorrect_logins', $maxFailedLoginsAllowed); /** @var Member $member */ $member = $this->objFromFixture(Member::class, 'test'); @@ -1282,7 +1282,7 @@ class MemberTest extends FunctionalTest public function testMemberValidator() { // clear custom requirements for this test - Member_Validator::config()->update('customRequired', null); + Member_Validator::config()->set('customRequired', null); /** @var Member $memberA */ $memberA = $this->objFromFixture(Member::class, 'admin'); /** @var Member $memberB */ @@ -1358,7 +1358,7 @@ class MemberTest extends FunctionalTest public function testMemberValidatorWithExtensions() { // clear custom requirements for this test - Member_Validator::config()->update('customRequired', null); + Member_Validator::config()->set('customRequired', null); // create a blank form $form = new MemberTest\ValidatorForm(); @@ -1422,7 +1422,7 @@ class MemberTest extends FunctionalTest public function testCustomMemberValidator() { // clear custom requirements for this test - Member_Validator::config()->update('customRequired', null); + Member_Validator::config()->set('customRequired', null); $member = $this->objFromFixture(Member::class, 'admin'); diff --git a/tests/php/Security/RandomGeneratorTest.php b/tests/php/Security/RandomGeneratorTest.php index 3d2048e94..6f7d2dea1 100644 --- a/tests/php/Security/RandomGeneratorTest.php +++ b/tests/php/Security/RandomGeneratorTest.php @@ -3,6 +3,7 @@ namespace SilverStripe\Security\Tests; use SilverStripe\Security\RandomGenerator; +use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; /** @@ -13,6 +14,9 @@ class RandomGeneratorTest extends SapphireTest public function testGenerateEntropy() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $r = new RandomGenerator(); $this->assertNotNull($r->generateEntropy()); $this->assertNotEquals($r->generateEntropy(), $r->generateEntropy()); diff --git a/tests/php/View/ArrayDataTest.php b/tests/php/View/ArrayDataTest.php index b90258f79..49d93309e 100644 --- a/tests/php/View/ArrayDataTest.php +++ b/tests/php/View/ArrayDataTest.php @@ -4,7 +4,6 @@ namespace SilverStripe\View\Tests; use SilverStripe\ORM\ArrayLib; use SilverStripe\ORM\FieldType\DBVarchar; -use SilverStripe\Dev\Deprecation; use SilverStripe\Dev\SapphireTest; use SilverStripe\View\ArrayData; use stdClass; @@ -67,9 +66,6 @@ class ArrayDataTest extends SapphireTest public function testGetArray() { - $originalDeprecation = Deprecation::dump_settings(); - Deprecation::notification_version('2.4'); - $array = [ 'Foo' => 'Foo', 'Bar' => 'Bar', @@ -79,8 +75,6 @@ class ArrayDataTest extends SapphireTest $arrayData = new ArrayData($array); $this->assertEquals($arrayData->toMap(), $array); - - Deprecation::restore_settings($originalDeprecation); } public function testArrayToObject() diff --git a/tests/php/View/RequirementsTest.php b/tests/php/View/RequirementsTest.php index 69144ea5b..ae9d19558 100644 --- a/tests/php/View/RequirementsTest.php +++ b/tests/php/View/RequirementsTest.php @@ -516,7 +516,7 @@ class RequirementsTest extends SapphireTest $combinedFileName = '/_combinedfiles/RequirementsTest_bc-2a55d56.js'; $combinedFilePath = TestAssetStore::base_path() . $combinedFileName; - $html = $backend->includeInHTML(false, self::$html_template); + $html = $backend->includeInHTML(self::$html_template); /* ASYNC IS INCLUDED IN SCRIPT TAG */ $this->assertMatchesRegularExpression( diff --git a/tests/php/View/SSViewerTest.php b/tests/php/View/SSViewerTest.php index cd1fe076c..ac3779942 100644 --- a/tests/php/View/SSViewerTest.php +++ b/tests/php/View/SSViewerTest.php @@ -32,6 +32,7 @@ use SilverStripe\View\SSViewer_FromString; use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModel; use SilverStripe\View\Tests\SSViewerTest\SSViewerTestModelController; use SilverStripe\View\ViewableData; +use SilverStripe\Dev\Deprecation; /** * @skipUpgrade @@ -53,8 +54,8 @@ class SSViewerTest extends SapphireTest protected function setUp(): void { parent::setUp(); - SSViewer::config()->update('source_file_comments', false); - SSViewer_FromString::config()->update('cache_template', false); + SSViewer::config()->set('source_file_comments', false); + SSViewer_FromString::config()->set('cache_template', false); TestAssetStore::activate('SSViewerTest'); $this->oldServer = $_SERVER; } @@ -73,7 +74,10 @@ class SSViewerTest extends SapphireTest */ public function testCurrentTheme() { - SSViewer::config()->update('theme', 'mytheme'); + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } + SSViewer::config()->set('theme', 'mytheme'); $this->assertEquals( 'mytheme', SSViewer::config()->uninherited('theme'), @@ -1269,39 +1273,39 @@ after' $this->assertEquals("12345678910", $result, "Numbers rendered in order"); //test First - $result = $this->render('<% loop Set %><% if First %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $IsFirst %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("1", $result, "Only the first number is rendered"); //test Last - $result = $this->render('<% loop Set %><% if Last %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $IsLast %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("10", $result, "Only the last number is rendered"); //test Even - $result = $this->render('<% loop Set %><% if Even() %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $Even() %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("246810", $result, "Even numbers rendered in order"); //test Even with quotes - $result = $this->render('<% loop Set %><% if Even("1") %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $Even("1") %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("246810", $result, "Even numbers rendered in order"); //test Even without quotes - $result = $this->render('<% loop Set %><% if Even(1) %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $Even(1) %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("246810", $result, "Even numbers rendered in order"); //test Even with zero-based start index - $result = $this->render('<% loop Set %><% if Even("0") %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $Even("0") %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("13579", $result, "Even (with zero-based index) numbers rendered in order"); //test Odd - $result = $this->render('<% loop Set %><% if Odd %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $Odd %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("13579", $result, "Odd numbers rendered in order"); //test FirstLast - $result = $this->render('<% loop Set %><% if FirstLast %>$Number$FirstLast<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $FirstLast %>$Number$FirstLast<% end_if %><% end_loop %>', $data); $this->assertEquals("1first10last", $result, "First and last numbers rendered in order"); //test Middle - $result = $this->render('<% loop Set %><% if Middle %>$Number<% end_if %><% end_loop %>', $data); + $result = $this->render('<% loop Set %><% if $Middle %>$Number<% end_if %><% end_loop %>', $data); $this->assertEquals("23456789", $result, "Middle numbers rendered in order"); //test MiddleString @@ -1611,7 +1615,7 @@ after' $this->assertEqualIgnoringWhitespace( '1ab23last', $this->render( - '<% loop $Foo %>$Name<% loop Children %>$Name<% end_loop %><% if Last %>last<% end_if %>' + '<% loop $Foo %>$Name<% loop Children %>$Name<% end_loop %><% if $IsLast %>last<% end_if %>' . '<% end_loop %>', $data ) @@ -1819,7 +1823,7 @@ EOC; public function testRenderWithSourceFileComments() { - SSViewer::config()->update('source_file_comments', true); + SSViewer::config()->set('source_file_comments', true); $i = __DIR__ . '/SSViewerTest/templates/Includes'; $f = __DIR__ . '/SSViewerTest/templates/SSViewerTestComments'; $templates = [ @@ -2099,7 +2103,7 @@ EOC; $this->render($content, null, null); $this->assertFalse(file_exists($cacheFile ?? ''), 'Cache file was created when caching was off'); - SSViewer_FromString::config()->update('cache_template', true); + SSViewer_FromString::config()->set('cache_template', true); $this->render($content, null, null); $this->assertTrue(file_exists($cacheFile ?? ''), 'Cache file wasn\'t created when it was meant to'); unlink($cacheFile ?? ''); diff --git a/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceInclude.ss b/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceInclude.ss index 0a67cba95..bd92206e7 100644 --- a/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceInclude.ss +++ b/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceInclude.ss @@ -1 +1 @@ -<% if $Title %>$Title<% else %>Untitled<% end_if %> <% if $ArgA %>_ $ArgA <% end_if %>- <% if $First %>First-<% end_if %><% if $Last %>Last-<% end_if %><%if $MultipleOf(2) %>EVEN<% else %>ODD<% end_if %> top:$Top.Title +<% if $Title %>$Title<% else %>Untitled<% end_if %> <% if $ArgA %>_ $ArgA <% end_if %>- <% if $IsFirst %>First-<% end_if %><% if $IsLast %>Last-<% end_if %><%if $MultipleOf(2) %>EVEN<% else %>ODD<% end_if %> top:$Top.Title diff --git a/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceWithArgsInLoop.ss b/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceWithArgsInLoop.ss index 44479e5ea..32dd1fccf 100644 --- a/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceWithArgsInLoop.ss +++ b/tests/php/View/SSViewerTest/templates/Includes/SSViewerTestIncludeScopeInheritanceWithArgsInLoop.ss @@ -1 +1 @@ -$Title - <% loop $Items %>$Title<% if not Last %> - <% else %> - {$Top.Title}<% end_if %><% end_loop %> \ No newline at end of file +$Title - <% loop $Items %>$Title<% if not $IsLast %> - <% else %> - {$Top.Title}<% end_if %><% end_loop %> \ No newline at end of file diff --git a/tests/php/View/ViewableDataTest.php b/tests/php/View/ViewableDataTest.php index 3f3e7b329..f3c776aaa 100644 --- a/tests/php/View/ViewableDataTest.php +++ b/tests/php/View/ViewableDataTest.php @@ -7,6 +7,7 @@ use SilverStripe\Dev\SapphireTest; use SilverStripe\View\ArrayData; use SilverStripe\View\SSViewer; use SilverStripe\View\ViewableData; +use SilverStripe\Dev\Deprecation; /** * See {@link SSViewerTest->testCastingHelpers()} for more tests related to casting and ViewableData behaviour, @@ -208,6 +209,9 @@ class ViewableDataTest extends SapphireTest public function testThemeDir() { + if (Deprecation::isEnabled()) { + $this->markTestSkipped('Test calls deprecated code'); + } $themes = [ "silverstripe/framework:/tests/php/View/ViewableDataTest/testtheme", SSViewer::DEFAULT_THEME diff --git a/tests/php/i18n/i18nTest.php b/tests/php/i18n/i18nTest.php index 08065a543..79882c940 100644 --- a/tests/php/i18n/i18nTest.php +++ b/tests/php/i18n/i18nTest.php @@ -149,7 +149,7 @@ class i18nTest extends SapphireTest public function testTemplateTranslation() { $oldLocale = i18n::get_locale(); - i18n::config()->update('missing_default_warning', false); + i18n::config()->set('missing_default_warning', false); /** @var SymfonyMessageProvider $provider */ $provider = Injector::inst()->get(MessageProvider::class); @@ -311,7 +311,7 @@ class i18nTest extends SapphireTest * */ public function testNewTemplateTranslation() { - i18n::config()->update('missing_default_warning', false); + i18n::config()->set('missing_default_warning', false); /** @var SymfonyMessageProvider $provider */ $provider = Injector::inst()->get(MessageProvider::class); @@ -468,7 +468,7 @@ class i18nTest extends SapphireTest public function testGetLanguageName() { - i18n::config()->update( + i18n::config()->merge( 'common_languages', ['de_CGN' => ['name' => 'German (Cologne)', 'native' => 'Kölsch']] ); diff --git a/tests/php/i18n/i18nTestManifest.php b/tests/php/i18n/i18nTestManifest.php index 3a06f06ce..b08c91a54 100644 --- a/tests/php/i18n/i18nTestManifest.php +++ b/tests/php/i18n/i18nTestManifest.php @@ -82,7 +82,7 @@ trait i18nTestManifest // Switch to test manifest $s = DIRECTORY_SEPARATOR; $this->alternateBasePath = __DIR__ . $s . 'i18nTest' . $s . "_fakewebroot"; - Director::config()->update('alternate_base_folder', $this->alternateBasePath); + Director::config()->set('alternate_base_folder', $this->alternateBasePath); // New module manifest $moduleManifest = new ModuleManifest($this->alternateBasePath); diff --git a/tests/php/i18n/i18nTextCollectorTest.php b/tests/php/i18n/i18nTextCollectorTest.php index 6812c9cc6..c79bdddaa 100644 --- a/tests/php/i18n/i18nTextCollectorTest.php +++ b/tests/php/i18n/i18nTextCollectorTest.php @@ -533,8 +533,8 @@ PHP; public function testCollectFromFilesystemAndWriteMasterTables() { i18n::set_locale('en_US'); //set the locale to the US locale expected in the asserts - i18n::config()->update('default_locale', 'en_US'); - i18n::config()->update('missing_default_warning', false); + i18n::config()->set('default_locale', 'en_US'); + i18n::config()->set('missing_default_warning', false); $c = i18nTextCollector::create(); $c->setWarnOnEmptyDefault(false);